max_stars_count
int64
301
224k
text
stringlengths
6
1.05M
token_count
int64
3
727k
678
<reponame>bzxy/cydia /** * This header is generated by class-dump-z 0.2b. * * Source: /System/Library/PrivateFrameworks/iLifeSlideshow.framework/iLifeSlideshow */ #import <iLifeSlideshow/XXUnknownSuperclass.h> #import <iLifeSlideshow/iLifeSlideshow-Structs.h> // iOSOpenDev: wrapped with define check (since occurs in other dumped files) #ifndef __XXUnknownSuperclass__ #define __XXUnknownSuperclass__ 1 @interface XXUnknownSuperclass : NSObject @end #endif @interface XXUnknownSuperclass (MCVectorExtension) + (id)valueWithMCVector:(XXStruct_Te64nB)mcvector; // 0x3951 - (XXStruct_Te64nB)MCVectorValue; // 0x3935 @end @interface XXUnknownSuperclass (ComponentAdditions) + (id)colorWithCalibratedRed:(float)calibratedRed green:(float)green blue:(float)blue alpha:(float)alpha; // 0x1b739 - (float)redComponent; // 0x1b775 - (float)greenComponent; // 0x1b7ad - (float)blueComponent; // 0x1b7dd - (float)alphaComponent; // 0x1b80d - (int)numberOfComponents; // 0x1b759 @end @interface XXUnknownSuperclass (MRMarimbaViewPlayback) - (double)relativeTime; // 0x73795 - (double)relativeTimeForBackgroundAudio; // 0x737e1 - (double)relativeTimeForLayer:(id)layer; // 0x7383d - (id)displayedEffectContainers; // 0x72ff5 - (void)moveToEffectContainer:(id)effectContainer withStartOffset:(double)startOffset toStopOffset:(double)stopOffset blocking:(BOOL)blocking; // 0x73055 - (void)moveToNextEffectContainer; // 0x73265 - (void)moveToPreviousEffectContainer; // 0x73331 - (void)moveToTitleSlide; // 0x733f9 - (id)_currentEffectContainer; // 0x738e5 - (id)_firstEffectContainer; // 0x73549 - (id)_effectContainerForTime:(double)time; // 0x73a41 - (int)_mainLayerIndex; // 0x735c1 - (void)watcherThread:(id)thread; // 0x73675 @end @interface XXUnknownSuperclass (Additions) - (int)indexAtIndex:(int)index; // 0x73b75 - (id)indexSetWithOffset:(int)offset; // 0x73bcd @end @interface XXUnknownSuperclass (MRUtilities) - (int)sortPatchworkAscendingVertical:(id)vertical; // 0x8c7e9 - (int)sortPatchworkDescendingVertical:(id)vertical; // 0x8c869 - (int)sortPatchworkAscendingHorizontal:(id)horizontal; // 0x8c8e9 - (int)sortPatchworkDescendingHorizontal:(id)horizontal; // 0x8c969 @end
815
1,529
### tf-nightly-2.2.0-dev20200502 import tensorflow as tf import numpy as np def representative_dataset_gen_kitti(): for image in raw_test_data_hand: image = tf.image.resize(image.astype(np.float32), (128, 416)) image = image[np.newaxis,:,:,:] image = image / 255 yield [image] def representative_dataset_gen_cityscapes(): for image in raw_test_data_hand: image = tf.image.resize(image.astype(np.float32), (128, 416)) image = image[np.newaxis,:,:,:] image = image / 255 yield [image] raw_test_data_hand = np.load('calibration_data_img_kitti.npy', allow_pickle=True) raw_test_data_joint = np.load('calibration_data_img_cityscapes.npy', allow_pickle=True) # Integer Quantization - Input/Output=float32 converter = tf.lite.TFLiteConverter.from_saved_model('saved_model_kitti') converter.optimizations = [tf.lite.Optimize.DEFAULT] converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS_INT8,tf.lite.OpsSet.SELECT_TF_OPS] converter.inference_input_type = tf.uint8 converter.inference_output_type = tf.uint8 converter.representative_dataset = representative_dataset_gen_kitti tflite_quant_model = converter.convert() with open('struct2depth_128x416_kitti_depth_full_integer_quant.tflite', 'wb') as w: w.write(tflite_quant_model) print("Integer Quantization complete! - struct2depth_128x416_kitti_depth_full_integer_quant.tflite") # Integer Quantization - Input/Output=float32 converter = tf.lite.TFLiteConverter.from_saved_model('saved_model_cityscapes') converter.optimizations = [tf.lite.Optimize.DEFAULT] converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS_INT8,tf.lite.OpsSet.SELECT_TF_OPS] converter.inference_input_type = tf.uint8 converter.inference_output_type = tf.uint8 converter.representative_dataset = representative_dataset_gen_cityscapes tflite_quant_model = converter.convert() with open('struct2depth_128x416_cityscapes_depth_full_integer_quant.tflite', 'wb') as w: w.write(tflite_quant_model) print("Integer Quantization complete! - struct2depth_128x416_cityscapes_depth_full_integer_quant.tflite")
803
5,169
<reponame>Gantios/Specs<gh_stars>1000+ { "name": "CMYLogger", "version": "2.0.0", "summary": "a demo of framework upload.", "description": "\"a demo of framework upload without source code \"", "homepage": "https://github.com/zhouyf14/CMYLogger", "license": { "type": "Apache 2.0", "file": "LICENSE" }, "authors": { "jojo": "<EMAIL>" }, "platforms": { "ios": "8.0" }, "source": { "git": "https://github.com/zhouyf14/CMYLogger.git", "tag": "2.0.0" }, "vendored_frameworks": "CMYLogger.framework", "frameworks": [ "UIKit", "AVFoundation", "Foundation" ] }
278
11,864
#include "utils.h" #include "peripherals/uart.h" #include "peripherals/gpio.h" void uart_send ( char c ) { /* Wait for TX FIFO to not be Full. * This would work way better if we used the fifo level interrupts :) */ while(get32(UART_FR) & (1 << 5)) {} put32(UART_DR,c); } char uart_recv ( void ) { /* Block while RX FIFO empty */ while(get32(UART_FR) & (1 << 4)) { } return(get32(UART_DR)&0xFF); } void uart_send_string(char* str) { for (int i = 0; str[i] != '\0'; i ++) { uart_send((char)str[i]); } } void uart_init ( void ) { unsigned int selector; selector = get32(GPFSEL1); selector &= ~(7<<12); // clean gpio14 selector |= 4<<12; // set alt0 for gpio14 selector &= ~(7<<15); // clean gpio15 selector |= 4<<15; // set alt0 for gpio15 put32(GPFSEL1,selector); put32(GPPUD,0); delay(150); put32(GPPUDCLK0,(1<<14)|(1<<15)); delay(150); put32(GPPUDCLK0,0); put32(UART_CR, 0); // Disable UART while we mess around put32(UART_IMSC, 0); // Disable all interrupts // Assume 48MHz UART Reference Clock (Standard) // Calculate UART clock divider per datasheet // BAUDDIV = (FUARTCLK/(16 Baud rate)) // Note: We get 6 bits of fraction for the baud div // 48000000/(16 * 115200) = 3000000/115200 = 26.0416666... // Integer part = 26 :) // From http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.ddi0183g/I54603.html // we want floor(0.04166666.. * 64 + 0.5) = 3 put32(UART_IBRD, 26); put32(UART_FBRD, 3); // set to 8 bits, enable fifo put32(UART_LCRH, (3 << 5) | (1 << 4)); // Enable RX, TX, UART put32(UART_CR, (1 << 9) | (1 << 8) | (1 << 0)); }
935
2,996
// Copyright 2021 The Terasology Foundation // SPDX-License-Identifier: Apache-2.0 package org.terasology.engine.utilities; import java.io.IOException; import java.nio.file.DirectoryStream; import java.nio.file.FileVisitResult; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.SimpleFileVisitor; import java.nio.file.attribute.BasicFileAttributes; public final class FilesUtil { /** * A filter for DirectoryStream that only accepts directories */ public static final DirectoryStream.Filter<Path> DIRECTORY_FILTER = file -> Files.isDirectory(file); private FilesUtil() { } /** * Note: Keep an eye out for recursive delete being added to the core Java API in the future - there are certain * circumstances in which this can be unsafe. * * @param path * @throws IOException */ public static void recursiveDelete(Path path) throws IOException { if (Files.isDirectory(path)) { Files.walkFileTree(path, new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { Files.delete(file); return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException { Files.delete(file); return FileVisitResult.CONTINUE; } @Override public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException { if (exc == null) { Files.delete(dir); return FileVisitResult.CONTINUE; } else { throw exc; } } }); } } }
871
3,296
/****************************************************************************** * Copyright (c) 2011, <NAME>. All rights reserved. * Copyright (c) 2011-2018, NVIDIA CORPORATION. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the NVIDIA CORPORATION 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 NVIDIA CORPORATION 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. * ******************************************************************************/ /** * \file * Thread utilities for reading memory using PTX cache modifiers. */ #pragma once #include <iterator> #include "3rdparty/cub/config.cuh.h" #include "3rdparty/cub/util_ptx.cuh.h" #include "3rdparty/cub/util_type.cuh.h" /// Optional outer namespace(s) CUB_NS_PREFIX /// CUB namespace namespace cub { /** * \addtogroup UtilIo * @{ */ //----------------------------------------------------------------------------- // Tags and constants //----------------------------------------------------------------------------- /** * \brief Enumeration of cache modifiers for memory load operations. */ enum CacheLoadModifier { LOAD_DEFAULT, ///< Default (no modifier) LOAD_CA, ///< Cache at all levels LOAD_CG, ///< Cache at global level LOAD_CS, ///< Cache streaming (likely to be accessed once) LOAD_CV, ///< Cache as volatile (including cached system lines) LOAD_LDG, ///< Cache as texture LOAD_VOLATILE, ///< Volatile (any memory space) }; /** * \name Thread I/O (cache modified) * @{ */ /** * \brief Thread utility for reading memory using cub::CacheLoadModifier cache modifiers. Can be used to load any data type. * * \par Example * \code * #include <3rdparty/cub/cub.cuh> // or equivalently <cub/thread/thread_load.cuh> * * // 32-bit load using cache-global modifier: * int *d_in; * int val = cub::ThreadLoad<cub::LOAD_CA>(d_in + threadIdx.x); * * // 16-bit load using default modifier * short *d_in; * short val = cub::ThreadLoad<cub::LOAD_DEFAULT>(d_in + threadIdx.x); * * // 256-bit load using cache-volatile modifier * double4 *d_in; * double4 val = cub::ThreadLoad<cub::LOAD_CV>(d_in + threadIdx.x); * * // 96-bit load using cache-streaming modifier * struct TestFoo { bool a; short b; }; * TestFoo *d_struct; * TestFoo val = cub::ThreadLoad<cub::LOAD_CS>(d_in + threadIdx.x); * \endcode * * \tparam MODIFIER <b>[inferred]</b> CacheLoadModifier enumeration * \tparam InputIteratorT <b>[inferred]</b> Input iterator type \iterator */ template < CacheLoadModifier MODIFIER, typename InputIteratorT> __device__ __forceinline__ typename std::iterator_traits<InputIteratorT>::value_type ThreadLoad(InputIteratorT itr); //@} end member group #ifndef DOXYGEN_SHOULD_SKIP_THIS // Do not document /// Helper structure for templated load iteration (inductive case) template <int COUNT, int MAX> struct IterateThreadLoad { template <CacheLoadModifier MODIFIER, typename T> static __device__ __forceinline__ void Load(T const *ptr, T *vals) { vals[COUNT] = ThreadLoad<MODIFIER>(ptr + COUNT); IterateThreadLoad<COUNT + 1, MAX>::template Load<MODIFIER>(ptr, vals); } template <typename InputIteratorT, typename T> static __device__ __forceinline__ void Dereference(InputIteratorT itr, T *vals) { vals[COUNT] = itr[COUNT]; IterateThreadLoad<COUNT + 1, MAX>::Dereference(itr, vals); } }; /// Helper structure for templated load iteration (termination case) template <int MAX> struct IterateThreadLoad<MAX, MAX> { template <CacheLoadModifier MODIFIER, typename T> static __device__ __forceinline__ void Load(T const * /*ptr*/, T * /*vals*/) {} template <typename InputIteratorT, typename T> static __device__ __forceinline__ void Dereference(InputIteratorT /*itr*/, T * /*vals*/) {} }; /** * Define a uint4 (16B) ThreadLoad specialization for the given Cache load modifier */ #define _CUB_LOAD_16(cub_modifier, ptx_modifier) \ template<> \ __device__ __forceinline__ uint4 ThreadLoad<cub_modifier, uint4 const *>(uint4 const *ptr) \ { \ uint4 retval; \ asm volatile ("ld."#ptx_modifier".v4.u32 {%0, %1, %2, %3}, [%4];" : \ "=r"(retval.x), \ "=r"(retval.y), \ "=r"(retval.z), \ "=r"(retval.w) : \ _CUB_ASM_PTR_(ptr)); \ return retval; \ } \ template<> \ __device__ __forceinline__ ulonglong2 ThreadLoad<cub_modifier, ulonglong2 const *>(ulonglong2 const *ptr) \ { \ ulonglong2 retval; \ asm volatile ("ld."#ptx_modifier".v2.u64 {%0, %1}, [%2];" : \ "=l"(retval.x), \ "=l"(retval.y) : \ _CUB_ASM_PTR_(ptr)); \ return retval; \ } /** * Define a uint2 (8B) ThreadLoad specialization for the given Cache load modifier */ #define _CUB_LOAD_8(cub_modifier, ptx_modifier) \ template<> \ __device__ __forceinline__ ushort4 ThreadLoad<cub_modifier, ushort4 const *>(ushort4 const *ptr) \ { \ ushort4 retval; \ asm volatile ("ld."#ptx_modifier".v4.u16 {%0, %1, %2, %3}, [%4];" : \ "=h"(retval.x), \ "=h"(retval.y), \ "=h"(retval.z), \ "=h"(retval.w) : \ _CUB_ASM_PTR_(ptr)); \ return retval; \ } \ template<> \ __device__ __forceinline__ uint2 ThreadLoad<cub_modifier, uint2 const *>(uint2 const *ptr) \ { \ uint2 retval; \ asm volatile ("ld."#ptx_modifier".v2.u32 {%0, %1}, [%2];" : \ "=r"(retval.x), \ "=r"(retval.y) : \ _CUB_ASM_PTR_(ptr)); \ return retval; \ } \ template<> \ __device__ __forceinline__ unsigned long long ThreadLoad<cub_modifier, unsigned long long const *>(unsigned long long const *ptr) \ { \ unsigned long long retval; \ asm volatile ("ld."#ptx_modifier".u64 %0, [%1];" : \ "=l"(retval) : \ _CUB_ASM_PTR_(ptr)); \ return retval; \ } /** * Define a uint (4B) ThreadLoad specialization for the given Cache load modifier */ #define _CUB_LOAD_4(cub_modifier, ptx_modifier) \ template<> \ __device__ __forceinline__ unsigned int ThreadLoad<cub_modifier, unsigned int const *>(unsigned int const *ptr) \ { \ unsigned int retval; \ asm volatile ("ld."#ptx_modifier".u32 %0, [%1];" : \ "=r"(retval) : \ _CUB_ASM_PTR_(ptr)); \ return retval; \ } /** * Define a unsigned short (2B) ThreadLoad specialization for the given Cache load modifier */ #define _CUB_LOAD_2(cub_modifier, ptx_modifier) \ template<> \ __device__ __forceinline__ unsigned short ThreadLoad<cub_modifier, unsigned short const *>(unsigned short const *ptr) \ { \ unsigned short retval; \ asm volatile ("ld."#ptx_modifier".u16 %0, [%1];" : \ "=h"(retval) : \ _CUB_ASM_PTR_(ptr)); \ return retval; \ } /** * Define an unsigned char (1B) ThreadLoad specialization for the given Cache load modifier */ #define _CUB_LOAD_1(cub_modifier, ptx_modifier) \ template<> \ __device__ __forceinline__ unsigned char ThreadLoad<cub_modifier, unsigned char const *>(unsigned char const *ptr) \ { \ unsigned short retval; \ asm volatile ( \ "{" \ " .reg .u8 datum;" \ " ld."#ptx_modifier".u8 datum, [%1];" \ " cvt.u16.u8 %0, datum;" \ "}" : \ "=h"(retval) : \ _CUB_ASM_PTR_(ptr)); \ return (unsigned char) retval; \ } /** * Define powers-of-two ThreadLoad specializations for the given Cache load modifier */ #define _CUB_LOAD_ALL(cub_modifier, ptx_modifier) \ _CUB_LOAD_16(cub_modifier, ptx_modifier) \ _CUB_LOAD_8(cub_modifier, ptx_modifier) \ _CUB_LOAD_4(cub_modifier, ptx_modifier) \ _CUB_LOAD_2(cub_modifier, ptx_modifier) \ _CUB_LOAD_1(cub_modifier, ptx_modifier) \ /** * Define powers-of-two ThreadLoad specializations for the various Cache load modifiers */ #if CUB_PTX_ARCH >= 200 _CUB_LOAD_ALL(LOAD_CA, ca) _CUB_LOAD_ALL(LOAD_CG, cg) _CUB_LOAD_ALL(LOAD_CS, cs) _CUB_LOAD_ALL(LOAD_CV, cv) #else _CUB_LOAD_ALL(LOAD_CA, global) // Use volatile to ensure coherent reads when this PTX is JIT'd to run on newer architectures with L1 _CUB_LOAD_ALL(LOAD_CG, volatile.global) _CUB_LOAD_ALL(LOAD_CS, global) _CUB_LOAD_ALL(LOAD_CV, volatile.global) #endif #if CUB_PTX_ARCH >= 350 _CUB_LOAD_ALL(LOAD_LDG, global.nc) #else _CUB_LOAD_ALL(LOAD_LDG, global) #endif // Macro cleanup #undef _CUB_LOAD_ALL #undef _CUB_LOAD_1 #undef _CUB_LOAD_2 #undef _CUB_LOAD_4 #undef _CUB_LOAD_8 #undef _CUB_LOAD_16 /** * ThreadLoad definition for LOAD_DEFAULT modifier on iterator types */ template <typename InputIteratorT> __device__ __forceinline__ typename std::iterator_traits<InputIteratorT>::value_type ThreadLoad( InputIteratorT itr, Int2Type<LOAD_DEFAULT> /*modifier*/, Int2Type<false> /*is_pointer*/) { return *itr; } /** * ThreadLoad definition for LOAD_DEFAULT modifier on pointer types */ template <typename T> __device__ __forceinline__ T ThreadLoad( T *ptr, Int2Type<LOAD_DEFAULT> /*modifier*/, Int2Type<true> /*is_pointer*/) { return *ptr; } /** * ThreadLoad definition for LOAD_VOLATILE modifier on primitive pointer types */ template <typename T> __device__ __forceinline__ T ThreadLoadVolatilePointer( T *ptr, Int2Type<true> /*is_primitive*/) { T retval = *reinterpret_cast<volatile T*>(ptr); return retval; } /** * ThreadLoad definition for LOAD_VOLATILE modifier on non-primitive pointer types */ template <typename T> __device__ __forceinline__ T ThreadLoadVolatilePointer( T *ptr, Int2Type<false> /*is_primitive*/) { typedef typename UnitWord<T>::VolatileWord VolatileWord; // Word type for memcopying const int VOLATILE_MULTIPLE = sizeof(T) / sizeof(VolatileWord); T retval; VolatileWord *words = reinterpret_cast<VolatileWord*>(&retval); IterateThreadLoad<0, VOLATILE_MULTIPLE>::Dereference( reinterpret_cast<volatile VolatileWord*>(ptr), words); return retval; } /** * ThreadLoad definition for LOAD_VOLATILE modifier on pointer types */ template <typename T> __device__ __forceinline__ T ThreadLoad( T *ptr, Int2Type<LOAD_VOLATILE> /*modifier*/, Int2Type<true> /*is_pointer*/) { // Apply tags for partial-specialization return ThreadLoadVolatilePointer(ptr, Int2Type<Traits<T>::PRIMITIVE>()); } /** * ThreadLoad definition for generic modifiers on pointer types */ template <typename T, int MODIFIER> __device__ __forceinline__ T ThreadLoad( T const *ptr, Int2Type<MODIFIER> /*modifier*/, Int2Type<true> /*is_pointer*/) { typedef typename UnitWord<T>::DeviceWord DeviceWord; const int DEVICE_MULTIPLE = sizeof(T) / sizeof(DeviceWord); DeviceWord words[DEVICE_MULTIPLE]; IterateThreadLoad<0, DEVICE_MULTIPLE>::template Load<CacheLoadModifier(MODIFIER)>( reinterpret_cast<DeviceWord*>(const_cast<T*>(ptr)), words); return *reinterpret_cast<T*>(words); } /** * ThreadLoad definition for generic modifiers */ template < CacheLoadModifier MODIFIER, typename InputIteratorT> __device__ __forceinline__ typename std::iterator_traits<InputIteratorT>::value_type ThreadLoad(InputIteratorT itr) { // Apply tags for partial-specialization return ThreadLoad( itr, Int2Type<MODIFIER>(), Int2Type<IsPointer<InputIteratorT>::VALUE>()); } #endif // DOXYGEN_SHOULD_SKIP_THIS /** @} */ // end group UtilIo } // CUB namespace CUB_NS_POSTFIX // Optional outer namespace(s)
10,693
1,338
/* * Copyright 2020, <NAME> <<EMAIL>>. * All rights reserved. Distributed under the terms of the MIT License. */ #ifndef RATING_STABILITY_H #define RATING_STABILITY_H #include <Referenceable.h> #include <String.h> class RatingStability : public BReferenceable { public: RatingStability(); RatingStability( const BString& code, const BString& name, int64 ordering); RatingStability( const RatingStability& other); RatingStability& operator=(const RatingStability& other); bool operator==(const RatingStability& other) const; bool operator!=(const RatingStability& other) const; const BString& Code() const { return fCode; } const BString& Name() const { return fName; } int64 Ordering() const { return fOrdering; } int Compare(const RatingStability& other) const; private: BString fCode; BString fName; int64 fOrdering; }; typedef BReference<RatingStability> RatingStabilityRef; extern bool IsRatingStabilityBefore(const RatingStabilityRef& rs1, const RatingStabilityRef& rs2); #endif // RATING_STABILITY_H
506
322
<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.eagle.alert.engine.publisher.email; public class AlertEmailConstants { public static final String CONN_PLAINTEXT = "plaintext"; public static final String CONN_TLS = "tls"; public static final String CONN_SSL = "ssl"; public static final String CONF_MAIL_HOST = "mail.smtp.host"; public static final String CONF_MAIL_PORT = "mail.smtp.port"; public static final String CONF_MAIL_AUTH = "mail.smtp.auth"; public static final String CONF_AUTH_USER = "mail.username"; public static final String CONF_AUTH_PASSWORD = "<PASSWORD>"; public static final String CONF_MAIL_CONN = "mail.connection"; public static final String CONF_MAIL_DEBUG = "mail.debug"; }
453
1,511
/* * Copyright (C) 2006, <NAME> (<EMAIL>) * Copyright (C) 2008, Nokia (<EMAIL>) * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser Lesser General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #include "config.h" #include <string.h> #include <stdlib.h> #include <glib.h> #include "tracker-class.h" #include "tracker-namespace.h" #include "tracker-ontologies.h" #define GET_PRIV(obj) (G_TYPE_INSTANCE_GET_PRIVATE ((obj), TRACKER_TYPE_CLASS, TrackerClassPriv)) typedef struct _TrackerClassPriv TrackerClassPriv; struct _TrackerClassPriv { gchar *uri; gchar *name; gint count; gint id; gboolean is_new; GArray *super_classes; }; static void class_finalize (GObject *object); static void class_get_property (GObject *object, guint param_id, GValue *value, GParamSpec *pspec); static void class_set_property (GObject *object, guint param_id, const GValue *value, GParamSpec *pspec); enum { PROP_0, PROP_URI, PROP_NAME, PROP_COUNT, PROP_ID, PROP_IS_NEW }; G_DEFINE_TYPE (TrackerClass, tracker_class, G_TYPE_OBJECT); static void tracker_class_class_init (TrackerClassClass *klass) { GObjectClass *object_class = G_OBJECT_CLASS (klass); object_class->finalize = class_finalize; object_class->get_property = class_get_property; object_class->set_property = class_set_property; g_object_class_install_property (object_class, PROP_URI, g_param_spec_string ("uri", "uri", "URI", NULL, G_PARAM_READWRITE)); g_object_class_install_property (object_class, PROP_NAME, g_param_spec_string ("name", "name", "Service name", NULL, G_PARAM_READABLE)); g_object_class_install_property (object_class, PROP_NAME, g_param_spec_int ("count", "count", "Count", 0, G_MAXINT, 0, G_PARAM_READWRITE)); g_object_class_install_property (object_class, PROP_ID, g_param_spec_int ("id", "id", "Id", 0, G_MAXINT, 0, G_PARAM_READABLE | G_PARAM_WRITABLE)); g_object_class_install_property (object_class, PROP_IS_NEW, g_param_spec_boolean ("is-new", "is-new", "Is new", FALSE, G_PARAM_READWRITE)); g_type_class_add_private (object_class, sizeof (TrackerClassPriv)); } static void tracker_class_init (TrackerClass *service) { TrackerClassPriv *priv; priv = GET_PRIV (service); priv->id = 0; priv->super_classes = g_array_new (TRUE, TRUE, sizeof (TrackerClass *)); } static void class_finalize (GObject *object) { TrackerClassPriv *priv; priv = GET_PRIV (object); g_free (priv->uri); g_free (priv->name); g_array_free (priv->super_classes, TRUE); (G_OBJECT_CLASS (tracker_class_parent_class)->finalize) (object); } static void class_get_property (GObject *object, guint param_id, GValue *value, GParamSpec *pspec) { TrackerClassPriv *priv; priv = GET_PRIV (object); switch (param_id) { case PROP_URI: g_value_set_string (value, priv->uri); break; case PROP_NAME: g_value_set_string (value, priv->name); break; case PROP_COUNT: g_value_set_int (value, priv->count); break; case PROP_ID: g_value_set_int (value, priv->id); break; case PROP_IS_NEW: g_value_set_boolean (value, priv->is_new); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID (object, param_id, pspec); break; }; } static void class_set_property (GObject *object, guint param_id, const GValue *value, GParamSpec *pspec) { switch (param_id) { case PROP_URI: tracker_class_set_uri (TRACKER_CLASS (object), g_value_get_string (value)); break; case PROP_COUNT: tracker_class_set_count (TRACKER_CLASS (object), g_value_get_int (value)); break; case PROP_ID: tracker_class_set_id (TRACKER_CLASS (object), g_value_get_int (value)); break; case PROP_IS_NEW: tracker_class_set_is_new (TRACKER_CLASS (object), g_value_get_boolean (value)); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID (object, param_id, pspec); break; }; } TrackerClass * tracker_class_new (void) { TrackerClass *service; service = g_object_new (TRACKER_TYPE_CLASS, NULL); return service; } const gchar * tracker_class_get_uri (TrackerClass *service) { TrackerClassPriv *priv; g_return_val_if_fail (TRACKER_IS_CLASS (service), NULL); priv = GET_PRIV (service); return priv->uri; } const gchar * tracker_class_get_name (TrackerClass *service) { TrackerClassPriv *priv; g_return_val_if_fail (TRACKER_IS_CLASS (service), NULL); priv = GET_PRIV (service); return priv->name; } gint tracker_class_get_count (TrackerClass *service) { TrackerClassPriv *priv; g_return_val_if_fail (TRACKER_IS_CLASS (service), 0); priv = GET_PRIV (service); return priv->count; } gint tracker_class_get_id (TrackerClass *service) { TrackerClassPriv *priv; g_return_val_if_fail (TRACKER_IS_CLASS (service), 0); priv = GET_PRIV (service); return priv->id; } TrackerClass ** tracker_class_get_super_classes (TrackerClass *service) { TrackerClassPriv *priv; g_return_val_if_fail (TRACKER_IS_CLASS (service), NULL); priv = GET_PRIV (service); return (TrackerClass **) priv->super_classes->data; } gboolean tracker_class_get_is_new (TrackerClass *service) { TrackerClassPriv *priv; g_return_val_if_fail (TRACKER_IS_CLASS (service), FALSE); priv = GET_PRIV (service); return priv->is_new; } void tracker_class_set_uri (TrackerClass *service, const gchar *value) { TrackerClassPriv *priv; g_return_if_fail (TRACKER_IS_CLASS (service)); priv = GET_PRIV (service); g_free (priv->uri); g_free (priv->name); priv->uri = NULL; priv->name = NULL; if (value) { gchar *namespace_uri, *hash; TrackerNamespace *namespace; priv->uri = g_strdup (value); hash = strrchr (priv->uri, '#'); if (hash == NULL) { /* support ontologies whose namespace uri does not end in a hash, e.g. dc */ hash = strrchr (priv->uri, '/'); } if (hash == NULL) { g_critical ("Unknown namespace of class %s", priv->uri); } else { namespace_uri = g_strndup (priv->uri, hash - priv->uri + 1); namespace = tracker_ontologies_get_namespace_by_uri (namespace_uri); if (namespace == NULL) { g_critical ("Unknown namespace %s of class %s", namespace_uri, priv->uri); } else { priv->name = g_strdup_printf ("%s:%s", tracker_namespace_get_prefix (namespace), hash + 1); } g_free (namespace_uri); } } g_object_notify (G_OBJECT (service), "uri"); } void tracker_class_set_count (TrackerClass *service, gint value) { TrackerClassPriv *priv; g_return_if_fail (TRACKER_IS_CLASS (service)); priv = GET_PRIV (service); priv->count = value; } void tracker_class_set_id (TrackerClass *service, gint value) { TrackerClassPriv *priv; g_return_if_fail (TRACKER_IS_CLASS (service)); priv = GET_PRIV (service); priv->id = value; } void tracker_class_set_super_classes (TrackerClass *service, TrackerClass **value) { TrackerClassPriv *priv; TrackerClass **super_class; g_return_if_fail (TRACKER_IS_CLASS (service)); priv = GET_PRIV (service); g_array_free (priv->super_classes, TRUE); priv->super_classes = g_array_new (TRUE, TRUE, sizeof (TrackerClass *)); for (super_class = value; *super_class; super_class++) { g_array_append_val (priv->super_classes, *super_class); } } void tracker_class_add_super_class (TrackerClass *service, TrackerClass *value) { TrackerClassPriv *priv; g_return_if_fail (TRACKER_IS_CLASS (service)); g_return_if_fail (TRACKER_IS_CLASS (value)); priv = GET_PRIV (service); g_array_append_val (priv->super_classes, value); } void tracker_class_set_is_new (TrackerClass *service, gboolean value) { TrackerClassPriv *priv; g_return_if_fail (TRACKER_IS_CLASS (service)); priv = GET_PRIV (service); priv->is_new = value; g_object_notify (G_OBJECT (service), "is-new"); }
5,423
807
<filename>Master/x360ce/x360ce/x360ce/SWIP.h /* SWIP - Simple Windows Ini Parser * * Copyright (C) 2013 <NAME> * * SWIP is free software: you can redistribute it and/or modify it under the terms * of the GNU Lesser General Public License as published by the Free Software Found- * ation, either version 3 of the License, or (at your option) any later version. * * SWIP is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR * PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with SWIP. * If not, see <http://www.gnu.org/licenses/>. */ #ifndef _SWIP_H_ #define _SWIP_H_ // C++ headers #if _MSC_VER < 1700 #include "pstdint.h" #else #include <stdint.h> #endif #include <string> #include <vector> #include <algorithm> #include <functional> #if _MSC_VER < 1700 #include "mutex.h" #else #include <mutex> #endif // Windows headers #include <shlwapi.h> #include <Shlobj.h> #pragma comment(lib, "shlwapi.lib") #pragma comment(lib, "shell32.lib") // 'identifier' : decorated name length exceeded, name was truncated #pragma warning(disable: 4503) // define INI_ORDERED to use map #ifdef INI_ORDERED #include <map> #define MAP_TYPE std::map #else #include <unordered_map> #define MAP_TYPE std::unordered_map #endif #ifndef CURRENT_MODULE extern "C" IMAGE_DOS_HEADER __ImageBase; #define CURRENT_MODULE reinterpret_cast<HMODULE>(&__ImageBase) #endif #define SWIP_BUFFERSIZE 32767 class SWIP { public: // maps typedef MAP_TYPE<std::string, std::string> section_t; typedef MAP_TYPE<std::string, section_t> ini_t; explicit SWIP() :m_inipath(), m_inimap() {} explicit SWIP(const std::string& filename) :m_inipath(), m_inimap() { this->open(filename); } bool open(const std::string& filename) { if (this->internal_open(filename)) return false; if (!PathIsRelativeA(filename.c_str())) return false; char buffer[MAX_PATH]; char path[MAX_PATH]; if (SHGetFolderPathA(NULL, CSIDL_COMMON_APPDATA, NULL, SHGFP_TYPE_CURRENT, path) == S_OK) { PathCombineA(buffer, path, "x360ce"); PathCombineA(path, buffer, filename.c_str()); if (PathFileExistsA(path) && PathIsDirectoryA(path) == FALSE) return this->internal_open(path); else return false; } return false; } virtual ~SWIP(void) {} bool is_open() const { return m_is_open; } const std::string get_inipath() const { return m_inipath; } std::string get_string(const std::string& section, const std::string& key, const std::string& def = std::string()) const { std::string toret = this->internal_get_string(section,key); if (toret.empty()) return def; else return toret; } bool get_bool(const std::string& section, const std::string& key, const bool& def = false) const { // get string, default is not used because conversion are slow! std::string strval = this->get_string(section,key); // and we can return default if empty here if(strval.empty()) return def; if(isdigit(strval[0])) { // convert to bool and return return strtol(strval.c_str(),NULL,0) != 0; } else { // "true" and "false" strings std::transform(strval.begin(), strval.end(), strval.begin(), tolower); if(strval.compare("true") == 0) return true; } return false; } int32_t get_int(const std::string& section, const std::string& key, const int32_t& def = 0) const { // get string, default is not used because conversion are slow! const std::string& strval = this->get_string(section,key); // and we can return default if empty here if(strval.empty()) return def; // convert to bool and return return strtol(strval.c_str(),NULL,0); } uint32_t get_uint(const std::string& section, const std::string& key, const uint32_t& def = 0) const { // get string, default is not used because conversion are slow! const std::string& strval = this->get_string(section,key); // and we can return default if empty here if(strval.empty()) return def; // convert to bool and return return strtoul(strval.c_str(),NULL,0); } int64_t get_int64(const std::string& section, const std::string& key, const int64_t& def = 0) const { // get string, default is not used because conversion are slow! const std::string& strval = this->get_string(section,key); // and we can return default if empty here if(strval.empty()) return def; // convert to bool and return return _strtoi64(strval.c_str(),NULL,0); } uint64_t get_uint64(const std::string& section, const std::string& key, const uint64_t& def = 0) const { // get string, default is not used because conversion are slow! const std::string& strval = this->get_string(section,key); // and we can return default if empty here if(strval.empty()) return def; // convert to bool and return return _strtoui64(strval.c_str(),NULL,0); } section_t get_section(const std::string& section) const { auto secit = m_inimap.find(section); if(secit != m_inimap.end()) { return secit->second; } return section_t(); } bool set_string(const std::string& section, const std::string& key, const std::string& val) { std::string strval = " " + val; m_inimap[section][key] = val; return WritePrivateProfileStringA(section.c_str(),key.c_str(),strval.c_str(),m_inipath.c_str()) != 0; } bool set_bool(const std::string& section, const std::string& key, const bool& val) { std::string strval; if(val) strval = "true"; else strval = "false"; if(val) m_inimap[section][key] = strval; strval = " " + strval; return WritePrivateProfileStringA(section.c_str(),key.c_str(),strval.c_str(),m_inipath.c_str()) != 0; } bool set_int(const std::string& section, const std::string& key, const int32_t& val) { char cstr[2 * _MAX_INT_DIG]; sprintf_s(cstr, sizeof (cstr), "%d", val); std::string strval = cstr; m_inimap[section][key] = strval; strval = " " + strval; return WritePrivateProfileStringA(section.c_str(),key.c_str(),strval.c_str(),m_inipath.c_str()) != 0; } bool set_uint(const std::string& section, const std::string& key, const uint32_t& val) { char cstr[2 * _MAX_INT_DIG]; sprintf_s(cstr, sizeof (cstr), "%u", val); std::string strval = cstr; m_inimap[section][key] = strval; strval = " " + strval; return WritePrivateProfileStringA(section.c_str(),key.c_str(),strval.c_str(),m_inipath.c_str()) != 0; } bool key_exist(const std::string& section, const std::string& key) { bool toret = this->internal_key_exist(section,key); // not found, populate section if needed if(toret == false && this->key_count(section) < this->populate_section(section)) { toret = this->internal_key_exist(section,key); } return toret; } bool value_not_empty(const std::string& section, const std::string& key) { return this->get_string(section,key).empty() != true; } size_t key_count(const std::string& section) { auto itr = m_inimap.find(section); if(itr != m_inimap.end()) return itr->second.size(); return 0; } size_t section_count() const { return m_inimap.size(); } private: bool internal_open(const std::string& filename) { // buffer for WinAPI functions char path[MAX_PATH]; // check is path is relative if (PathIsRelativeA(filename.c_str())) { // if path is relative get full path to ini file DWORD dwLen = GetModuleFileNameA(CURRENT_MODULE, path, MAX_PATH); if (dwLen > 0 && PathRemoveFileSpecA(path)) { PathAppendA(path, filename.c_str()); m_inipath = path; // check if file exist and is not a directory if (PathFileExistsA(m_inipath.c_str()) && PathIsDirectoryA(m_inipath.c_str()) == FALSE) { return m_is_open = this->populate_ini(); } } else return m_is_open = false; } else { // if path is absolute copy path m_inipath = filename; // check if file exist and is not a directory if (PathFileExistsA(m_inipath.c_str()) && PathIsDirectoryA(m_inipath.c_str()) == FALSE) { return m_is_open = this->populate_ini(); } } return m_is_open = false; } std::string internal_get_string(const std::string& section, const std::string& key) const { if(m_inimap.empty()) return std::string(); std::string internal_section = section; std::string internal_key = key; std::transform(internal_section.begin(), internal_section.end(), internal_section.begin(), tolower); std::transform(internal_key.begin(), internal_key.end(), internal_key.begin(), tolower); // find section auto secit = m_inimap.find(internal_section); if(secit != m_inimap.end()) { // find key auto keyit = secit->second.find(internal_key); if(keyit != secit->second.end()) { // return value return keyit->second; } } return std::string(); } bool internal_key_exist(const std::string& section, const std::string& key) { #if _MSC_VER < 1700 lock_guard lock(m_mutex); #else std::lock_guard<std::recursive_mutex> lock(m_mutex); #endif auto secit = m_inimap.find(section); if(secit != m_inimap.end()) { // find key auto keyit = secit->second.find(key); if(keyit != secit->second.end()) return true; } return false; } size_t populate_section(const std::string& section) { char *keyvalbuf = new char[SWIP_BUFFERSIZE]; // read all section data to buffer using WinAPI #if _MSC_VER < 1700 lock_guard lock(m_mutex); #else std::lock_guard<std::recursive_mutex> lock(m_mutex); #endif GetPrivateProfileSectionA(section.c_str(), keyvalbuf, SWIP_BUFFERSIZE, m_inipath.c_str()); // store pointer for data iteration char* pData = keyvalbuf; size_t count = 0; // last "key=value" string is double null terminated while (*pData != '\0') { // set both, key and val to "key=value" string std::string strSection(section); std::string strkey(pData); std::string strval(pData); // get real key and value from "key=value" string strkey = strkey.substr(0,strkey.find("=")); strval = strval.substr(strval.find("=")+1,strval.length()); // strip commentary NOTE: WinAPI strip only ';' commentaries at start of line! strip_comment_and_trim(&strSection); strip_comment_and_trim(&strkey); strip_comment_and_trim(&strval); // add key/value to correct section, skip empty to save memory if(!strSection.empty() && !strkey.empty() && !strval.empty()) { m_inimap[strSection][strkey] = strval; ++count; } // get next "key=value" string pData = pData + strlen(pData) + 1; } delete [] keyvalbuf; return count; } bool populate_ini() { // allocate buffers char *sectionbuf = new char[SWIP_BUFFERSIZE]; // read all section names to buffer using WinAPI #if _MSC_VER < 1700 lock_guard lock(m_mutex); #else std::lock_guard<std::recursive_mutex> lock(m_mutex); #endif GetPrivateProfileSectionNamesA(sectionbuf, SWIP_BUFFERSIZE, m_inipath.c_str()); // store pointer for sections iteration char* pSection = sectionbuf; // last section name is double null terminated while (*pSection != '\0') { this->populate_section(pSection); // get next section name pSection = pSection + strlen(pSection) + 1; } delete [] sectionbuf; return !m_inimap.empty(); } void strip_comment_and_trim(std::string* str) const { size_t pos = std::string::npos; if(str == nullptr) return; std::transform(str->begin(), str->end(), str->begin(), tolower); pos = str->find('#'); if( pos != std::string::npos) str->resize(pos); pos = str->find(';'); if( pos != std::string::npos) str->resize(pos); pos = str->find_first_not_of(' '); if( pos != std::string::npos) str->erase(0, pos); pos = str->find_last_not_of(' ') + 1; if( pos != std::string::npos) str->resize(pos); pos = str->find_first_not_of('"'); if( pos != std::string::npos) str->erase(0, pos); pos = str->find_last_not_of('"') + 1; if( pos != std::string::npos) str->resize(pos); return; } private: std::string m_inipath; ini_t m_inimap; #if _MSC_VER < 1700 recursive_mutex m_mutex; #else std::recursive_mutex m_mutex; #endif bool m_is_open; }; #endif
5,815
348
{"nom":"Taron-Sadirac-Viellenave","circ":"3ème circonscription","dpt":"Pyrénées-Atlantiques","inscrits":150,"abs":53,"votants":97,"blancs":1,"nuls":4,"exp":92,"res":[{"nuance":"REM","nom":"<NAME>","voix":49},{"nuance":"SOC","nom":"<NAME>","voix":43}]}
105
521
/* $Id: fwudp.c $ */ /** @file * NAT Network - UDP port-forwarding. */ /* * Copyright (C) 2013-2017 Oracle Corporation * * This file is part of VirtualBox Open Source Edition (OSE), as * available from http://www.virtualbox.org. This file is free software; * you can redistribute it and/or modify it under the terms of the GNU * General Public License (GPL) as published by the Free Software * Foundation, in version 2 as it comes in the "COPYING" file of the * VirtualBox OSE distribution. VirtualBox OSE is distributed in the * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind. */ #define LOG_GROUP LOG_GROUP_NAT_SERVICE #include "winutils.h" #include "proxy.h" #include "proxy_pollmgr.h" #include "portfwd.h" #include "pxremap.h" #ifndef RT_OS_WINDOWS #include <sys/types.h> #include <sys/socket.h> #include <stdio.h> #include <string.h> #include <poll.h> #include <err.h> /* BSD'ism */ #else #include <stdio.h> #include <string.h> #include "winpoll.h" #endif #include "lwip/opt.h" #include "lwip/memp.h" /* XXX: for bulk delete of pcbs */ #include "lwip/sys.h" #include "lwip/tcpip.h" #include "lwip/udp.h" struct fwudp_dgram { struct pbuf *p; ipX_addr_t src_addr; u16_t src_port; }; /** * UDP port-forwarding. * * Unlike pxudp that uses 1:1 mapping between pcb and socket, for * port-forwarded UDP the setup is bit more elaborated. * * For fwtcp things are simple since incoming TCP connection get a new * socket that we just hand off to pxtcp. Thus fwtcp only handles * connection initiation. * * For fwudp all proxied UDP conversations share the same socket, so * single fwudp multiplexes to several UDP pcbs. * * XXX: TODO: Currently pcbs point back directly to fwudp. It might * make sense to introduce a per-pcb structure that points to fwudp * and carries additional information, like pre-mapped peer address. */ struct fwudp { /** * Our poll manager handler. */ struct pollmgr_handler pmhdl; /** * Forwarding specification. */ struct fwspec fwspec; /** * XXX: lwip-format copy of destination */ ipX_addr_t dst_addr; u16_t dst_port; /** * Listening socket. */ SOCKET sock; /** * Ring-buffer for inbound datagrams. */ struct { struct fwudp_dgram *buf; size_t bufsize; volatile size_t vacant; volatile size_t unsent; } inbuf; struct tcpip_msg msg_send; struct tcpip_msg msg_delete; struct fwudp *next; }; struct fwudp *fwudp_create(struct fwspec *); /* poll manager callback for fwudp socket */ static int fwudp_pmgr_pump(struct pollmgr_handler *, SOCKET, int); /* lwip thread callbacks called via proxy_lwip_post() */ static void fwudp_pcb_send(void *); static void fwudp_pcb_delete(void *); static void fwudp_pcb_recv(void *, struct udp_pcb *, struct pbuf *, ip_addr_t *, u16_t); static void fwudp_pcb_forward_outbound(struct fwudp *, struct udp_pcb *, struct pbuf *); /** * Linked list of active fwtcp forwarders. */ struct fwudp *fwudp_list = NULL; void fwudp_init(void) { return; } void fwudp_add(struct fwspec *fwspec) { struct fwudp *fwudp; fwudp = fwudp_create(fwspec); if (fwudp == NULL) { DPRINTF0(("%s: failed to add rule for UDP ...\n", __func__)); return; } DPRINTF0(("%s\n", __func__)); /* fwudp_create has put fwudp on the linked list */ } void fwudp_del(struct fwspec *fwspec) { struct fwudp *fwudp; struct fwudp **pprev; for (pprev = &fwudp_list; (fwudp = *pprev) != NULL; pprev = &fwudp->next) { if (fwspec_equal(&fwudp->fwspec, fwspec)) { *pprev = fwudp->next; fwudp->next = NULL; break; } } if (fwudp == NULL) { DPRINTF0(("%s: not found\n", __func__)); return; } DPRINTF0(("%s\n", __func__)); pollmgr_del_slot(fwudp->pmhdl.slot); fwudp->pmhdl.slot = -1; /* let pending msg_send be processed before we delete fwudp */ proxy_lwip_post(&fwudp->msg_delete); } struct fwudp * fwudp_create(struct fwspec *fwspec) { struct fwudp *fwudp; SOCKET sock; int status; sock = proxy_bound_socket(fwspec->sdom, fwspec->stype, &fwspec->src.sa); if (sock == INVALID_SOCKET) { return NULL; } fwudp = (struct fwudp *)malloc(sizeof(*fwudp)); if (fwudp == NULL) { closesocket(sock); return NULL; } fwudp->pmhdl.callback = fwudp_pmgr_pump; fwudp->pmhdl.data = (void *)fwudp; fwudp->pmhdl.slot = -1; fwudp->sock = sock; fwudp->fwspec = *fwspec; /* struct copy */ /* XXX */ if (fwspec->sdom == PF_INET) { struct sockaddr_in *dst4 = &fwspec->dst.sin; memcpy(&fwudp->dst_addr.ip4, &dst4->sin_addr, sizeof(ip_addr_t)); fwudp->dst_port = htons(dst4->sin_port); } else { /* PF_INET6 */ struct sockaddr_in6 *dst6 = &fwspec->dst.sin6; memcpy(&fwudp->dst_addr.ip6, &dst6->sin6_addr, sizeof(ip6_addr_t)); fwudp->dst_port = htons(dst6->sin6_port); } fwudp->inbuf.bufsize = 256; /* elements */ fwudp->inbuf.buf = (struct fwudp_dgram *)calloc(fwudp->inbuf.bufsize, sizeof(struct fwudp_dgram)); if (fwudp->inbuf.buf == NULL) { closesocket(sock); free(fwudp); return (NULL); } fwudp->inbuf.vacant = 0; fwudp->inbuf.unsent = 0; #define CALLBACK_MSG(MSG, FUNC) \ do { \ fwudp->MSG.type = TCPIP_MSG_CALLBACK_STATIC; \ fwudp->MSG.sem = NULL; \ fwudp->MSG.msg.cb.function = FUNC; \ fwudp->MSG.msg.cb.ctx = (void *)fwudp; \ } while (0) CALLBACK_MSG(msg_send, fwudp_pcb_send); CALLBACK_MSG(msg_delete, fwudp_pcb_delete); #undef CALLBACK_MSG status = pollmgr_add(&fwudp->pmhdl, fwudp->sock, POLLIN); if (status < 0) { closesocket(sock); free(fwudp->inbuf.buf); free(fwudp); return NULL; } fwudp->next = fwudp_list; fwudp_list = fwudp; return fwudp; } /** * Poll manager callaback for fwudp::sock */ int fwudp_pmgr_pump(struct pollmgr_handler *handler, SOCKET fd, int revents) { struct fwudp *fwudp; struct sockaddr_storage ss; socklen_t sslen = sizeof(ss); size_t beg, lim; struct fwudp_dgram *dgram; struct pbuf *p; ssize_t nread; int status; err_t error; fwudp = (struct fwudp *)handler->data; LWIP_ASSERT1(fwudp != NULL); LWIP_ASSERT1(fd == fwudp->sock); LWIP_ASSERT1(revents == POLLIN); LWIP_UNUSED_ARG(fd); LWIP_UNUSED_ARG(revents); #ifdef RT_OS_WINDOWS nread = recvfrom(fwudp->sock, (char *)pollmgr_udpbuf, sizeof(pollmgr_udpbuf), 0, (struct sockaddr *)&ss, &sslen); #else nread = recvfrom(fwudp->sock, pollmgr_udpbuf, sizeof(pollmgr_udpbuf), 0, (struct sockaddr *)&ss, &sslen); #endif if (nread < 0) { DPRINTF(("%s: %R[sockerr]\n", __func__, SOCKERRNO())); return POLLIN; } /* Check that ring buffer is not full */ lim = fwudp->inbuf.unsent; if (lim == 0) { lim = fwudp->inbuf.bufsize - 1; /* guard slot at the end */ } else { --lim; } beg = fwudp->inbuf.vacant; if (beg == lim) { /* no vacant slot */ return POLLIN; } dgram = &fwudp->inbuf.buf[beg]; status = fwany_ipX_addr_set_src(&dgram->src_addr, (struct sockaddr *)&ss); if (status == PXREMAP_FAILED) { return POLLIN; } if (ss.ss_family == AF_INET) { const struct sockaddr_in *peer4 = (const struct sockaddr_in *)&ss; dgram->src_port = htons(peer4->sin_port); } else { /* PF_INET6 */ const struct sockaddr_in6 *peer6 = (const struct sockaddr_in6 *)&ss; dgram->src_port = htons(peer6->sin6_port); } p = pbuf_alloc(PBUF_RAW, nread, PBUF_RAM); if (p == NULL) { DPRINTF(("%s: pbuf_alloc(%d) failed\n", __func__, (int)nread)); return POLLIN; } error = pbuf_take(p, pollmgr_udpbuf, nread); if (error != ERR_OK) { DPRINTF(("%s: pbuf_take(%d) failed\n", __func__, (int)nread)); pbuf_free(p); return POLLIN; } dgram->p = p; ++beg; if (beg == fwudp->inbuf.bufsize) { beg = 0; } fwudp->inbuf.vacant = beg; proxy_lwip_post(&fwudp->msg_send); return POLLIN; } /** * Lwip thread callback invoked via fwudp::msg_send */ void fwudp_pcb_send(void *arg) { struct fwudp *fwudp = (struct fwudp *)arg; struct fwudp_dgram dgram; struct udp_pcb *pcb; struct udp_pcb **pprev; int isv6; size_t idx; idx = fwudp->inbuf.unsent; if (idx == fwudp->inbuf.vacant) { /* empty buffer - shouldn't happen! */ DPRINTF(("%s: ring buffer empty!\n", __func__)); return; } dgram = fwudp->inbuf.buf[idx]; /* struct copy */ #if 1 /* valgrind hint */ fwudp->inbuf.buf[idx].p = NULL; #endif if (++idx == fwudp->inbuf.bufsize) { idx = 0; } fwudp->inbuf.unsent = idx; /* XXX: this is *STUPID* */ isv6 = (fwudp->fwspec.sdom == PF_INET6); pprev = &udp_proxy_pcbs; for (pcb = udp_proxy_pcbs; pcb != NULL; pcb = pcb->next) { if (PCB_ISIPV6(pcb) == isv6 && pcb->remote_port == fwudp->dst_port && ipX_addr_cmp(isv6, &fwudp->dst_addr, &pcb->remote_ip) && pcb->local_port == dgram.src_port && ipX_addr_cmp(isv6, &dgram.src_addr, &pcb->local_ip)) { break; } else { pprev = &pcb->next; } } if (pcb != NULL) { *pprev = pcb->next; pcb->next = udp_proxy_pcbs; udp_proxy_pcbs = pcb; /* * XXX: check that its ours and not accidentally created by * outbound traffic. * * ???: Otherwise? Expire it and set pcb = NULL; to create a * new one below? */ } if (pcb == NULL) { pcb = udp_new(); if (pcb == NULL) { goto out; } ip_set_v6(pcb, isv6); /* equivalent of udp_bind */ ipX_addr_set(isv6, &pcb->local_ip, &dgram.src_addr); pcb->local_port = dgram.src_port; /* equivalent to udp_connect */ ipX_addr_set(isv6, &pcb->remote_ip, &fwudp->dst_addr); pcb->remote_port = fwudp->dst_port; pcb->flags |= UDP_FLAGS_CONNECTED; udp_recv(pcb, fwudp_pcb_recv, fwudp); pcb->next = udp_proxy_pcbs; udp_proxy_pcbs = pcb; udp_proxy_timer_needed(); } udp_send(pcb, dgram.p); out: pbuf_free(dgram.p); } /** * udp_recv() callback. */ void fwudp_pcb_recv(void *arg, struct udp_pcb *pcb, struct pbuf *p, ip_addr_t *addr, u16_t port) { struct fwudp *fwudp = (struct fwudp *)arg; LWIP_UNUSED_ARG(addr); LWIP_UNUSED_ARG(port); LWIP_ASSERT1(fwudp != NULL); if (p == NULL) { DPRINTF(("%s: pcb %p (fwudp %p); sock %d: expired\n", __func__, (void *)pcb, (void *)fwudp, fwudp->sock)); /* NB: fwudp is "global" and not deleted */ /* XXX: TODO: delete local reference when we will keep one */ udp_remove(pcb); return; } else { fwudp_pcb_forward_outbound(fwudp, pcb, p); } } /* * XXX: This is pxudp_pcb_forward_outbound modulo: * - s/pxudp/fwudp/g * - addr/port (unused in either) dropped * - destination is specified since host socket is not connected */ static void fwudp_pcb_forward_outbound(struct fwudp *fwudp, struct udp_pcb *pcb, struct pbuf *p) { union { struct sockaddr_in sin; struct sockaddr_in6 sin6; } peer; socklen_t namelen; memset(&peer, 0, sizeof(peer)); /* XXX: shut up valgrind */ if (fwudp->fwspec.sdom == PF_INET) { peer.sin.sin_family = AF_INET; #if HAVE_SA_LEN peer.sin.sin_len = #endif namelen = sizeof(peer.sin); pxremap_outbound_ip4((ip_addr_t *)&peer.sin.sin_addr, &pcb->local_ip.ip4); peer.sin.sin_port = htons(pcb->local_port); } else { peer.sin6.sin6_family = AF_INET6; #if HAVE_SA_LEN peer.sin6.sin6_len = #endif namelen = sizeof(peer.sin6); pxremap_outbound_ip6((ip6_addr_t *)&peer.sin6.sin6_addr, &pcb->local_ip.ip6); peer.sin6.sin6_port = htons(pcb->local_port); } proxy_sendto(fwudp->sock, p, &peer, namelen); pbuf_free(p); } /** * Lwip thread callback invoked via fwudp::msg_delete */ static void fwudp_pcb_delete(void *arg) { struct fwudp *fwudp = (struct fwudp *)arg; struct udp_pcb *pcb; struct udp_pcb **pprev; LWIP_ASSERT1(fwudp->inbuf.unsent == fwudp->inbuf.vacant); pprev = &udp_proxy_pcbs; pcb = udp_proxy_pcbs; while (pcb != NULL) { if (pcb->recv_arg != fwudp) { pprev = &pcb->next; pcb = pcb->next; } else { struct udp_pcb *dead = pcb; pcb = pcb->next; *pprev = pcb; memp_free(MEMP_UDP_PCB, dead); } } closesocket(fwudp->sock); free(fwudp->inbuf.buf); free(fwudp); }
6,721
844
<gh_stars>100-1000 { "github-username": "ManojNathIC", "favourite-emoji": "😊", "favourite-music": "https://soundcloud.com/edsheeran/photograph", "favourite-color": "#2611c2" }
88
506
<reponame>Ashindustry007/competitive-programming #!/usr/bin/env python3 # https://codeforces.com/contest/1058/problem/C n = int(input()) d = [int(x) for x in input()] s = sum(d) y = s == 0 for i in range(2,s+1): if y == True: break if s%i == 0: k = s//i c = 0 ok = True for x in d: c += x if c > k: ok = False break if c == k: c = 0 if ok: y = True print('YES' if y else 'NO')
301
930
from socket import * import datetime import os import time import random import threading from _thread import * import shutil # to implement delete method import csv # used in put and post method to insert data import base64 # used for decoding autherization header in delete method import sys import logging from config import * # import variables import signal # signal to handle Ctrl+C and other SIGNALS from supplement.breakdown import * # to breakdown entity from supplement.last_modified import * # last_modified for condi get class http_methods: def response_get_head(self, connectionsocket, entity, switcher, query, method, glob): serversocket, file_extension, conditional_get, conn, ip, serverport, scode, IDENTITY, client_thread = glob isItFile = os.path.isfile(entity) isItDir = os.path.isdir(entity) show_response = '' if isItFile: show_response += 'HTTP/1.1 200 OK' scode = 200 if (os.access(entity, os.R_OK)): if (os.access(entity, os.W_OK)): pass else: glob = status(connectionsocket, 403, [ip, client_thread, scode]) ip, client_thread, scode = glob else: glob = status(connectionsocket, 403, [ip, client_thread, scode]) ip, client_thread, scode = glob try: size = os.path.getsize(entity) f = open(entity, "rb") data = f.read(size) except: glob = status(connectionsocket, 500, [ip, client_thread, scode]) ip, client_thread, scode = glob elif isItDir: dir_list = os.listdir(entity) show_response += 'HTTP/1.1 200 OK' scode = 200 # if it is a directory if os.access(entity, os.R_OK): if (os.access(entity, os.W_OK)): pass else: glob = status(connectionsocket, 403, [ip, client_thread, scode]) ip, client_thread, scode = glob else: glob = status(connectionsocket, 403, [ip, client_thread, scode]) ip, client_thread, scode = glob for i in dir_list: if i.startswith('.'): dir_list.remove(i) else: pass else: entity = entity.rstrip('/') isItDir = os.path.isdir(entity) isItFile = os.path.isfile(entity) if isItDir: scode = 200 show_response += 'HTTP/1.1 200 OK' dir_list = os.listdir(entity) entity = entity.rstrip('/') if (os.access(entity, os.W_OK)): if (os.access(entity, os.R_OK)): pass else: glob = status(connectionsocket, 403, [ip, client_thread, scode]) ip, client_thread, scode = glob else: glob = status(connectionsocket, 403, [ip, client_thread, scode]) ip, client_thread, scode = glob for i in dir_list: if i.startswith('.'): dir_list.remove(i) else: pass elif isItFile: show_response += 'HTTP/1.1 200 OK' scode = 200 if (os.access(entity, os.R_OK)): if (os.access(entity, os.W_OK)): pass else: glob = status(connectionsocket, 403, [ip, client_thread, scode]) ip, client_thread, scode = glob try: size = os.path.getsize(entity) f = open(entity, "rb") data = f.read(size) except: # error while accesing the file glob = status(connectionsocket, 500, [ip, client_thread, scode]) ip, client_thread, scode = glob else: glob = status(connectionsocket, 404, [ip, client_thread, scode]) ip, client_thread, scode = glob show_response += '\r\n' + COOKIE + str(IDENTITY) + MAXAGE IDENTITY += random.randint(1, 10) for state in switcher: if state == 'User-Agent': if isItDir: show_response += '\r\nServer: ' + ip elif isItFile: l = time.ctime().split(' ') l[0] = l[0] + ',' conversation = (' ').join(l) show_response += '\r\nServer: ' + ip conversation = '\r\nDate: ' + conversation show_response += conversation show_response += '\r\n' + last_modified(entity) else: pass elif state == 'Host': pass elif state == 'Accept': if isItFile: try: file_ext = os.path.splitext(entity) if file_ext[1] in file_extension.keys(): conversation = file_extension[file_ext[1]] temp = 0 else: conversation = 'text/plain' temp = 1 conversation = '\r\nContent-Type: ' + conversation show_response += conversation except: glob = status(connectionsocket, 415, [ip, client_thread, scode]) ip, client_thread, scode = glob # scode = 415 elif isItDir: conversation = '\r\nContent-Type: text/html' show_response += conversation else: pass elif state == 'Accept-Language': conversation = '\r\nContent-Language: ' + switcher[state] show_response += conversation elif state == 'Accept-Encoding': if isItFile: conversation = '\r\nContent-Length: ' + str(size) show_response += conversation else: pass elif state == 'Connection': if isItFile: conn = True show_response += '\r\nConnection: keep-alive' elif isItDir: conn = False show_response += '\r\nConnection: close' else: pass elif state == 'If-Modified-Since': if_modify(switcher[state], entity) else: continue if isItDir and method == 'GET': show_response += '\r\n\r\n' show_response += '\r\n<!DOCTYPE html>' show_response += '\r\n<html>\n<head>' show_response += '\r\n<title>Directory listing</title>' show_response += '\r\n<meta http-equiv="Content-type" content="text/html;charset=UTF-8" /></head>' show_response += '\r\n<body><h1>Directory listing..</h1><ul>' for line in dir_list: if entity == '/': link = 'http://' + ip + ':' + \ str(serverport) + entity + line l = '\r\n<li><a href ="' + link + '">' + line + '</a></li>' show_response += l else: link = 'http://' + ip + ':' + \ str(serverport) + entity + '/' + line l = '\r\n<li><a href ="' + link + '">' + line + '</a></li>' show_response += l show_response += '\r\n</ul></body></html>' encoded = show_response.encode() connectionsocket.send(encoded) connectionsocket.close() elif len(query) > 0 and not isItFile and not isItDir: show_response = '' row = '' entity = CSVFILE fields = '' for d in query: fields += d + ',' for i in query[d]: row += i + ',' file_exists = os.path.exists(entity) if file_exists: scode = 200 show_response += 'HTTP/1.1 200 OK' fi = open(entity, "a") row = list(row.split(",")) csvwriter = csv.writer(fi) csvwriter.writerow(row) else: fi = open(entity, "w") show_response += 'HTTP/1.1 201 Created' scode = 201 show_response.append('Location: ' + entity) csvwriter = csv.writer(fi) csvwriter.writerow(fields) csvwriter.writerow(row) fi.close() show_response += '\r\nServer: ' + ip show_response += '\r\n' + date() f = open(WORKFILE, "rb") show_response += '\r\nContent-Language: en-US,en' size = os.path.getsize(WORKFILE) conversation = '\r\nContent-Length: ' + str(size) show_response += '\r\nContent-Type: text/html' show_response += conversation show_response += '\r\n' + last_modified(entity) show_response += '\r\n\r\n' encoded = show_response.encode() connectionsocket.send(encoded) connectionsocket.sendfile(f) elif isItFile: show_response += '\r\n\r\n' if conditional_get == False and method == 'GET': encoded = show_response.encode() connectionsocket.send(encoded) connectionsocket.sendfile(f) elif conditional_get == False and method == 'HEAD': encoded = show_response.encode() connectionsocket.send(encoded) elif conditional_get == True and (method == 'GET' or method == 'HEAD'): status_304(connectionsocket, entity, [ip, scode]) else: glob = status(connectionsocket, 400, [ip, client_thread, scode]) ip, client_thread, scode = glob return [ serversocket, file_extension, conditional_get, conn, ip, serverport, scode, IDENTITY ] def response_post(self, ent_body, connectionsocket, switcher, glob): ip, serverport, scode = glob show_response = '' entity = CSVFILE query = parse_qs(ent_body) if os.access(entity, os.W_OK): pass else: status(connectionsocket, 403, [ip, client_thread, scode]) fields = '' row = '' for d in query: fields += d + ', ' for i in query[d]: row += i + ', ' file_exists = os.path.exists(entity) if file_exists: fi = open(entity, "a") show_response += 'HTTP/1.1 200 OK' scode = 200 csvwriter = csv.writer(fi) csvwriter.writerow(row) else: fi = open(entity, "w") show_response += 'HTTP/1.1 201 Created' scode = 201 show_response += '\r\nLocation: ' + entity csvwriter = csv.writer(fi) csvwriter.writerow(fields) csvwriter.writerow(row) fi.close() show_response += '\r\nServer: ' + ip show_response += date() f = open(WORKFILE, "rb") show_response += '\r\nContent-Language: en-US,en' size = os.path.getsize(WORKFILE) conversation = 'Content-Length: ' + str(size) show_response += '\r\nContent-Type: text/html' show_response += '\r\n' + conversation show_response += '\r\n' + last_modified(entity) show_response += '\r\n\r\n' encoded = show_response.encode() connectionsocket.send(encoded) connectionsocket.sendfile(f) return [ip, serverport, scode] def response_put(self, connectionsocket, addr, ent_body, filedata, entity, switcher, f_flag, scode, glob): ip, client_thread, scode = glob try: length = int(switcher['Content-Length']) except: scode = 411 glob = status(connectionsocket, 411, [ip, client_thread, scode]) ip, client_thread, scode = glob show_response = '' try: filedata = filedata + ent_body except TypeError: ent_body = ent_body.encode() filedata = filedata + ent_body isItFile = os.path.isfile(entity) isItDir = os.path.isdir(entity) i = len(ent_body) size = length - i # r = length % SIZE # q = int(length // SIZE) # isItDir = os.path.isdir(entity) # isItFile = os.path.isdir(entity) for _ in iter(int, 1): if not size > 0: break ent_body = connectionsocket.recv(SIZE) try: filedata = filedata + ent_body except: ent_body = ent_body.encode() print("encoding...") filedata = filedata + ent_body size -= len(ent_body) mode_f, r_201, move_p = True, False, False limit = len(ROOT) l = len(entity) if not l < limit: if isItFile: if os.access(entity, os.W_OK): # no need for read access if os.access(entity, os.R_OK): pass else: pass else: glob = status(connectionsocket, 403, [ip, client_thread, scode]) ip, client_thread, scode = glob # writing File mode ON mode_f = True if f_flag == 1: f = open(entity, "wb") f.write(filedata) elif f_flag == 0: f = open(entity, "w") f.write(filedata.decode()) else: f = open(entity, "wb") f.write(filedata) f.close() elif isItDir: move_p = True loc = ROOT + '/' + str(addr[1]) if os.access(entity, os.W_OK): # no need for read access if os.access(entity, os.R_OK): pass else: pass else: glob = status(connectionsocket, 403, [ip, client_thread, scode]) ip, client_thread, scode = glob try: loc = loc + \ file_type[switcher['Content-Type'].split(';')[0]] except: glob = status(connectionsocket, 403, [ip, client_thread, scode]) ip, client_thread, scode = glob if f_flag == 1: f = open(loc, "wb") f.write(filedata) elif f_flag == 0: f = open(loc, "w") f.write(filedata.decode()) else: f = open(loc, "wb") f.write(filedata) f.close() else: if ROOT in entity: entity = ROOT + '/' + str(addr[1]) try: entity = entity + \ file_type[switcher['Content-Type'].split(';')[0]] except: # error in header glob = status(connectionsocket, 403, [ip, client_thread, scode]) ip, client_thread, scode = glob if f_flag: f = open(entity, "wb") f.write(filedata) elif f_flag == 0: # open the file in write mode f = open(entity, "w") f.write(filedata.decode()) else: # open the file in write binary mode f = open(entity, "wb") f.write(filedata) f.close() r_201 = True else: mode_f = False else: move_p = True loc = ROOT + '/' + str(addr[1]) try: loc = loc + file_type[switcher['Content-Type']] except: glob = status(connectionsocket, 403, [ip, client_thread, scode]) ip, client_thread, scode = glob if f_flag == 0: f = open(loc, "w") else: f = open(loc, "wb") f.write(filedata) f.close() if move_p: scode = 301 show_response += 'HTTP/1.1 301 Moved Permanently' show_response += '\r\nLocation: ' + loc elif mode_f: scode = 204 show_response += 'HTTP/1.1 204 No Content' show_response += '\r\n\Content-Location: ' + entity elif r_201: scode = 201 show_response += 'HTTP/1.1 201 Created' show_response += '\r\nContent-Location: ' + entity elif not mode_f: scode = 501 show_response += 'HTTP/1.1 501 Not Implemented' show_response += '\r\nConnection: keep-alive' show_response += '\r\n\r\n' encoded = show_response.encode() connectionsocket.send(encoded) connectionsocket.close() return None def response_delete(self, entity, connectionsocket, ent_body, switcher, glob): ip, serverport, scode, client_thread = glob isItDir = os.path.isdir(entity) isItFile = os.path.isfile(entity) # print(f"deleting {entity} ") # print(isItFile) option_list = entity.split('/') show_response = '' if 'Authorization' in switcher.keys(): conversation = switcher['Authorization'] # print("Auth process started:") if conversation: conversation = conversation.split(' ') conversation = base64.decodebytes( conversation[1].encode()).decode() conversation = conversation.split(':') else: scode = 401 show_response += 'HTTP/1.1 401 Unauthorized' show_response += '\r\nWWW-Authenticate: Basic' show_response += '\r\n\r\n' encoded = show_response.encode() connectionsocket.send(encoded) return [ip, serverport, scode] if conversation[0] == USERNAME: if conversation[1] == PASSWORD: pass else: scode = 401 show_response += 'HTTP/1.1 401 Unauthorized' show_response += '\r\nWWW-Authenticate: Basic' show_response += '\r\n\r\n' encoded = show_response.encode() connectionsocket.send(encoded) return [ip, serverport, scode] else: scode = 401 show_response += 'HTTP/1.1 401 Unauthorized' show_response += '\r\nWWW-Authenticate: Basic' show_response += '\r\n\r\n' encoded = show_response.encode() connectionsocket.send(encoded) return [ip, serverport, scode] else: scode = 401 show_response += 'HTTP/1.1 401 Unauthorized' show_response += '\r\nWWW-Authenticate: Basic' show_response += '\r\n\r\n' encoded = show_response.encode() connectionsocket.send(encoded) return [ip, serverport, scode] if len(ent_body) > 1 or 'delete' in option_list or isItDir: scode = 405 show_response += 'HTTP/1.1 405 Method Not Allowed' show_response += '\r\nAllow: GET, HEAD, POST, PUT' elif isItFile: scode = 200 show_response += 'HTTP/1.1 200 OK' try: if (os.access(entity, os.W_OK)): if (os.access(entity, os.R_OK)): pass else: glob = status(connectionsocket, 403, [ip, client_thread, scode]) ip, client_thread, scode = glob else: glob = status(connectionsocket, 403, [ip, client_thread, scode]) ip, client_thread, scode = glob shutil.move(entity, DELETE) except shutil.Error: os.remove(entity) else: scode = 400 show_response += 'HTTP/1.1 400 Bad Request' show_response += '\r\nServer: ' + ip show_response += '\r\nConnection: keep-alive' show_response += '\r\n' + date() show_response += '\r\n\r\n' encoded = show_response.encode() connectionsocket.send(encoded) return [ip, serverport, scode] m = http_methods() # function to check if the resource has been modified or not since the date in HTTP request def if_modify(state, entity): global conditional_get, month valid = False day = state.split(' ') if len(day) == 5: valid = True if valid: m = month[day[1]] date = int(day[2]) t = day[3].split(':') t[0], t[1], t[2] = int(t[0]), int(t[1]), int(t[2]) y = int(day[4]) ti = datetime.datetime(y, m, date, t[0], t[1], t[2]) hsec = int(time.mktime(ti.timetuple())) fsec = int(os.path.getmtime(entity)) if hsec == fsec: conditional_get = True elif hsec < fsec: conditional_get = False return conditional_get # function to return current date def date(): # Sun, 06 Nov 1994 08:49:37 GMT ; RFC 822, updated by RFC 1123 # Sunday, 06-Nov-94 08:49:37 GMT ; RFC 850, obsoleted by RFC 1036 # Sun Nov 6 08:49:37 1994 ; ANSI C's asctime() format now = datetime.datetime.now() datenow = now.strftime('%A,%d %B %Y %H:%M:%S ') datenow += "GMT" conversation = 'Date: ' + datenow return conversation # function to give response if server is busy def status(connectionsocket, code, glob): ip, client_thread, scode = glob scode = code show_response = '' if (code == '505') or (code == 505): show_response += 'HTTP/1.1 505 HTTP version not supported' elif (code == '415') or (code == 415): show_response += 'HTTP/1.1 415 Unsupported Media Type' elif (code == '403') or (code == 403): show_response += 'HTTP/1.1 403 Forbidden' elif (code == '404') or (code == 404): show_response += 'HTTP/1.1 404 Not Found' elif (code == '414') or (code == 414): show_response += 'HTTP/1.1 414 Request-URI Too Long' elif (code == '500') or (code == 500): show_response += 'HTTP/1.1 500 Internal Server Error' elif (code == '503') or (code == 503): show_response += 'HTTP/1.1 503 Server Unavailable' show_response += '\r\nServer: ' + ip show_response += '\r\n' + date() show_response += '\r\n\r\n' if code == 505: show_response += '\r\nSupported Version - HTTP/1.1 \n Rest Unsupported' encoded = show_response.encode() connectionsocket.send(encoded) logging.info(' {} {}\n'.format(connectionsocket, scode)) try: client_thread.remove(connectionsocket) connectionsocket.close() except: pass server([ serversocket, file_extension, conditional_get, conn, SIZE, client_thread, scode, ip, IDENTITY, serverport ]) return [ip, client_thread, scode] # function for conditional get implementation def status_304(connectionsocket, entity, glob): ip, scode = glob scode = 304 show_response = '' show_response += 'HTTP/1.1 304 Not Modified' show_response += '\r\n' + date() show_response += '\r\n' + last_modified(entity) show_response += '\r\nServer: ' + ip show_response += '\r\n\r\n' encoded = show_response.encode() connectionsocket.send(encoded) # function which operates between response and requests def bridgeFunction(connectionsocket, addr, start, glob): serversocket, file_extension, conditional_get, conn, SIZE, client_thread, scode, ip, IDENTITY, serverport = glob conditional_get = False urlflag = 0 f_flag = 0 filedata = b"" conn = True for _ in iter(int, 1): if not conn: # print("Connection not established") break if SIZE > 0: pass else: break try: message = connectionsocket.recv(SIZE) except OSError: message = connectionsocket.recv(SIZE) try: f_flag = 0 message = message.decode('utf-8') req_list = message.split('\r\n\r\n') # print(req_list) except UnicodeDecodeError: f_flag = 1 # if you're using non UTF-8 chars req_list = message.split(b'\r\n\r\n') req_list[0] = req_list[0].decode(errors='ignore') # print(req_list) if len(req_list) == 1: status(connectionsocket, 505, [ip, client_thread, scode]) print("\nBlank line expected at the end\n") break elif len(req_list) > 1: # every line ends with a \r\n so for only headers it'll create ['req', ''] pass else: status(connectionsocket, 505, [ip, client_thread, scode]) print("Error in headers\n") break try: LOG.write(((addr[0]) + '\n' + req_list[0] + '\n\n')) except: pass # show_response = '' # header_len = len(header_list) ent_body = req_list[1] header_list = req_list[0].split('\r\n') request_line = header_list[0].split(' ') if len(req_list) < 2: status(connectionsocket, 505, [ip, client_thread, scode]) else: pass entity = request_line[1] method = request_line[0] if entity == '/': entity = os.getcwd() elif (entity == favicon) or (entity == 'favicon') or (entity == 'favicon.ico'): entity = FAVICON entity, query = breakdown(entity) if (len(entity) > MAX_URL and urlflag == 0): status(connectionsocket, 414, [ip, client_thread, scode]) connectionsocket.close() break elif len(entity) <= MAX_URL: # print("working Fine") urlflag = 1 pass else: urlflag = 1 version = request_line[2] try: version_num = version.split('/')[1] if (version_num == RUNNING_VERSION): # print("using HTTP 1.1") pass elif not (version_num == RUNNING_VERSION): status(connectionsocket, 505, [ip, client_thread, scode]) except IndexError: # print("EXPECTED HTTP version number") status(connectionsocket, 505, [ip, client_thread, scode]) request_line = header_list.pop(0) switcher = {} i = 0 while i < len(header_list): line = header_list[i] line_list = line.split(': ') switcher[line_list[0]] = line_list[1] i += 1 if (method == 'HEAD') or (method == 'GET'): # connectionsocket, entity, switcher, query, method, glob glob = m.response_get_head( connectionsocket, entity, switcher, query, method, [ serversocket, file_extension, conditional_get, conn, ip, serverport, scode, IDENTITY, client_thread ]) serversocket, file_extension, conditional_get, conn, ip, serverport, scode, IDENTITY = glob elif method == 'POST': glob = m.response_post(ent_body, connectionsocket, switcher, [ip, serverport, scode]) ip, serverport, scode = glob elif method == 'DELETE': glob = m.response_delete(entity, connectionsocket, ent_body, switcher, [ip, serverport, scode, client_thread]) ip, serverport, scode = glob conn = False connectionsocket.close() elif method == 'PUT': m.response_put(connectionsocket, addr, ent_body, filedata, entity, switcher, f_flag, scode, [ip, client_thread, scode]) else: method = 'Not Defined' break # use the logging formatting logging.info(' {} {} {} {} {}\n'.format(addr[0], addr[1], request_line, entity, scode)) try: connectionsocket.close() client_thread.remove(connectionsocket) except: pass # function handling multiple requests def server(glob): serversocket, file_extension, conditional_get, conn, SIZE, client_thread, scode, ip, IDENTITY, serverport = glob for _ in iter(int, 1): # connectionsocket = request, addr = port,ip connectionsocket, addr = serversocket.accept() start = 0 client_thread.append(connectionsocket) # add connections if not (len(client_thread) < MAX_REQUEST): status(connectionsocket, 503, [ip, client_thread, scode]) connectionsocket.close() else: start_new_thread(bridgeFunction, (connectionsocket, addr, start, [ serversocket, file_extension, conditional_get, conn, SIZE, client_thread, scode, ip, IDENTITY, serverport ])) serversocket.close() ''' Function to handle the exit ( Ctrl+C and other signals ) ''' sig_rec = False def signal_handler(sig, frame): print('You pressed Ctrl+C!') print("q for quit\n r for restart") sys.exit(0) if __name__ == '__main__': ip = None # IP conn = True # to receive requests continuously in client's thread scode = 0 # Status code initialization IDENTITY = 0 # Cookie ID . This project Increments it by 1 conditional_get = False # check : is it conditional get method? month = MONTH # Dictionary to convert content types into the file extentions eg. text/html to .html file_type = FORMAT2 # Dictionary to convert file extentions into the content types eg. .html to text/html file_extension = FORMAT client_thread = [] # list to work with the threads serversocket = socket(AF_INET, SOCK_STREAM) s = socket(AF_INET, SOCK_DGRAM) logging.basicConfig(filename=LOG, level=logging.INFO, format='%(asctime)s:%(filename)s:%(message)s') # To run it on the localhost if you dont want google DNS ip = '127.0.0.1' # print(ip) try: serverport = int(sys.argv[1]) except: print( "Port Number missing\n\nTO RUN\nType: python3 httpserver.py port_number" ) sys.exit() try: serversocket.bind(('', serverport)) except: print('\nTO RUN:python3 httpserver.py port_number') sys.exit() serversocket.listen(5) print('HTTP server running on ip: ' + ip + ' port: ' + str(serverport) + '\nGo to this in the browser: (http://' + ip + ':' + str(serverport) + '/)') server([ serversocket, file_extension, conditional_get, conn, SIZE, client_thread, scode, ip, IDENTITY, serverport ]) # IMP calling the main server Function sys.exit()
17,844
957
<reponame>OneToolsCollection/tangramdotdev-tangram from pandas.api.types import CategoricalDtype from sklearn.metrics import mean_squared_error import argparse import numpy as np import pandas as pd import json parser = argparse.ArgumentParser() parser.add_argument('--library', choices=['h2o', 'lightgbm', 'sklearn', 'xgboost', 'catboost'], required=True) args = parser.parse_args() # Load the data. path_train = 'data/boston_train.csv' path_test = 'data/boston_test.csv' target_column_name = "medv" chas_options = ["0", "1"] dtype = { 'crim': np.float64, 'zn': np.float64, 'indus': np.float64, 'chas': CategoricalDtype(categories=chas_options), 'nox': np.float64, 'rm': np.float64, 'age': np.float64, 'dis': np.float64, 'rad': np.int64, 'tax': np.float64, 'ptratio': np.float64, 'b': np.float64, 'lstat': np.float64, } data_train = pd.read_csv(path_train, dtype=dtype) data_test = pd.read_csv(path_test, dtype=dtype) if args.library == 'xgboost' or args.library == 'sklearn' or args.library == 'catboost': categorical_columns = data_train.select_dtypes(['category']).columns data_train.loc[:, categorical_columns] = data_train.loc[:, categorical_columns].apply(lambda x: x.cat.codes) data_test.loc[:, categorical_columns] = data_test.loc[:, categorical_columns].apply(lambda x: x.cat.codes) labels_train = data_train.pop(target_column_name) features_train = data_train labels_test = data_test.pop(target_column_name) features_test = data_test # Train the model. if args.library == 'h2o': import h2o from h2o.estimators import H2OGradientBoostingEstimator h2o.init() data_train = pd.concat([features_train, labels_train], axis=1) data_test = pd.concat([features_test, labels_test], axis=1) data_train = h2o.H2OFrame(python_obj=data_train) data_test = h2o.H2OFrame(python_obj=data_test) feature_column_names = [column for column in data_train.columns if column != target_column_name] model = H2OGradientBoostingEstimator( distribution="gaussian", learn_rate=0.1, ntrees=100, ) model.train( training_frame=data_train, y=target_column_name, x=feature_column_names, ) elif args.library == 'lightgbm': import lightgbm as lgb model = lgb.LGBMRegressor( learning_rate=0.1, n_estimators=100, num_leaves=255, ) model.fit(features_train, labels_train) elif args.library == 'sklearn': from sklearn.experimental import enable_hist_gradient_boosting from sklearn.ensemble import HistGradientBoostingRegressor model = HistGradientBoostingRegressor( learning_rate=0.1, max_iter=100, max_leaf_nodes=255, validation_fraction=None, ) model.fit(features_train, labels_train) elif args.library == 'xgboost': import xgboost as xgb model = xgb.XGBRegressor( eta=0.1, eval_metric='logloss', grow_policy='lossguide', max_leaves=255, n_estimators=100, tree_method='hist', use_label_encoder=False, ) model.fit(features_train, labels_train) elif args.library == 'catboost': from catboost import CatBoostRegressor model = CatBoostRegressor( grow_policy='Lossguide', learning_rate=0.1, n_estimators=100, num_leaves=255, train_dir='data/catboost_info', verbose=False ) model.fit(features_train, labels_train, silent=True) # Make predictions on the test data. if args.library == 'h2o': predictions = model.predict(data_test).as_data_frame() else: predictions = model.predict(features_test) # Compute metrics. mse = mean_squared_error(predictions, labels_test) print(json.dumps({ 'mse': mse, }))
1,369
647
#ifndef HANDLE_HTTP_GET_HELLO #define HANDLE_HTTP_GET_HELLO #ifndef SWIG void handle_HTTP_GET_hello(struct mg_connection *nc, void *hm); #endif #endif
65
4,184
/** * Copyright (c) 2007-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 of Timothy Stack 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 REGENTS 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 REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef textfile_sub_source_hh #define textfile_sub_source_hh #include <deque> #include "logfile.hh" #include "textview_curses.hh" #include "filter_observer.hh" class textfile_sub_source : public text_sub_source, public vis_location_history { public: typedef std::deque<std::shared_ptr<logfile>>::iterator file_iterator; textfile_sub_source() { this->tss_supports_filtering = true; }; bool empty() const { return this->tss_files.empty(); } size_t size() const { return this->tss_files.size(); } size_t text_line_count(); size_t text_line_width(textview_curses &curses) { return this->tss_files.empty() ? 0 : this->current_file()->get_longest_line_length(); }; void text_value_for_line(textview_curses &tc, int line, std::string &value_out, line_flags_t flags); void text_attrs_for_line(textview_curses &tc, int row, string_attrs_t &value_out); size_t text_size_for_line(textview_curses &tc, int line, line_flags_t flags); std::shared_ptr<logfile> current_file() const { if (this->tss_files.empty()) { return nullptr; } return this->tss_files.front(); }; std::string text_source_name(const textview_curses &tv) { if (this->tss_files.empty()) { return ""; } return this->tss_files.front()->get_filename(); }; void to_front(const std::shared_ptr<logfile>& lf); void rotate_left(); void rotate_right(); void remove(const std::shared_ptr<logfile>& lf); void push_back(const std::shared_ptr<logfile>& lf); template<class T> bool rescan_files(T &callback, nonstd::optional<ui_clock::time_point> deadline = nonstd::nullopt) { file_iterator iter; bool retval = false; if (this->tss_view->is_paused()) { return retval; } std::vector<std::shared_ptr<logfile>> closed_files; for (iter = this->tss_files.begin(); iter != this->tss_files.end();) { std::shared_ptr<logfile> lf = (*iter); if (lf->is_closed()) { iter = this->tss_files.erase(iter); this->detach_observer(lf); closed_files.template emplace_back(lf); continue; } try { uint32_t old_size = lf->size(); logfile::rebuild_result_t new_text_data = lf->rebuild_index(deadline); if (lf->get_format() != nullptr) { iter = this->tss_files.erase(iter); this->detach_observer(lf); callback.promote_file(lf); continue; } switch (new_text_data) { case logfile::rebuild_result_t::NEW_LINES: case logfile::rebuild_result_t::NEW_ORDER: retval = true; break; default: break; } callback.scanned_file(lf); uint32_t filter_in_mask, filter_out_mask; this->get_filters().get_enabled_mask(filter_in_mask, filter_out_mask); auto *lfo = (line_filter_observer *) lf->get_logline_observer(); for (uint32_t lpc = old_size; lpc < lf->size(); lpc++) { if (this->tss_apply_filters && lfo->excluded(filter_in_mask, filter_out_mask, lpc)) { continue; } lfo->lfo_filter_state.tfs_index.push_back(lpc); } } catch (const line_buffer::error &e) { iter = this->tss_files.erase(iter); lf->close(); this->detach_observer(lf); closed_files.template emplace_back(lf); continue; } ++iter; } if (!closed_files.empty()) { callback.closed_files(closed_files); } if (retval) { this->tss_view->search_new_data(); } return retval; }; void text_filters_changed(); int get_filtered_count() const; int get_filtered_count_for(size_t filter_index) const; text_format_t get_text_format() const; nonstd::optional<location_history *> get_location_history() { return this; } private: void detach_observer(std::shared_ptr<logfile> lf) { auto *lfo = (line_filter_observer *) lf->get_logline_observer(); lf->set_logline_observer(nullptr); delete lfo; }; std::deque<std::shared_ptr<logfile>> tss_files; std::deque<std::shared_ptr<logfile>> tss_hidden_files; }; #endif
2,976
5,903
<reponame>zhouguangping/pentaho-kettle<gh_stars>1000+ /* * This file is part of PaloKettlePlugin. * * PaloKettlePlugin is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * PaloKettlePlugin is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with PaloKettlePlugin. If not, see <http://www.gnu.org/licenses/>. * * Portions Copyright 2008 Stratebi Business Solutions, S.L. * Portions Copyright 2011 De Bortoli Wines Pty Limited (Australia) * Portions Copyright 2011 - 2017 <NAME> */ package org.pentaho.di.ui.trans.steps.palo.diminput; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.CCombo; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.ShellAdapter; import org.eclipse.swt.events.ShellEvent; import org.eclipse.swt.layout.FormAttachment; import org.eclipse.swt.layout.FormData; import org.eclipse.swt.layout.FormLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Combo; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Text; import org.pentaho.di.core.Const; import org.pentaho.di.core.database.DatabaseMeta; import org.pentaho.di.core.exception.KettleException; import org.pentaho.di.i18n.BaseMessages; import org.pentaho.di.palo.core.PaloDimensionLevel; import org.pentaho.di.palo.core.PaloNameComparator; import org.pentaho.di.trans.Trans; import org.pentaho.di.trans.TransMeta; import org.pentaho.di.trans.TransPreviewFactory; import org.pentaho.di.trans.step.BaseStepMeta; import org.pentaho.di.trans.step.StepDialogInterface; import org.pentaho.di.trans.steps.palo.diminput.PaloDimInputData; import org.pentaho.di.trans.steps.palo.diminput.PaloDimInputMeta; import org.pentaho.di.ui.core.dialog.EnterNumberDialog; import org.pentaho.di.ui.core.dialog.EnterTextDialog; import org.pentaho.di.ui.core.dialog.ErrorDialog; import org.pentaho.di.ui.core.dialog.PreviewRowsDialog; import org.pentaho.di.ui.core.widget.ColumnInfo; import org.pentaho.di.ui.core.widget.TableView; import org.pentaho.di.ui.trans.dialog.TransPreviewProgressDialog; import org.pentaho.di.ui.trans.step.BaseStepDialog; import org.pentaho.di.ui.trans.steps.palo.cellinput.PaloCellInputDialog; public class PaloDimInputDialog extends BaseStepDialog implements StepDialogInterface { private static Class<?> PKG = PaloDimInputMeta.class; // for i18n // purposes, // needed by // Translator2!! private final PaloDimInputMeta meta; private TableView tableViewFields; private Combo comboDimension; private Text textStepName; private Button buttonClearLevels; private Button buttonGetLevels; private Label labelStepName; private Label labelDimension; private Button buttonOk; private Button buttonCancel; private Button buttonPreview; private CCombo addConnectionLine; private Label labelBaseElementsOnly; private Button buttonBaseElementsOnly; public PaloDimInputDialog( Shell parent, Object in, TransMeta transMeta, String sname ) { super( parent, (BaseStepMeta) in, transMeta, sname ); this.meta = (PaloDimInputMeta) in; } public String open() { final Display display = getParent().getDisplay(); shell = new Shell( getParent(), SWT.DIALOG_TRIM | SWT.RESIZE | SWT.MAX | SWT.MIN ); props.setLook( shell ); setShellImage( shell, meta ); FormLayout formLayout = new FormLayout(); formLayout.marginWidth = Const.FORM_MARGIN; formLayout.marginHeight = Const.FORM_MARGIN; shell.setLayout( formLayout ); int middle = props.getMiddlePct(); int margin = Const.MARGIN; FormData fd; labelStepName = new Label( shell, SWT.RIGHT ); fd = new FormData(); fd.left = new FormAttachment( 0, 0 ); fd.right = new FormAttachment( middle, -margin ); fd.top = new FormAttachment( 0, margin ); labelStepName.setLayoutData( fd ); textStepName = new Text( shell, SWT.BORDER ); fd = new FormData(); fd.left = new FormAttachment( middle, 0 ); fd.right = new FormAttachment( 100, 0 ); fd.top = new FormAttachment( 0, margin ); textStepName.setLayoutData( fd ); addConnectionLine = addConnectionLine( shell, textStepName, Const.MIDDLE_PCT, margin ); labelDimension = new Label( shell, SWT.RIGHT ); fd = new FormData(); fd.left = new FormAttachment( 0, 0 ); fd.right = new FormAttachment( middle, -margin ); fd.top = new FormAttachment( addConnectionLine, margin ); labelDimension.setLayoutData( fd ); comboDimension = new Combo( shell, SWT.READ_ONLY ); fd = new FormData(); fd.left = new FormAttachment( middle, 0 ); fd.right = new FormAttachment( 100, 0 ); fd.top = new FormAttachment( addConnectionLine, margin ); comboDimension.setLayoutData( fd ); labelBaseElementsOnly = new Label( shell, SWT.RIGHT ); fd = new FormData(); fd.left = new FormAttachment( 0, 0 ); fd.right = new FormAttachment( middle, -margin ); fd.top = new FormAttachment( comboDimension, margin ); labelBaseElementsOnly.setLayoutData( fd ); buttonBaseElementsOnly = new Button( shell, SWT.CHECK ); fd = new FormData(); fd.left = new FormAttachment( middle, 0 ); fd.right = new FormAttachment( 100, 0 ); fd.top = new FormAttachment( comboDimension, margin ); buttonBaseElementsOnly.setLayoutData( fd ); ModifyListener lsMod = new ModifyListener() { public void modifyText( ModifyEvent e ) { meta.setChanged(); } }; ColumnInfo[] colinf = new ColumnInfo[]{ new ColumnInfo( getLocalizedColumn( 0 ), ColumnInfo.COLUMN_TYPE_TEXT, false, true ), new ColumnInfo( getLocalizedColumn( 1 ), ColumnInfo.COLUMN_TYPE_TEXT, false, true ), new ColumnInfo( getLocalizedColumn( 2 ), ColumnInfo.COLUMN_TYPE_TEXT, false, false ), new ColumnInfo( getLocalizedColumn( 3 ), ColumnInfo.COLUMN_TYPE_CCOMBO, new String[]{ "String", "Number" }, true ) }; tableViewFields = new TableView( null, shell, SWT.FILL | SWT.BORDER, colinf, 10, true, lsMod, props ); tableViewFields.setSize( 477, 280 ); tableViewFields.setBounds( 5, 125, 477, 280 ); tableViewFields.setReadonly( true ); tableViewFields.setSortable( false ); fd = new FormData(); fd.left = new FormAttachment( 0, margin ); fd.top = new FormAttachment( buttonBaseElementsOnly, 3 * margin ); fd.right = new FormAttachment( 100, -150 ); fd.bottom = new FormAttachment( 100, -50 ); tableViewFields.setLayoutData( fd ); buttonGetLevels = new Button( shell, SWT.NONE ); fd = new FormData(); fd.left = new FormAttachment( tableViewFields, margin ); fd.top = new FormAttachment( buttonBaseElementsOnly, 3 * margin ); fd.right = new FormAttachment( 100, 0 ); buttonGetLevels.setLayoutData( fd ); buttonClearLevels = new Button( shell, SWT.NONE ); fd = new FormData(); fd.left = new FormAttachment( tableViewFields, margin ); fd.top = new FormAttachment( buttonGetLevels, margin ); fd.right = new FormAttachment( 100, 0 ); buttonClearLevels.setLayoutData( fd ); buttonOk = new Button( shell, SWT.CENTER ); buttonCancel = new Button( shell, SWT.CENTER ); buttonPreview = new Button( shell, SWT.CENTER ); buttonOk.setText( BaseMessages.getString( "System.Button.OK" ) ); buttonPreview.setText( BaseMessages.getString( "System.Button.Preview" ) ); buttonCancel.setText( BaseMessages.getString( "System.Button.Cancel" ) ); setButtonPositions( new Button[]{ buttonOk, buttonPreview, buttonCancel }, margin, null ); buttonCancel.addSelectionListener( new SelectionAdapter() { public void widgetSelected( SelectionEvent e ) { cancel(); } } ); buttonPreview.addSelectionListener( new SelectionAdapter() { public void widgetSelected( SelectionEvent e ) { preview(); } } ); buttonOk.addSelectionListener( new SelectionAdapter() { public void widgetSelected( SelectionEvent e ) { ok(); } } ); buttonClearLevels.addSelectionListener( new SelectionAdapter() { public void widgetSelected( SelectionEvent e ) { doClearLevels(); } } ); buttonGetLevels.addSelectionListener( new SelectionAdapter() { public void widgetSelected( SelectionEvent e ) { doGetLevels(); } } ); comboDimension.addSelectionListener( new SelectionAdapter() { public void widgetSelected( SelectionEvent e ) { doSelectDimension(); } } ); addConnectionLine.addSelectionListener( new SelectionAdapter() { public void widgetSelected( SelectionEvent e ) { doSelectConnection( false ); } } ); this.fillLocalizationData(); this.fillStoredData(); this.doSelectConnection( false ); props.setLook( tableViewFields ); props.setLook( comboDimension ); props.setLook( textStepName ); props.setLook( buttonClearLevels ); props.setLook( buttonGetLevels ); props.setLook( labelStepName ); props.setLook( labelDimension ); props.setLook( buttonOk ); props.setLook( buttonCancel ); props.setLook( buttonPreview ); props.setLook( addConnectionLine ); props.setLook( labelBaseElementsOnly ); props.setLook( buttonBaseElementsOnly ); shell.addShellListener( new ShellAdapter() { public void shellClosed( ShellEvent e ) { cancel(); } } ); meta.setChanged( changed ); setSize(); shell.open(); PaloCellInputDialog.showPaloLibWarningDialog( shell ); while ( !shell.isDisposed() ) { if ( !display.readAndDispatch() ) { display.sleep(); } } return stepname; } private String getLocalizedColumn( int columnIndex ) { switch ( columnIndex ) { case 0: return BaseMessages.getString( PKG, "PaloDimInputDialog.ColumnLevelName" ); case 1: return BaseMessages.getString( PKG, "PaloDimInputDialog.ColumnLevelNumber" ); case 2: return BaseMessages.getString( PKG, "PaloDimInputDialog.ColumnField" ); case 3: return BaseMessages.getString( PKG, "PaloDimInputDialog.ColumnType" ); default: return ""; } } private void fillLocalizationData() { labelDimension.setText( BaseMessages.getString( PKG, "PaloDimInputDialog.SelectDimension" ) ); labelStepName.setText( BaseMessages.getString( PKG, "PaloDimInputDialog.StepName" ) ); shell.setText( BaseMessages.getString( PKG, "PaloDimInputDialog.PaloDimInput" ) ); buttonGetLevels.setText( BaseMessages.getString( PKG, "PaloDimInputDialog.GetLevels" ) ); buttonClearLevels.setText( BaseMessages.getString( PKG, "PaloDimInputDialog.ClearLevels" ) ); labelBaseElementsOnly.setText( BaseMessages.getString( PKG, "PaloDimInputDialog.BaseElementsOnly" ) ); } private void fillStoredData() { if ( stepname != null ) { textStepName.setText( stepname ); } int index = addConnectionLine.indexOf( meta.getDatabaseMeta() != null ? meta.getDatabaseMeta().getName() : "" ); if ( index >= 0 ) { addConnectionLine.select( index ); } if ( meta.getDimension() != null ) { comboDimension.add( meta.getDimension() ); comboDimension.select( 0 ); } buttonBaseElementsOnly.setSelection( meta.getBaseElementsOnly() ); tableViewFields.table.removeAll(); if ( meta.getLevels().size() > 0 ) { for ( PaloDimensionLevel level : meta.getLevels() ) { tableViewFields.add( level.getLevelName(), String.valueOf( level.getLevelNumber() ), level.getFieldName(), level.getFieldType() ); } tableViewFields.setRowNums(); tableViewFields.optWidth( true ); } } private void doSelectConnection( boolean clearCurrentData ) { try { if ( clearCurrentData ) { tableViewFields.table.removeAll(); comboDimension.removeAll(); } if ( addConnectionLine.getText() != null ) { DatabaseMeta dbMeta = transMeta.findDatabase( addConnectionLine.getText() ); if ( dbMeta != null ) { PaloDimInputData data = new PaloDimInputData( dbMeta ); data.helper.connect(); List<String> dimensions = data.helper.getDimensionsNames(); Collections.sort( dimensions, new PaloNameComparator() ); for ( String dimensionName : dimensions ) { if ( comboDimension.indexOf( dimensionName ) == -1 ) { comboDimension.add( dimensionName ); } } data.helper.disconnect(); } } } catch ( Exception ex ) { new ErrorDialog( shell, BaseMessages.getString( PKG, "PaloDimInputDialog.RetreiveDimensionsErrorTitle" ), BaseMessages.getString( PKG, "PaloDimInputDialog.RetreiveDimensionsError" ), ex ); } } private void doSelectDimension() { // tableViewFields.table.removeAll(); } private void doClearLevels() { tableViewFields.table.removeAll(); } private void doGetLevels() { if ( buttonBaseElementsOnly.getSelection() ) { tableViewFields.table.removeAll(); tableViewFields.add( BaseMessages.getString( PKG, "PaloDimInputDialog.BaseElementName" ), "0", comboDimension .getText(), "String" ); } else if ( comboDimension.getText() != null && comboDimension.getText() != "" ) { try { if ( addConnectionLine.getText() != null ) { DatabaseMeta dbMeta = transMeta.findDatabase( addConnectionLine.getText() ); if ( dbMeta != null ) { PaloDimInputData data = new PaloDimInputData( dbMeta ); tableViewFields.table.removeAll(); data.helper.connect(); List<PaloDimensionLevel> levels = data.helper.getDimensionLevels( comboDimension.getText() ); for ( int i = 0; i < levels.size(); i++ ) { PaloDimensionLevel level = levels.get( i ); tableViewFields .add( level.getLevelName(), String.valueOf( level.getLevelNumber() ), level.getFieldName() ); } tableViewFields.setRowNums(); tableViewFields.optWidth( true ); data.helper.disconnect(); } } } catch ( Exception ex ) { new ErrorDialog( shell, BaseMessages.getString( "System.Dialog.GetFieldsFailed.Title" ), BaseMessages .getString( "System.Dialog.GetFieldsFailed.Message" ), ex ); } } else { new ErrorDialog( shell, BaseMessages.getString( "System.Dialog.GetFieldsFailed.Title" ), BaseMessages .getString( "System.Dialog.GetFieldsFailed.Message" ), new Exception( BaseMessages.getString( PKG, "PaloDimInputDialog.SelectDimensionFirstError" ) ) ); } } private void cancel() { stepname = null; meta.setChanged( changed ); dispose(); } private void ok() { try { getInfo( this.meta ); dispose(); } catch ( KettleException e ) { new ErrorDialog( shell, BaseMessages.getString( PKG, "PaloDimInputDialog.FailedToSaveDataErrorTitle" ), BaseMessages.getString( PKG, "PaloDimInputDialog.FailedToSaveDataError" ), e ); } } private void getInfo( PaloDimInputMeta myMeta ) throws KettleException { stepname = textStepName.getText(); List<PaloDimensionLevel> levels = new ArrayList<PaloDimensionLevel>(); for ( int i = 0; i < tableViewFields.table.getItemCount(); i++ ) { PaloDimensionLevel level = new PaloDimensionLevel( tableViewFields.table.getItem( i ).getText( 1 ), Integer .parseInt( tableViewFields.table.getItem( i ).getText( 2 ) ), tableViewFields.table.getItem( i ).getText( 3 ), tableViewFields.table.getItem( i ).getText( 4 ) ); levels.add( level ); } myMeta.setDatabaseMeta( transMeta.findDatabase( addConnectionLine.getText() ) ); myMeta.setLevels( levels ); myMeta.setDimension( comboDimension.getText() ); myMeta.setBaseElementsOnly( buttonBaseElementsOnly.getSelection() ); myMeta.setChanged( true ); } private void preview() { PaloDimInputMeta oneMeta = new PaloDimInputMeta(); try { getInfo( oneMeta ); } catch ( KettleException e ) { new ErrorDialog( shell, BaseMessages.getString( PKG, "PaloInputDialog.Illegal.Dialog.Settings.Title" ), BaseMessages.getString( PKG, "PaloInputDialog.Illegal.Dialog.Settings.Message" ), e ); return; } TransMeta previewMeta = TransPreviewFactory.generatePreviewTransformation( transMeta, oneMeta, textStepName.getText() ); EnterNumberDialog numberDialog = new EnterNumberDialog( shell, 500, BaseMessages.getString( "System.Dialog.EnterPreviewSize.Title" ), BaseMessages.getString( "System.Dialog.EnterPreviewSize.Message" ) ); int previewSize = numberDialog.open(); if ( previewSize > 0 ) { TransPreviewProgressDialog progressDialog = new TransPreviewProgressDialog( shell, previewMeta, new String[]{ textStepName.getText() }, new int[]{ previewSize } ); progressDialog.open(); Trans trans = progressDialog.getTrans(); String loggingText = progressDialog.getLoggingText(); if ( !progressDialog.isCancelled() ) { if ( trans.getResult() != null && trans.getResult().getNrErrors() > 0 ) { EnterTextDialog etd = new EnterTextDialog( shell, BaseMessages.getString( "System.Dialog.PreviewError.Title" ), BaseMessages .getString( "System.Dialog.PreviewError.Message" ), loggingText, true ); etd.setReadOnly(); etd.open(); } } PreviewRowsDialog prd = new PreviewRowsDialog( shell, transMeta, SWT.NONE, textStepName.getText(), progressDialog .getPreviewRowsMeta( textStepName.getText() ), progressDialog.getPreviewRows( textStepName.getText() ), loggingText ); prd.open(); } } }
6,891
6,851
<filename>tests/requests/valid/099.py<gh_stars>1000+ request = { "method": "POST", "uri": uri("/test-form"), "version": (1, 1), "headers": [ ("HOST", "0.0.0.0:5000"), ("USER-AGENT", "Mozilla/5.0 (Windows NT 6.2; WOW64; rv:25.0) Gecko/20100101 Firefox/25.0"), ("ACCEPT", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"), ("ACCEPT-LANGUAGE", "en-us,en;q=0.7,el;q=0.3"), ("ACCEPT-ENCODING", "gzip, deflate"), ("COOKIE", "csrftoken=<PASSWORD> <KEY> <PASSWORD>XXX; sessionid=YYYYYYYYYYYYYYYYYYYYYYYYYYYY"), ("CONNECTION", "keep-alive"), ("CONTENT-TYPE", "multipart/form-data; boundary=---------------------------320761477111544"), ("CONTENT-LENGTH", "17914"), ], "body": b"""-----------------------------320761477111544 Content-Disposition: form-data; name="csrfmiddlewaretoken" XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX -----------------------------320761477111544 Content-Disposition: form-data; name="_save" Save -----------------------------320761477111544 Content-Disposition: form-data; name="name" test.example.org -----------------------------320761477111544 Content-Disposition: form-data; name="type" NATIVE -----------------------------320761477111544 Content-Disposition: form-data; name="master" -----------------------------320761477111544 Content-Disposition: form-data; name="foobar_manager_dynamiczone_domain-TOTAL_FORMS" 1 -----------------------------320761477111544 Content-Disposition: form-data; name="foobar_manager_dynamiczone_domain-INITIAL_FORMS" 1 -----------------------------320761477111544 Content-Disposition: form-data; name="foobar_manager_dynamiczone_domain-MAX_NUM_FORMS" 1 -----------------------------320761477111544 Content-Disposition: form-data; name="foobar_manager_dynamiczone_domain-0-is_dynamic" on -----------------------------320761477111544 Content-Disposition: form-data; name="foobar_manager_dynamiczone_domain-0-id" 1 -----------------------------320761477111544 Content-Disposition: form-data; name="foobar_manager_dynamiczone_domain-0-domain" 2 -----------------------------320761477111544 Content-Disposition: form-data; name="foobar_manager_dynamiczone_domain-__prefix__-id" -----------------------------320761477111544 Content-Disposition: form-data; name="foobar_manager_dynamiczone_domain-__prefix__-domain" 2 -----------------------------320761477111544 Content-Disposition: form-data; name="foobar_manager_record_domain-TOTAL_FORMS" 1 -----------------------------320761477111544 Content-Disposition: form-data; name="foobar_manager_record_domain-INITIAL_FORMS" 1 -----------------------------320761477111544 Content-Disposition: form-data; name="foobar_manager_record_domain-MAX_NUM_FORMS" 1 -----------------------------320761477111544 Content-Disposition: form-data; name="foobar_manager_record_domain-0-ttl" 3600 -----------------------------320761477111544 Content-Disposition: form-data; name="foobar_manager_record_domain-0-primary" ns.example.org -----------------------------320761477111544 Content-Disposition: form-data; name="foobar_manager_record_domain-0-hostmaster" hostmaster.test.example.org -----------------------------320761477111544 Content-Disposition: form-data; name="foobar_manager_record_domain-0-serial" 2013121701 -----------------------------320761477111544 Content-Disposition: form-data; name="foobar_manager_record_domain-0-refresh" 10800 -----------------------------320761477111544 Content-Disposition: form-data; name="foobar_manager_record_domain-0-retry" 3600 -----------------------------320761477111544 Content-Disposition: form-data; name="foobar_manager_record_domain-0-expire" 604800 -----------------------------320761477111544 Content-Disposition: form-data; name="foobar_manager_record_domain-0-default_ttl" 3600 -----------------------------320761477111544 Content-Disposition: form-data; name="foobar_manager_record_domain-0-id" 16 -----------------------------320761477111544 Content-Disposition: form-data; name="foobar_manager_record_domain-0-domain" 2 -----------------------------320761477111544 Content-Disposition: form-data; name="foobar_manager_record_domain-__prefix__-ttl" -----------------------------320761477111544 Content-Disposition: form-data; name="foobar_manager_record_domain-__prefix__-primary" -----------------------------320761477111544 Content-Disposition: form-data; name="foobar_manager_record_domain-__prefix__-hostmaster" -----------------------------320761477111544 Content-Disposition: form-data; name="foobar_manager_record_domain-__prefix__-serial" 1 -----------------------------320761477111544 Content-Disposition: form-data; name="foobar_manager_record_domain-__prefix__-refresh" 10800 -----------------------------320761477111544 Content-Disposition: form-data; name="foobar_manager_record_domain-__prefix__-retry" 3600 -----------------------------320761477111544 Content-Disposition: form-data; name="foobar_manager_record_domain-__prefix__-expire" 604800 -----------------------------320761477111544 Content-Disposition: form-data; name="foobar_manager_record_domain-__prefix__-default_ttl" 3600 -----------------------------320761477111544 Content-Disposition: form-data; name="foobar_manager_record_domain-__prefix__-id" -----------------------------320761477111544 Content-Disposition: form-data; name="foobar_manager_record_domain-__prefix__-domain" 2 -----------------------------320761477111544 Content-Disposition: form-data; name="foobar_manager_record_domain-2-TOTAL_FORMS" 0 -----------------------------320761477111544 Content-Disposition: form-data; name="foobar_manager_record_domain-2-INITIAL_FORMS" 0 -----------------------------320761477111544 Content-Disposition: form-data; name="foobar_manager_record_domain-2-MAX_NUM_FORMS" 1000 -----------------------------320761477111544 Content-Disposition: form-data; name="foobar_manager_record_domain-2-__prefix__-id" -----------------------------320761477111544 Content-Disposition: form-data; name="foobar_manager_record_domain-2-__prefix__-domain" 2 -----------------------------320761477111544 Content-Disposition: form-data; name="foobar_manager_record_domain-2-__prefix__-name" -----------------------------320761477111544 Content-Disposition: form-data; name="foobar_manager_record_domain-2-__prefix__-ttl" -----------------------------320761477111544 Content-Disposition: form-data; name="foobar_manager_record_domain-2-__prefix__-content" -----------------------------320761477111544 Content-Disposition: form-data; name="foobar_manager_record_domain-3-TOTAL_FORMS" 0 -----------------------------320761477111544 Content-Disposition: form-data; name="foobar_manager_record_domain-3-INITIAL_FORMS" 0 -----------------------------320761477111544 Content-Disposition: form-data; name="foobar_manager_record_domain-3-MAX_NUM_FORMS" 1000 -----------------------------320761477111544 Content-Disposition: form-data; name="foobar_manager_record_domain-3-__prefix__-id" -----------------------------320761477111544 Content-Disposition: form-data; name="foobar_manager_record_domain-3-__prefix__-domain" 2 -----------------------------320761477111544 Content-Disposition: form-data; name="foobar_manager_record_domain-3-__prefix__-name" -----------------------------320761477111544 Content-Disposition: form-data; name="foobar_manager_record_domain-3-__prefix__-ttl" -----------------------------320761477111544 Content-Disposition: form-data; name="foobar_manager_record_domain-3-__prefix__-prio" -----------------------------320761477111544 Content-Disposition: form-data; name="foobar_manager_record_domain-3-__prefix__-content" -----------------------------320761477111544 Content-Disposition: form-data; name="foobar_manager_record_domain-4-TOTAL_FORMS" 0 -----------------------------320761477111544 Content-Disposition: form-data; name="foobar_manager_record_domain-4-INITIAL_FORMS" 0 --------------------- -----------------------------320761477111544 Content-Disposition: form-data; name="foobar_manager_record_domain-5-TOTAL_FORMS" 0 -----------------------------320761477111544 Content-Disposition: form-data; name="foobar_manager_record_domain-5-INITIAL_FORMS" 0 --------------------- -----------------------------320761477111544 Content-Disposition: form-data; name="foobar_manager_record_domain-6-TOTAL_FORMS" 0 -----------------------------320761477111544 Content-Disposition: form-data; name="foobar_manager_record_domain-6-INITIAL_FORMS" 0 --------------------- -----------------------------320761477111544 Content-Disposition: form-data; name="foobar_manager_record_domain-7-TOTAL_FORMS" 0 -----------------------------320761477111544 Content-Disposition: form-data; name="foobar_manager_record_domain-7-INITIAL_FORMS" 0 --------------------- -----------------------------320761477111544 Content-Disposition: form-data; name="foobar_manager_record_domain-8-TOTAL_FORMS" 0 -----------------------------320761477111544 Content-Disposition: form-data; name="foobar_manager_record_domain-8-INITIAL_FORMS" 0 --------------------- """.decode('utf-8').replace('\n', '\r\n').encode('utf-8'), }
2,979
14,425
<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.security; import static org.apache.hadoop.security.UGIExceptionMessages.*; import java.io.IOException; import org.apache.hadoop.classification.InterfaceAudience; import org.apache.hadoop.classification.InterfaceStability; /** * Thrown when {@link UserGroupInformation} failed with an unrecoverable error, * such as failure in kerberos login/logout, invalid subject etc. * * Caller should not retry when catching this exception. */ @InterfaceAudience.Public @InterfaceStability.Unstable public class KerberosAuthException extends IOException { static final long serialVersionUID = 31L; private String user; private String principal; private String keytabFile; private String ticketCacheFile; private String initialMessage; public KerberosAuthException(String msg) { super(msg); } public KerberosAuthException(Throwable cause) { super(cause); } public KerberosAuthException(String initialMsg, Throwable cause) { this(cause); initialMessage = initialMsg; } public void setUser(final String u) { user = u; } public void setPrincipal(final String p) { principal = p; } public void setKeytabFile(final String k) { keytabFile = k; } public void setTicketCacheFile(final String t) { ticketCacheFile = t; } /** @return The initial message, or null if not set. */ public String getInitialMessage() { return initialMessage; } /** @return The keytab file path, or null if not set. */ public String getKeytabFile() { return keytabFile; } /** @return The principal, or null if not set. */ public String getPrincipal() { return principal; } /** @return The ticket cache file path, or null if not set. */ public String getTicketCacheFile() { return ticketCacheFile; } /** @return The user, or null if not set. */ public String getUser() { return user; } @Override public String getMessage() { final StringBuilder sb = new StringBuilder(); if (initialMessage != null) { sb.append(initialMessage); } if (user != null) { sb.append(FOR_USER + user); } if (principal != null) { sb.append(FOR_PRINCIPAL + principal); } if (keytabFile != null) { sb.append(FROM_KEYTAB + keytabFile); } if (ticketCacheFile != null) { sb.append(USING_TICKET_CACHE_FILE+ ticketCacheFile); } sb.append(" " + super.getMessage()); return sb.toString(); } }
1,030
573
/* * This software is licensed under the terms of the MIT License. * See COPYING for further information. * --- * Copyright (c) 2011-2019, <NAME> <<EMAIL>>. * Copyright (c) 2012-2019, <NAME> <<EMAIL>>. */ #include "taisei.h" #include "fileformats.h" #include "util.h" #include "util/pngcruft.h" static const uint8_t png_magic[] = { 0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A }; static bool px_png_probe(SDL_RWops *stream) { uint8_t magic[sizeof(png_magic)] = { 0 }; SDL_RWread(stream, magic, sizeof(magic), 1); return !memcmp(magic, png_magic, sizeof(magic)); } static inline PixmapLayout clrtype_to_layout(png_byte color_type) { switch(color_type) { case PNG_COLOR_TYPE_RGB: return PIXMAP_LAYOUT_RGB; case PNG_COLOR_TYPE_RGB_ALPHA: return PIXMAP_LAYOUT_RGBA; case PNG_COLOR_TYPE_GRAY: return PIXMAP_LAYOUT_R; } UNREACHABLE; } static bool px_png_load(SDL_RWops *stream, Pixmap *pixmap, PixmapFormat preferred_format) { png_structp png = NULL; png_infop png_info = NULL; const char *volatile error = NULL; pixmap->data.untyped = NULL; if(!(png = pngutil_create_read_struct())) { error = "png_create_read_struct() failed"; goto done; } if(!(png_info = png_create_info_struct(png))) { error = "png_create_info_struct() failed"; goto done; } if(setjmp(png_jmpbuf(png))) { error = "PNG error"; goto done; } pngutil_init_rwops_read(png, stream); png_read_info(png, png_info); png_byte color_type = png_get_color_type(png, png_info); png_set_alpha_mode(png, PNG_ALPHA_PNG, PNG_DEFAULT_sRGB); /* * Expand palette into RGB * Expand grayscale to full 8 bits * Expand transparency to full RGBA */ png_set_expand(png); // avoid unnecessary back-and-forth conversion bool keep_gray = ( color_type == PNG_COLOR_TYPE_GRAY && PIXMAP_FORMAT_LAYOUT(preferred_format) == PIXMAP_LAYOUT_R ); if(!keep_gray) { png_set_gray_to_rgb(png); } if(PIXMAP_FORMAT_DEPTH(preferred_format) == 16) { png_set_expand_16(png); } #if SDL_BYTEORDER == SDL_LIL_ENDIAN png_set_swap(png); #endif int num_passes = png_set_interlace_handling(png); png_read_update_info(png, png_info); attr_unused png_byte channels = png_get_channels(png, png_info); color_type = png_get_color_type(png, png_info); png_byte bit_depth = png_get_bit_depth(png, png_info); assert( (color_type == PNG_COLOR_TYPE_RGB && channels == 3) || (color_type == PNG_COLOR_TYPE_RGB_ALPHA && channels == 4) || (color_type == PNG_COLOR_TYPE_GRAY && channels == 1) ); assert(bit_depth == 8 || bit_depth == 16); pixmap->width = png_get_image_width(png, png_info); pixmap->height = png_get_image_height(png, png_info); pixmap->format = PIXMAP_MAKE_FORMAT( clrtype_to_layout(color_type), bit_depth ); // NOTE: We read the image upside down here to avoid needing to flip it for // the GL backend. This is just a slight optimization, not a hard dependency. pixmap->origin = PIXMAP_ORIGIN_BOTTOMLEFT; size_t pixel_size = pixmap_format_pixel_size(pixmap->format); if(pixmap->height > PIXMAP_BUFFER_MAX_SIZE / (pixmap->width * pixel_size)) { error = "The image is too large"; goto done; } png_bytep buffer = pixmap->data.untyped = pixmap_alloc_buffer_for_copy(pixmap, &pixmap->data_size); for(int pass = 0; pass < num_passes; ++pass) { for(int row = pixmap->height - 1; row >= 0; --row) { png_read_row(png, buffer + row * pixmap->width * pixel_size, NULL); } } done: if(png != NULL) { png_destroy_read_struct( &png, png_info ? &png_info : NULL, NULL ); } if(error) { log_error("Failed to load image: %s", error); free(pixmap->data.untyped); pixmap->data.untyped = NULL; return false; } return true; } static void px_png_save_apply_conversions( const Pixmap *src_pixmap, Pixmap *dst_pixmap ) { PixmapLayout fmt_layout = pixmap_format_layout(src_pixmap->format); PixmapLayout fmt_depth = pixmap_format_layout(src_pixmap->format); if(fmt_depth > 16) { fmt_depth = 16; } else if(fmt_depth < 16) { fmt_depth = 8; } if(fmt_layout == PIXMAP_LAYOUT_RG) { fmt_layout = PIXMAP_LAYOUT_RGB; } PixmapFormat fmt = PIXMAP_MAKE_FORMAT(fmt_layout, fmt_depth); if(fmt == src_pixmap->format) { *dst_pixmap = *src_pixmap; } else { pixmap_convert_alloc(src_pixmap, dst_pixmap, fmt); } } DIAGNOSTIC_GCC(push) DIAGNOSTIC_GCC(ignored "-Wclobbered") static bool px_png_save( SDL_RWops *stream, const Pixmap *src_pixmap, const PixmapSaveOptions *base_opts ) { if( pixmap_format_is_compressed(src_pixmap->format) || pixmap_format_is_float(src_pixmap->format) ) { log_error("Can't write %s image to PNG", pixmap_format_name(src_pixmap->format)); return false; } const PixmapPNGSaveOptions *opts, default_opts = PIXMAP_DEFAULT_PNG_SAVE_OPTIONS; opts = &default_opts; if( base_opts && base_opts->file_format == PIXMAP_FILEFORMAT_PNG && base_opts->struct_size > sizeof(*base_opts) ) { assert(base_opts->struct_size == sizeof(*opts)); opts = UNION_CAST(const PixmapSaveOptions*, const PixmapPNGSaveOptions*, base_opts); } const char *error = NULL; png_structp png; png_infop info_ptr; Pixmap px = { 0 }; png = pngutil_create_write_struct(); if(png == NULL) { error = "pngutil_create_write_struct() failed"; goto done; } info_ptr = png_create_info_struct(png); if(info_ptr == NULL) { error = "png_create_info_struct() failed"; goto done; } if(setjmp(png_jmpbuf(png))) { error = "PNG error"; goto done; } px_png_save_apply_conversions(src_pixmap, &px); size_t pixel_size = pixmap_format_pixel_size(px.format); uint png_color; switch(pixmap_format_layout(px.format)) { case PIXMAP_LAYOUT_R: png_color = PNG_COLOR_TYPE_GRAY; break; case PIXMAP_LAYOUT_RGB: png_color = PNG_COLOR_TYPE_RGB; break; case PIXMAP_LAYOUT_RGBA: png_color = PNG_COLOR_TYPE_RGBA; break; default: UNREACHABLE; } pngutil_init_rwops_write(png, stream); png_set_IHDR( png, info_ptr, px.width, px.height, pixmap_format_depth(px.format), png_color, PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT ); if(opts->zlib_compression_level >= 0) { png_set_compression_level(png, opts->zlib_compression_level); } png_write_info(png, info_ptr); #if SDL_BYTEORDER == SDL_LIL_ENDIAN if(pixmap_format_depth(px.format) > 8) { png_set_swap(png); } #endif if(px.origin == PIXMAP_ORIGIN_BOTTOMLEFT) { for(int row = px.height - 1; row >= 0; --row) { png_write_row(png, px.data.r8->values + row * px.width * pixel_size); } } else { for(int row = 0; row < px.height; ++row) { png_write_row(png, px.data.r8->values + row * px.width * pixel_size); } } png_write_end(png, info_ptr); done: if(error) { log_error("%s", error); } if(px.data.untyped != src_pixmap->data.untyped) { free(px.data.untyped); } if(png != NULL) { png_destroy_write_struct(&png, info_ptr ? &info_ptr : NULL); } return !error; } DIAGNOSTIC_GCC(pop) PixmapFileFormatHandler pixmap_fileformat_png = { .probe = px_png_probe, .load = px_png_load, .save = px_png_save, .filename_exts = (const char*[]) { "png", NULL }, .name = "PNG", };
3,138
5,169
{ "name": "QuangFramework", "version": "1.0.0", "summary": "This is the best framework", "description": "I have no idea what to write as a description", "homepage": "https://github.com/quang10296/Quang", "license": "MIT", "authors": { "quang10296": "<EMAIL>" }, "platforms": { "ios": "12.1" }, "source": { "git": "https://github.com/quang10296/Quang.git", "tag": "1.0.0" }, "source_files": "Quang/**/*.{swift}", "swift_versions": "5.0", "swift_version": "5.0" }
221
386
<gh_stars>100-1000 #include <onnx.h> union onnx_scalar_t { uint8_t v_bool; int8_t v_int8; int16_t v_int16; int32_t v_int32; int64_t v_int64; uint8_t v_uint8; uint16_t v_uint16; uint32_t v_uint32; uint64_t v_uint64; uint16_t v_bfloat16; uint16_t v_float16; float v_float32; double v_float64; struct { float real; float imaginary; } v_complex64; struct { double real; double imaginary; } v_complex128; }; struct operator_pdata_t { enum onnx_tensor_type_t type; union onnx_scalar_t scalar; int size; }; static int ConstantOfShape_init(struct onnx_node_t * n) { struct operator_pdata_t * pdat; Onnx__AttributeProto * attr; Onnx__TensorProto * t = NULL; int i; if((n->ninput == 1) && (n->noutput == 1)) { pdat = malloc(sizeof(struct operator_pdata_t)); if(pdat) { for(i = 0; i < n->proto->n_attribute; i++) { attr = n->proto->attribute[i]; if((attr->type == ONNX__ATTRIBUTE_PROTO__ATTRIBUTE_TYPE__TENSOR) && (strcmp(attr->name, "value") == 0)) { t = attr->t; break; } } if(t) { pdat->type = (enum onnx_tensor_type_t)t->data_type; switch(t->data_type) { case ONNX__TENSOR_PROTO__DATA_TYPE__FLOAT: pdat->scalar.v_float32 = t->float_data[0]; break; case ONNX__TENSOR_PROTO__DATA_TYPE__UINT8: pdat->scalar.v_uint8 = t->int32_data[0]; break; case ONNX__TENSOR_PROTO__DATA_TYPE__INT8: pdat->scalar.v_int8 = t->int32_data[0]; break; case ONNX__TENSOR_PROTO__DATA_TYPE__UINT16: pdat->scalar.v_uint16 = t->int32_data[0]; break; case ONNX__TENSOR_PROTO__DATA_TYPE__INT16: pdat->scalar.v_int16 = t->int32_data[0]; break; case ONNX__TENSOR_PROTO__DATA_TYPE__INT32: pdat->scalar.v_int32 = t->int32_data[0]; break; case ONNX__TENSOR_PROTO__DATA_TYPE__BOOL: pdat->scalar.v_bool = t->int32_data[0]; break; case ONNX__TENSOR_PROTO__DATA_TYPE__FLOAT16: pdat->scalar.v_float16 = t->int32_data[0]; break; case ONNX__TENSOR_PROTO__DATA_TYPE__BFLOAT16: pdat->scalar.v_bfloat16 = t->int32_data[0]; break; case ONNX__TENSOR_PROTO__DATA_TYPE__INT64: pdat->scalar.v_int64 = t->int64_data[0]; break; case ONNX__TENSOR_PROTO__DATA_TYPE__DOUBLE: pdat->scalar.v_float64 = t->double_data[0]; break; case ONNX__TENSOR_PROTO__DATA_TYPE__UINT32: pdat->scalar.v_uint32 = t->uint64_data[0]; break; case ONNX__TENSOR_PROTO__DATA_TYPE__UINT64: pdat->scalar.v_uint64 = t->uint64_data[0]; break; case ONNX__TENSOR_PROTO__DATA_TYPE__COMPLEX64: pdat->scalar.v_complex64.real = t->float_data[0]; pdat->scalar.v_complex64.imaginary = t->float_data[1]; break; case ONNX__TENSOR_PROTO__DATA_TYPE__COMPLEX128: pdat->scalar.v_complex128.real = t->double_data[0]; pdat->scalar.v_complex128.imaginary = t->double_data[1]; break; default: memset(&pdat->scalar, 0, sizeof(union onnx_scalar_t)); break; } } else { pdat->type = ONNX_TENSOR_TYPE_FLOAT32; memset(&pdat->scalar, 0, sizeof(union onnx_scalar_t)); } pdat->size = onnx_tensor_type_sizeof(pdat->type); n->priv = pdat; return 1; } } return 0; } static int ConstantOfShape_exit(struct onnx_node_t * n) { struct operator_pdata_t * pdat = (struct operator_pdata_t *)n->priv; if(pdat) free(pdat); return 1; } static int ConstantOfShape_reshape(struct onnx_node_t * n) { return 1; } static void ConstantOfShape_operator(struct onnx_node_t * n) { struct operator_pdata_t * pdat = (struct operator_pdata_t *)n->priv; struct onnx_tensor_t * x = n->inputs[0]; struct onnx_tensor_t * y = n->outputs[0]; char * p; size_t i, l; if(x->ndata > 0) { int dims[x->ndata]; for(i = 0; i < x->ndata; i++) dims[i] = ((int64_t *)x->datas)[i]; onnx_tensor_reinit(y, pdat->type, dims, x->ndata); } else { onnx_tensor_reinit(y, pdat->type, NULL, 0); } for(i = 0, l = y->ndata, p = y->datas; i < l; i++, p += pdat->size) memcpy(p, &pdat->scalar, pdat->size); } void resolver_default_op_ConstantOfShape(struct onnx_node_t * n) { if(n->opset >= 9) { n->init = ConstantOfShape_init; n->exit = ConstantOfShape_exit; n->reshape = ConstantOfShape_reshape; n->operator = ConstantOfShape_operator; } }
2,223
302
package io.github.iamazy.elasticsearch.dsl.sql.parser.delete; import io.github.iamazy.elasticsearch.dsl.antlr4.ElasticsearchParser; import io.github.iamazy.elasticsearch.dsl.sql.enums.SqlOperation; import io.github.iamazy.elasticsearch.dsl.sql.model.ElasticDslContext; import io.github.iamazy.elasticsearch.dsl.sql.parser.BoolExpressionParser; import io.github.iamazy.elasticsearch.dsl.sql.parser.QueryParser; import io.github.iamazy.elasticsearch.dsl.utils.StringManager; import org.elasticsearch.action.delete.DeleteRequest; import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.index.reindex.DeleteByQueryRequest; import java.util.ArrayList; import java.util.List; /** * @author iamazy * @date 2019/12/14 **/ public class DeleteQueryParser implements QueryParser { @Override public void parse(ElasticDslContext dslContext) { if (dslContext.getSqlContext().deleteOperation() != null) { if (dslContext.getSqlContext().deleteOperation().identifyClause() == null) { parseDeleteByQuery(dslContext); } else { parseDelete(dslContext); } } } private void parseDelete(ElasticDslContext dslContext) { dslContext.getParseResult().setSqlOperation(SqlOperation.DELETE); ElasticsearchParser.DeleteOperationContext deleteOperationContext = dslContext.getSqlContext().deleteOperation(); DeleteRequest deleteRequest = new DeleteRequest(deleteOperationContext.tableRef(0).indexName.getText()); deleteRequest.id(StringManager.removeStringSymbol(deleteOperationContext.identifyClause().id.getText())); if (deleteOperationContext.routingClause() != null) { deleteRequest.routing(StringManager.removeStringSymbol(deleteOperationContext.routingClause().STRING(0).getText())); } dslContext.getParseResult().setDeleteRequest(deleteRequest); } private void parseDeleteByQuery(ElasticDslContext dslContext) { dslContext.getParseResult().setSqlOperation(SqlOperation.DELETE_BY_QUERY); ElasticsearchParser.DeleteOperationContext deleteOperationContext = dslContext.getSqlContext().deleteOperation(); List<String> indices = new ArrayList<>(0); for (ElasticsearchParser.TableRefContext tableRefContext : deleteOperationContext.tableRef()) { indices.add(tableRefContext.indexName.getText()); } DeleteByQueryRequest deleteByQueryRequest = new DeleteByQueryRequest(indices.toArray(new String[0])); BoolExpressionParser boolExpressionParser = new BoolExpressionParser(); if (deleteOperationContext.whereClause() != null) { deleteByQueryRequest.setQuery(boolExpressionParser.parseBoolQueryExpr(deleteOperationContext.whereClause().expression())); } else { deleteByQueryRequest.setQuery(QueryBuilders.matchAllQuery()); } if (deleteOperationContext.routingClause() != null) { deleteByQueryRequest.setRouting(StringManager.removeStringSymbol(deleteOperationContext.routingClause().STRING(0).getText())); } if (deleteOperationContext.batchClause() != null) { deleteByQueryRequest.setBatchSize(Integer.parseInt(deleteOperationContext.batchClause().size.getText())); } if (deleteOperationContext.limitClause() != null) { deleteByQueryRequest.setMaxDocs(Integer.parseInt(deleteOperationContext.limitClause().size.getText())); } dslContext.getParseResult().setDeleteByQueryRequest(deleteByQueryRequest); } }
1,302
2,504
//********************************************************* // // Copyright (c) Microsoft. All rights reserved. // This code is licensed under the MIT License (MIT). // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. // //********************************************************* #pragma once #include "pch.h" namespace winrt::SDKTemplate { bool TryParseInt32(wchar_t const* text, int32_t& value); // RAII type for ensuring an object is closed. struct ensure_close { Windows::Foundation::IClosable m_closable; ensure_close(Windows::Foundation::IClosable closable) : m_closable(std::move(closable)) { } ~ensure_close() { if (m_closable) m_closable.Close(); } ensure_close(const ensure_close&) = delete; ensure_close& operator=(const ensure_close&) = delete; ensure_close(ensure_close&& other) = default; ensure_close& operator=(ensure_close&& other) = default; }; }
422
324
/* * 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.jclouds.location.predicates.fromconfig; import static org.testng.Assert.assertEquals; import java.util.Set; import org.jclouds.location.Provider; import org.jclouds.location.predicates.ZoneIdFilter; import org.testng.annotations.Test; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Sets; import com.google.inject.AbstractModule; import com.google.inject.Guice; import com.google.inject.name.Names; /** * Tests behavior of {@code AnyOrConfiguredZoneId} */ @Test(groups = "unit", testName = "AnyOrConfiguredZoneIdTest") public class AnyOrConfiguredZoneIdTest { @Test public void testWithoutConfigAllIdsMatch() { Set<String> zoneIds = ImmutableSet.of("us-east-1a", "us-east-1b"); ZoneIdFilter filter = Guice.createInjector(new AbstractModule() { @Override protected void configure() { bindConstant().annotatedWith(Provider.class).to("aws-ec2"); } }).getInstance(AnyOrConfiguredZoneId.class); assertEquals(Sets.filter(zoneIds, filter), ImmutableSet.of("us-east-1a", "us-east-1b")); } @Test public void testWithConfigOnlyMatchingIds() { Set<String> zoneIds = ImmutableSet.of("us-east-1a", "us-east-1b"); ZoneIdFilter filter = Guice.createInjector(new AbstractModule() { @Override protected void configure() { bindConstant().annotatedWith(Provider.class).to("aws-ec2"); bindConstant().annotatedWith(Names.named("jclouds.zones")).to("us-east-1a,us-east-1d"); } }).getInstance(AnyOrConfiguredZoneId.class); assertEquals(Sets.filter(zoneIds, filter), ImmutableSet.of("us-east-1a")); } }
900
677
<gh_stars>100-1000 /* * Copyright (C) 2006, 2007 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #include "JSStringRefCF.h" #include "APICast.h" #include "InitializeThreading.h" #include "JSCJSValue.h" #include "JSStringRef.h" #include "OpaqueJSString.h" #include <wtf/StdLibExtras.h> JSStringRef JSStringCreateWithCFString(CFStringRef string) { JSC::initializeThreading(); // We cannot use CFIndex here since CFStringGetLength can return values larger than // it can hold. (<rdar://problem/6806478>) size_t length = CFStringGetLength(string); if (!length) return &OpaqueJSString::create(reinterpret_cast<const LChar*>(""), 0).leakRef(); Vector<LChar, 1024> lcharBuffer(length); CFIndex usedBufferLength; CFIndex convertedSize = CFStringGetBytes(string, CFRangeMake(0, length), kCFStringEncodingISOLatin1, 0, false, lcharBuffer.data(), length, &usedBufferLength); if (static_cast<size_t>(convertedSize) == length && static_cast<size_t>(usedBufferLength) == length) return &OpaqueJSString::create(lcharBuffer.data(), length).leakRef(); auto buffer = std::make_unique<UniChar[]>(length); CFStringGetCharacters(string, CFRangeMake(0, length), buffer.get()); static_assert(sizeof(UniChar) == sizeof(UChar), "UniChar and UChar must be same size"); return &OpaqueJSString::create(reinterpret_cast<UChar*>(buffer.get()), length).leakRef(); } CFStringRef JSStringCopyCFString(CFAllocatorRef allocator, JSStringRef string) { if (!string || !string->length()) return CFSTR(""); if (string->is8Bit()) return CFStringCreateWithBytes(allocator, reinterpret_cast<const UInt8*>(string->characters8()), string->length(), kCFStringEncodingISOLatin1, false); return CFStringCreateWithCharacters(allocator, reinterpret_cast<const UniChar*>(string->characters16()), string->length()); }
1,021
2,550
/* * Copyright 2014-2021 Sayi * * 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.deepoove.poi.plugin.markdown.converter; import static com.deepoove.poi.data.NumberingFormat.BULLET; import static com.deepoove.poi.data.NumberingFormat.DECIMAL_PARENTHESES_BUILDER; import static com.deepoove.poi.data.NumberingFormat.LOWER_LETTER_BUILDER; import static com.deepoove.poi.data.NumberingFormat.UPPER_LETTER_BUILDER; import static com.deepoove.poi.data.NumberingFormat.UPPER_ROMAN_BUILDER; import java.util.Arrays; import java.util.Iterator; import java.util.List; import org.apache.commons.lang3.StringUtils; import org.commonmark.ext.gfm.tables.TableBlock; import org.commonmark.ext.gfm.tables.TableHead; import org.commonmark.node.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.deepoove.poi.data.*; import com.deepoove.poi.data.Cells.CellBuilder; import com.deepoove.poi.data.Documents.DocumentBuilder; import com.deepoove.poi.data.NumberingFormat.Builder; import com.deepoove.poi.data.Paragraphs.ParagraphBuilder; import com.deepoove.poi.data.Rows.RowBuilder; import com.deepoove.poi.data.Tables.TableBuilder; import com.deepoove.poi.data.Texts.TextBuilder; import com.deepoove.poi.data.style.ParagraphStyle; import com.deepoove.poi.exception.RenderException; import com.deepoove.poi.plugin.highlight.HighlightRenderData; import com.deepoove.poi.plugin.highlight.converter.HighlightToDocumentRenderDataConverter; import com.deepoove.poi.plugin.markdown.MarkdownStyle; /** * @author Sayi */ public class DocumentVisitor extends AbstractVisitor { protected static final Logger LOGGER = LoggerFactory.getLogger(DocumentVisitor.class); private static HighlightToDocumentRenderDataConverter highlightConverter = new HighlightToDocumentRenderDataConverter(); private static List<Builder> multiLevelFormat = Arrays.asList(DECIMAL_PARENTHESES_BUILDER, LOWER_LETTER_BUILDER, UPPER_LETTER_BUILDER, UPPER_ROMAN_BUILDER); private DocumentBuilder of = Documents.of(); private MarkdownStyle style; private int[] headerNumberArray = new int[10]; private Iterator<Builder> iterator; public DocumentVisitor(MarkdownStyle style) { this.style = null == style ? new MarkdownStyle() : style; } @Override public void visit(Heading heading) { int level = heading.getLevel(); resetHeaderNumberArray(level); ParagraphBuilder paraOf = Paragraphs.of().styleId(String.valueOf(level)).left().allowWordBreak(); if (style.isShowHeaderNumber()) { paraOf.addText(getHeaderNumber(level)); } DocumentRenderData renderData = parseNode(heading); if (!renderData.getContents().isEmpty()) { ParagraphRenderData headerParagraph = (ParagraphRenderData) renderData.getContents().get(0); paraOf.addParagraph(headerParagraph); paraOf.addText(Texts.of("").bookmark(evalText(headerParagraph)).create()); } of.addParagraph(paraOf.create()); } @Override public void visit(Paragraph paragraph) { of.addDocument(parseNode(paragraph)); } private DocumentRenderData parseNode(Node block) { if (block instanceof FencedCodeBlock) { return parseFencedCodeBlock((FencedCodeBlock) block); } if (block instanceof IndentedCodeBlock) { return parseIndentedCodeBlock((IndentedCodeBlock) block); } DocumentBuilder docOf = Documents.of(); Node node = block.getFirstChild(); ParagraphBuilder paraOf = Paragraphs.of().left(); while (node != null) { if (node instanceof Text) { paraOf.addText(((Text) node).getLiteral()).create(); } else if (node instanceof StrongEmphasis || node instanceof Emphasis) { DocumentRenderData ret = parseNode(node); for (RenderData r : ret.getContents()) { paraOf.addParagraph((ParagraphRenderData) r); } } else if (node instanceof Code) { TextBuilder ofCode = Texts.of(((Code) node).getLiteral()).style(style.getInlineCodeStyle()); paraOf.addText(ofCode.create()).create(); } else if (node instanceof SoftLineBreak || node instanceof HardLineBreak) { docOf.addParagraph(paraOf.create()); paraOf = Paragraphs.of().left(); } else if (node instanceof HtmlInline) { paraOf.addText(((HtmlInline) node).getLiteral()).create(); } else if (node instanceof HtmlBlock) { paraOf.addText(((HtmlBlock) node).getLiteral()).create(); } else if (node instanceof Image) { paraOf.addPicture(parsePicture((Image) node)); } else if (node instanceof Link) { String destination = ((Link) node).getDestination(); Node textLink = node.getFirstChild(); if (textLink instanceof Text) { paraOf.addText(Texts.of(((Text) textLink).getLiteral()).link(destination).create()).create(); } else if (textLink instanceof Image) { // TODO picture link paraOf.addPicture(parsePicture((Image) textLink)); } } else { LOGGER.warn("Current not support visit node: " + node); } node = node.getNext(); } return docOf.addParagraph(paraOf.create()).create(); } private PictureRenderData parsePicture(Image image) { String uri = image.getDestination(); if (!uri.startsWith("http")) { uri = style.getImagesDir() + uri; } return Pictures.of(uri).altMeta(image.getTitle()).fitSize().create(); } private DocumentRenderData parseIndentedCodeBlock(IndentedCodeBlock indentedCodeBlock) { return parseCode(indentedCodeBlock.getLiteral(), "java"); } private DocumentRenderData parseFencedCodeBlock(FencedCodeBlock fencedCodeBlock) { return parseCode(fencedCodeBlock.getLiteral(), fencedCodeBlock.getInfo()); } private DocumentRenderData parseCode(String code, String language) { HighlightRenderData highlight = new HighlightRenderData(); highlight.setCode(code.endsWith("\n") ? code.substring(0, code.length() - 1) : code); highlight.setLanguage(language); highlight.setStyle(style.getHighlightStyle()); try { DocumentRenderData apply = highlightConverter.convert(highlight); for (RenderData doc : apply.getContents()) { if (doc instanceof ParagraphRenderData) { ParagraphStyle paragraphStyle = ((ParagraphRenderData) doc).getParagraphStyle(); if (null == paragraphStyle) { paragraphStyle = new ParagraphStyle(); ((ParagraphRenderData) doc).setParagraphStyle(paragraphStyle); } paragraphStyle.setSpacing(1.0); // paragraphStyle.setSpacing(0.0f); // paragraphStyle.setSpacingRule(LineSpacingRule.AT_LEAST); } } return apply; } catch (Exception e) { throw new RenderException("Error Parse Code", e); } } @Override public void visit(IndentedCodeBlock indentedCodeBlock) { of.addDocument(parseIndentedCodeBlock(indentedCodeBlock)); } @Override public void visit(FencedCodeBlock fencedCodeBlock) { of.addDocument(parseFencedCodeBlock(fencedCodeBlock)); } @Override public void visit(OrderedList orderedList) { resetFormatIterator(); of.addNumbering(parseList(orderedList, new NumberingRenderData(), 0)); } @Override public void visit(BulletList bulletList) { resetFormatIterator(); of.addNumbering(parseList(bulletList, new NumberingRenderData(), 0)); } private void resetFormatIterator() { iterator = multiLevelFormat.iterator(); } private NumberingRenderData parseList(ListBlock listBlock, NumberingRenderData numberingRenderData, int index) { List<NumberingFormat> formats = numberingRenderData.getFormats(); if (listBlock instanceof BulletList) { formats.add(BULLET); } else if (null != iterator && iterator.hasNext()) { formats.add(iterator.next().build(index)); } else { formats.add(DECIMAL_PARENTHESES_BUILDER.build(index)); } List<NumberingItemRenderData> result = numberingRenderData.getItems(); Node node = listBlock.getFirstChild(); while (null != node) { if (node instanceof ListItem) { Node itemNode = node.getFirstChild(); boolean first = true; while (null != itemNode) { if (itemNode instanceof ListBlock) { parseList((ListBlock) itemNode, numberingRenderData, index + 1); // } else if (first instanceof TableBlock) { // TableRenderData tableRenderData = parseTable((TableBlock) first); } else { DocumentRenderData ret = parseNode(itemNode); List<RenderData> contents = ret.getContents(); for (int i = 0; i < contents.size(); i++) { RenderData content = contents.get(i); ParagraphRenderData paragraph = (ParagraphRenderData) content; if (first) { result.add(new NumberingItemRenderData(index, paragraph)); first = false; } else { if (paragraph.getParagraphStyle() == null) { paragraph.setParagraphStyle(new ParagraphStyle()); } paragraph.getParagraphStyle().setIndentLeftChars(index * 1.8); result.add(new NumberingItemRenderData(-1, paragraph)); } } } itemNode = itemNode.getNext(); } } node = node.getNext(); } return numberingRenderData; } @Override public void visit(BlockQuote blockQuote) { Node node = blockQuote.getFirstChild(); boolean first = true; while (null != node) { if (node instanceof BlockQuote) { visit((BlockQuote) node); } else { DocumentRenderData ret = parseNode((Paragraph) node); List<RenderData> contents = ret.getContents(); int size = contents.size(); for (int i = 0; i < size; i++) { RenderData content = contents.get(i); ParagraphRenderData paragraph = (ParagraphRenderData) content; paragraph.setParagraphStyle(style.getQuoteStyle()); ParagraphStyle paragraphStyle = paragraph.getParagraphStyle(); if (null == paragraphStyle) { paragraphStyle = new ParagraphStyle(); paragraph.setParagraphStyle(paragraphStyle); } if (first) { paragraphStyle.setSpacingBeforeLines(Double.valueOf(0.4)); first = false; } if (i == size - 1) { paragraphStyle.setSpacingAfterLines(Double.valueOf(0.4)); } of.addParagraph(paragraph); } } node = node.getNext(); } } @Override public void visit(CustomBlock customBlock) { if (customBlock instanceof TableBlock) { visitTable((TableBlock) customBlock); } else { super.visit(customBlock); } } private void visitTable(TableBlock table) { of.addTable(parseTable(table)); } private TableRenderData parseTable(TableBlock table) { TableBuilder tableOf = Tables.ofPercentWidth("100%"); tableOf.cellMargin(0.19f, 0.19f, 0.19f, 0.19f); Node headOrBody = table.getFirstChild(); while (null != headOrBody) { boolean isTH = headOrBody instanceof TableHead; Node row = headOrBody.getFirstChild(); while (row != null) { RowBuilder rowOf = Rows.of(); if (isTH) rowOf.rowStyle(style.getTableHeaderStyle()); Node cell = row.getFirstChild(); while (null != cell) { CellBuilder cellOf = Cells.of(); DocumentRenderData ret = parseNode(cell); if (ret.getContents().isEmpty()) { rowOf.addCell(Cells.of("").create()); } else { for (RenderData r : ret.getContents()) { cellOf.addParagraph((ParagraphRenderData) r); } rowOf.addCell(cellOf.create()); } cell = cell.getNext(); } tableOf.addRow(rowOf.create()); row = row.getNext(); } headOrBody = headOrBody.getNext(); } return tableOf.border(style.getTableBorderStyle()).create(); } @Override public void visit(Image image) { } @Override public void visit(Text text) { } @Override public void visit(ThematicBreak thematicBreak) { } @Override public void visit(HtmlBlock node) { of.addParagraph(Paragraphs.of(((HtmlBlock) node).getLiteral()).create()); } @Override protected void visitChildren(Node parent) { if (parent instanceof Document || parent instanceof Paragraph) { Node node = parent.getFirstChild(); while (node != null) { // A subclass of this visitor might modify the node, resulting in getNext // returning a different node or no // node after visiting it. So get the next node before visiting. Node next = node.getNext(); node.accept(this); node = next; } } else { LOGGER.warn("Current not support visit node: " + parent); } } public DocumentRenderData getResult() { return of.create(); } private String evalText(ParagraphRenderData paragraph) { StringBuilder text = new StringBuilder(); paragraph.getContents().stream().filter(r -> r instanceof TextRenderData).forEach(r -> { text.append(((TextRenderData) r).getText()); }); return text.toString(); } private void resetHeaderNumberArray(int level) { headerNumberArray[level] += 1; for (int i = level + 1; i < headerNumberArray.length; i++) { headerNumberArray[i] = 0; } } private String getHeaderNumber(int level) { if (level == 1) return ""; String str = StringUtils.join(Arrays.copyOfRange(headerNumberArray, 2, headerNumberArray.length), '.'); String substring = str.substring(0, (level - 1) * 2 >= str.length() ? str.length() : (level - 1) * 2); return substring + " "; } }
7,218
1,144
package de.metas.device.adempiere.impl; import java.util.List; import java.util.Set; import org.adempiere.mm.attributes.AttributeCode; import org.adempiere.service.ClientId; import org.adempiere.service.ISysConfigBL; import org.adempiere.util.net.IHostIdentifier; import org.adempiere.util.net.NetUtils; import org.adempiere.warehouse.WarehouseId; import org.compiere.util.Env; import org.junit.Assert; import com.google.common.collect.ImmutableSet; import de.metas.device.adempiere.AttributesDevicesHub; import de.metas.device.adempiere.DeviceConfig; import de.metas.organization.OrgId; import de.metas.util.Check; import de.metas.util.Services; import de.metas.util.collections.CollectionUtils; import lombok.NonNull; /* * #%L * de.metas.device.adempiere * %% * Copyright (C) 2017 metas GmbH * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 2 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program. If not, see * <http://www.gnu.org/licenses/gpl-2.0.html>. * #L% */ public class SysConfigDeviceConfigPoolTestHelper { private static final String MOCKED_DEVICE_DeviceClass = MockedDevice.class.getName(); private static final String MOCKED_DEVICE_RequestClass = MockedDeviceRequest.class.getName(); private final IHostIdentifier clientHost = NetUtils.getLocalHost(); public final DeviceConfig createDeviceConfigAndAssertValid( final String deviceName, final AttributeCode attributeCode, final Set<WarehouseId> warehouseIds) { createMockedDeviceSysconfigs(deviceName, attributeCode, warehouseIds); final SysConfigDeviceConfigPool configPool = createSysConfigDeviceConfigPool(); final List<DeviceConfig> deviceConfigs = configPool.getDeviceConfigsForAttributeCode(attributeCode); final DeviceConfig deviceConfig = CollectionUtils.singleElement(deviceConfigs); // System.out.println("Checking " + deviceConfig); Assert.assertEquals("deviceName", deviceName, deviceConfig.getDeviceName()); Assert.assertEquals("attributeCode", ImmutableSet.of(attributeCode), deviceConfig.getAssignedAttributeCodes()); Assert.assertEquals("DeviceClass", MOCKED_DEVICE_DeviceClass, deviceConfig.getDeviceClassname()); Assert.assertEquals("RequestClassname", ImmutableSet.of(MOCKED_DEVICE_RequestClass), deviceConfig.getRequestClassnames(attributeCode)); Assert.assertEquals("M_Warehouse_ID", warehouseIds, deviceConfig.getAssignedWarehouseIds()); return deviceConfig; } private final void createMockedDeviceSysconfigs( @NonNull final String deviceName, @NonNull final AttributeCode attributeCode, @NonNull final Set<WarehouseId> warehouseIds) { Check.assumeNotEmpty(deviceName, "deviceName is not empty"); final String host = SysConfigDeviceConfigPool.IPADDRESS_ANY; putSysConfig("de.metas.device.Name." + deviceName, deviceName); putSysConfig("de.metas.device." + deviceName + "." + host + ".DeviceClass", MOCKED_DEVICE_DeviceClass); putSysConfig("de.metas.device." + deviceName + "." + host + ".Endpoint.Class", "de.metas.device.scales.endpoint.MockedEndpoint"); putSysConfig("de.metas.device." + deviceName + "." + host + ".Endpoint.IP", "DOES NOT MATTER"); putSysConfig("de.metas.device." + deviceName + "." + host + ".Endpoint.Port", "0"); putSysConfig("de.metas.device." + deviceName + "." + host + ".RoundToPrecision", "1"); putSysConfig("de.metas.device." + deviceName + ".AttributeInternalName", attributeCode.getCode()); putSysConfig("de.metas.device." + deviceName + ".AvailableOn1", host); putSysConfig("de.metas.device." + deviceName + "." + attributeCode, MOCKED_DEVICE_RequestClass); warehouseIds.forEach(warehouseId -> putSysConfig("de.metas.device." + deviceName + ".M_Warehouse_ID." + warehouseId.getRepoId(), String.valueOf(warehouseId.getRepoId()))); } private static final void putSysConfig(final String name, final String value) { Services.get(ISysConfigBL.class).setValue(name, value, ClientId.SYSTEM, OrgId.ANY); } private final SysConfigDeviceConfigPool createSysConfigDeviceConfigPool() { final ClientId adClientId = Env.getClientId(Env.getCtx()); final OrgId adOrgId = OrgId.ANY; final SysConfigDeviceConfigPool configPool = new SysConfigDeviceConfigPool(clientHost, adClientId, adOrgId); return configPool; } public AttributesDevicesHub createDevicesHub() { final SysConfigDeviceConfigPool configPool = createSysConfigDeviceConfigPool(); return new AttributesDevicesHub(configPool); } }
1,560
423
<gh_stars>100-1000 // The MIT License (MIT) // Copyright © 2015 AppsLandia. All rights reserved. // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. package com.appslandia.plum.base; import java.util.Collections; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import com.appslandia.common.caching.AppCache; import com.appslandia.common.caching.AppCacheManager; import com.appslandia.common.utils.AssertUtils; import com.appslandia.common.utils.ObjectUtils; /** * * @author <a href="mailto:<EMAIL>"><NAME></a> * */ public class MemAppCacheManager implements AppCacheManager { final ConcurrentMap<String, AppCache<Object, Object>> caches = new ConcurrentHashMap<>(); public <K, V> AppCache<K, V> createCache(String cacheName, int size) { AssertUtils.assertFalse(this.caches.containsKey(cacheName)); AppCache<K, V> cache = new MemAppCache<>(cacheName, size); this.caches.put(cacheName, ObjectUtils.cast(cache)); return cache; } @Override public <K, V> AppCache<K, V> getCache(String cacheName) { return ObjectUtils.cast(this.caches.get(cacheName)); } @Override public boolean clearCache(String cacheName) { AppCache<Object, Object> cache = this.caches.get(cacheName); if (cache != null) { cache.clear(); return true; } return false; } @Override public boolean destroyCache(String cacheName) { AppCache<Object, Object> cache = this.caches.remove(cacheName); if (cache != null) { cache.clear(); return true; } return false; } @Override public Iterable<String> getCacheNames() { return Collections.unmodifiableSet(this.caches.keySet()); } @Override public void close() { for (AppCache<Object, Object> cache : this.caches.values()) { cache.clear(); } this.caches.clear(); } }
885
1,020
# -*- coding=utf -*- import unittest from sqlalchemy import create_engine, MetaData, Table, Integer, String, Column from cubes import * from cubes.errors import * from ..common import CubesTestCaseBase from json import dumps def printable(obj): return dumps(obj, indent=4) class AggregatesTestCase(CubesTestCaseBase): sql_engine = "sqlite:///" def setUp(self): super(AggregatesTestCase, self).setUp() self.facts = Table("facts", self.metadata, Column("id", Integer), Column("year", Integer), Column("amount", Integer), Column("price", Integer), Column("discount", Integer) ) self.metadata.create_all() data = [ ( 1, 2010, 1, 100, 0), ( 2, 2010, 2, 200, 10), ( 3, 2010, 4, 300, 0), ( 4, 2010, 8, 400, 20), ( 5, 2011, 1, 500, 0), ( 6, 2011, 2, 600, 40), ( 7, 2011, 4, 700, 0), ( 8, 2011, 8, 800, 80), ( 9, 2012, 1, 100, 0), (10, 2012, 2, 200, 0), (11, 2012, 4, 300, 0), (12, 2012, 8, 400, 10), (13, 2013, 1, 500, 0), (14, 2013, 2, 600, 0), (15, 2013, 4, 700, 0), (16, 2013, 8, 800, 20), ] self.load_data(self.facts, data) self.workspace = self.create_workspace(model="aggregates.json") def test_unknown_function(self): browser = self.workspace.browser("unknown_function") with self.assertRaisesRegex(ArgumentError, "Unknown.*function"): browser.aggregate() def test_explicit(self): browser = self.workspace.browser("default") result = browser.aggregate() summary = result.summary self.assertEqual(60, summary["amount_sum"]) self.assertEqual(16, summary["count"]) def test_post_calculation(self): browser = self.workspace.browser("postcalc_in_measure") result = browser.aggregate(drilldown=["year"]) cells = list(result.cells) aggregates = sorted(cells[0].keys()) self.assertSequenceEqual(['amount_sma', 'amount_sum', 'count', 'year'], aggregates)
1,151
554
<filename>x-apm-base/src/main/java/github/tornaco/xposedmoduletest/xposed/app/IBackupCallbackAdapter.java package github.tornaco.xposedmoduletest.xposed.app; import android.os.RemoteException; import github.tornaco.xposedmoduletest.IBackupCallback; /** * Created by Tornaco on 2018/5/29 13:53. * This file is writen for project X-APM at host guohao4. */ @SuppressWarnings("RedundantThrows") public class IBackupCallbackAdapter extends IBackupCallback.Stub { @Override public void onBackupFinished(String domain, String path) throws RemoteException { } @Override public void onRestoreFinished(String domain, String path) throws RemoteException { } @Override public void onFail(String message) throws RemoteException { } @Override public void onProgress(String progressMessage) throws RemoteException { } }
321
1,738
<filename>dev/Gems/CloudGemDefectReporter/v1/AWS/lambda-code/ServiceLambda/recent_searches.py<gh_stars>1000+ # # All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or # its licensors. # # For complete copyright and license terms please see the LICENSE at the root of this # distribution (the "License"). All use of this software is governed by the License, # or, if provided, by the license below or the license accompanying this file. Do not # remove or modify any license notices. This file is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # import boto3 import CloudCanvas from datetime import datetime import uuid from errors import ClientError RECENT_SEARCHES_TABLE = None MAX_SIZE = 10 def add_new_search(search_entry): global RECENT_SEARCHES_TABLE __validate_search_entry(search_entry) search_entry['sql_id'] = str(uuid.uuid4()) search_entry['timestamp'] = datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%SZ") search_entry['query_params'] = '*' if not search_entry.get('query_params', '') else search_entry['query_params'] count = 0 oldest_entry_index = 0 __scan_recent_searches_table() for index, entry in enumerate(RECENT_SEARCHES_TABLE): if entry['user_id'] == search_entry['user_id']: count = count + 1 current_entry_timestamp = datetime.strptime(entry['timestamp'], "%Y-%m-%dT%H:%M:%SZ") oldest_entry_timestamp = datetime.strptime(RECENT_SEARCHES_TABLE[oldest_entry_index]['timestamp'], "%Y-%m-%dT%H:%M:%SZ") if current_entry_timestamp < oldest_entry_timestamp: oldest_entry_index = index if (count >= MAX_SIZE): oldest_entry_key = {'user_id': RECENT_SEARCHES_TABLE[oldest_entry_index]['user_id'], 'sql_id': RECENT_SEARCHES_TABLE[oldest_entry_index]['sql_id']} __get_table().delete_item(Key = oldest_entry_key) del RECENT_SEARCHES_TABLE[oldest_entry_index] __get_table().put_item(Item = search_entry) RECENT_SEARCHES_TABLE.append(search_entry) return 'SUCCESS' def get_recent_searches(user_id): __scan_recent_searches_table() recent_searches = [] for search_entry in RECENT_SEARCHES_TABLE: if search_entry['user_id'] == user_id: recent_searches.append(search_entry) return recent_searches def __validate_search_entry(search_entry): valid_fields = ['user_id', 'query_params'] for valid_field in valid_fields: if valid_field not in search_entry: raise ClientError(valid_field + ' is missing in the request body') if not search_entry['user_id']: raise ClientError(valid_field + ' is empty in the request body') def __get_table(): if not hasattr(__get_table,'recent_searches'): __get_table.recent_searches = boto3.resource('dynamodb').Table(CloudCanvas.get_setting('RecentSearches')) return __get_table.recent_searches def __scan_recent_searches_table(): global RECENT_SEARCHES_TABLE if not RECENT_SEARCHES_TABLE: response = __get_table().scan() RECENT_SEARCHES_TABLE = response.get('Items', [])
1,234
777
<gh_stars>100-1000 /* * Artificial Intelligence for Humans * Volume 3: Deep Learning and Neural Networks * Java Version * http://www.aifh.org * http://www.jeffheaton.com * * Code repository: * https://github.com/jeffheaton/aifh * * Copyright 2014-2015 by <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information on Heaton Research copyrights, licenses * and trademarks visit: * http://www.heatonresearch.com/copyright */ package com.heatonresearch.aifh.som.neighborhood; /** * Defines how a neighborhood function should work in competitive training. This * is most often used in the training process for a self-organizing map. This * function determines to what degree the training should take place on a * neuron, based on its proximity to the "winning" neuron. * * @author jheaton * */ public interface NeighborhoodFunction { /** * Determine how much the current neuron should be affected by training * based on its proximity to the winning neuron. * * @param currentNeuron * THe current neuron being evaluated. * @param bestNeuron * The winning neuron. * @return The ratio for this neuron's adjustment. */ double function(int currentNeuron, int bestNeuron); /** * @return The radius. */ double getRadius(); /** * Set the radius. * @param radius The new radius. */ void setRadius(double radius); }
552
2,341
<filename>backend/middleware.py # # Copyright 2016 Cluster Labs, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import json from django.conf import settings from django.http import HttpResponsePermanentRedirect class SetRemoteAddrFromForwardedFor(object): def process_request(self, request): try: real_ip = request.META['HTTP_X_FORWARDED_FOR'] # HTTP_X_FORWARDED_FOR can be a comma-separated list of IPs. # Take just the first one. real_ip = real_ip.split(',')[0] except KeyError: real_ip = request.META['REMOTE_ADDR'] setattr(request, 'remote_addr', real_ip) class SecureRequiredMiddleware(object): def process_request(self, request): my_host = request.META.get('HTTP_HOST') # Redirect HTTP to HTTPS for the domains we like... if my_host in settings.REDIRECT_INSECURE_DOMAINS and not request.is_secure(): redirect_url = request.build_absolute_uri().replace('http://', 'https://') return HttpResponsePermanentRedirect(redirect_url) redirect_base_url = settings.UNDESIRABLE_DOMAINS.get(my_host) if not redirect_base_url: return None redirect_url = redirect_base_url + request.get_full_path().lstrip('/') return HttpResponsePermanentRedirect(redirect_url) def process_response(self, request, response): response['X-Frame-Options'] = 'SAMEORIGIN' if request.is_secure(): response['Strict-Transport-Security'] = 'max-age=631138519' return response class JSONPostMiddleware(object): def process_request(self, request): setattr(request, 'DATA', None) if request.method != 'POST': return None content_type = request.META.get('CONTENT_TYPE', '') if '/json' not in content_type: return None try: json_data = json.loads(request.body) except (ValueError, TypeError): json_data = None # TODO(Taylor): Allow returning of invalid codes here somehow? # Assuming each endpoint will validate its own data, however. if isinstance(json_data, dict): setattr(request, 'DATA', json_data)
874
13,846
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. #pragma once #ifndef _LIST_ENTRY_H #define _LIST_ENTRY_H // // Doubly-linked list manipulation routines. // #define InitializeListHead32(ListHead) (\ (ListHead)->Flink = (ListHead)->Blink = PtrToUlong((ListHead))) FORCEINLINE VOID InitializeListHead( IN PLIST_ENTRY ListHead ) { ListHead->Flink = ListHead->Blink = ListHead; } FORCEINLINE BOOLEAN IsListEmpty( IN const LIST_ENTRY * ListHead ) { return (BOOLEAN)(ListHead->Flink == ListHead); } FORCEINLINE BOOLEAN RemoveEntryList( IN PLIST_ENTRY Entry ) { PLIST_ENTRY Blink; PLIST_ENTRY Flink; Flink = Entry->Flink; Blink = Entry->Blink; Blink->Flink = Flink; Flink->Blink = Blink; return (BOOLEAN)(Flink == Blink); } FORCEINLINE PLIST_ENTRY RemoveHeadList( IN PLIST_ENTRY ListHead ) { PLIST_ENTRY Flink; PLIST_ENTRY Entry; Entry = ListHead->Flink; Flink = Entry->Flink; ListHead->Flink = Flink; Flink->Blink = ListHead; return Entry; } FORCEINLINE PLIST_ENTRY RemoveTailList( IN PLIST_ENTRY ListHead ) { PLIST_ENTRY Blink; PLIST_ENTRY Entry; Entry = ListHead->Blink; Blink = Entry->Blink; ListHead->Blink = Blink; Blink->Flink = ListHead; return Entry; } FORCEINLINE VOID InsertTailList( IN PLIST_ENTRY ListHead, IN PLIST_ENTRY Entry ) { PLIST_ENTRY Blink; Blink = ListHead->Blink; Entry->Flink = ListHead; Entry->Blink = Blink; Blink->Flink = Entry; ListHead->Blink = Entry; } FORCEINLINE VOID InsertHeadList( IN PLIST_ENTRY ListHead, IN PLIST_ENTRY Entry ) { PLIST_ENTRY Flink; Flink = ListHead->Flink; Entry->Flink = Flink; Entry->Blink = ListHead; Flink->Blink = Entry; ListHead->Flink = Entry; } FORCEINLINE VOID AppendTailList( IN PLIST_ENTRY ListHead, IN PLIST_ENTRY ListToAppend ) { PLIST_ENTRY ListEnd = ListHead->Blink; ListHead->Blink->Flink = ListToAppend; ListHead->Blink = ListToAppend->Blink; ListToAppend->Blink->Flink = ListHead; ListToAppend->Blink = ListEnd; } FORCEINLINE PSINGLE_LIST_ENTRY PopEntryList( PSINGLE_LIST_ENTRY ListHead ) { PSINGLE_LIST_ENTRY FirstEntry; FirstEntry = ListHead->Next; if (FirstEntry != NULL) { ListHead->Next = FirstEntry->Next; } return FirstEntry; } FORCEINLINE VOID PushEntryList( PSINGLE_LIST_ENTRY ListHead, PSINGLE_LIST_ENTRY Entry ) { Entry->Next = ListHead->Next; ListHead->Next = Entry; } #endif
1,148
1,127
// Copyright (C) 2018-2022 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #include "transformations/common_optimizations/relu_fake_quantize_fusion.hpp" #include <memory> #include <ngraph/opsets/opset5.hpp> #include <ngraph/pattern/op/wrap_type.hpp> #include <ngraph/rt_info.hpp> #include <vector> #include "itt.hpp" #include "transformations/utils/utils.hpp" ngraph::pass::ReluFakeQuantizeFusion::ReluFakeQuantizeFusion() { MATCHER_SCOPE(ReluFakeQuantizeFusion); auto data_pattern = ngraph::pattern::any_input(); auto relu_pattern = ngraph::pattern::wrap_type<opset5::Relu>({data_pattern}, pattern::consumers_count(1)); auto input_low_pattern = ngraph::pattern::wrap_type<opset5::Constant>(); auto fq_pattern = ngraph::pattern::wrap_type<opset5::FakeQuantize>({relu_pattern, input_low_pattern, ngraph::pattern::any_input(), ngraph::pattern::any_input(), ngraph::pattern::any_input()}); ngraph::matcher_pass_callback callback = [=](pattern::Matcher& m) { auto pattern_map = m.get_pattern_value_map(); auto data = pattern_map[data_pattern]; auto relu = pattern_map[relu_pattern]; auto input_low = pattern_map[input_low_pattern]; auto input_low_const = std::dynamic_pointer_cast<opset5::Constant>(input_low.get_node_shared_ptr()); if (!input_low_const) return false; auto input_low_values = input_low_const->cast_vector<float>(); if (std::any_of(input_low_values.begin(), input_low_values.end(), [](float f) -> bool { return f < 0; })) return false; auto fq = std::dynamic_pointer_cast<opset5::FakeQuantize>(pattern_map[fq_pattern].get_node_shared_ptr()); if (!fq) return false; auto new_fq = register_new_node<ngraph::opset5::FakeQuantize>(data, fq->input_value(1), fq->input_value(2), fq->input_value(3), fq->input_value(4), fq->get_levels()); new_fq->set_friendly_name(fq->get_friendly_name()); copy_runtime_info({relu.get_node_shared_ptr(), fq}, new_fq); replace_node(fq, new_fq); MATCHER_SCOPE_ENABLE(ReluFakeQuantizeFusion); return true; }; auto m = std::make_shared<ngraph::pattern::Matcher>(fq_pattern, matcher_name); this->register_matcher(m, callback); }
1,601
313
<reponame>vishalbelsare/RedisGraph /* * Copyright 2018-2022 Redis Labs Ltd. and Contributors * * This file is available under the Redis Labs Source Available License Agreement */ #include "op_skip.h" #include "../../RG.h" #include "../../errors.h" #include "../../arithmetic/arithmetic_expression.h" /* Forward declarations. */ static Record SkipConsume(OpBase *opBase); static OpResult SkipReset(OpBase *opBase); static void SkipFree(OpBase *opBase); static OpBase *SkipClone(const ExecutionPlan *plan, const OpBase *opBase); static void _eval_skip(OpSkip *op, AR_ExpNode *skip_exp) { /* Store a copy of the original expression. * This is required in the case of a parameterized skip: "SKIP $L" * Evaluating the expression will modify it, replacing the parameter with a constant. * As a result, clones of this operation would invalidly resolve to an outdated constant. */ op->skip_exp = AR_EXP_Clone(skip_exp); // Evaluate using the input expression, leaving the stored expression untouched. SIValue s = AR_EXP_Evaluate(skip_exp, NULL); // Validate that the skip value is numeric and non-negative. if(SI_TYPE(s) != T_INT64 || SI_GET_NUMERIC(s) < 0) { ErrorCtx_SetError("Skip operates only on non-negative integers"); } op->skip = SI_GET_NUMERIC(s); // Free the expression we've evaluated. AR_EXP_Free(skip_exp); } OpBase *NewSkipOp(const ExecutionPlan *plan, AR_ExpNode *skip_exp) { OpSkip *op = rm_malloc(sizeof(OpSkip)); op->skip = 0; op->skipped = 0; op->skip_exp = NULL; _eval_skip(op, skip_exp); // set operations OpBase_Init((OpBase *)op, OPType_SKIP, "Skip", NULL, SkipConsume, SkipReset, NULL, SkipClone, SkipFree, false, plan); return (OpBase *)op; } static Record SkipConsume(OpBase *opBase) { OpSkip *skip = (OpSkip *)opBase; OpBase *child = skip->op.children[0]; // As long as we're required to skip while(skip->skipped < skip->skip) { Record discard = OpBase_Consume(child); // Depleted. if(!discard) return NULL; // Discard. OpBase_DeleteRecord(discard); // Advance. skip->skipped++; } return OpBase_Consume(child); } static OpResult SkipReset(OpBase *ctx) { OpSkip *skip = (OpSkip *)ctx; skip->skipped = 0; return OP_OK; } static inline OpBase *SkipClone(const ExecutionPlan *plan, const OpBase *opBase) { ASSERT(opBase->type == OPType_SKIP); OpSkip *op = (OpSkip *)opBase; /* Clone the skip expression stored on the ExecutionPlan, * as we don't want to modify the templated ExecutionPlan * (which may occur if this expression is a parameter). */ AR_ExpNode *skip_exp = AR_EXP_Clone(op->skip_exp); return NewSkipOp(plan, skip_exp); } static void SkipFree(OpBase *opBase) { OpSkip *op = (OpSkip *)opBase; if(op->skip_exp != NULL) { AR_EXP_Free(op->skip_exp); op->skip_exp = NULL; } }
982
768
<gh_stars>100-1000 # Copyright (c) 2020. JetBrains s.r.o. # Use of this source code is governed by the MIT license that can be found in the LICENSE file. import json from .geo_data import get_data_meta, get_map_data_meta from geopandas import GeoDataFrame from shapely.geometry import MultiPolygon, Polygon, LinearRing, Point, mapping from lets_plot._type_utils import _standardize_value from lets_plot.plot import ggplot, geom_polygon POINT = Point(-12.34, 56.78) POLYGON = Polygon( LinearRing([(1, 1), (1, 9), (9, 9), (9, 1)]), [ LinearRing([(2, 2), (3, 2), (3, 3), (2, 3)]), LinearRing([(4, 4), (6, 4), (6, 6), (4, 6)]) ] ) MULTIPOLYGON = MultiPolygon([ POLYGON, Polygon(LinearRing([(11, 12), (13, 14), (15, 16)])) ]) names = ['A', 'B', 'C'] geoms = [POINT, POLYGON, MULTIPOLYGON] EXPECTED_GDF_META = { 'geodataframe': { 'geometry': 'coord' } } def make_geodataframe() -> GeoDataFrame: return GeoDataFrame( data={ 'name': names, 'coord': geoms }, geometry='coord' ) def test_geodataframe_should_be_mapped(): expected_value = { 'name': names, 'coord': [json.dumps(mapping(geom)) for geom in geoms] } assert expected_value == _standardize_value(make_geodataframe()) def test_plot_should_has_meta_data_for_geodataframe(): plot_spec = ggplot() + geom_polygon(data=make_geodataframe()) assert EXPECTED_GDF_META == get_data_meta(plot_spec, 0) def test_plot_should_has_meta_map_for_geodataframe(): plot_spec = ggplot() + geom_polygon(map=make_geodataframe()) assert EXPECTED_GDF_META == get_map_data_meta(plot_spec, 0) def test_when_both_data_and_map_are_gdf_should_has_geodataframe_meta_only_for_map(): plot_spec = ggplot() + geom_polygon(data=make_geodataframe(), map=make_geodataframe()) assert EXPECTED_GDF_META == get_map_data_meta(plot_spec, 0) assert {} == get_data_meta(plot_spec, 0)
869
5,079
#------------------------------------------------------------------------------ # Copyright 2016, 2017, Oracle and/or its affiliates. All rights reserved. # # Portions Copyright 2007-2015, <NAME>. All rights reserved. # # Portions Copyright 2001-2007, Computronix (Canada) Ltd., Edmonton, Alberta, # Canada. All rights reserved. #------------------------------------------------------------------------------ """Module for testing LOB (CLOB and BLOB) variables.""" import sys class TestLobVar(BaseTestCase): def __GetTempLobs(self, sid): cursor = self.connection.cursor() cursor.execute(""" select abstract_lobs from v$temporary_lobs where sid = :sid""", sid = sid) row = cursor.fetchone() if row is None: return 0 return int(row[0]) def __PerformTest(self, lobType, inputType): longString = "" directType = getattr(cx_Oracle, lobType) self.cursor.execute("truncate table Test%ss" % lobType) for i in range(0, 11): if i > 0: char = chr(ord('A') + i - 1) longString += char * 25000 elif inputType != directType: continue self.cursor.setinputsizes(longString = inputType) if lobType == "BLOB" and sys.version_info[0] >= 3: bindValue = longString.encode("ascii") else: bindValue = longString self.cursor.execute(""" insert into Test%ss ( IntCol, %sCol ) values ( :integerValue, :longString )""" % (lobType, lobType), integerValue = i, longString = bindValue) self.connection.commit() self.cursor.execute(""" select * from Test%ss order by IntCol""" % lobType) self.__ValidateQuery(self.cursor, lobType) def __TestLobOperations(self, lobType): self.cursor.execute("truncate table Test%ss" % lobType) self.cursor.setinputsizes(longString = getattr(cx_Oracle, lobType)) longString = "X" * 75000 writeValue = "TEST" if lobType == "BLOB" and sys.version_info[0] >= 3: longString = longString.encode("ascii") writeValue = writeValue.encode("ascii") self.cursor.execute(""" insert into Test%ss ( IntCol, %sCol ) values ( :integerValue, :longString )""" % (lobType, lobType), integerValue = 1, longString = longString) self.cursor.execute(""" select %sCol from Test%ss where IntCol = 1""" % (lobType, lobType)) lob, = self.cursor.fetchone() self.assertEqual(lob.isopen(), False) lob.open() self.assertEqual(lob.isopen(), True) lob.close() self.assertEqual(lob.isopen(), False) self.assertEqual(lob.size(), 75000) lob.write(writeValue, 75001) self.assertEqual(lob.size(), 75000 + len(writeValue)) self.assertEqual(lob.read(), longString + writeValue) lob.write(writeValue, 1) self.assertEqual(lob.read(), writeValue + longString[4:] + writeValue) lob.trim(25000) self.assertEqual(lob.size(), 25000) lob.trim() self.assertEqual(lob.size(), 0) def __TestTemporaryLOB(self, lobType): self.cursor.execute("truncate table Test%ss" % lobType) value = "A test string value" if lobType == "BLOB" and sys.version_info[0] >= 3: value = value.encode("ascii") lobTypeObj = getattr(cx_Oracle, lobType) lob = self.connection.createlob(lobTypeObj) lob.write(value) self.cursor.execute(""" insert into Test%ss (IntCol, %sCol) values (:intVal, :lobVal)""" % (lobType, lobType), intVal = 1, lobVal = lob) self.cursor.execute("select %sCol from Test%ss" % (lobType, lobType)) lob, = self.cursor.fetchone() self.assertEqual(lob.read(), value) def __ValidateQuery(self, rows, lobType): longString = "" for row in rows: integerValue, lob = row if integerValue == 0: self.assertEqual(lob.size(), 0) expectedValue = "" if lobType == "BLOB" and sys.version_info[0] >= 3: expectedValue = expectedValue.encode("ascii") self.assertEqual(lob.read(), expectedValue) else: char = chr(ord('A') + integerValue - 1) prevChar = chr(ord('A') + integerValue - 2) longString += char * 25000 if lobType == "BLOB" and sys.version_info[0] >= 3: actualValue = longString.encode("ascii") char = char.encode("ascii") prevChar = prevChar.encode("ascii") else: actualValue = longString self.assertEqual(lob.size(), len(actualValue)) self.assertEqual(lob.read(), actualValue) if lobType == "CLOB": self.assertEqual(str(lob), actualValue) self.assertEqual(lob.read(len(actualValue)), char) if integerValue > 1: offset = (integerValue - 1) * 25000 - 4 string = prevChar * 5 + char * 5 self.assertEqual(lob.read(offset, 10), string) def testBindLobValue(self): "test binding a LOB value directly" self.cursor.execute("truncate table TestCLOBs") self.cursor.execute("insert into TestCLOBs values (1, 'Short value')") self.cursor.execute("select ClobCol from TestCLOBs") lob, = self.cursor.fetchone() self.cursor.execute("insert into TestCLOBs values (2, :value)", value = lob) def testBLOBCursorDescription(self): "test cursor description is accurate for BLOBs" self.cursor.execute("select * from TestBLOBs") self.assertEqual(self.cursor.description, [ ('INTCOL', cx_Oracle.NUMBER, 10, None, 9, 0, 0), ('BLOBCOL', cx_Oracle.BLOB, None, None, None, None, 0) ]) def testBLOBsDirect(self): "test binding and fetching BLOB data (directly)" self.__PerformTest("BLOB", cx_Oracle.BLOB) def testBLOBsIndirect(self): "test binding and fetching BLOB data (indirectly)" self.__PerformTest("BLOB", cx_Oracle.LONG_BINARY) def testBLOBOperations(self): "test operations on BLOBs" self.__TestLobOperations("BLOB") def testCLOBCursorDescription(self): "test cursor description is accurate for CLOBs" self.cursor.execute("select * from TestCLOBs") self.assertEqual(self.cursor.description, [ ('INTCOL', cx_Oracle.NUMBER, 10, None, 9, 0, 0), ('CLOBCOL', cx_Oracle.CLOB, None, None, None, None, 0) ]) def testCLOBsDirect(self): "test binding and fetching CLOB data (directly)" self.__PerformTest("CLOB", cx_Oracle.CLOB) def testCLOBsIndirect(self): "test binding and fetching CLOB data (indirectly)" self.__PerformTest("CLOB", cx_Oracle.LONG_STRING) def testCLOBOperations(self): "test operations on CLOBs" self.__TestLobOperations("CLOB") def testCreateBlob(self): "test creating a temporary BLOB" self.__TestTemporaryLOB("BLOB") def testCreateClob(self): "test creating a temporary CLOB" self.__TestTemporaryLOB("CLOB") def testCreateNclob(self): "test creating a temporary NCLOB" self.__TestTemporaryLOB("NCLOB") def testMultipleFetch(self): "test retrieving data from a CLOB after multiple fetches" self.cursor.arraysize = 1 self.cursor.execute("select * from TestCLOBS") rows = self.cursor.fetchall() self.__ValidateQuery(rows, "CLOB") def testNCLOBCursorDescription(self): "test cursor description is accurate for NCLOBs" self.cursor.execute("select * from TestNCLOBs") self.assertEqual(self.cursor.description, [ ('INTCOL', cx_Oracle.NUMBER, 10, None, 9, 0, 0), ('NCLOBCOL', cx_Oracle.NCLOB, None, None, None, None, 0) ]) def testNCLOBsDirect(self): "test binding and fetching NCLOB data (directly)" self.__PerformTest("NCLOB", cx_Oracle.NCLOB) def testNCLOBDifferentEncodings(self): "test binding and fetching NCLOB data (different encodings)" connection = cx_Oracle.connect(USERNAME, PASSWORD, TNSENTRY, encoding = "UTF-8", nencoding = "UTF-16") value = u"\u03b4\u4e2a" cursor = connection.cursor() cursor.execute("truncate table TestNCLOBs") cursor.setinputsizes(val = cx_Oracle.NCHAR) cursor.execute("insert into TestNCLOBs values (1, :val)", val = value) cursor.execute("select NCLOBCol from TestNCLOBs") nclob, = cursor.fetchone() cursor.setinputsizes(val = cx_Oracle.NCHAR) cursor.execute("update TestNCLOBs set NCLOBCol = :val", val = nclob.read() + value) cursor.execute("select NCLOBCol from TestNCLOBs") nclob, = cursor.fetchone() self.assertEqual(nclob.read(), value + value) def testNCLOBsIndirect(self): "test binding and fetching NCLOB data (indirectly)" self.__PerformTest("NCLOB", cx_Oracle.LONG_STRING) def testNCLOBOperations(self): "test operations on NCLOBs" self.__TestLobOperations("NCLOB") def testTemporaryLobs(self): "test temporary LOBs" cursor = self.connection.cursor() cursor.arraysize = self.cursor.arraysize cursor.execute(""" select sid from v$session where audsid = userenv('sessionid')""") sid, = cursor.fetchone() tempLobs = self.__GetTempLobs(sid) self.assertEqual(tempLobs, 0) cursor.execute(""" select extract(xmlcol, '/').getclobval() from TestXML""") for lob, in cursor: value = lob.read() del lob cursor.close() tempLobs = self.__GetTempLobs(sid) self.assertEqual(tempLobs, 0) def testAssignStringBeyondArraySize(self): "test assign string to NCLOB beyond array size" nclobVar = self.cursor.var(cx_Oracle.NCLOB) self.assertRaises(IndexError, nclobVar.setvalue, 1, "test char")
5,236
7,892
/********************************************************************** Audacity: A Digital Audio Editor AVFormatContextWrapper.h <NAME> **********************************************************************/ #pragma once #include <cstdint> #include <vector> #include <memory> #include "FFmpegTypes.h" #include "AVIOContextWrapper.h" #include "AVPacketWrapper.h" struct FFmpegFunctions; typedef struct AVFormatContext AVFormatContext; class AVDictionaryWrapper; class AVStreamWrapper; class AVInputFormatWrapper; class AVOutputFormatWrapper; class AVCodecWrapper; class FFMPEG_SUPPORT_API AVFormatContextWrapper { public: using StreamsList = std::vector<std::unique_ptr<AVStreamWrapper>>; AVFormatContextWrapper(const AVFormatContextWrapper&) = delete; AVFormatContextWrapper& operator=(AVFormatContextWrapper&) = delete; AVFormatContextWrapper(AVFormatContextWrapper&&) = delete; AVFormatContextWrapper& operator=(AVFormatContextWrapper&&) = delete; explicit AVFormatContextWrapper( const FFmpegFunctions& ffmpeg) noexcept; //! @return null if OpenInputContext or OpenOutputContext has not been called AVFormatContext* GetWrappedValue() noexcept; //! @return null if OpenInputContext or OpenOutputContext has not been called const AVFormatContext* GetWrappedValue() const noexcept; virtual ~AVFormatContextWrapper(); AVIOContextWrapper::OpenResult OpenInputContext(const wxString& path, const AVInputFormatWrapper* inputFormat, AVDictionaryWrapper options); AVIOContextWrapper::OpenResult OpenOutputContext(const wxString& path); //! @return is null at end of stream std::unique_ptr<AVPacketWrapper> ReadNextPacket(); std::unique_ptr<AVStreamWrapper> CreateStream(); const AVInputFormatWrapper* GetInputFormat() const noexcept; const AVOutputFormatWrapper* GetOutputFormat() const noexcept; virtual void SetOutputFormat(std::unique_ptr<AVOutputFormatWrapper> oformat) noexcept = 0; virtual AVIOContextWrapper* GetAVIOContext() const noexcept = 0; virtual void SetAVIOContext(std::unique_ptr<AVIOContextWrapper> pb) noexcept = 0; virtual int GetCtxFlags() const noexcept = 0; virtual unsigned int GetStreamsCount() const noexcept = 0; virtual const StreamsList& GetStreams() const noexcept = 0; virtual const AVStreamWrapper* GetStream(int index) const noexcept; virtual const char* GetFilename() const noexcept = 0; virtual void SetFilename(const char* filename) noexcept = 0; virtual int64_t GetStartTime() const noexcept = 0; virtual int64_t GetDuration() const noexcept = 0; virtual int GetBitRate() const noexcept = 0; virtual void SetBitRate(int bit_rate) noexcept = 0; virtual unsigned int GetPacketSize() const noexcept = 0; virtual void SetPacketSize(unsigned int packet_size) noexcept = 0; virtual int GetMaxDelay() const noexcept = 0; virtual void SetMaxDelay(int max_delay) noexcept = 0; virtual int GetFlags() const noexcept = 0; virtual void SetFlags(int flags) noexcept = 0; virtual unsigned int GetProbeSize() const noexcept = 0; virtual void SetProbeSize(unsigned int probesize) noexcept = 0; virtual int GetMaxAnalyzeDuration() const noexcept = 0; virtual void SetMaxAnalyzeDuration(int max_analyze_duration) noexcept = 0; virtual AVCodecIDFwd GetAudioCodecId() const noexcept = 0; virtual void SetAudioCodecId(AVCodecIDFwd audio_codec_id) noexcept = 0; virtual unsigned int GetMaxIndexSize() const noexcept = 0; virtual void SetMaxIndexSize(unsigned int max_index_size) noexcept = 0; virtual AVDictionaryWrapper GetMetadata() const noexcept = 0; virtual void SetMetadata(AVDictionaryWrapper metadata) noexcept = 0; virtual int64_t GetStartTimeRealtime() const noexcept = 0; virtual void SetStartTimeRealtime(int64_t start_time_realtime) noexcept = 0; virtual int GetFpsProbeSize() const noexcept = 0; virtual void SetFpsProbeSize(int fps_probe_size) noexcept = 0; virtual int GetErrorRecognition() const noexcept = 0; virtual void SetErrorRecognition(int error_recognition) noexcept = 0; virtual int64_t GetMaxInterleaveDelta() const noexcept = 0; virtual void SetMaxInterleaveDelta(int64_t max_interleave_delta) noexcept = 0; virtual int GetStrictStdCompliance() const noexcept = 0; virtual void SetStrictStdCompliance(int strict_std_compliance) noexcept = 0; virtual int GetAudioPreload() const noexcept = 0; virtual void SetAudioPreload(int audio_preload) noexcept = 0; virtual int GetMaxChunkDuration() const noexcept = 0; virtual void SetMaxChunkDuration(int max_chunk_duration) noexcept = 0; virtual int GetMaxChunkSize() const noexcept = 0; virtual void SetMaxChunkSize(int max_chunk_size) noexcept = 0; virtual int GetUseWallclockAsTimestamps() const noexcept = 0; virtual void SetUseWallclockAsTimestamps(int use_wallclock_as_timestamps) noexcept = 0; virtual int GetAvoidNegativeTs() const noexcept = 0; virtual void SetAvoidNegativeTs(int avoid_negative_ts) noexcept = 0; virtual int GetAvioFlags() const noexcept = 0; virtual void SetAvioFlags(int avio_flags) noexcept = 0; virtual int64_t GetSkipInitialBytes() const noexcept = 0; virtual void SetSkipInitialBytes(int64_t skip_initial_bytes) noexcept = 0; virtual unsigned int GetCorrectTsOverflow() const noexcept = 0; virtual void SetCorrectTsOverflow(unsigned int correct_ts_overflow) noexcept = 0; virtual int GetSeek2any() const noexcept = 0; virtual void SetSeek2any(int seek2any) noexcept = 0; virtual int GetFlushPackets() const noexcept = 0; virtual void SetFlushPackets(int flush_packets) noexcept = 0; virtual int GetProbeScore() const noexcept = 0; virtual int GetFormatProbeSize() const noexcept = 0; virtual void SetFormatProbeSize(int format_probesize) noexcept = 0; virtual AVCodecWrapper* GetAudioCodec() const noexcept = 0; virtual void SetAudioCodec( std::unique_ptr<AVCodecWrapper> audio_codec) noexcept = 0; virtual void* GetOpaque() const noexcept = 0; virtual void SetOpaque(void* opaque) noexcept = 0; virtual int64_t GetOutputTsOffset() const noexcept = 0; virtual void SetOutputTsOffset(int64_t output_ts_offset) noexcept = 0; protected: virtual AVInputFormat* GetIFormat() const noexcept = 0; virtual AVOutputFormat* GetOFormat() const noexcept = 0; virtual void UpdateStreamList() noexcept = 0; const FFmpegFunctions& mFFmpeg; AVFormatContext* mAVFormatContext { nullptr }; std::unique_ptr<AVIOContextWrapper> mAVIOContext; StreamsList mStreams; std::unique_ptr<AVInputFormatWrapper> mInputFormat; std::unique_ptr<AVOutputFormatWrapper> mOutputFormat; std::unique_ptr<AVCodecWrapper> mForcedAudioCodec; };
2,113
1,199
Fix with Qt5-5.14 Obtained from: https://github.com/quassel/quassel/commit/579e559a6322209df7cd51c34801fecff5fe734b --- src/common/types.h.orig 2020-04-04 10:50:56 UTC +++ src/common/types.h @@ -140,6 +140,7 @@ Q_DECLARE_METATYPE(QHostAddress) typedef QList<MsgId> MsgIdList; typedef QList<BufferId> BufferIdList; +#if QT_VERSION < QT_VERSION_CHECK(5, 14, 0) /** * Catch-all stream serialization operator for enum types. * @@ -169,6 +170,7 @@ QDataStream &operator>>(QDataStream &in, T &value) { value = static_cast<T>(v); return in; } +#endif // Exceptions
250
602
<reponame>the1042/cookiecutter-django import datetime as dt import os import re from pathlib import Path from typing import Iterable import git import github.PullRequest import github.Repository from github import Github from jinja2 import Template CURRENT_FILE = Path(__file__) ROOT = CURRENT_FILE.parents[1] GITHUB_TOKEN = os.getenv("GITHUB_TOKEN") GITHUB_REPO = os.getenv("GITHUB_REPOSITORY") GIT_BRANCH = os.getenv("GITHUB_REF_NAME") def main() -> None: """ Script entry point. """ # Generate changelog for PRs merged yesterday merged_date = dt.date.today() - dt.timedelta(days=1) repo = Github(login_or_token=GITHUB_TOKEN).get_repo(GITHUB_REPO) merged_pulls = list(iter_pulls(repo, merged_date)) print(f"Merged pull requests: {merged_pulls}") if not merged_pulls: print("Nothing was merged, existing.") return # Group pull requests by type of change grouped_pulls = group_pulls_by_change_type(merged_pulls) # Generate portion of markdown release_changes_summary = generate_md(grouped_pulls) print(f"Summary of changes: {release_changes_summary}") # Update CHANGELOG.md file release = f"{merged_date:%Y.%m.%d}" changelog_path = ROOT / "CHANGELOG.md" write_changelog(changelog_path, release, release_changes_summary) print(f"Wrote {changelog_path}") # Update version setup_py_path = ROOT / "setup.py" update_version(setup_py_path, release) print(f"Updated version in {setup_py_path}") # Commit changes, create tag and push update_git_repo([changelog_path, setup_py_path], release) # Create GitHub release github_release = repo.create_git_release( tag=release, name=release, message=release_changes_summary, ) print(f"Created release on GitHub {github_release}") def iter_pulls( repo: github.Repository.Repository, merged_date: dt.date, ) -> Iterable[github.PullRequest.PullRequest]: """Fetch merged pull requests at the date we're interested in.""" recent_pulls = repo.get_pulls( state="closed", sort="updated", direction="desc", ).get_page(0) for pull in recent_pulls: if pull.merged and pull.merged_at.date() == merged_date: yield pull def group_pulls_by_change_type( pull_requests_list: list[github.PullRequest.PullRequest], ) -> dict[str, list[github.PullRequest.PullRequest]]: """Group pull request by change type.""" grouped_pulls = { "Changed": [], "Fixed": [], "Updated": [], } for pull in pull_requests_list: label_names = {label.name for label in pull.labels} if "update" in label_names: group_name = "Updated" elif "bug" in label_names: group_name = "Fixed" else: group_name = "Changed" grouped_pulls[group_name].append(pull) return grouped_pulls def generate_md(grouped_pulls: dict[str, list[github.PullRequest.PullRequest]]) -> str: """Generate markdown file from Jinja template.""" changelog_template = ROOT / ".github" / "changelog-template.md" template = Template(changelog_template.read_text(), autoescape=True) return template.render(grouped_pulls=grouped_pulls) def write_changelog(file_path: Path, release: str, content: str) -> None: """Write Release details to the changelog file.""" content = f"## {release}\n{content}" old_content = file_path.read_text() updated_content = old_content.replace( "<!-- GENERATOR_PLACEHOLDER -->", f"<!-- GENERATOR_PLACEHOLDER -->\n\n{content}", ) file_path.write_text(updated_content) def update_version(file_path: Path, release: str) -> None: """Update template version in setup.py.""" old_content = file_path.read_text() updated_content = re.sub( r'\nversion = "\d+\.\d+\.\d+"\n', f'\nversion = "{release}"\n', old_content, ) file_path.write_text(updated_content) def update_git_repo(paths: list[Path], release: str) -> None: """Commit, tag changes in git repo and push to origin.""" repo = git.Repo(ROOT) for path in paths: repo.git.add(path) message = f"Release {release}" user = repo.git.config("--get", "user.name") email = repo.git.config("--get", "user.email") repo.git.commit( m=message, author=f"{user} <{email}>", ) repo.git.tag("-a", release, m=message) server = f"https://{GITHUB_TOKEN}@github.com/{GITHUB_REPO}.git" print(f"Pushing changes to {GIT_BRANCH} branch of {GITHUB_REPO}") repo.git.push(server, GIT_BRANCH) repo.git.push("--tags", server, GIT_BRANCH) if __name__ == "__main__": if GITHUB_REPO is None: raise RuntimeError( "No github repo, please set the environment variable GITHUB_REPOSITORY" ) if GIT_BRANCH is None: raise RuntimeError( "No git branch set, please set the GITHUB_REF_NAME environment variable" ) main()
2,065
1,443
{ "copyright": "<NAME>", "url": "https://github.com/DamonOehlman", "email": "<EMAIL>" }
42
586
<filename>tests/test_ipv4.py # -*- coding: utf-8 -*- import pytest from validators import ipv4, ipv6, ValidationFailure @pytest.mark.parametrize(('address',), [ ('127.0.0.1',), ('192.168.127.12',), ('12.12.12.12',), ]) def test_returns_true_on_valid_ipv4_address(address): assert ipv4(address) assert not ipv6(address) @pytest.mark.parametrize(('address',), [ ('abc.0.0.1',), ('1278.0.0.1',), ('127.0.0.abc',), ('900.200.100.75',), ]) def test_returns_failed_validation_on_invalid_ipv4_address(address): assert isinstance(ipv4(address), ValidationFailure)
274
764
{"symbol": "DOOH","address": "0x18C525cce3ad9A48D82F91B874754be78E9d0F85","overview":{"en": ""},"email": "<EMAIL>","website": "https://bidooh.io/","state": "NORMAL","links": {"blog": "","twitter": "","telegram": "https://t.me/bidoohio","github": "https://github.com/Bidooh"}}
114
1,848
<reponame>pcwalton/rust-bindgen // bindgen-flags: --bitfield-enum "Foo" --rust-target 1.28 -- -std=c++11 enum Foo { Bar = 1 << 1, Baz = 1 << 2, Duplicated = 1 << 2, Negative = -3, };
84
413
<reponame>DaanDeMeyer/cpp-process-library<gh_stars>100-1000 #include <reproc/run.h> #include "assert.h" int main(void) { const char *argv[] = { RESOURCE_DIRECTORY "/overflow", NULL }; char *output = NULL; reproc_sink sink = reproc_sink_string(&output); int r = -1; r = reproc_run_ex(argv, (reproc_options){ 0 }, sink, sink); ASSERT_OK(r); ASSERT(output != NULL); reproc_free(output); }
167
3,070
from dataclasses import dataclass import multiprocessing from io import StringIO from unittest import mock from typing import List from pytest_cov.embed import cleanup_on_sigterm import pytest from outrun.rpc import Client, Encoding, InvalidTokenError, Server def start_server_process(server: Server) -> multiprocessing.Process: def run_server(): cleanup_on_sigterm() server.serve("tcp://127.0.0.1:8000") proc = multiprocessing.Process(target=run_server) proc.start() return proc def test_call(): class Service: @staticmethod def add(a, b): return a + b server = Server(Service()) server_process = start_server_process(server) try: client = Client(Service, "tcp://127.0.0.1:8000", timeout_ms=1000) assert client.add(3, 5) == 8 finally: server_process.terminate() server_process.join() def test_nonexistent_call(): class Service: pass server = Server(Service()) server_process = start_server_process(server) try: client = Client(Service, "tcp://127.0.0.1:8000", timeout_ms=1000) with pytest.raises(AttributeError): client.foo() finally: server_process.terminate() server_process.join() def test_successful_ping(): class Service: pass server = Server(Service()) server_process = start_server_process(server) try: client = Client(Service, "tcp://127.0.0.1:8000", timeout_ms=1000) client.ping() finally: server_process.terminate() server_process.join() def test_failing_ping_with_custom_timeout(): class Service: pass client = Client(Service, "tcp://127.0.0.1:8000", timeout_ms=-1) with pytest.raises(IOError): client.ping(timeout_ms=1) def test_timeout(): class Service: pass client = Client(Service, "tcp://127.0.0.1:8000", timeout_ms=1) with pytest.raises(IOError): client.foo() def test_socket_per_thread(): class Service: pass server = Server(Service()) server_process = start_server_process(server) try: client = Client(Service, "tcp://127.0.0.1:8000", timeout_ms=1000) with mock.patch("threading.current_thread") as m: m.return_value = 1 client.ping() m.return_value = 2 client.ping() assert client.socket_count == 2 finally: server_process.terminate() server_process.join() def test_tuple_serialization(): class Service: @staticmethod def get_tuple(): return (1, 2, 3) server = Server(Service()) server_process = start_server_process(server) try: client = Client(Service, "tcp://127.0.0.1:8000", timeout_ms=1000) # tuples are serialized as lists assert client.get_tuple() == [1, 2, 3] finally: server_process.terminate() server_process.join() def test_dataclasses(): @dataclass class Point: x: int y: int @dataclass class Line: p1: Point p2: Point class Service: @staticmethod def make_line(p1: Point, p2: Point) -> Line: return Line(p1, p2) server = Server(Service()) server_process = start_server_process(server) try: client = Client(Service, "tcp://127.0.0.1:8000", timeout_ms=1000) p1 = Point(1, 2) p2 = Point(3, 4) assert client.make_line(p1, p2) == Line(p1, p2) finally: server_process.terminate() server_process.join() def test_dataclass_in_container_type(): @dataclass class Point: x: int y: int class Service: @staticmethod def make_point_list(x: int, y: int) -> List[Point]: return [Point(x, y)] server = Server(Service()) server_process = start_server_process(server) try: client = Client(Service, "tcp://127.0.0.1:8000", timeout_ms=1000) assert client.make_point_list(1, 2) == [Point(1, 2)] finally: server_process.terminate() server_process.join() def test_builtin_exceptions(): class Service: @staticmethod def os_failure(): raise OSError("foo") @staticmethod def value_failure(): raise ValueError("bar") server = Server(Service()) server_process = start_server_process(server) try: client = Client(Service, "tcp://127.0.0.1:8000", timeout_ms=1000) with pytest.raises(OSError) as e: client.os_failure() assert e.value.args == ("foo",) with pytest.raises(ValueError) as e: client.value_failure() assert e.value.args == ("bar",) finally: server_process.terminate() server_process.join() def test_custom_exception(): class CustomException(Exception): pass class Service: @staticmethod def custom_failure(): raise CustomException("a", "b", "c") server = Server(Service()) server_process = start_server_process(server) try: client = Client(Service, "tcp://127.0.0.1:8000", timeout_ms=1000) with pytest.raises(Exception) as e: client.custom_failure() assert e.value.args == ("a", "b", "c") finally: server_process.terminate() server_process.join() def test_missing_token(): class Service: pass server = Server(Service(), token="<PASSWORD>") server_process = start_server_process(server) try: client = Client(Service, "tcp://127.0.0.1:8000", timeout_ms=1000) with pytest.raises(InvalidTokenError): client.ping() finally: server_process.terminate() server_process.join() def test_invalid_token(): class Service: pass server = Server(Service(), token="<PASSWORD>") server_process = start_server_process(server) try: client = Client(Service, "tcp://127.0.0.1:8000", token="<PASSWORD>", timeout_ms=1000) with pytest.raises(InvalidTokenError): client.ping() finally: server_process.terminate() server_process.join() def test_valid_token(): class Service: pass server = Server(Service(), token="<PASSWORD>") server_process = start_server_process(server) try: client = Client(Service, "tcp://127.0.0.1:8000", token="<PASSWORD>", timeout_ms=1000) client.ping() finally: server_process.terminate() server_process.join() def test_json_encoding_dataclasses(): @dataclass class Point: x: int y: int @dataclass class Line: p1: Point p2: Point encoding = Encoding(Line) obj_in = ["abc", True, Line(Point(1, 2), Point(3, 4)), Point(5, 6)] io = StringIO() encoding.dump_json(obj_in, io) io.seek(0) obj_out = encoding.load_json(io) assert obj_in == obj_out def test_json_encoding_exceptions(): encoding = Encoding() exceptions_in = [OSError("a", "b"), TypeError("c"), NotImplementedError()] io = StringIO() encoding.dump_json(exceptions_in, io) io.seek(0) exceptions_out = encoding.load_json(io) with pytest.raises(OSError) as e: raise exceptions_out[0] assert e.value.args == ("a", "b") with pytest.raises(TypeError) as e: raise exceptions_out[1] assert e.value.args == ("c",) with pytest.raises(NotImplementedError) as e: raise exceptions_out[2] assert e.value.args == () def test_unserializable_object(): encoding = Encoding() with pytest.raises(ValueError): encoding.serialize_obj(set()) def test_deserialize_unknown_dataclass(): @dataclass class Point: x: int y: int encoding = Encoding(Point) serialized = encoding.serialize_obj(Point(1, 2)) with pytest.raises(TypeError): encoding = Encoding() encoding.deserialize_obj(serialized)
3,530
351
<filename>src/network/time.hpp /** * > Author: UncP * > Github: www.github.com/UncP/Mushroom * > License: BSD-3 * > Time: 2017-05-14 21:19:07 **/ #ifndef _TIME_HPP_ #define _TIME_HPP_ #include <sys/time.h> namespace Mushroom { class Time { public: static int64_t Now() { return NowMicro() / 1000; } static int64_t NowMicro() { struct timeval tv; gettimeofday(&tv, 0); return (int64_t(tv.tv_sec) * 1000000 + tv.tv_usec); } }; } // namespace Mushroom #endif /* _TIME_HPP_ */
251
3,262
/* * Tencent is pleased to support the open source community by making Angel available. * * Copyright (C) 2017-2018 THL A29 Limited, a Tencent company. 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 * * https://opensource.org/licenses/Apache-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.tencent.angel.ps.storage.partition.op; import com.tencent.angel.ps.storage.vector.ServerRow; import java.util.Iterator; import java.util.List; import java.util.Map.Entry; /** * Basic operation for Row-based storage */ public interface IServerRowsStorageOp { /** * Get the server row from storage use row id * @param rowId row id * @return server row */ ServerRow getRow(int rowId); /** * Get batch of server rows use row ids * @param rowIds row ids * @return batch of server rows */ List<ServerRow> getRows(List<Integer> rowIds); /** * Put the server row to the storage * @param rowId row id * @param row server row */ void putRow(int rowId, ServerRow row); /** * Put the server rows to the storage * @param rowIds row ids * @param rows server rows */ void putRows(List<Integer> rowIds, List<ServerRow> rows); /** * Get the row number * @return the row number */ int getRowNum(); /** * Is the server row exist * @param rowId row id * @return True means exist */ boolean hasRow(int rowId); /** * Get the <row id, server row> iterator * @return the <row id, server row> iterator */ Iterator<Entry<Integer, ServerRow>> iterator(); }
619
770
// Copyright (C) 2014 The Regents of the University of California (Regents). // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following // disclaimer in the documentation and/or other materials provided // with the distribution. // // * Neither the name of The Regents or University of California 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 HOLDERS 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. // // Please contact the author of this library if you have any questions. // Author: <NAME> (<EMAIL>) #ifndef THEIA_SFM_POSE_SIM_TRANSFORM_PARTIAL_ROTATION_H_ #define THEIA_SFM_POSE_SIM_TRANSFORM_PARTIAL_ROTATION_H_ #include <Eigen/Core> #include <Eigen/Geometry> #include <vector> namespace theia { // Solves for the similarity transformation that will transform rays in image // two such that the intersect with rays in image one such that: // s * R * X' + t = X // where s, R, t are the scale, rotation, and translation returned, X' is a // point in coordinate system 2 and X is the point transformed back to // coordinate system 1. Up to 8 solutions will be returned. // // Please cite the paper "Computing Similarity Transformations from Only Image // Correspondences" by <NAME> et al (CVPR 2015) when using this algorithm. void SimTransformPartialRotation( const Eigen::Vector3d& rotation_axis, const Eigen::Vector3d image_one_ray_directions[5], const Eigen::Vector3d image_one_ray_origins[5], const Eigen::Vector3d image_two_ray_directions[5], const Eigen::Vector3d image_two_ray_origins[5], std::vector<Eigen::Quaterniond>* soln_rotations, std::vector<Eigen::Vector3d>* soln_translations, std::vector<double>* soln_scales); } // namespace theia #endif // THEIA_SFM_POSE_SIM_TRANSFORM_PARTIAL_ROTATION_H_
944
317
<gh_stars>100-1000 #include "base.hpp" VkResult gl_base::createInstance(bool enableValidation) { this->enableValidation = enableValidation; VkApplicationInfo appInfo = {}; appInfo.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO; appInfo.pApplicationName = name.c_str(); appInfo.pEngineName = name.c_str(); appInfo.apiVersion = VK_API_VERSION_1_0; std::vector<const char*> enabledExtensions = { VK_KHR_SURFACE_EXTENSION_NAME }; enabledExtensions.push_back(VK_KHR_WIN32_SURFACE_EXTENSION_NAME); VkInstanceCreateInfo instanceCreateInfo = {}; instanceCreateInfo.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO; instanceCreateInfo.pNext = NULL; instanceCreateInfo.pApplicationInfo = &appInfo; if (enabledExtensions.size() > 0) { if (enableValidation) { enabledExtensions.push_back(VK_EXT_DEBUG_REPORT_EXTENSION_NAME); } instanceCreateInfo.enabledExtensionCount = (uint32_t)enabledExtensions.size(); instanceCreateInfo.ppEnabledExtensionNames = enabledExtensions.data(); } if (enableValidation) { instanceCreateInfo.enabledLayerCount = vkDebug::validationLayerCount; instanceCreateInfo.ppEnabledLayerNames = vkDebug::validationLayerNames; } return vkCreateInstance(&instanceCreateInfo, nullptr, &instance); } std::string gl_base::getWindowTitle() { std::string device(deviceProperties.deviceName); std::string windowTitle = title + " - " + device + " - " + std::to_string(frameCounter) + " fps"; return windowTitle; } const std::string gl_base::getAssetPath() { return std::string(SOURCE_DIR) + "/data/"; } void gl_base::createSetupCommandBuffer() { if (setupCmdBuffer != VK_NULL_HANDLE) { vkFreeCommandBuffers(device, cmdPool, 1, &setupCmdBuffer); setupCmdBuffer = VK_NULL_HANDLE; } VkCommandBufferAllocateInfo cmdBufAllocateInfo = vkTools::initializers::commandBufferAllocateInfo( cmdPool, VK_COMMAND_BUFFER_LEVEL_PRIMARY, 1); VK_CHECK_RESULT(vkAllocateCommandBuffers(device, &cmdBufAllocateInfo, &setupCmdBuffer)); VkCommandBufferBeginInfo cmdBufInfo = {}; cmdBufInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO; VK_CHECK_RESULT(vkBeginCommandBuffer(setupCmdBuffer, &cmdBufInfo)); } void gl_base::flushSetupCommandBuffer() { if (setupCmdBuffer == VK_NULL_HANDLE) return; VK_CHECK_RESULT(vkEndCommandBuffer(setupCmdBuffer)); VkSubmitInfo submitInfo = {}; submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO; submitInfo.commandBufferCount = 1; submitInfo.pCommandBuffers = &setupCmdBuffer; VK_CHECK_RESULT(vkQueueSubmit(queue, 1, &submitInfo, VK_NULL_HANDLE)); VK_CHECK_RESULT(vkQueueWaitIdle(queue)); vkFreeCommandBuffers(device, cmdPool, 1, &setupCmdBuffer); setupCmdBuffer = VK_NULL_HANDLE; } VkCommandBuffer gl_base::createCommandBuffer(VkCommandBufferLevel level, bool begin) { VkCommandBuffer cmdBuffer; VkCommandBufferAllocateInfo cmdBufAllocateInfo = vkTools::initializers::commandBufferAllocateInfo( cmdPool, level, 1); VK_CHECK_RESULT(vkAllocateCommandBuffers(device, &cmdBufAllocateInfo, &cmdBuffer)); if (begin) { VkCommandBufferBeginInfo cmdBufInfo = vkTools::initializers::commandBufferBeginInfo(); VK_CHECK_RESULT(vkBeginCommandBuffer(cmdBuffer, &cmdBufInfo)); } return cmdBuffer; } void gl_base::flushCommandBuffer(VkCommandBuffer commandBuffer, VkQueue queue, bool free) { if (commandBuffer == VK_NULL_HANDLE) return; VK_CHECK_RESULT(vkEndCommandBuffer(commandBuffer)); VkSubmitInfo submitInfo = {}; submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO; submitInfo.commandBufferCount = 1; submitInfo.pCommandBuffers = &commandBuffer; VK_CHECK_RESULT(vkQueueSubmit(queue, 1, &submitInfo, VK_NULL_HANDLE)); VK_CHECK_RESULT(vkQueueWaitIdle(queue)); if (free) { vkFreeCommandBuffers(device, cmdPool, 1, &commandBuffer); } } void gl_base::createPipelineCache() { VkPipelineCacheCreateInfo pipelineCacheCreateInfo = {}; pipelineCacheCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO; VK_CHECK_RESULT(vkCreatePipelineCache(device, &pipelineCacheCreateInfo, nullptr, &pipelineCache)); } void gl_base::prepare() { if (vulkanDevice->enableDebugMarkers) { vkDebug::DebugMarker::setup(device); } createCommandPool(); createSetupCommandBuffer(); setupSwapChain(); setupDepthStencil(); setupRenderPass(); createPipelineCache(); setupFrameBuffer(); flushSetupCommandBuffer(); createSetupCommandBuffer(); textureLoader = new vkTools::VulkanTextureLoader(vulkanDevice, queue, cmdPool); } VkPipelineShaderStageCreateInfo gl_base::loadShader(std::string fileName, VkShaderStageFlagBits stage) { VkPipelineShaderStageCreateInfo shaderStage = {}; shaderStage.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO; shaderStage.stage = stage; shaderStage.module = vkTools::loadShader(fileName.c_str(), device, stage); shaderStage.pName = "main"; assert(shaderStage.module != NULL); shaderModules.push_back(shaderStage.module); return shaderStage; } VkBool32 gl_base::createBuffer(VkBufferUsageFlags usageFlags, VkMemoryPropertyFlags memoryPropertyFlags, VkDeviceSize size, void * data, VkBuffer * buffer, VkDeviceMemory * memory) { VkMemoryRequirements memReqs; VkMemoryAllocateInfo memAlloc = vkTools::initializers::memoryAllocateInfo(); VkBufferCreateInfo bufferCreateInfo = vkTools::initializers::bufferCreateInfo(usageFlags, size); VK_CHECK_RESULT(vkCreateBuffer(device, &bufferCreateInfo, nullptr, buffer)); vkGetBufferMemoryRequirements(device, *buffer, &memReqs); memAlloc.allocationSize = memReqs.size; memAlloc.memoryTypeIndex = vulkanDevice->getMemoryType(memReqs.memoryTypeBits, memoryPropertyFlags); VK_CHECK_RESULT(vkAllocateMemory(device, &memAlloc, nullptr, memory)); if (data != nullptr) { void *mapped; VK_CHECK_RESULT(vkMapMemory(device, *memory, 0, size, 0, &mapped)); memcpy(mapped, data, size); vkUnmapMemory(device, *memory); } VK_CHECK_RESULT(vkBindBufferMemory(device, *buffer, *memory, 0)); return true; } VkBool32 gl_base::createBuffer(VkBufferUsageFlags usage, VkDeviceSize size, void * data, VkBuffer *buffer, VkDeviceMemory *memory) { return createBuffer(usage, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT, size, data, buffer, memory); } VkBool32 gl_base::createBuffer(VkBufferUsageFlags usage, VkDeviceSize size, void * data, VkBuffer * buffer, VkDeviceMemory * memory, VkDescriptorBufferInfo * descriptor) { VkBool32 res = createBuffer(usage, size, data, buffer, memory); if (res) { descriptor->offset = 0; descriptor->buffer = *buffer; descriptor->range = size; return true; } else { return false; } } VkBool32 gl_base::createBuffer(VkBufferUsageFlags usage, VkMemoryPropertyFlags memoryPropertyFlags, VkDeviceSize size, void * data, VkBuffer * buffer, VkDeviceMemory * memory, VkDescriptorBufferInfo * descriptor) { VkBool32 res = createBuffer(usage, memoryPropertyFlags, size, data, buffer, memory); if (res) { descriptor->offset = 0; descriptor->buffer = *buffer; descriptor->range = size; return true; } else { return false; } } void gl_base::renderLoop() { destWidth = width; destHeight = height; MSG msg; while (TRUE) { auto tStart = std::chrono::high_resolution_clock::now(); if (viewUpdated) { viewUpdated = false; viewChanged(); } while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) { TranslateMessage(&msg); DispatchMessage(&msg); } if (msg.message == WM_QUIT) { break; } render(); frameCounter++; auto tEnd = std::chrono::high_resolution_clock::now(); auto tDiff = std::chrono::duration<double, std::milli>(tEnd - tStart).count(); frameTimer = (float)tDiff / 1000.0f; camera.update(frameTimer); if (camera.moving()) { viewUpdated = true; } if (!paused) { timer += timerSpeed * frameTimer; if (timer > 1.0) { timer -= 1.0f; } } fpsTimer += (float)tDiff; if (fpsTimer > 1000.0f) { std::string windowTitle = getWindowTitle(); SetWindowText(window, windowTitle.c_str()); lastFPS = glm::iround(1.0f / frameTimer); fpsTimer = 0.0f; frameCounter = 0; } } vkDeviceWaitIdle(device); } gl_base::gl_base(bool enableValidation, PFN_GetEnabledFeatures enabledFeaturesFn) { for (int32_t i = 0; i < __argc; i++) { if (__argv[i] == std::string("-validation")) enableValidation = true; if (__argv[i] == std::string("-vsync")) enableVSync = true; } if (enabledFeaturesFn != nullptr) this->enabledFeatures = enabledFeaturesFn(); if (enableValidation) setupConsole("VulkanExample"); initVulkan(enableValidation); } gl_base::~gl_base() { Swapchain.cleanup(); if (descriptorPool != VK_NULL_HANDLE) { vkDestroyDescriptorPool(device, descriptorPool, nullptr); } if (setupCmdBuffer != VK_NULL_HANDLE) { vkFreeCommandBuffers(device, cmdPool, 1, &setupCmdBuffer); } vkDestroyRenderPass(device, renderPass, nullptr); for (uint32_t i = 0; i < frameBuffers.size(); i++) { vkDestroyFramebuffer(device, frameBuffers[i], nullptr); } for (auto& shaderModule : shaderModules) { vkDestroyShaderModule(device, shaderModule, nullptr); } vkDestroyImageView(device, depthStencil.view, nullptr); vkDestroyImage(device, depthStencil.image, nullptr); vkFreeMemory(device, depthStencil.mem, nullptr); vkDestroyPipelineCache(device, pipelineCache, nullptr); if (textureLoader) { delete textureLoader; } vkDestroyCommandPool(device, cmdPool, nullptr); vkDestroySemaphore(device, semaphores.presentComplete, nullptr); vkDestroySemaphore(device, semaphores.renderComplete, nullptr); vkDestroySemaphore(device, semaphores.textOverlayComplete, nullptr); delete vulkanDevice; if (enableValidation) { vkDebug::freeDebugCallback(instance); } vkDestroyInstance(instance, nullptr); } void gl_base::initVulkan(bool enableValidation) { VkResult err; err = createInstance(enableValidation); if (err) { vkTools::exitFatal("Could not create Vulkan instance : \n" + vkTools::errorString(err), "Fatal error"); } if (enableValidation) { VkDebugReportFlagsEXT debugReportFlags = VK_DEBUG_REPORT_ERROR_BIT_EXT; // | VK_DEBUG_REPORT_WARNING_BIT_EXT | VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT; vkDebug::setupDebugging(instance, debugReportFlags, VK_NULL_HANDLE); } uint32_t gpuCount = 0; VK_CHECK_RESULT(vkEnumeratePhysicalDevices(instance, &gpuCount, nullptr)); assert(gpuCount > 0); std::vector<VkPhysicalDevice> physicalDevices(gpuCount); err = vkEnumeratePhysicalDevices(instance, &gpuCount, physicalDevices.data()); if (err) { vkTools::exitFatal("Could not enumerate phyiscal devices : \n" + vkTools::errorString(err), "Fatal error"); } physicalDevice = physicalDevices[0]; vulkanDevice = new vk::VulkanDevice(physicalDevice); VK_CHECK_RESULT(vulkanDevice->createLogicalDevice(enabledFeatures)); device = vulkanDevice->logicalDevice; vkGetPhysicalDeviceProperties(physicalDevice, &deviceProperties); vkGetPhysicalDeviceFeatures(physicalDevice, &deviceFeatures); vkGetPhysicalDeviceMemoryProperties(physicalDevice, &deviceMemoryProperties); vkGetDeviceQueue(device, vulkanDevice->queueFamilyIndices.graphics, 0, &queue); VkBool32 validDepthFormat = vkTools::getSupportedDepthFormat(physicalDevice, &depthFormat); assert(validDepthFormat); Swapchain.connect(instance, physicalDevice, device); VkSemaphoreCreateInfo semaphoreCreateInfo = vkTools::initializers::semaphoreCreateInfo(); VK_CHECK_RESULT(vkCreateSemaphore(device, &semaphoreCreateInfo, nullptr, &semaphores.presentComplete)); VK_CHECK_RESULT(vkCreateSemaphore(device, &semaphoreCreateInfo, nullptr, &semaphores.renderComplete)); VK_CHECK_RESULT(vkCreateSemaphore(device, &semaphoreCreateInfo, nullptr, &semaphores.textOverlayComplete)); submitInfo = vkTools::initializers::submitInfo(); submitInfo.pWaitDstStageMask = &submitPipelineStages; submitInfo.waitSemaphoreCount = 1; submitInfo.pWaitSemaphores = &semaphores.presentComplete; submitInfo.signalSemaphoreCount = 1; submitInfo.pSignalSemaphores = &semaphores.renderComplete; } void gl_base::setupConsole(std::string title) { AllocConsole(); AttachConsole(GetCurrentProcessId()); FILE *stream; freopen_s(&stream, "CONOUT$", "w+", stdout); SetConsoleTitle(TEXT(title.c_str())); } HWND gl_base::setupWindow(HINSTANCE hinstance, WNDPROC wndproc) { this->windowInstance = hinstance; bool fullscreen = false; for (int32_t i = 0; i < __argc; i++) { if (__argv[i] == std::string("-fullscreen")) { fullscreen = true; } } WNDCLASSEX wndClass; wndClass.cbSize = sizeof(WNDCLASSEX); wndClass.style = CS_HREDRAW | CS_VREDRAW; wndClass.lpfnWndProc = wndproc; wndClass.cbClsExtra = 0; wndClass.cbWndExtra = 0; wndClass.hInstance = hinstance; wndClass.hIcon = LoadIcon(NULL, IDI_APPLICATION); wndClass.hCursor = LoadCursor(NULL, IDC_ARROW); wndClass.hbrBackground = (HBRUSH)GetStockObject(BLACK_BRUSH); wndClass.lpszMenuName = NULL; wndClass.lpszClassName = name.c_str(); wndClass.hIconSm = LoadIcon(NULL, IDI_WINLOGO); if (!RegisterClassEx(&wndClass)) { std::cout << "Could not register window class!\n"; fflush(stdout); exit(1); } int screenWidth = GetSystemMetrics(SM_CXSCREEN); int screenHeight = GetSystemMetrics(SM_CYSCREEN); if (fullscreen) { DEVMODE dmScreenSettings; memset(&dmScreenSettings, 0, sizeof(dmScreenSettings)); dmScreenSettings.dmSize = sizeof(dmScreenSettings); dmScreenSettings.dmPelsWidth = screenWidth; dmScreenSettings.dmPelsHeight = screenHeight; dmScreenSettings.dmBitsPerPel = 32; dmScreenSettings.dmFields = DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT; if ((width != screenWidth) && (height != screenHeight)) { if (ChangeDisplaySettings(&dmScreenSettings, CDS_FULLSCREEN) != DISP_CHANGE_SUCCESSFUL) { if (MessageBox(NULL, "Fullscreen Mode not supported!\n Switch to window mode?", "Error", MB_YESNO | MB_ICONEXCLAMATION) == IDYES) { fullscreen = FALSE; } else { return FALSE; } } } } DWORD dwExStyle; DWORD dwStyle; if (fullscreen) { dwExStyle = WS_EX_APPWINDOW; dwStyle = WS_POPUP | WS_CLIPSIBLINGS | WS_CLIPCHILDREN; } else { dwExStyle = WS_EX_APPWINDOW | WS_EX_WINDOWEDGE; dwStyle = WS_OVERLAPPEDWINDOW | WS_CLIPSIBLINGS | WS_CLIPCHILDREN; } RECT windowRect; windowRect.left = 0L; windowRect.top = 0L; windowRect.right = fullscreen ? (long)screenWidth : (long)width; windowRect.bottom = fullscreen ? (long)screenHeight : (long)height; AdjustWindowRectEx(&windowRect, dwStyle, FALSE, dwExStyle); std::string windowTitle = getWindowTitle(); window = CreateWindowEx(0, name.c_str(), windowTitle.c_str(), dwStyle | WS_CLIPSIBLINGS | WS_CLIPCHILDREN, 0, 0, windowRect.right - windowRect.left, windowRect.bottom - windowRect.top, NULL, NULL, hinstance, NULL); if (!fullscreen) { // Center on screen uint32_t x = (GetSystemMetrics(SM_CXSCREEN) - windowRect.right) / 2; uint32_t y = (GetSystemMetrics(SM_CYSCREEN) - windowRect.bottom) / 2; SetWindowPos(window, 0, x, y, 0, 0, SWP_NOZORDER | SWP_NOSIZE); } if (!window) { printf("Could not create window!\n"); fflush(stdout); return 0; exit(1); } ShowWindow(window, SW_SHOW); SetForegroundWindow(window); SetFocus(window); return window; } void gl_base::handleMessages(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { switch (uMsg) { case WM_CLOSE: prepared = false; DestroyWindow(hWnd); PostQuitMessage(0); break; case WM_PAINT: ValidateRect(window, NULL); break; case WM_KEYDOWN: switch (wParam) { case KEY_P: paused = !paused; break; case KEY_ESCAPE: PostQuitMessage(0); break; } if (camera.firstperson) { switch (wParam) { case KEY_W: camera.keys.up = true; break; case KEY_S: camera.keys.down = true; break; case KEY_A: camera.keys.left = true; break; case KEY_D: camera.keys.right = true; break; } } keyPressed((uint32_t)wParam); break; case WM_KEYUP: if (camera.firstperson) { switch (wParam) { case KEY_W: camera.keys.up = false; break; case KEY_S: camera.keys.down = false; break; case KEY_A: camera.keys.left = false; break; case KEY_D: camera.keys.right = false; break; } } break; case WM_RBUTTONDOWN: case WM_LBUTTONDOWN: case WM_MBUTTONDOWN: mousePos.x = (float)LOWORD(lParam); mousePos.y = (float)HIWORD(lParam); break; case WM_MOUSEWHEEL: { short wheelDelta = GET_WHEEL_DELTA_WPARAM(wParam); zoom += (float)wheelDelta * 0.005f * zoomSpeed; camera.translate(glm::vec3(0.0f, 0.0f, (float)wheelDelta * 0.005f * zoomSpeed)); viewUpdated = true; break; } case WM_MOUSEMOVE: if (wParam & MK_RBUTTON) { int32_t posx = LOWORD(lParam); int32_t posy = HIWORD(lParam); zoom += (mousePos.y - (float)posy) * .005f * zoomSpeed; camera.translate(glm::vec3(-0.0f, 0.0f, (mousePos.y - (float)posy) * .005f * zoomSpeed)); mousePos = glm::vec2((float)posx, (float)posy); viewUpdated = true; } if (wParam & MK_LBUTTON) { int32_t posx = LOWORD(lParam); int32_t posy = HIWORD(lParam); rotation.x += (mousePos.y - (float)posy) * 1.25f * rotationSpeed; rotation.y -= (mousePos.x - (float)posx) * 1.25f * rotationSpeed; camera.rotate(glm::vec3((mousePos.y - (float)posy) * camera.rotationSpeed, -(mousePos.x - (float)posx) * camera.rotationSpeed, 0.0f)); mousePos = glm::vec2((float)posx, (float)posy); viewUpdated = true; } if (wParam & MK_MBUTTON) { int32_t posx = LOWORD(lParam); int32_t posy = HIWORD(lParam); cameraPos.x -= (mousePos.x - (float)posx) * 0.01f; cameraPos.y -= (mousePos.y - (float)posy) * 0.01f; camera.translate(glm::vec3(-(mousePos.x - (float)posx) * 0.01f, -(mousePos.y - (float)posy) * 0.01f, 0.0f)); viewUpdated = true; mousePos.x = (float)posx; mousePos.y = (float)posy; } break; case WM_SIZE: if ((prepared) && (wParam != SIZE_MINIMIZED)) { destWidth = LOWORD(lParam); destHeight = HIWORD(lParam); if ((wParam == SIZE_MAXIMIZED) || (wParam == SIZE_MINIMIZED)) { windowResize(); } } break; case WM_EXITSIZEMOVE: if ((prepared) && ((destWidth != width) || (destHeight != height))) { windowResize(); } break; } } void gl_base::viewChanged() { } void gl_base::keyPressed(uint32_t keyCode) { } uint32_t g_QueueFamilyIndex = 0; void gl_base::createCommandPool() { VkCommandPoolCreateInfo cmdPoolInfo = {}; cmdPoolInfo.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO; g_QueueFamilyIndex = cmdPoolInfo.queueFamilyIndex = Swapchain.queueNodeIndex; cmdPoolInfo.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT; VK_CHECK_RESULT(vkCreateCommandPool(device, &cmdPoolInfo, nullptr, &cmdPool)); } void gl_base::setupDepthStencil() { VkImageCreateInfo image = {}; image.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO; image.pNext = NULL; image.imageType = VK_IMAGE_TYPE_2D; image.format = depthFormat; image.extent = { width, height, 1 }; image.mipLevels = 1; image.arrayLayers = 1; image.samples = VK_SAMPLE_COUNT_1_BIT; image.tiling = VK_IMAGE_TILING_OPTIMAL; image.usage = VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT; image.flags = 0; VkMemoryAllocateInfo mem_alloc = {}; mem_alloc.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; mem_alloc.pNext = NULL; mem_alloc.allocationSize = 0; mem_alloc.memoryTypeIndex = 0; VkImageViewCreateInfo depthStencilView = {}; depthStencilView.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO; depthStencilView.pNext = NULL; depthStencilView.viewType = VK_IMAGE_VIEW_TYPE_2D; depthStencilView.format = depthFormat; depthStencilView.flags = 0; depthStencilView.subresourceRange = {}; depthStencilView.subresourceRange.aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT; depthStencilView.subresourceRange.baseMipLevel = 0; depthStencilView.subresourceRange.levelCount = 1; depthStencilView.subresourceRange.baseArrayLayer = 0; depthStencilView.subresourceRange.layerCount = 1; VkMemoryRequirements memReqs; VK_CHECK_RESULT(vkCreateImage(device, &image, nullptr, &depthStencil.image)); vkGetImageMemoryRequirements(device, depthStencil.image, &memReqs); mem_alloc.allocationSize = memReqs.size; mem_alloc.memoryTypeIndex = vulkanDevice->getMemoryType(memReqs.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT); VK_CHECK_RESULT(vkAllocateMemory(device, &mem_alloc, nullptr, &depthStencil.mem)); VK_CHECK_RESULT(vkBindImageMemory(device, depthStencil.image, depthStencil.mem, 0)); depthStencilView.image = depthStencil.image; VK_CHECK_RESULT(vkCreateImageView(device, &depthStencilView, nullptr, &depthStencil.view)); } void gl_base::setupFrameBuffer() { VkImageView attachments[2]; attachments[1] = depthStencil.view; VkFramebufferCreateInfo frameBufferCreateInfo = {}; frameBufferCreateInfo.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO; frameBufferCreateInfo.pNext = NULL; frameBufferCreateInfo.renderPass = renderPass; frameBufferCreateInfo.attachmentCount = 2; frameBufferCreateInfo.pAttachments = attachments; frameBufferCreateInfo.width = width; frameBufferCreateInfo.height = height; frameBufferCreateInfo.layers = 1; frameBuffers.resize(Swapchain.imageCount); for (uint32_t i = 0; i < frameBuffers.size(); i++) { attachments[0] = Swapchain.buffers[i].view; VK_CHECK_RESULT(vkCreateFramebuffer(device, &frameBufferCreateInfo, nullptr, &frameBuffers[i])); } } void gl_base::setupRenderPass() { std::array<VkAttachmentDescription, 2> attachments = {}; attachments[0].format = colorformat; attachments[0].samples = VK_SAMPLE_COUNT_1_BIT; attachments[0].loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR; attachments[0].storeOp = VK_ATTACHMENT_STORE_OP_STORE; attachments[0].stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE; attachments[0].stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE; attachments[0].initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; attachments[0].finalLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR; attachments[1].format = depthFormat; attachments[1].samples = VK_SAMPLE_COUNT_1_BIT; attachments[1].loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR; attachments[1].storeOp = VK_ATTACHMENT_STORE_OP_STORE; attachments[1].stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE; attachments[1].stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE; attachments[1].initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; attachments[1].finalLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL; VkAttachmentReference colorReference = {}; colorReference.attachment = 0; colorReference.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; VkAttachmentReference depthReference = {}; depthReference.attachment = 1; depthReference.layout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL; VkSubpassDescription subpassDescription = {}; subpassDescription.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS; subpassDescription.colorAttachmentCount = 1; subpassDescription.pColorAttachments = &colorReference; subpassDescription.pDepthStencilAttachment = &depthReference; subpassDescription.inputAttachmentCount = 0; subpassDescription.pInputAttachments = nullptr; subpassDescription.preserveAttachmentCount = 0; subpassDescription.pPreserveAttachments = nullptr; subpassDescription.pResolveAttachments = nullptr; std::array<VkSubpassDependency, 2> dependencies; dependencies[0].srcSubpass = VK_SUBPASS_EXTERNAL; dependencies[0].dstSubpass = 0; dependencies[0].srcStageMask = VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT; dependencies[0].dstStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT; dependencies[0].srcAccessMask = VK_ACCESS_MEMORY_READ_BIT; dependencies[0].dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; dependencies[0].dependencyFlags = VK_DEPENDENCY_BY_REGION_BIT; dependencies[1].srcSubpass = 0; dependencies[1].dstSubpass = VK_SUBPASS_EXTERNAL; dependencies[1].srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT; dependencies[1].dstStageMask = VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT; dependencies[1].srcAccessMask = VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; dependencies[1].dstAccessMask = VK_ACCESS_MEMORY_READ_BIT; dependencies[1].dependencyFlags = VK_DEPENDENCY_BY_REGION_BIT; VkRenderPassCreateInfo renderPassInfo = {}; renderPassInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO; renderPassInfo.attachmentCount = static_cast<uint32_t>(attachments.size()); renderPassInfo.pAttachments = attachments.data(); renderPassInfo.subpassCount = 1; renderPassInfo.pSubpasses = &subpassDescription; renderPassInfo.dependencyCount = static_cast<uint32_t>(dependencies.size()); renderPassInfo.pDependencies = dependencies.data(); VK_CHECK_RESULT(vkCreateRenderPass(device, &renderPassInfo, nullptr, &renderPass)); } void gl_base::windowResize() { if (!prepared) return; prepared = false; width = destWidth; height = destHeight; createSetupCommandBuffer(); setupSwapChain(); vkDestroyImageView(device, depthStencil.view, nullptr); vkDestroyImage(device, depthStencil.image, nullptr); vkFreeMemory(device, depthStencil.mem, nullptr); setupDepthStencil(); for (uint32_t i = 0; i < frameBuffers.size(); i++) { vkDestroyFramebuffer(device, frameBuffers[i], nullptr); } setupFrameBuffer(); flushSetupCommandBuffer(); vkQueueWaitIdle(queue); vkDeviceWaitIdle(device); camera.updateAspectRatio((float)width / (float)height); windowResized(); viewChanged(); prepared = true; } void gl_base::windowResized() { } void gl_base::initSwapchain() { Swapchain.init(windowInstance, window); } void gl_base::setupSwapChain() { Swapchain.create(&width, &height, enableVSync); }
9,990
373
<filename>bundle/src/main/java/com/adobe/acs/commons/util/datadefinitions/impl/LowercaseWithDashesDefinitionBuilderImpl.java /* * #%L * ACS AEM Commons Bundle * %% * Copyright (C) 2015 Adobe * %% * 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% */ package com.adobe.acs.commons.util.datadefinitions.impl; import com.adobe.acs.commons.util.datadefinitions.ResourceDefinitionBuilder; import com.adobe.acs.commons.util.datadefinitions.ResourceDefinition; import org.apache.commons.lang3.StringUtils; import org.apache.felix.scr.annotations.Component; import org.apache.felix.scr.annotations.Properties; import org.apache.felix.scr.annotations.Property; import org.apache.felix.scr.annotations.Service; @Component @Properties({ @Property( name = ResourceDefinitionBuilder.PROP_NAME, value = LowercaseWithDashesDefinitionBuilderImpl.NAME ) }) @Service public class LowercaseWithDashesDefinitionBuilderImpl implements ResourceDefinitionBuilder { public static final String NAME = "LOWERCASE_WITH_DASHES"; @Override public final ResourceDefinition convert(final String data) { final String title = data; String name = data; name = StringUtils.stripToEmpty(name); name = StringUtils.lowerCase(name); name = StringUtils.replace(name, "&", " and "); name = StringUtils.replace(name, "/", " or "); name = StringUtils.replace(name, "%", " percent "); name = name.replaceAll("[^a-z0-9-]+", "-"); name = StringUtils.stripEnd(name, "-"); name = StringUtils.stripStart(name, "-"); final BasicResourceDefinition dataDefinition = new BasicResourceDefinition(name); dataDefinition.setTitle(title); return dataDefinition; } @Override public boolean accepts(String data) { // Accepts any formats return true; } }
832
401
<reponame>JSY1988/tcpkit /* * pcap-dag.c: Packet capture interface for Endace DAG cards. * * The functionality of this code attempts to mimic that of pcap-linux as much * as possible. This code is compiled in several different ways depending on * whether DAG_ONLY and HAVE_DAG_API are defined. If HAVE_DAG_API is not * defined it should not get compiled in, otherwise if DAG_ONLY is defined then * the 'dag_' function calls are renamed to 'pcap_' equivalents. If DAG_ONLY * is not defined then nothing is altered - the dag_ functions will be * called as required from their pcap-linux/bpf equivalents. * * Authors: <NAME>, <NAME> ({<EMAIL>,<EMAIL>) * Modifications: <NAME> * <NAME> * <NAME> <<EMAIL>> */ #ifdef HAVE_CONFIG_H #include <config.h> #endif #include <sys/param.h> /* optionally get BSD define */ #include <stdlib.h> #include <string.h> #include <errno.h> #include "pcap-int.h" #include <ctype.h> #include <netinet/in.h> #include <sys/mman.h> #include <sys/socket.h> #include <sys/types.h> #include <unistd.h> struct mbuf; /* Squelch compiler warnings on some platforms for */ struct rtentry; /* declarations in <net/if.h> */ #include <net/if.h> #include "dagnew.h" #include "dagapi.h" #include "dagpci.h" #include "dag_config_api.h" #include "pcap-dag.h" /* * DAG devices have names beginning with "dag", followed by a number * from 0 to DAG_MAX_BOARDS, then optionally a colon and a stream number * from 0 to DAG_STREAM_MAX. */ #ifndef DAG_MAX_BOARDS #define DAG_MAX_BOARDS 32 #endif #ifndef ERF_TYPE_AAL5 #define ERF_TYPE_AAL5 4 #endif #ifndef ERF_TYPE_MC_HDLC #define ERF_TYPE_MC_HDLC 5 #endif #ifndef ERF_TYPE_MC_RAW #define ERF_TYPE_MC_RAW 6 #endif #ifndef ERF_TYPE_MC_ATM #define ERF_TYPE_MC_ATM 7 #endif #ifndef ERF_TYPE_MC_RAW_CHANNEL #define ERF_TYPE_MC_RAW_CHANNEL 8 #endif #ifndef ERF_TYPE_MC_AAL5 #define ERF_TYPE_MC_AAL5 9 #endif #ifndef ERF_TYPE_COLOR_HDLC_POS #define ERF_TYPE_COLOR_HDLC_POS 10 #endif #ifndef ERF_TYPE_COLOR_ETH #define ERF_TYPE_COLOR_ETH 11 #endif #ifndef ERF_TYPE_MC_AAL2 #define ERF_TYPE_MC_AAL2 12 #endif #ifndef ERF_TYPE_IP_COUNTER #define ERF_TYPE_IP_COUNTER 13 #endif #ifndef ERF_TYPE_TCP_FLOW_COUNTER #define ERF_TYPE_TCP_FLOW_COUNTER 14 #endif #ifndef ERF_TYPE_DSM_COLOR_HDLC_POS #define ERF_TYPE_DSM_COLOR_HDLC_POS 15 #endif #ifndef ERF_TYPE_DSM_COLOR_ETH #define ERF_TYPE_DSM_COLOR_ETH 16 #endif #ifndef ERF_TYPE_COLOR_MC_HDLC_POS #define ERF_TYPE_COLOR_MC_HDLC_POS 17 #endif #ifndef ERF_TYPE_AAL2 #define ERF_TYPE_AAL2 18 #endif #ifndef ERF_TYPE_COLOR_HASH_POS #define ERF_TYPE_COLOR_HASH_POS 19 #endif #ifndef ERF_TYPE_COLOR_HASH_ETH #define ERF_TYPE_COLOR_HASH_ETH 20 #endif #ifndef ERF_TYPE_INFINIBAND #define ERF_TYPE_INFINIBAND 21 #endif #ifndef ERF_TYPE_IPV4 #define ERF_TYPE_IPV4 22 #endif #ifndef ERF_TYPE_IPV6 #define ERF_TYPE_IPV6 23 #endif #ifndef ERF_TYPE_RAW_LINK #define ERF_TYPE_RAW_LINK 24 #endif #ifndef ERF_TYPE_INFINIBAND_LINK #define ERF_TYPE_INFINIBAND_LINK 25 #endif #ifndef ERF_TYPE_META #define ERF_TYPE_META 27 #endif #ifndef ERF_TYPE_PAD #define ERF_TYPE_PAD 48 #endif #define ATM_CELL_SIZE 52 #define ATM_HDR_SIZE 4 /* * A header containing additional MTP information. */ #define MTP2_SENT_OFFSET 0 /* 1 byte */ #define MTP2_ANNEX_A_USED_OFFSET 1 /* 1 byte */ #define MTP2_LINK_NUMBER_OFFSET 2 /* 2 bytes */ #define MTP2_HDR_LEN 4 /* length of the header */ #define MTP2_ANNEX_A_NOT_USED 0 #define MTP2_ANNEX_A_USED 1 #define MTP2_ANNEX_A_USED_UNKNOWN 2 /* SunATM pseudo header */ struct sunatm_hdr { unsigned char flags; /* destination and traffic type */ unsigned char vpi; /* VPI */ unsigned short vci; /* VCI */ }; /* * Private data for capturing on DAG devices. */ struct pcap_dag { struct pcap_stat stat; u_char *dag_mem_bottom; /* DAG card current memory bottom pointer */ u_char *dag_mem_top; /* DAG card current memory top pointer */ int dag_fcs_bits; /* Number of checksum bits from link layer */ int dag_flags; /* Flags */ int dag_stream; /* DAG stream number */ int dag_timeout; /* timeout specified to pcap_open_live. * Same as in linux above, introduce * generally? */ dag_card_ref_t dag_ref; /* DAG Configuration/Status API card reference */ dag_component_t dag_root; /* DAG CSAPI Root component */ attr_uuid_t drop_attr; /* DAG Stream Drop Attribute handle, if available */ struct timeval required_select_timeout; /* Timeout caller must use in event loops */ }; typedef struct pcap_dag_node { struct pcap_dag_node *next; pcap_t *p; pid_t pid; } pcap_dag_node_t; static pcap_dag_node_t *pcap_dags = NULL; static int atexit_handler_installed = 0; static const unsigned short endian_test_word = 0x0100; #define IS_BIGENDIAN() (*((unsigned char *)&endian_test_word)) #define MAX_DAG_PACKET 65536 static unsigned char TempPkt[MAX_DAG_PACKET]; #ifndef HAVE_DAG_LARGE_STREAMS_API #define dag_attach_stream64(a, b, c, d) dag_attach_stream(a, b, c, d) #define dag_get_stream_poll64(a, b, c, d, e) dag_get_stream_poll(a, b, c, d, e) #define dag_set_stream_poll64(a, b, c, d, e) dag_set_stream_poll(a, b, c, d, e) #define dag_size_t uint32_t #endif static int dag_setfilter(pcap_t *p, struct bpf_program *fp); static int dag_stats(pcap_t *p, struct pcap_stat *ps); static int dag_set_datalink(pcap_t *p, int dlt); static int dag_get_datalink(pcap_t *p); static int dag_setnonblock(pcap_t *p, int nonblock); static void delete_pcap_dag(pcap_t *p) { pcap_dag_node_t *curr = NULL, *prev = NULL; for (prev = NULL, curr = pcap_dags; curr != NULL && curr->p != p; prev = curr, curr = curr->next) { /* empty */ } if (curr != NULL && curr->p == p) { if (prev != NULL) { prev->next = curr->next; } else { pcap_dags = curr->next; } } } /* * Performs a graceful shutdown of the DAG card, frees dynamic memory held * in the pcap_t structure, and closes the file descriptor for the DAG card. */ static void dag_platform_cleanup(pcap_t *p) { struct pcap_dag *pd = p->priv; if(dag_stop_stream(p->fd, pd->dag_stream) < 0) fprintf(stderr,"dag_stop_stream: %s\n", strerror(errno)); if(dag_detach_stream(p->fd, pd->dag_stream) < 0) fprintf(stderr,"dag_detach_stream: %s\n", strerror(errno)); if(pd->dag_ref != NULL) { dag_config_dispose(pd->dag_ref); p->fd = -1; pd->dag_ref = NULL; } delete_pcap_dag(p); pcap_cleanup_live_common(p); /* Note: don't need to call close(p->fd) or dag_close(p->fd) as dag_config_dispose(pd->dag_ref) does this. */ } static void atexit_handler(void) { while (pcap_dags != NULL) { if (pcap_dags->pid == getpid()) { if (pcap_dags->p != NULL) dag_platform_cleanup(pcap_dags->p); } else { delete_pcap_dag(pcap_dags->p); } } } static int new_pcap_dag(pcap_t *p) { pcap_dag_node_t *node = NULL; if ((node = malloc(sizeof(pcap_dag_node_t))) == NULL) { return -1; } if (!atexit_handler_installed) { atexit(atexit_handler); atexit_handler_installed = 1; } node->next = pcap_dags; node->p = p; node->pid = getpid(); pcap_dags = node; return 0; } static unsigned int dag_erf_ext_header_count(uint8_t * erf, size_t len) { uint32_t hdr_num = 0; uint8_t hdr_type; /* basic sanity checks */ if ( erf == NULL ) return 0; if ( len < 16 ) return 0; /* check if we have any extension headers */ if ( (erf[8] & 0x80) == 0x00 ) return 0; /* loop over the extension headers */ do { /* sanity check we have enough bytes */ if ( len < (24 + (hdr_num * 8)) ) return hdr_num; /* get the header type */ hdr_type = erf[(16 + (hdr_num * 8))]; hdr_num++; } while ( hdr_type & 0x80 ); return hdr_num; } /* * Read at most max_packets from the capture stream and call the callback * for each of them. Returns the number of packets handled, -1 if an * error occured, or -2 if we were told to break out of the loop. */ static int dag_read(pcap_t *p, int cnt, pcap_handler callback, u_char *user) { struct pcap_dag *pd = p->priv; unsigned int processed = 0; unsigned int nonblocking = pd->dag_flags & DAGF_NONBLOCK; unsigned int num_ext_hdr = 0; unsigned int ticks_per_second; /* Get the next bufferful of packets (if necessary). */ while (pd->dag_mem_top - pd->dag_mem_bottom < dag_record_size) { /* * Has "pcap_breakloop()" been called? */ if (p->break_loop) { /* * Yes - clear the flag that indicates that * it has, and return -2 to indicate that * we were told to break out of the loop. */ p->break_loop = 0; return -2; } /* dag_advance_stream() will block (unless nonblock is called) * until 64kB of data has accumulated. * If to_ms is set, it will timeout before 64kB has accumulated. * We wait for 64kB because processing a few packets at a time * can cause problems at high packet rates (>200kpps) due * to inefficiencies. * This does mean if to_ms is not specified the capture may 'hang' * for long periods if the data rate is extremely slow (<64kB/sec) * If non-block is specified it will return immediately. The user * is then responsible for efficiency. */ if ( NULL == (pd->dag_mem_top = dag_advance_stream(p->fd, pd->dag_stream, &(pd->dag_mem_bottom))) ) { return -1; } if (nonblocking && (pd->dag_mem_top - pd->dag_mem_bottom < dag_record_size)) { /* Pcap is configured to process only available packets, and there aren't any, return immediately. */ return 0; } if(!nonblocking && pd->dag_timeout && (pd->dag_mem_top - pd->dag_mem_bottom < dag_record_size)) { /* Blocking mode, but timeout set and no data has arrived, return anyway.*/ return 0; } } /* Process the packets. */ while (pd->dag_mem_top - pd->dag_mem_bottom >= dag_record_size) { unsigned short packet_len = 0; int caplen = 0; struct pcap_pkthdr pcap_header; dag_record_t *header = (dag_record_t *)(pd->dag_mem_bottom); u_char *dp = ((u_char *)header); /* + dag_record_size; */ unsigned short rlen; /* * Has "pcap_breakloop()" been called? */ if (p->break_loop) { /* * Yes - clear the flag that indicates that * it has, and return -2 to indicate that * we were told to break out of the loop. */ p->break_loop = 0; return -2; } rlen = ntohs(header->rlen); if (rlen < dag_record_size) { strncpy(p->errbuf, "dag_read: record too small", PCAP_ERRBUF_SIZE); return -1; } pd->dag_mem_bottom += rlen; /* Count lost packets. */ switch((header->type & 0x7f)) { /* in these types the color value overwrites the lctr */ case ERF_TYPE_COLOR_HDLC_POS: case ERF_TYPE_COLOR_ETH: case ERF_TYPE_DSM_COLOR_HDLC_POS: case ERF_TYPE_DSM_COLOR_ETH: case ERF_TYPE_COLOR_MC_HDLC_POS: case ERF_TYPE_COLOR_HASH_ETH: case ERF_TYPE_COLOR_HASH_POS: break; default: if ( (pd->drop_attr == kNullAttributeUuid) && (header->lctr) ) { pd->stat.ps_drop += ntohs(header->lctr); } } if ((header->type & 0x7f) == ERF_TYPE_PAD) { continue; } num_ext_hdr = dag_erf_ext_header_count(dp, rlen); /* ERF encapsulation */ /* The Extensible Record Format is not dropped for this kind of encapsulation, * and will be handled as a pseudo header by the decoding application. * The information carried in the ERF header and in the optional subheader (if present) * could be merged with the libpcap information, to offer a better decoding. * The packet length is * o the length of the packet on the link (header->wlen), * o plus the length of the ERF header (dag_record_size), as the length of the * pseudo header will be adjusted during the decoding, * o plus the length of the optional subheader (if present). * * The capture length is header.rlen and the byte stuffing for alignment will be dropped * if the capture length is greater than the packet length. */ if (p->linktype == DLT_ERF) { packet_len = ntohs(header->wlen) + dag_record_size; caplen = rlen; switch ((header->type & 0x7f)) { case ERF_TYPE_MC_AAL5: case ERF_TYPE_MC_ATM: case ERF_TYPE_MC_HDLC: case ERF_TYPE_MC_RAW_CHANNEL: case ERF_TYPE_MC_RAW: case ERF_TYPE_MC_AAL2: case ERF_TYPE_COLOR_MC_HDLC_POS: packet_len += 4; /* MC header */ break; case ERF_TYPE_COLOR_HASH_ETH: case ERF_TYPE_DSM_COLOR_ETH: case ERF_TYPE_COLOR_ETH: case ERF_TYPE_ETH: packet_len += 2; /* ETH header */ break; } /* switch type */ /* Include ERF extension headers */ packet_len += (8 * num_ext_hdr); if (caplen > packet_len) { caplen = packet_len; } } else { /* Other kind of encapsulation according to the header Type */ /* Skip over generic ERF header */ dp += dag_record_size; /* Skip over extension headers */ dp += 8 * num_ext_hdr; switch((header->type & 0x7f)) { case ERF_TYPE_ATM: case ERF_TYPE_AAL5: if ((header->type & 0x7f) == ERF_TYPE_AAL5) { packet_len = ntohs(header->wlen); caplen = rlen - dag_record_size; } case ERF_TYPE_MC_ATM: if ((header->type & 0x7f) == ERF_TYPE_MC_ATM) { caplen = packet_len = ATM_CELL_SIZE; dp+=4; } case ERF_TYPE_MC_AAL5: if ((header->type & 0x7f) == ERF_TYPE_MC_AAL5) { packet_len = ntohs(header->wlen); caplen = rlen - dag_record_size - 4; dp+=4; } /* Skip over extension headers */ caplen -= (8 * num_ext_hdr); if ((header->type & 0x7f) == ERF_TYPE_ATM) { caplen = packet_len = ATM_CELL_SIZE; } if (p->linktype == DLT_SUNATM) { struct sunatm_hdr *sunatm = (struct sunatm_hdr *)dp; unsigned long rawatm; rawatm = ntohl(*((unsigned long *)dp)); sunatm->vci = htons((rawatm >> 4) & 0xffff); sunatm->vpi = (rawatm >> 20) & 0x00ff; sunatm->flags = ((header->flags.iface & 1) ? 0x80 : 0x00) | ((sunatm->vpi == 0 && sunatm->vci == htons(5)) ? 6 : ((sunatm->vpi == 0 && sunatm->vci == htons(16)) ? 5 : ((dp[ATM_HDR_SIZE] == 0xaa && dp[ATM_HDR_SIZE+1] == 0xaa && dp[ATM_HDR_SIZE+2] == 0x03) ? 2 : 1))); } else if (p->linktype == DLT_ATM_RFC1483) { packet_len -= ATM_HDR_SIZE; caplen -= ATM_HDR_SIZE; dp += ATM_HDR_SIZE; } else continue; break; case ERF_TYPE_COLOR_HASH_ETH: case ERF_TYPE_DSM_COLOR_ETH: case ERF_TYPE_COLOR_ETH: case ERF_TYPE_ETH: if ((p->linktype != DLT_EN10MB) && (p->linktype != DLT_DOCSIS)) continue; packet_len = ntohs(header->wlen); packet_len -= (pd->dag_fcs_bits >> 3); caplen = rlen - dag_record_size - 2; /* Skip over extension headers */ caplen -= (8 * num_ext_hdr); if (caplen > packet_len) { caplen = packet_len; } dp += 2; break; case ERF_TYPE_COLOR_HASH_POS: case ERF_TYPE_DSM_COLOR_HDLC_POS: case ERF_TYPE_COLOR_HDLC_POS: case ERF_TYPE_HDLC_POS: if ((p->linktype != DLT_CHDLC) && (p->linktype != DLT_PPP_SERIAL) && (p->linktype != DLT_FRELAY)) continue; packet_len = ntohs(header->wlen); packet_len -= (pd->dag_fcs_bits >> 3); caplen = rlen - dag_record_size; /* Skip over extension headers */ caplen -= (8 * num_ext_hdr); if (caplen > packet_len) { caplen = packet_len; } break; case ERF_TYPE_COLOR_MC_HDLC_POS: case ERF_TYPE_MC_HDLC: if ((p->linktype != DLT_CHDLC) && (p->linktype != DLT_PPP_SERIAL) && (p->linktype != DLT_FRELAY) && (p->linktype != DLT_MTP2) && (p->linktype != DLT_MTP2_WITH_PHDR) && (p->linktype != DLT_LAPD)) continue; packet_len = ntohs(header->wlen); packet_len -= (pd->dag_fcs_bits >> 3); caplen = rlen - dag_record_size - 4; /* Skip over extension headers */ caplen -= (8 * num_ext_hdr); if (caplen > packet_len) { caplen = packet_len; } /* jump the MC_HDLC_HEADER */ dp += 4; #ifdef DLT_MTP2_WITH_PHDR if (p->linktype == DLT_MTP2_WITH_PHDR) { /* Add the MTP2 Pseudo Header */ caplen += MTP2_HDR_LEN; packet_len += MTP2_HDR_LEN; TempPkt[MTP2_SENT_OFFSET] = 0; TempPkt[MTP2_ANNEX_A_USED_OFFSET] = MTP2_ANNEX_A_USED_UNKNOWN; *(TempPkt+MTP2_LINK_NUMBER_OFFSET) = ((header->rec.mc_hdlc.mc_header>>16)&0x01); *(TempPkt+MTP2_LINK_NUMBER_OFFSET+1) = ((header->rec.mc_hdlc.mc_header>>24)&0xff); memcpy(TempPkt+MTP2_HDR_LEN, dp, caplen); dp = TempPkt; } #endif break; case ERF_TYPE_IPV4: if ((p->linktype != DLT_RAW) && (p->linktype != DLT_IPV4)) continue; packet_len = ntohs(header->wlen); caplen = rlen - dag_record_size; /* Skip over extension headers */ caplen -= (8 * num_ext_hdr); if (caplen > packet_len) { caplen = packet_len; } break; case ERF_TYPE_IPV6: if ((p->linktype != DLT_RAW) && (p->linktype != DLT_IPV6)) continue; packet_len = ntohs(header->wlen); caplen = rlen - dag_record_size; /* Skip over extension headers */ caplen -= (8 * num_ext_hdr); if (caplen > packet_len) { caplen = packet_len; } break; /* These types have no matching 'native' DLT, but can be used with DLT_ERF above */ case ERF_TYPE_MC_RAW: case ERF_TYPE_MC_RAW_CHANNEL: case ERF_TYPE_IP_COUNTER: case ERF_TYPE_TCP_FLOW_COUNTER: case ERF_TYPE_INFINIBAND: case ERF_TYPE_RAW_LINK: case ERF_TYPE_INFINIBAND_LINK: default: /* Unhandled ERF type. * Ignore rather than generating error */ continue; } /* switch type */ } /* ERF encapsulation */ if (caplen > p->snapshot) caplen = p->snapshot; /* Run the packet filter if there is one. */ if ((p->fcode.bf_insns == NULL) || bpf_filter(p->fcode.bf_insns, dp, packet_len, caplen)) { /* convert between timestamp formats */ register unsigned long long ts; if (IS_BIGENDIAN()) { ts = SWAPLL(header->ts); } else { ts = header->ts; } switch (p->opt.tstamp_precision) { case PCAP_TSTAMP_PRECISION_NANO: ticks_per_second = 1000000000; break; case PCAP_TSTAMP_PRECISION_MICRO: default: ticks_per_second = 1000000; break; } pcap_header.ts.tv_sec = ts >> 32; ts = (ts & 0xffffffffULL) * ticks_per_second; ts += 0x80000000; /* rounding */ pcap_header.ts.tv_usec = ts >> 32; if (pcap_header.ts.tv_usec >= ticks_per_second) { pcap_header.ts.tv_usec -= ticks_per_second; pcap_header.ts.tv_sec++; } /* Fill in our own header data */ pcap_header.caplen = caplen; pcap_header.len = packet_len; /* Count the packet. */ pd->stat.ps_recv++; /* Call the user supplied callback function */ callback(user, &pcap_header, dp); /* Only count packets that pass the filter, for consistency with standard Linux behaviour. */ processed++; if (processed == cnt && !PACKET_COUNT_IS_UNLIMITED(cnt)) { /* Reached the user-specified limit. */ return cnt; } } } return processed; } static int dag_inject(pcap_t *p, const void *buf _U_, size_t size _U_) { strlcpy(p->errbuf, "Sending packets isn't supported on DAG cards", PCAP_ERRBUF_SIZE); return (-1); } /* * Get a handle for a live capture from the given DAG device. Passing a NULL * device will result in a failure. The promisc flag is ignored because DAG * cards are always promiscuous. The to_ms parameter is used in setting the * API polling parameters. * * snaplen is now also ignored, until we get per-stream slen support. Set * slen with approprite DAG tool BEFORE pcap_activate(). * * See also pcap(3). */ static int dag_activate(pcap_t* p) { struct pcap_dag *pd = p->priv; char *s; int n; daginf_t* daginf; char * newDev = NULL; char * device = p->opt.device; dag_size_t mindata; struct timeval maxwait; struct timeval poll; if (device == NULL) { pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "device is NULL"); return -1; } /* Initialize some components of the pcap structure. */ newDev = (char *)malloc(strlen(device) + 16); if (newDev == NULL) { pcap_fmt_errmsg_for_errno(p->errbuf, PCAP_ERRBUF_SIZE, errno, "Can't allocate string for device name"); goto fail; } /* Parse input name to get dag device and stream number if provided */ if (dag_parse_name(device, newDev, strlen(device) + 16, &pd->dag_stream) < 0) { pcap_fmt_errmsg_for_errno(p->errbuf, PCAP_ERRBUF_SIZE, errno, "dag_parse_name"); goto fail; } device = newDev; if (pd->dag_stream%2) { pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "dag_parse_name: tx (even numbered) streams not supported for capture"); goto fail; } /* setup device parameters */ if((pd->dag_ref = dag_config_init((char *)device)) == NULL) { pcap_fmt_errmsg_for_errno(p->errbuf, PCAP_ERRBUF_SIZE, errno, "dag_config_init %s", device); goto fail; } if((p->fd = dag_config_get_card_fd(pd->dag_ref)) < 0) { pcap_fmt_errmsg_for_errno(p->errbuf, PCAP_ERRBUF_SIZE, errno, "dag_config_get_card_fd %s", device); goto fail; } /* Open requested stream. Can fail if already locked or on error */ if (dag_attach_stream64(p->fd, pd->dag_stream, 0, 0) < 0) { pcap_fmt_errmsg_for_errno(p->errbuf, PCAP_ERRBUF_SIZE, errno, "dag_attach_stream"); goto failclose; } /* Try to find Stream Drop attribute */ pd->drop_attr = kNullAttributeUuid; pd->dag_root = dag_config_get_root_component(pd->dag_ref); if ( dag_component_get_subcomponent(pd->dag_root, kComponentStreamFeatures, 0) ) { pd->drop_attr = dag_config_get_indexed_attribute_uuid(pd->dag_ref, kUint32AttributeStreamDropCount, pd->dag_stream/2); } /* Set up default poll parameters for stream * Can be overridden by pcap_set_nonblock() */ if (dag_get_stream_poll64(p->fd, pd->dag_stream, &mindata, &maxwait, &poll) < 0) { pcap_fmt_errmsg_for_errno(p->errbuf, PCAP_ERRBUF_SIZE, errno, "dag_get_stream_poll"); goto faildetach; } /* Use the poll time as the required select timeout for callers * who are using select()/etc. in an event loop waiting for * packets to arrive. */ pd->required_select_timeout = poll; p->required_select_timeout = &pd->required_select_timeout; /* * Turn a negative snapshot value (invalid), a snapshot value of * 0 (unspecified), or a value bigger than the normal maximum * value, into the maximum allowed value. * * If some application really *needs* a bigger snapshot * length, we should just increase MAXIMUM_SNAPLEN. */ if (p->snapshot <= 0 || p->snapshot > MAXIMUM_SNAPLEN) p->snapshot = MAXIMUM_SNAPLEN; if (p->opt.immediate) { /* Call callback immediately. * XXX - is this the right way to p this? */ mindata = 0; } else { /* Amount of data to collect in Bytes before calling callbacks. * Important for efficiency, but can introduce latency * at low packet rates if to_ms not set! */ mindata = 65536; } /* Obey opt.timeout (was to_ms) if supplied. This is a good idea! * Recommend 10-100ms. Calls will time out even if no data arrived. */ maxwait.tv_sec = p->opt.timeout/1000; maxwait.tv_usec = (p->opt.timeout%1000) * 1000; if (dag_set_stream_poll64(p->fd, pd->dag_stream, mindata, &maxwait, &poll) < 0) { pcap_fmt_errmsg_for_errno(p->errbuf, PCAP_ERRBUF_SIZE, errno, "dag_set_stream_poll"); goto faildetach; } /* XXX Not calling dag_configure() to set slen; this is unsafe in * multi-stream environments as the gpp config is global. * Once the firmware provides 'per-stream slen' this can be supported * again via the Config API without side-effects */ #if 0 /* set the card snap length to the specified snaplen parameter */ /* This is a really bad idea, as different cards have different * valid slen ranges. Should fix in Config API. */ if (p->snapshot == 0 || p->snapshot > MAX_DAG_SNAPLEN) { p->snapshot = MAX_DAG_SNAPLEN; } else if (snaplen < MIN_DAG_SNAPLEN) { p->snapshot = MIN_DAG_SNAPLEN; } /* snap len has to be a multiple of 4 */ #endif if(dag_start_stream(p->fd, pd->dag_stream) < 0) { pcap_fmt_errmsg_for_errno(p->errbuf, PCAP_ERRBUF_SIZE, errno, "dag_start_stream %s", device); goto faildetach; } /* * Important! You have to ensure bottom is properly * initialized to zero on startup, it won't give you * a compiler warning if you make this mistake! */ pd->dag_mem_bottom = 0; pd->dag_mem_top = 0; /* * Find out how many FCS bits we should strip. * First, query the card to see if it strips the FCS. */ daginf = dag_info(p->fd); if ((0x4200 == daginf->device_code) || (0x4230 == daginf->device_code)) { /* DAG 4.2S and 4.23S already strip the FCS. Stripping the final word again truncates the packet. */ pd->dag_fcs_bits = 0; /* Note that no FCS will be supplied. */ p->linktype_ext = LT_FCS_DATALINK_EXT(0); } else { /* * Start out assuming it's 32 bits. */ pd->dag_fcs_bits = 32; /* Allow an environment variable to override. */ if ((s = getenv("ERF_FCS_BITS")) != NULL) { if ((n = atoi(s)) == 0 || n == 16 || n == 32) { pd->dag_fcs_bits = n; } else { pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "pcap_activate %s: bad ERF_FCS_BITS value (%d) in environment", device, n); goto failstop; } } /* * Did the user request that they not be stripped? */ if ((s = getenv("ERF_DONT_STRIP_FCS")) != NULL) { /* Yes. Note the number of bytes that will be supplied. */ p->linktype_ext = LT_FCS_DATALINK_EXT(pd->dag_fcs_bits/16); /* And don't strip them. */ pd->dag_fcs_bits = 0; } } pd->dag_timeout = p->opt.timeout; p->linktype = -1; if (dag_get_datalink(p) < 0) goto failstop; p->bufsize = 0; if (new_pcap_dag(p) < 0) { pcap_fmt_errmsg_for_errno(p->errbuf, PCAP_ERRBUF_SIZE, errno, "new_pcap_dag %s", device); goto failstop; } /* * "select()" and "poll()" don't work on DAG device descriptors. */ p->selectable_fd = -1; if (newDev != NULL) { free((char *)newDev); } p->read_op = dag_read; p->inject_op = dag_inject; p->setfilter_op = dag_setfilter; p->setdirection_op = NULL; /* Not implemented.*/ p->set_datalink_op = dag_set_datalink; p->getnonblock_op = pcap_getnonblock_fd; p->setnonblock_op = dag_setnonblock; p->stats_op = dag_stats; p->cleanup_op = dag_platform_cleanup; pd->stat.ps_drop = 0; pd->stat.ps_recv = 0; pd->stat.ps_ifdrop = 0; return 0; failstop: if (dag_stop_stream(p->fd, pd->dag_stream) < 0) { fprintf(stderr,"dag_stop_stream: %s\n", strerror(errno)); } faildetach: if (dag_detach_stream(p->fd, pd->dag_stream) < 0) fprintf(stderr,"dag_detach_stream: %s\n", strerror(errno)); failclose: dag_config_dispose(pd->dag_ref); delete_pcap_dag(p); fail: pcap_cleanup_live_common(p); if (newDev != NULL) { free((char *)newDev); } return PCAP_ERROR; } pcap_t *dag_create(const char *device, char *ebuf, int *is_ours) { const char *cp; char *cpend; long devnum; pcap_t *p; long stream = 0; /* Does this look like a DAG device? */ cp = strrchr(device, '/'); if (cp == NULL) cp = device; /* Does it begin with "dag"? */ if (strncmp(cp, "dag", 3) != 0) { /* Nope, doesn't begin with "dag" */ *is_ours = 0; return NULL; } /* Yes - is "dag" followed by a number from 0 to DAG_MAX_BOARDS-1 */ cp += 3; devnum = strtol(cp, &cpend, 10); if (*cpend == ':') { /* Followed by a stream number. */ stream = strtol(++cpend, &cpend, 10); } if (cpend == cp || *cpend != '\0') { /* Not followed by a number. */ *is_ours = 0; return NULL; } if (devnum < 0 || devnum >= DAG_MAX_BOARDS) { /* Followed by a non-valid number. */ *is_ours = 0; return NULL; } if (stream <0 || stream >= DAG_STREAM_MAX) { /* Followed by a non-valid stream number. */ *is_ours = 0; return NULL; } /* OK, it's probably ours. */ *is_ours = 1; p = pcap_create_common(ebuf, sizeof (struct pcap_dag)); if (p == NULL) return NULL; p->activate_op = dag_activate; /* * We claim that we support microsecond and nanosecond time * stamps. * * XXX Our native precision is 2^-32s, but libpcap doesn't support * power of two precisions yet. We can convert to either MICRO or NANO. */ p->tstamp_precision_count = 2; p->tstamp_precision_list = malloc(2 * sizeof(u_int)); if (p->tstamp_precision_list == NULL) { pcap_fmt_errmsg_for_errno(ebuf, PCAP_ERRBUF_SIZE, errno, "malloc"); pcap_close(p); return NULL; } p->tstamp_precision_list[0] = PCAP_TSTAMP_PRECISION_MICRO; p->tstamp_precision_list[1] = PCAP_TSTAMP_PRECISION_NANO; return p; } static int dag_stats(pcap_t *p, struct pcap_stat *ps) { struct pcap_dag *pd = p->priv; uint32_t stream_drop; dag_err_t dag_error; /* * Packet records received (ps_recv) are counted in dag_read(). * Packet records dropped (ps_drop) are read from Stream Drop attribute if present, * otherwise integrate the ERF Header lctr counts (if available) in dag_read(). * We are reporting that no records are dropped by the card/driver (ps_ifdrop). */ if(pd->drop_attr != kNullAttributeUuid) { /* Note this counter is cleared at start of capture and will wrap at UINT_MAX. * The application is responsible for polling ps_drop frequently enough * to detect each wrap and integrate total drop with a wider counter */ if ((dag_error = dag_config_get_uint32_attribute_ex(pd->dag_ref, pd->drop_attr, &stream_drop) == kDagErrNone)) { pd->stat.ps_drop = stream_drop; } else { pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "reading stream drop attribute: %s", dag_config_strerror(dag_error)); return -1; } } *ps = pd->stat; return 0; } /* * Add all DAG devices. */ int dag_findalldevs(pcap_if_list_t *devlistp, char *errbuf) { char name[12]; /* XXX - pick a size */ int c; char dagname[DAGNAME_BUFSIZE]; int dagstream; int dagfd; dag_card_inf_t *inf; char *description; int stream, rxstreams; /* Try all the DAGs 0-DAG_MAX_BOARDS */ for (c = 0; c < DAG_MAX_BOARDS; c++) { pcap_snprintf(name, 12, "dag%d", c); if (-1 == dag_parse_name(name, dagname, DAGNAME_BUFSIZE, &dagstream)) { (void) pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "dag: device name %s can't be parsed", name); return (-1); } if ( (dagfd = dag_open(dagname)) >= 0 ) { description = NULL; if ((inf = dag_pciinfo(dagfd))) description = dag_device_name(inf->device_code, 1); /* * XXX - is there a way to determine whether * the card is plugged into a network or not? * If so, we should check that and set * PCAP_IF_CONNECTION_STATUS_CONNECTED or * PCAP_IF_CONNECTION_STATUS_DISCONNECTED. * * Also, are there notions of "up" and "running"? */ if (add_dev(devlistp, name, 0, description, errbuf) == NULL) { /* * Failure. */ return (-1); } rxstreams = dag_rx_get_stream_count(dagfd); for(stream=0;stream<DAG_STREAM_MAX;stream+=2) { if (0 == dag_attach_stream(dagfd, stream, 0, 0)) { dag_detach_stream(dagfd, stream); pcap_snprintf(name, 10, "dag%d:%d", c, stream); if (add_dev(devlistp, name, 0, description, errbuf) == NULL) { /* * Failure. */ return (-1); } rxstreams--; if(rxstreams <= 0) { break; } } } dag_close(dagfd); } } return (0); } /* * Installs the given bpf filter program in the given pcap structure. There is * no attempt to store the filter in kernel memory as that is not supported * with DAG cards. */ static int dag_setfilter(pcap_t *p, struct bpf_program *fp) { if (!p) return -1; if (!fp) { strncpy(p->errbuf, "setfilter: No filter specified", sizeof(p->errbuf)); return -1; } /* Make our private copy of the filter */ if (install_bpf_program(p, fp) < 0) return -1; return (0); } static int dag_set_datalink(pcap_t *p, int dlt) { p->linktype = dlt; return (0); } static int dag_setnonblock(pcap_t *p, int nonblock) { struct pcap_dag *pd = p->priv; dag_size_t mindata; struct timeval maxwait; struct timeval poll; /* * Set non-blocking mode on the FD. * XXX - is that necessary? If not, don't bother calling it, * and have a "dag_getnonblock()" function that looks at * "pd->dag_flags". */ if (pcap_setnonblock_fd(p, nonblock) < 0) return (-1); if (dag_get_stream_poll64(p->fd, pd->dag_stream, &mindata, &maxwait, &poll) < 0) { pcap_fmt_errmsg_for_errno(p->errbuf, PCAP_ERRBUF_SIZE, errno, "dag_get_stream_poll"); return -1; } /* Amount of data to collect in Bytes before calling callbacks. * Important for efficiency, but can introduce latency * at low packet rates if to_ms not set! */ if(nonblock) mindata = 0; else mindata = 65536; if (dag_set_stream_poll64(p->fd, pd->dag_stream, mindata, &maxwait, &poll) < 0) { pcap_fmt_errmsg_for_errno(p->errbuf, PCAP_ERRBUF_SIZE, errno, "dag_set_stream_poll"); return -1; } if (nonblock) { pd->dag_flags |= DAGF_NONBLOCK; } else { pd->dag_flags &= ~DAGF_NONBLOCK; } return (0); } static int dag_get_datalink(pcap_t *p) { struct pcap_dag *pd = p->priv; int index=0, dlt_index=0; uint8_t types[255]; memset(types, 0, 255); if (p->dlt_list == NULL && (p->dlt_list = malloc(255*sizeof(*(p->dlt_list)))) == NULL) { pcap_fmt_errmsg_for_errno(p->errbuf, sizeof(p->errbuf), errno, "malloc"); return (-1); } p->linktype = 0; #ifdef HAVE_DAG_GET_STREAM_ERF_TYPES /* Get list of possible ERF types for this card */ if (dag_get_stream_erf_types(p->fd, pd->dag_stream, types, 255) < 0) { pcap_fmt_errmsg_for_errno(p->errbuf, sizeof(p->errbuf), errno, "dag_get_stream_erf_types"); return (-1); } while (types[index]) { #elif defined HAVE_DAG_GET_ERF_TYPES /* Get list of possible ERF types for this card */ if (dag_get_erf_types(p->fd, types, 255) < 0) { pcap_fmt_errmsg_for_errno(p->errbuf, sizeof(p->errbuf), errno, "dag_get_erf_types"); return (-1); } while (types[index]) { #else /* Check the type through a dagapi call. */ types[index] = dag_linktype(p->fd); { #endif switch((types[index] & 0x7f)) { case ERF_TYPE_HDLC_POS: case ERF_TYPE_COLOR_HDLC_POS: case ERF_TYPE_DSM_COLOR_HDLC_POS: case ERF_TYPE_COLOR_HASH_POS: if (p->dlt_list != NULL) { p->dlt_list[dlt_index++] = DLT_CHDLC; p->dlt_list[dlt_index++] = DLT_PPP_SERIAL; p->dlt_list[dlt_index++] = DLT_FRELAY; } if(!p->linktype) p->linktype = DLT_CHDLC; break; case ERF_TYPE_ETH: case ERF_TYPE_COLOR_ETH: case ERF_TYPE_DSM_COLOR_ETH: case ERF_TYPE_COLOR_HASH_ETH: /* * This is (presumably) a real Ethernet capture; give it a * link-layer-type list with DLT_EN10MB and DLT_DOCSIS, so * that an application can let you choose it, in case you're * capturing DOCSIS traffic that a Cisco Cable Modem * Termination System is putting out onto an Ethernet (it * doesn't put an Ethernet header onto the wire, it puts raw * DOCSIS frames out on the wire inside the low-level * Ethernet framing). */ if (p->dlt_list != NULL) { p->dlt_list[dlt_index++] = DLT_EN10MB; p->dlt_list[dlt_index++] = DLT_DOCSIS; } if(!p->linktype) p->linktype = DLT_EN10MB; break; case ERF_TYPE_ATM: case ERF_TYPE_AAL5: case ERF_TYPE_MC_ATM: case ERF_TYPE_MC_AAL5: if (p->dlt_list != NULL) { p->dlt_list[dlt_index++] = DLT_ATM_RFC1483; p->dlt_list[dlt_index++] = DLT_SUNATM; } if(!p->linktype) p->linktype = DLT_ATM_RFC1483; break; case ERF_TYPE_COLOR_MC_HDLC_POS: case ERF_TYPE_MC_HDLC: if (p->dlt_list != NULL) { p->dlt_list[dlt_index++] = DLT_CHDLC; p->dlt_list[dlt_index++] = DLT_PPP_SERIAL; p->dlt_list[dlt_index++] = DLT_FRELAY; p->dlt_list[dlt_index++] = DLT_MTP2; p->dlt_list[dlt_index++] = DLT_MTP2_WITH_PHDR; p->dlt_list[dlt_index++] = DLT_LAPD; } if(!p->linktype) p->linktype = DLT_CHDLC; break; case ERF_TYPE_IPV4: if (p->dlt_list != NULL) { p->dlt_list[dlt_index++] = DLT_RAW; p->dlt_list[dlt_index++] = DLT_IPV4; } if(!p->linktype) p->linktype = DLT_RAW; break; case ERF_TYPE_IPV6: if (p->dlt_list != NULL) { p->dlt_list[dlt_index++] = DLT_RAW; p->dlt_list[dlt_index++] = DLT_IPV6; } if(!p->linktype) p->linktype = DLT_RAW; break; case ERF_TYPE_LEGACY: case ERF_TYPE_MC_RAW: case ERF_TYPE_MC_RAW_CHANNEL: case ERF_TYPE_IP_COUNTER: case ERF_TYPE_TCP_FLOW_COUNTER: case ERF_TYPE_INFINIBAND: case ERF_TYPE_RAW_LINK: case ERF_TYPE_INFINIBAND_LINK: case ERF_TYPE_META: default: /* Libpcap cannot deal with these types yet */ /* Add no 'native' DLTs, but still covered by DLT_ERF */ break; } /* switch */ index++; } p->dlt_list[dlt_index++] = DLT_ERF; p->dlt_count = dlt_index; if(!p->linktype) p->linktype = DLT_ERF; return p->linktype; } #ifdef DAG_ONLY /* * This libpcap build supports only DAG cards, not regular network * interfaces. */ /* * There are no regular interfaces, just DAG interfaces. */ int pcap_platform_finddevs(pcap_if_list_t *devlistp _U_, char *errbuf) { return (0); } /* * Attempts to open a regular interface fail. */ pcap_t * pcap_create_interface(const char *device, char *errbuf) { pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "This version of libpcap only supports DAG cards"); return NULL; } /* * Libpcap version string. */ const char * pcap_lib_version(void) { return (PCAP_VERSION_STRING " (DAG-only)"); } #endif
16,758
3,227
<reponame>ffteja/cgal<filename>Mesh_3/doc/Mesh_3/Concepts/MeshPolyline_3.h /*! \ingroup PkgMesh3SecondaryConcepts \cgalConcept The concept `MeshPolyline_3` implements a container of points designed to represent a polyline (i.e.\ a sequence of points). Types and functions provided in this concept are such as standard template library containers are natural models of this concept. \cgalHasModel `std::vector<Kernel::Point_3>` for any Kernel of \cgal is a natural model of this concept. \sa `CGAL::Mesh_domain_with_polyline_features_3<MD>` */ class MeshPolyline_3 { public: /// \name Types /// @{ /*! Point type. Must match the type `MeshDomain_3::Point_3`. */ typedef unspecified_type value_type; /*! A constant iterator on points. Must be a model of Bidirectional iterator and have `value_type` as value type. */ typedef unspecified_type const_iterator; /// @} /// \name Operations /// @{ /*! Returns an iterator on the first point of the polyline. */ const_iterator begin(); /*! Returns the past-the-end iterator for the above iterator. */ const_iterator end(); /// @} }; /* end MeshPolyline_3 */
358
519
<filename>include/cpp-sort/detail/ska_sort.h /* * Copyright (c) 2017-2021 Morwenn * SPDX-License-Identifier: MIT */ // Copyright <NAME> 2016. // Distributed under the Boost Software License, Version 1.0. // (See http://www.boost.org/LICENSE_1_0.txt) // #ifndef CPPSORT_DETAIL_SKA_SORT_H_ #define CPPSORT_DETAIL_SKA_SORT_H_ //////////////////////////////////////////////////////////// // Headers //////////////////////////////////////////////////////////// #include <algorithm> #include <array> #include <climits> #include <cstddef> #include <cstdint> #include <functional> #include <iterator> #include <limits> #include <tuple> #include <type_traits> #include <utility> #include <cpp-sort/utility/as_function.h> #include <cpp-sort/utility/iter_move.h> #include "attributes.h" #include "iterator_traits.h" #include "memcpy_cast.h" #include "pdqsort.h" #include "type_traits.h" namespace cppsort { namespace detail { //////////////////////////////////////////////////////////// // ska_sort algorithm inline auto to_unsigned_or_bool(bool b) -> bool { return b; } inline auto to_unsigned_or_bool(unsigned char c) -> unsigned char { return c; } inline auto to_unsigned_or_bool(signed char c) -> unsigned char { return static_cast<unsigned char>(c) + 128; } inline auto to_unsigned_or_bool(char c) -> unsigned char { return static_cast<unsigned char>(c); } inline auto to_unsigned_or_bool(char16_t c) -> std::uint16_t { return static_cast<std::uint16_t>(c); } inline auto to_unsigned_or_bool(char32_t c) -> std::uint32_t { return static_cast<std::uint32_t>(c); } inline auto to_unsigned_or_bool(wchar_t c) -> std::uint32_t { return static_cast<std::uint32_t>(c); } inline auto to_unsigned_or_bool(short i) -> unsigned short { return static_cast<unsigned short>(i) + static_cast<unsigned short>(1 << std::numeric_limits<short>::digits); } inline auto to_unsigned_or_bool(unsigned short i) -> unsigned short { return i; } inline auto to_unsigned_or_bool(int i) -> unsigned int { return static_cast<unsigned int>(i) + static_cast<unsigned int>(1 << std::numeric_limits<int>::digits); } inline auto to_unsigned_or_bool(unsigned int i) -> unsigned int { return i; } inline auto to_unsigned_or_bool(long l) -> unsigned long { return static_cast<unsigned long>(l) + static_cast<unsigned long>(1l << std::numeric_limits<long>::digits); } inline auto to_unsigned_or_bool(unsigned long l) -> unsigned long { return l; } inline auto to_unsigned_or_bool(long long l) -> unsigned long long { return static_cast<unsigned long long>(l) + static_cast<unsigned long long>(1ll << std::numeric_limits<long long>::digits); } inline auto to_unsigned_or_bool(unsigned long long l) -> unsigned long long { return l; } #ifdef __SIZEOF_INT128__ inline auto to_unsigned_or_bool(__int128_t l) -> __uint128_t { return static_cast<__uint128_t>(l) + static_cast<__uint128_t>(__int128_t(1) << (CHAR_BIT * sizeof(__int128_t) - 1)); } inline auto to_unsigned_or_bool(__uint128_t l) -> __uint128_t { return l; } #endif inline auto to_unsigned_or_bool(float f) -> std::uint32_t { auto u = memcpy_cast<std::uint32_t>(f); std::uint32_t sign_bit = -std::int32_t(u >> 31); return u ^ (sign_bit | 0x80000000); } inline auto to_unsigned_or_bool(double f) -> std::uint64_t { auto u = memcpy_cast<std::uint64_t>(f); std::uint64_t sign_bit = -std::int64_t(u >> 63); return u ^ (sign_bit | 0x8000000000000000); } #ifdef UINTPTR_MAX template<typename T> auto to_unsigned_or_bool(T* ptr) -> std::uintptr_t { return reinterpret_cast<std::uintptr_t>(ptr); } #else template<typename T> auto to_unsigned_or_bool(T* ptr) -> std::size_t { return reinterpret_cast<std::size_t>(ptr); } #endif template<typename RandomAccessIterator, typename Function> auto unroll_loop_four_times(RandomAccessIterator begin, std::size_t iteration_count, Function&& to_call_func) -> void { auto&& to_call = utility::as_function(to_call_func); std::size_t loop_count = iteration_count / 4; std::size_t remainder_count = iteration_count - loop_count * 4; for (; loop_count > 0 ; --loop_count) { to_call(begin); ++begin; to_call(begin); ++begin; to_call(begin); ++begin; to_call(begin); ++begin; } switch (remainder_count) { case 3: to_call(begin); ++begin; CPPSORT_ATTRIBUTE_FALLTHROUGH; case 2: to_call(begin); ++begin; CPPSORT_ATTRIBUTE_FALLTHROUGH; case 1: to_call(begin); } } template<typename RandomAccessIterator, typename Function> auto custom_std_partition(RandomAccessIterator begin, RandomAccessIterator end, Function function) -> RandomAccessIterator { auto&& func = utility::as_function(function); for (;; ++begin) { if (begin == end) { return end; } if (not func(*begin)) { break; } } RandomAccessIterator it = begin; for (++it ; it != end ; ++it) { if (not func(*it)) { continue; } using utility::iter_swap; iter_swap(begin, it); ++begin; } return begin; } struct PartitionInfo { PartitionInfo(): count(0) {} union { std::size_t count; std::size_t offset; }; std::size_t next_offset; }; template<std::size_t> struct UnsignedForSize; template<> struct UnsignedForSize<1> { using type = std::uint8_t; }; template<> struct UnsignedForSize<2> { using type = std::uint16_t; }; template<> struct UnsignedForSize<4> { using type = std::uint32_t; }; template<> struct UnsignedForSize<8> { using type = std::uint64_t; }; #ifdef __SIZEOF_INT128__ template<> struct UnsignedForSize<16> { using type = __uint128_t; }; #endif template<typename T> struct SubKey; template<std::size_t Size> struct SizedSubKey { template<typename T> static auto sub_key(T&& value, void*) -> decltype(auto) { return to_unsigned_or_bool(value); } using next = SubKey<void>; using sub_key_type = typename UnsignedForSize<Size>::type; }; template<typename T> struct SubKey<const T>: SubKey<T> {}; template<typename T> struct SubKey<T&>: SubKey<T> {}; template<typename T> struct SubKey<T&&>: SubKey<T> {}; template<typename T> struct SubKey<const T&>: SubKey<T> {}; template<typename T> struct SubKey<const T&&>: SubKey<T> {}; template<typename T, typename Enable=void> struct FallbackSubKey: SubKey<decltype(to_radix_sort_key(std::declval<T>()))> { using base = SubKey<decltype(to_radix_sort_key(std::declval<T>()))>; template<typename U> static auto sub_key(U&& value, void* data) -> decltype(auto) { return base::sub_key(to_radix_sort_key(value), data); } }; template<typename T> struct FallbackSubKey<T, detail::enable_if_t<not std::is_same<void, decltype(to_unsigned_or_bool(std::declval<T>()))>::value>>: SubKey<decltype(to_unsigned_or_bool(std::declval<T>()))> {}; template<typename T> struct SubKey: conditional_t< is_unsigned<T>::value, SizedSubKey<sizeof(T)>, FallbackSubKey<T> > {}; template<> struct SubKey<bool> { template<typename T> static auto sub_key(T&& value, void*) -> bool { return value; } using next = SubKey<void>; using sub_key_type = bool; }; template<> struct SubKey<void>; template<typename T> struct SubKey<T*>: SizedSubKey<sizeof(T*)> {}; template<typename F, typename S, typename Current> struct PairSecondSubKey: Current { static auto sub_key(const std::pair<F, S>& value, void* sort_data) -> decltype(auto) { return Current::sub_key(value.second, sort_data); } using next = conditional_t< std::is_same<SubKey<void>, typename Current::next>::value, SubKey<void>, PairSecondSubKey<F, S, typename Current::next> >; }; template<typename F, typename S, typename Current> struct PairFirstSubKey: Current { static auto sub_key(const std::pair<F, S>& value, void* sort_data) -> decltype(auto) { return Current::sub_key(value.first, sort_data); } using next = conditional_t< std::is_same<SubKey<void>, typename Current::next>::value, PairSecondSubKey<F, S, SubKey<S>>, PairFirstSubKey<F, S, typename Current::next> >; }; template<typename F, typename S> struct SubKey<std::pair<F, S>>: PairFirstSubKey<F, S, SubKey<F>> {}; template<std::size_t Index, typename First, typename... More> struct TypeAt: TypeAt<Index - 1, More..., void> {}; template<typename First, typename... More> struct TypeAt<0, First, More...> { using type = First; }; template<std::size_t Index, typename Current, typename First, typename... More> struct TupleSubKey; template<std::size_t Index, typename Next, typename First, typename... More> struct NextTupleSubKey { using type = TupleSubKey<Index, Next, First, More...>; }; template<std::size_t Index, typename First, typename Second, typename... More> struct NextTupleSubKey<Index, SubKey<void>, First, Second, More...> { using type = TupleSubKey<Index + 1, SubKey<Second>, Second, More...>; }; template<std::size_t Index, typename First> struct NextTupleSubKey<Index, SubKey<void>, First> { using type = SubKey<void>; }; template<std::size_t Index, typename Current, typename First, typename... More> struct TupleSubKey: Current { template<typename Tuple> static auto sub_key(const Tuple& value, void* sort_data) -> decltype(auto) { return Current::sub_key(std::get<Index>(value), sort_data); } using next = typename NextTupleSubKey<Index, typename Current::next, First, More...>::type; }; template<std::size_t Index, typename Current, typename First> struct TupleSubKey<Index, Current, First>: Current { template<typename Tuple> static auto sub_key(const Tuple& value, void* sort_data) -> decltype(auto) { return Current::sub_key(std::get<Index>(value), sort_data); } using next = typename NextTupleSubKey<Index, typename Current::next, First>::type; }; template<typename First, typename... More> struct SubKey<std::tuple<First, More...>>: TupleSubKey<0, SubKey<First>, First, More...> {}; struct BaseListSortData { std::size_t current_index; std::size_t recursion_limit; void* next_sort_data; }; template<typename RandomAccessIterator, typename Projection> struct ListSortData: BaseListSortData { void (*next_sort)(RandomAccessIterator, RandomAccessIterator, std::ptrdiff_t, Projection, void*); }; template<typename CurrentSubKey, typename T> struct ListElementSubKey: SubKey<remove_cvref_t<decltype(std::declval<T>()[0])>> { using base = SubKey<remove_cvref_t<decltype(std::declval<T>()[0])>>; using next = ListElementSubKey; template<typename U> static auto sub_key(U&& value, void* sort_data) -> decltype(auto) { BaseListSortData* list_sort_data = static_cast<BaseListSortData*>(sort_data); const T& list = CurrentSubKey::sub_key(value, list_sort_data->next_sort_data); return base::sub_key(list[list_sort_data->current_index], list_sort_data->next_sort_data); } }; template<typename T> struct ListSubKey { using next = SubKey<void>; using sub_key_type = T; static auto sub_key(const T& value, void*) -> const T& { return value; } }; template<typename T> struct FallbackSubKey<T, detail::enable_if_t<not std::is_same<void, decltype(std::declval<T>()[0])>::value>>: ListSubKey<T> {}; template<typename RandomAccessIterator, typename Projection> auto StdSortFallback(RandomAccessIterator begin, RandomAccessIterator end, Projection projection) -> void { pdqsort(std::move(begin), std::move(end), std::less<>{}, std::move(projection)); } template<std::ptrdiff_t StdSortThreshold, typename RandomAccessIterator, typename Projection> auto StdSortIfLessThanThreshold(RandomAccessIterator begin, RandomAccessIterator end, std::ptrdiff_t num_elements, Projection projection) -> bool { if (num_elements <= 1) { return true; } if (num_elements >= StdSortThreshold) { return false; } StdSortFallback(std::move(begin), std::move(end), std::move(projection)); return true; } template<std::ptrdiff_t StdSortThreshold, std::ptrdiff_t AmericanFlagSortThreshold, typename CurrentSubKey, typename SubKeyType=typename CurrentSubKey::sub_key_type> struct InplaceSorter; template<std::ptrdiff_t StdSortThreshold, std::ptrdiff_t AmericanFlagSortThreshold, typename CurrentSubKey, std::size_t NumBytes, std::size_t Offset=0> struct UnsignedInplaceSorter { static constexpr std::size_t ShiftAmount = (((NumBytes - 1) - Offset) * 8); template<typename T> static auto current_byte(T&& elem, void* sort_data) -> std::uint8_t { return CurrentSubKey::sub_key(elem, sort_data) >> ShiftAmount; } template<typename RandomAccessIterator, typename Projection> static auto sort(RandomAccessIterator begin, RandomAccessIterator end, std::ptrdiff_t num_elements, Projection projection, void (*next_sort)(RandomAccessIterator, RandomAccessIterator, std::ptrdiff_t, Projection, void*), void* sort_data) -> void { if (num_elements < AmericanFlagSortThreshold) { american_flag_sort(std::move(begin), std::move(end), std::move(projection), next_sort, sort_data); } else { ska_byte_sort(std::move(begin), std::move(end), std::move(projection), next_sort, sort_data); } } template<typename RandomAccessIterator, typename Projection> static auto sort_partition(RandomAccessIterator partition_begin, RandomAccessIterator partition_end, std::ptrdiff_t num_elements, Projection projection, void (*next_sort)(RandomAccessIterator, RandomAccessIterator, std::ptrdiff_t, Projection, void*), void* sort_data) -> void { if (not StdSortIfLessThanThreshold<StdSortThreshold>(partition_begin, partition_end, num_elements, projection)) { UnsignedInplaceSorter<StdSortThreshold, AmericanFlagSortThreshold, CurrentSubKey, NumBytes, Offset + 1>::sort( partition_begin, partition_end, num_elements, projection, next_sort, sort_data); } } template<typename RandomAccessIterator, typename Projection> static auto american_flag_sort(RandomAccessIterator begin, RandomAccessIterator end, Projection projection, void (*next_sort)(RandomAccessIterator, RandomAccessIterator, std::ptrdiff_t, Projection, void*), void* sort_data) -> void { auto&& proj = utility::as_function(projection); PartitionInfo partitions[256]; for (auto it = begin ; it != end ; ++it) { ++partitions[current_byte(proj(*it), sort_data)].count; } std::size_t total = 0; std::uint8_t remaining_partitions[256]; int num_partitions = 0; for (int i = 0 ; i < 256 ; ++i) { std::size_t count = partitions[i].count; if (!count) continue; partitions[i].offset = total; total += count; partitions[i].next_offset = total; remaining_partitions[num_partitions] = i; ++num_partitions; } if (num_partitions > 1) { std::uint8_t* current_block_ptr = remaining_partitions; PartitionInfo* current_block = partitions + *current_block_ptr; std::uint8_t* last_block = remaining_partitions + num_partitions - 1; auto it = begin; auto block_end = begin + current_block->next_offset; auto last_element = end - 1; for (;;) { PartitionInfo* block = partitions + current_byte(proj(*it), sort_data); if (block == current_block) { ++it; if (it == last_element) { break; } else if (it == block_end) { for (;;) { ++current_block_ptr; if (current_block_ptr == last_block) { goto recurse; } current_block = partitions + *current_block_ptr; if (current_block->offset != current_block->next_offset) break; } it = begin + current_block->offset; block_end = begin + current_block->next_offset; } } else { std::size_t offset = block->offset++; using utility::iter_swap; iter_swap(it, begin + offset); } } } recurse: if (Offset + 1 != NumBytes || next_sort) { std::size_t start_offset = 0; auto partition_begin = begin; for (std::uint8_t *it = remaining_partitions, *end = remaining_partitions + num_partitions ; it != end ; ++it) { std::size_t end_offset = partitions[*it].next_offset; auto partition_end = begin + end_offset; std::ptrdiff_t num_elements = end_offset - start_offset; sort_partition(partition_begin, partition_end, num_elements, projection, next_sort, sort_data); start_offset = end_offset; partition_begin = partition_end; } } } template<typename RandomAccessIterator, typename Projection> static auto ska_byte_sort(RandomAccessIterator begin, RandomAccessIterator end, Projection projection, void (*next_sort)(RandomAccessIterator, RandomAccessIterator, std::ptrdiff_t, Projection, void*), void* sort_data) -> void { auto&& proj = utility::as_function(projection); PartitionInfo partitions[256]; for (auto it = begin ; it != end ; ++it) { ++partitions[current_byte(proj(*it), sort_data)].count; } std::uint8_t remaining_partitions[256]; std::size_t total = 0; int num_partitions = 0; for (int i = 0 ; i < 256 ; ++i) { std::size_t count = partitions[i].count; if (count) { partitions[i].offset = total; total += count; remaining_partitions[num_partitions] = i; ++num_partitions; } partitions[i].next_offset = total; } for (std::uint8_t *last_remaining = remaining_partitions + num_partitions, *end_partition = remaining_partitions + 1 ; last_remaining > end_partition ;) { last_remaining = custom_std_partition(remaining_partitions, last_remaining, [&](std::uint8_t partition) { std::size_t& begin_offset = partitions[partition].offset; std::size_t& end_offset = partitions[partition].next_offset; if (begin_offset == end_offset) { return false; } unroll_loop_four_times(begin + begin_offset, end_offset - begin_offset, [partitions=partitions, begin, &proj, sort_data](RandomAccessIterator it) { std::uint8_t this_partition = current_byte(proj(*it), sort_data); std::size_t offset = partitions[this_partition].offset++; using utility::iter_swap; iter_swap(it, begin + offset); }); return begin_offset != end_offset; }); } if (Offset + 1 != NumBytes || next_sort) { for (std::uint8_t* it = remaining_partitions + num_partitions ; it != remaining_partitions ; --it) { std::uint8_t partition = it[-1]; std::size_t start_offset = (partition == 0 ? 0 : partitions[partition - 1].next_offset); std::size_t end_offset = partitions[partition].next_offset; auto partition_begin = begin + start_offset; auto partition_end = begin + end_offset; std::ptrdiff_t num_elements = end_offset - start_offset; sort_partition(partition_begin, partition_end, num_elements, projection, next_sort, sort_data); } } } }; template<std::ptrdiff_t StdSortThreshold, std::ptrdiff_t AmericanFlagSortThreshold, typename CurrentSubKey, size_t NumBytes> struct UnsignedInplaceSorter<StdSortThreshold, AmericanFlagSortThreshold, CurrentSubKey, NumBytes, NumBytes> { template<typename RandomAccessIterator, typename Projection> static auto sort(RandomAccessIterator begin, RandomAccessIterator end, std::ptrdiff_t num_elements, Projection projection, void (*next_sort)(RandomAccessIterator, RandomAccessIterator, std::ptrdiff_t, Projection, void*), void* next_sort_data) -> void { next_sort(std::move(begin), std::move(end), num_elements, std::move(projection), next_sort_data); } }; template<typename RandomAccessIterator, typename Projection, typename ElementKey> auto CommonPrefix(RandomAccessIterator begin, RandomAccessIterator end, std::size_t start_index, Projection projection, ElementKey&& element_key) -> std::size_t { auto proj = utility::as_function(projection); const auto& largest_match_list = proj(*begin); std::size_t largest_match = largest_match_list.size(); if (largest_match == start_index) { return start_index; } for (++begin ; begin != end ; ++begin) { const auto& current_list = proj(*begin); std::size_t current_size = current_list.size(); if (current_size < largest_match) { largest_match = current_size; if (largest_match == start_index) { return start_index; } } if (element_key(largest_match_list[start_index]) != element_key(current_list[start_index])) { return start_index; } for (std::size_t i = start_index + 1 ; i < largest_match ; ++i) { if (element_key(largest_match_list[i]) != element_key(current_list[i])) { largest_match = i; break; } } } return largest_match; } template<std::ptrdiff_t StdSortThreshold, std::ptrdiff_t AmericanFlagSortThreshold, typename CurrentSubKey, typename ListType> struct ListInplaceSorter { using ElementSubKey = ListElementSubKey<CurrentSubKey, ListType>; template<typename RandomAccessIterator, typename Projection> static auto sort(RandomAccessIterator begin, RandomAccessIterator end, Projection projection, ListSortData<RandomAccessIterator, Projection>* sort_data) -> void { auto&& proj = utility::as_function(projection); std::size_t current_index = sort_data->current_index; void* next_sort_data = sort_data->next_sort_data; auto current_key = [&](auto&& elem) -> decltype(auto) { return CurrentSubKey::sub_key(proj(elem), next_sort_data); }; auto element_key = [&](auto&& elem) -> decltype(auto) { return ElementSubKey::base::sub_key(elem, sort_data); }; sort_data->current_index = current_index = CommonPrefix(begin, end, current_index, current_key, element_key); auto end_of_shorter_ones = std::partition(begin, end, [&](auto&& elem) { return current_key(elem).size() <= current_index; }); std::ptrdiff_t num_shorter_ones = end_of_shorter_ones - begin; if (sort_data->next_sort && not StdSortIfLessThanThreshold<StdSortThreshold>(begin, end_of_shorter_ones, num_shorter_ones, projection)) { sort_data->next_sort(begin, end_of_shorter_ones, num_shorter_ones, projection, next_sort_data); } std::ptrdiff_t num_elements = end - end_of_shorter_ones; if (not StdSortIfLessThanThreshold<StdSortThreshold>(end_of_shorter_ones, end, num_elements, projection)) { using SortType = void (*)(RandomAccessIterator, RandomAccessIterator, std::ptrdiff_t, Projection, void*); SortType sort_next_element = static_cast<SortType>(&sort_from_recursion); InplaceSorter<StdSortThreshold, AmericanFlagSortThreshold, ElementSubKey>::sort(end_of_shorter_ones, end, num_elements, projection, sort_next_element, sort_data); } } template<typename RandomAccessIterator, typename Projection> static auto sort_from_recursion(RandomAccessIterator begin, RandomAccessIterator end, std::ptrdiff_t, Projection projection, void* next_sort_data) -> void { ListSortData<RandomAccessIterator, Projection> offset = *static_cast<ListSortData<RandomAccessIterator, Projection>*>(next_sort_data); ++offset.current_index; --offset.recursion_limit; if (offset.recursion_limit == 0) { StdSortFallback(begin, end, projection); } else { sort(begin, end, projection, &offset); } } template<typename RandomAccessIterator, typename Projection> static auto sort(RandomAccessIterator begin, RandomAccessIterator end, std::ptrdiff_t, Projection projection, void (*next_sort)(RandomAccessIterator, RandomAccessIterator, std::ptrdiff_t, Projection, void*), void *next_sort_data) -> void { ListSortData<RandomAccessIterator, Projection> offset; offset.current_index = 0; offset.recursion_limit = 16; offset.next_sort = next_sort; offset.next_sort_data = next_sort_data; sort(begin, end, projection, &offset); } }; template<std::ptrdiff_t StdSortThreshold, std::ptrdiff_t AmericanFlagSortThreshold, typename CurrentSubKey> struct InplaceSorter<StdSortThreshold, AmericanFlagSortThreshold, CurrentSubKey, bool> { template<typename RandomAccessIterator, typename Projection> static auto sort(RandomAccessIterator begin, RandomAccessIterator end, std::ptrdiff_t, Projection projection, void (*next_sort)(RandomAccessIterator, RandomAccessIterator, std::ptrdiff_t, Projection, void*), void* sort_data) -> void { auto&& proj = utility::as_function(projection); auto middle = std::partition(begin, end, [&](auto&& a) { return not CurrentSubKey::sub_key(proj(a), sort_data); }); if (next_sort) { next_sort(begin, middle, middle - begin, projection, sort_data); next_sort(middle, end, end - middle, projection, sort_data); } } }; template<std::ptrdiff_t StdSortThreshold, std::ptrdiff_t AmericanFlagSortThreshold, typename CurrentSubKey> struct InplaceSorter<StdSortThreshold, AmericanFlagSortThreshold, CurrentSubKey, std::uint8_t>: UnsignedInplaceSorter<StdSortThreshold, AmericanFlagSortThreshold, CurrentSubKey, 1> {}; template<std::ptrdiff_t StdSortThreshold, std::ptrdiff_t AmericanFlagSortThreshold, typename CurrentSubKey> struct InplaceSorter<StdSortThreshold, AmericanFlagSortThreshold, CurrentSubKey, std::uint16_t>: UnsignedInplaceSorter<StdSortThreshold, AmericanFlagSortThreshold, CurrentSubKey, 2> {}; template<std::ptrdiff_t StdSortThreshold, std::ptrdiff_t AmericanFlagSortThreshold, typename CurrentSubKey> struct InplaceSorter<StdSortThreshold, AmericanFlagSortThreshold, CurrentSubKey, std::uint32_t>: UnsignedInplaceSorter<StdSortThreshold, AmericanFlagSortThreshold, CurrentSubKey, 4> {}; template<std::ptrdiff_t StdSortThreshold, std::ptrdiff_t AmericanFlagSortThreshold, typename CurrentSubKey> struct InplaceSorter<StdSortThreshold, AmericanFlagSortThreshold, CurrentSubKey, std::uint64_t>: UnsignedInplaceSorter<StdSortThreshold, AmericanFlagSortThreshold, CurrentSubKey, 8> {}; #ifdef __SIZEOF_INT128__ template<std::ptrdiff_t StdSortThreshold, std::ptrdiff_t AmericanFlagSortThreshold, typename CurrentSubKey> struct InplaceSorter<StdSortThreshold, AmericanFlagSortThreshold, CurrentSubKey, __uint128_t>: UnsignedInplaceSorter<StdSortThreshold, AmericanFlagSortThreshold, CurrentSubKey, 16> {}; #endif template<std::ptrdiff_t StdSortThreshold, std::ptrdiff_t AmericanFlagSortThreshold, typename CurrentSubKey, typename SubKeyType, typename Enable=void> struct FallbackInplaceSorter; template<std::ptrdiff_t StdSortThreshold, std::ptrdiff_t AmericanFlagSortThreshold, typename CurrentSubKey, typename SubKeyType> struct InplaceSorter: FallbackInplaceSorter<StdSortThreshold, AmericanFlagSortThreshold, CurrentSubKey, SubKeyType> {}; template<std::ptrdiff_t StdSortThreshold, std::ptrdiff_t AmericanFlagSortThreshold, typename CurrentSubKey, typename SubKeyType> struct FallbackInplaceSorter<StdSortThreshold, AmericanFlagSortThreshold, CurrentSubKey, SubKeyType, detail::enable_if_t<not std::is_same<void, decltype(std::declval<SubKeyType>()[0])>::value>>: ListInplaceSorter<StdSortThreshold, AmericanFlagSortThreshold, CurrentSubKey, SubKeyType> {}; template<std::ptrdiff_t StdSortThreshold, std::ptrdiff_t AmericanFlagSortThreshold, typename CurrentSubKey> struct SortStarter; template<std::ptrdiff_t StdSortThreshold, std::ptrdiff_t AmericanFlagSortThreshold> struct SortStarter<StdSortThreshold, AmericanFlagSortThreshold, SubKey<void>> { template<typename RandomAccessIterator, typename Projection> static auto sort(RandomAccessIterator, RandomAccessIterator, std::ptrdiff_t, Projection, void*) -> void {} }; template<std::ptrdiff_t StdSortThreshold, std::ptrdiff_t AmericanFlagSortThreshold, typename CurrentSubKey> struct SortStarter { template<typename RandomAccessIterator, typename Projection> static auto sort(RandomAccessIterator begin, RandomAccessIterator end, std::ptrdiff_t num_elements, Projection projection, void* next_sort_data=nullptr) -> void { if (StdSortIfLessThanThreshold<StdSortThreshold>(begin, end, num_elements, projection)) { return; } using SortType = void (*)(RandomAccessIterator, RandomAccessIterator, std::ptrdiff_t, Projection, void*); SortType next_sort = static_cast<SortType>(&SortStarter<StdSortThreshold, AmericanFlagSortThreshold, typename CurrentSubKey::next>::sort); if (next_sort == static_cast<SortType>(&SortStarter<StdSortThreshold, AmericanFlagSortThreshold, SubKey<void>>::sort)) { next_sort = nullptr; } InplaceSorter<StdSortThreshold, AmericanFlagSortThreshold, CurrentSubKey>::sort( std::move(begin), std::move(end), num_elements, std::move(projection), next_sort, next_sort_data); } }; template< std::ptrdiff_t StdSortThreshold, std::ptrdiff_t AmericanFlagSortThreshold, typename RandomAccessIterator, typename Projection > auto inplace_radix_sort(RandomAccessIterator begin, RandomAccessIterator end, Projection projection) -> void { using SubKey = SubKey<projected_t<RandomAccessIterator, Projection>>; SortStarter<StdSortThreshold, AmericanFlagSortThreshold, SubKey>::sort(begin, end, end - begin, std::move(projection)); } template<typename RandomAccessIterator, typename Projection> auto ska_sort(RandomAccessIterator begin, RandomAccessIterator end, Projection projection) -> void { detail::inplace_radix_sort<128, 1024>(std::move(begin), std::move(end), std::move(projection)); } //////////////////////////////////////////////////////////// // Whether a type is sortable with ska_sort template<typename T> struct is_ska_sortable; template<typename T> using has_indexing_operator_t = remove_cvref_t<decltype(std::declval<T&>()[0])>; template<template<typename...> class Op, typename... Args> using is_index_ska_sortable = is_ska_sortable<detected_t<Op, Args...>>; // A bit hackish, but I'm bad at workarounds... template<> struct is_ska_sortable<nonesuch>: std::false_type {}; template<typename T> struct is_ska_sortable: disjunction< is_integral<T>, is_index_ska_sortable<has_indexing_operator_t, T> > {}; template<typename T> struct is_ska_sortable<T*>: std::true_type {}; template<> struct is_ska_sortable<float>: std::integral_constant<bool, sizeof(float) == sizeof(std::uint32_t) && std::numeric_limits<float>::is_iec559 > {}; template<> struct is_ska_sortable<double>: std::integral_constant<bool, sizeof(double) == sizeof(std::uint64_t) && std::numeric_limits<double>::is_iec559 > {}; template<typename T, typename U> struct is_ska_sortable<std::pair<T, U>>: conjunction< is_ska_sortable<T>, is_ska_sortable<U> > {}; template<typename... Args> struct is_ska_sortable<std::tuple<Args...>>: conjunction< is_ska_sortable<Args>... > {}; template<typename T> constexpr bool is_ska_sortable_v = is_ska_sortable<T>::value; }} #endif // CPPSORT_DETAIL_SKA_SORT_H_
18,348
884
<reponame>rt112000/CDM // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. package com.microsoft.commondatamodel.objectmodel.persistence.cdmfolder; import com.fasterxml.jackson.databind.JsonNode; import com.microsoft.commondatamodel.objectmodel.cdm.CdmCorpusContext; import com.microsoft.commondatamodel.objectmodel.cdm.CdmEntityReference; import com.microsoft.commondatamodel.objectmodel.cdm.CdmTraitReferenceBase; import com.microsoft.commondatamodel.objectmodel.cdm.projections.CdmProjection; import com.microsoft.commondatamodel.objectmodel.enums.CdmObjectType; import com.microsoft.commondatamodel.objectmodel.persistence.cdmfolder.projections.ProjectionPersistence; import com.microsoft.commondatamodel.objectmodel.utilities.CopyOptions; import com.microsoft.commondatamodel.objectmodel.utilities.ResolveOptions; import java.util.List; public class EntityReferencePersistence { public static CdmEntityReference fromData(final CdmCorpusContext ctx, final JsonNode obj) { if (obj == null) { return null; } final Object entity; boolean simpleReference = true; if (obj.isValueNode()) { entity = obj.asText(); } else { entity = getEntityReference(ctx, obj); simpleReference = false; } final CdmEntityReference entityReference = ctx.getCorpus().makeRef(CdmObjectType.EntityRef, entity, simpleReference); if (!(obj.isValueNode())) { Utils.addListToCdmCollection(entityReference.getAppliedTraits(), Utils.createTraitReferenceList(ctx, obj.get("appliedTraits"))); } return entityReference; } public static Object toData(final CdmEntityReference instance, final ResolveOptions resOpt, final CopyOptions options) { if (instance.getExplicitReference() != null && instance.getExplicitReference() instanceof CdmProjection) { return ProjectionPersistence.toData((CdmProjection) instance.getExplicitReference(), resOpt, options); } else { return CdmObjectRefPersistence.toData(instance, resOpt, options); } } private static Object getEntityReference(final CdmCorpusContext ctx, final JsonNode obj) { Object entity = null; if (obj.get("entityReference") != null && obj.get("entityReference").isValueNode()) { entity = obj.get("entityReference"); } else if (obj.get("entityReference") != null && obj.get("entityReference").get("entityShape") != null) { entity = ConstantEntityPersistence.fromData(ctx, obj.get("entityReference")); } else if (obj.get("source") != null || obj.get("operations") != null) { entity = ProjectionPersistence.fromData(ctx, obj); } else { entity = EntityPersistence.fromData(ctx, obj.get("entityReference")); } return entity; } }
1,123
1,162
package io.digdag.core.schedule; import java.time.Instant; import com.google.common.base.*; import com.google.common.collect.*; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import org.immutables.value.Value; import io.digdag.client.config.Config; @Value.Immutable @JsonSerialize(as = ImmutableStoredSchedule.class) @JsonDeserialize(as = ImmutableStoredSchedule.class) public abstract class StoredSchedule extends Schedule { public abstract int getId(); public abstract int getProjectId(); public abstract Instant getCreatedAt(); public abstract Instant getUpdatedAt(); public abstract Optional<Instant> getDisabledAt(); public abstract Optional<Instant> getLastSessionTime(); }
256
1,467
<gh_stars>1000+ /** * Copyright Soramitsu Co., Ltd. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0 */ #include <gtest/gtest.h> #include "common/blob.hpp" #include "cryptography/ed25519_sha3_impl/internal/ed25519_impl.hpp" #include "model/generators/query_generator.hpp" #include "model/generators/transaction_generator.hpp" #include "model/model_crypto_provider_impl.hpp" namespace iroha { namespace model { class CryptoProviderTest : public ::testing::Test { public: CryptoProviderTest() : provider(create_keypair()) {} ModelCryptoProviderImpl provider; }; TEST_F(CryptoProviderTest, SignAndVerifyTransaction) { auto model_tx = generators::TransactionGenerator().generateTransaction("test", {}); provider.sign(model_tx); ASSERT_TRUE(provider.verify(model_tx)); // now modify transaction's meta, so verify should fail model_tx.creator_account_id = "test1"; ASSERT_FALSE(provider.verify(model_tx)); } TEST_F(CryptoProviderTest, SignAndVerifyQuery) { auto query = generators::QueryGenerator().generateGetAccount(0, "test", 0, "test"); provider.sign(*query); ASSERT_TRUE(provider.verify(*query)); // modify account id, verification should fail query->account_id = "kappa"; ASSERT_FALSE(provider.verify(*query)); } TEST_F(CryptoProviderTest, SameQueryHashAfterSign) { auto query = iroha::model::generators::QueryGenerator().generateGetAccount( 0, "test", 0, "test"); auto hash = iroha::hash(*query); provider.sign(*query); auto hash_signed = iroha::hash(*query); ASSERT_EQ(hash_signed, hash); } } // namespace model } // namespace iroha
689
852
<reponame>ckamtsikis/cmssw<filename>DataFormats/JetReco/interface/CaloJet.h #ifndef JetReco_CaloJet_h #define JetReco_CaloJet_h /** \class reco::CaloJet * * \short Jets made from CaloTowers * * CaloJet represents Jets made from CaloTowers * Provide energy contributions from different subdetectors * in addition to generic Jet parameters * * \author <NAME>, UMd * * \version Original: April 22, 2005 by <NAME>. * * \version Oct 19, 2005, <NAME>, modified to work * with real CaloTowers. No energy fractions yet. * * \version May 3, 2006, F.Ratnikov, include all different * energy components separately ************************************************************/ #include "DataFormats/JetReco/interface/Jet.h" #include "DataFormats/CaloTowers/interface/CaloTowerCollection.h" namespace reco { class CaloJet : public Jet { public: typedef CaloTowerPtr ConstituentTypePtr; typedef CaloTowerFwdPtr ConstituentTypeFwdPtr; struct Specific { Specific() : mMaxEInEmTowers(0), mMaxEInHadTowers(0), mHadEnergyInHO(0), mHadEnergyInHB(0), mHadEnergyInHF(0), mHadEnergyInHE(0), mEmEnergyInEB(0), mEmEnergyInEE(0), mEmEnergyInHF(0), mEnergyFractionHadronic(0), mEnergyFractionEm(0), mTowersArea(0) {} /// Maximum energy in EM towers float mMaxEInEmTowers; /// Maximum energy in HCAL towers float mMaxEInHadTowers; /// Hadronic nergy fraction in HO float mHadEnergyInHO; /// Hadronic energy in HB float mHadEnergyInHB; /// Hadronic energy in HF float mHadEnergyInHF; /// Hadronic energy in HE float mHadEnergyInHE; /// Em energy in EB float mEmEnergyInEB; /// Em energy in EE float mEmEnergyInEE; /// Em energy in HF float mEmEnergyInHF; /// Hadronic energy fraction float mEnergyFractionHadronic; /// Em energy fraction float mEnergyFractionEm; /// Area of contributing CaloTowers float mTowersArea; }; /** Default constructor*/ CaloJet() {} /** Constructor from values*/ CaloJet(const LorentzVector& fP4, const Point& fVertex, const Specific& fSpecific, const Jet::Constituents& fConstituents); /** Constructor from values*/ CaloJet(const LorentzVector& fP4, const Point& fVertex, const Specific& fSpecific); /** backward compatible, vertex=(0,0,0) */ CaloJet(const LorentzVector& fP4, const Specific& fSpecific, const Jet::Constituents& fConstituents); ~CaloJet() override{}; /** Returns the maximum energy deposited in ECAL towers*/ float maxEInEmTowers() const { return m_specific.mMaxEInEmTowers; } /** Returns the maximum energy deposited in HCAL towers*/ float maxEInHadTowers() const { return m_specific.mMaxEInHadTowers; } /** Returns the jet hadronic energy fraction*/ float energyFractionHadronic() const { return m_specific.mEnergyFractionHadronic; } /** Returns the jet electromagnetic energy fraction*/ float emEnergyFraction() const { return m_specific.mEnergyFractionEm; } /** Returns the jet hadronic energy in HB*/ float hadEnergyInHB() const { return m_specific.mHadEnergyInHB; } /** Returns the jet hadronic energy in HO*/ float hadEnergyInHO() const { return m_specific.mHadEnergyInHO; } /** Returns the jet hadronic energy in HE*/ float hadEnergyInHE() const { return m_specific.mHadEnergyInHE; } /** Returns the jet hadronic energy in HF*/ float hadEnergyInHF() const { return m_specific.mHadEnergyInHF; } /** Returns the jet electromagnetic energy in EB*/ float emEnergyInEB() const { return m_specific.mEmEnergyInEB; } /** Returns the jet electromagnetic energy in EE*/ float emEnergyInEE() const { return m_specific.mEmEnergyInEE; } /** Returns the jet electromagnetic energy extracted from HF*/ float emEnergyInHF() const { return m_specific.mEmEnergyInHF; } /** Returns area of contributing towers */ float towersArea() const { return m_specific.mTowersArea; } /** Returns the number of constituents carrying a 90% of the total Jet energy*/ int n90() const { return nCarrying(0.9); } /** Returns the number of constituents carrying a 60% of the total Jet energy*/ int n60() const { return nCarrying(0.6); } /// Physics Eta (use jet Z and kinematics only) // float physicsEtaQuick (float fZVertex) const; /// Physics Eta (use jet Z and kinematics only) //float physicsEta (float fZVertex) const {return physicsEtaQuick (fZVertex);} /// Physics p4 (use jet Z and kinematics only) //LorentzVector physicsP4 (float fZVertex) const; /// Physics p4 for full 3d vertex corretion LorentzVector physicsP4(const Particle::Point& vertex) const; /// detector p4 for full 3d vertex correction. LorentzVector detectorP4() const; /// Physics Eta (loop over constituents) //float physicsEtaDetailed (float fZVertex) const; /// Detector Eta (default for CaloJets) //float detectorEta () const {return eta();} /// get specific constituent virtual CaloTowerPtr getCaloConstituent(unsigned fIndex) const; /// get all constituents virtual std::vector<CaloTowerPtr> getCaloConstituents() const; // block accessors const Specific& getSpecific() const { return m_specific; } /// Polymorphic clone CaloJet* clone() const override; /// Print object std::string print() const override; /// CaloTowers indexes std::vector<CaloTowerDetId> getTowerIndices() const; private: /// Polymorphic overlap bool overlap(const Candidate&) const override; //Variables specific to to the CaloJet class Specific m_specific; }; } // namespace reco // temporary fix before include_checcker runs globally #include "DataFormats/JetReco/interface/CaloJetCollection.h" //INCLUDECHECKER:SKIP #endif
2,181
1,561
/* * Copyright (c) 2019 Cossack Labs Limited * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "themis/secure_keygen.h" #include <string.h> #include "soter/soter_container.h" #include "soter/soter_ec_key.h" #include "soter/soter_rand.h" #include "soter/soter_rsa_key.h" #include "soter/soter_rsa_key_pair_gen.h" #include "soter/soter_t.h" #include "soter/soter_wipe.h" #include "themis/themis_portable_endian.h" #ifndef THEMIS_RSA_KEY_LENGTH #define THEMIS_RSA_KEY_LENGTH RSA_KEY_LENGTH_2048 #endif /* * This is the default key length recommended for use with Secure Cell. * It will have enough randomness for AES-256 (normally used by Themis) * and is consistent with NIST recommendations for the next ten years, * as of 2020. See: https://www.keylength.com/en/4/ */ #define THEMIS_SYM_KEY_LENGTH 32 static themis_status_t combine_key_generation_results(uint8_t* private_key, const size_t* private_key_length, themis_status_t private_result, uint8_t* public_key, const size_t* public_key_length, themis_status_t public_result) { if (private_result == THEMIS_SUCCESS && public_result == THEMIS_SUCCESS) { return THEMIS_SUCCESS; } if (private_result != THEMIS_BUFFER_TOO_SMALL) { soter_wipe(private_key, *private_key_length); } if (public_result != THEMIS_BUFFER_TOO_SMALL) { soter_wipe(public_key, *public_key_length); } if (private_result == THEMIS_BUFFER_TOO_SMALL || public_result == THEMIS_BUFFER_TOO_SMALL) { return THEMIS_BUFFER_TOO_SMALL; } return (private_result != THEMIS_SUCCESS) ? private_result : public_result; } themis_status_t themis_gen_key_pair(soter_sign_alg_t alg, uint8_t* private_key, size_t* private_key_length, uint8_t* public_key, size_t* public_key_length) { themis_status_t private_result = THEMIS_FAIL; themis_status_t public_result = THEMIS_FAIL; soter_sign_ctx_t* ctx = NULL; if (!private_key_length || !public_key_length) { return THEMIS_INVALID_PARAMETER; } ctx = soter_sign_create(alg, NULL, 0, NULL, 0); if (!ctx) { return THEMIS_FAIL; } private_result = soter_sign_export_key(ctx, private_key, private_key_length, true); public_result = soter_sign_export_key(ctx, public_key, public_key_length, false); soter_sign_destroy(ctx); return combine_key_generation_results(private_key, private_key_length, private_result, public_key, public_key_length, public_result); } themis_status_t themis_gen_rsa_key_pair(uint8_t* private_key, size_t* private_key_length, uint8_t* public_key, size_t* public_key_length) { themis_status_t private_result = THEMIS_FAIL; themis_status_t public_result = THEMIS_FAIL; soter_rsa_key_pair_gen_t* ctx = NULL; if (!private_key_length || !public_key_length) { return THEMIS_INVALID_PARAMETER; } ctx = soter_rsa_key_pair_gen_create(THEMIS_RSA_KEY_LENGTH); if (!ctx) { return THEMIS_FAIL; } private_result = soter_rsa_key_pair_gen_export_key(ctx, private_key, private_key_length, true); public_result = soter_rsa_key_pair_gen_export_key(ctx, public_key, public_key_length, false); soter_rsa_key_pair_gen_destroy(ctx); return combine_key_generation_results(private_key, private_key_length, private_result, public_key, public_key_length, public_result); } themis_status_t themis_gen_ec_key_pair(uint8_t* private_key, size_t* private_key_length, uint8_t* public_key, size_t* public_key_length) { return themis_gen_key_pair(SOTER_SIGN_ecdsa_none_pkcs8, private_key, private_key_length, public_key, public_key_length); } themis_key_kind_t themis_get_asym_key_kind(const uint8_t* key, size_t length) { const soter_container_hdr_t* container = (const void*)key; if (!key || (length < sizeof(soter_container_hdr_t))) { return THEMIS_KEY_INVALID; } if (!memcmp(container->tag, RSA_PRIV_KEY_PREF, strlen(RSA_PRIV_KEY_PREF))) { return THEMIS_KEY_RSA_PRIVATE; } if (!memcmp(container->tag, RSA_PUB_KEY_PREF, strlen(RSA_PUB_KEY_PREF))) { return THEMIS_KEY_RSA_PUBLIC; } if (!memcmp(container->tag, EC_PRIV_KEY_PREF, strlen(EC_PRIV_KEY_PREF))) { return THEMIS_KEY_EC_PRIVATE; } if (!memcmp(container->tag, EC_PUB_KEY_PREF, strlen(EC_PUB_KEY_PREF))) { return THEMIS_KEY_EC_PUBLIC; } return THEMIS_KEY_INVALID; } themis_status_t themis_is_valid_asym_key(const uint8_t* key, size_t length) { const soter_container_hdr_t* container = (const void*)key; themis_key_kind_t kind = THEMIS_KEY_INVALID; if (!key || (length < sizeof(soter_container_hdr_t))) { return THEMIS_INVALID_PARAMETER; } kind = themis_get_asym_key_kind(key, length); if (kind == THEMIS_KEY_INVALID) { return THEMIS_INVALID_PARAMETER; } if (length != be32toh(container->size)) { return THEMIS_INVALID_PARAMETER; } if (SOTER_SUCCESS != soter_verify_container_checksum(container)) { return THEMIS_DATA_CORRUPT; } switch (kind) { case THEMIS_KEY_RSA_PRIVATE: return soter_rsa_priv_key_check_length(container, length); case THEMIS_KEY_RSA_PUBLIC: return soter_rsa_pub_key_check_length(container, length); case THEMIS_KEY_EC_PRIVATE: return soter_ec_priv_key_check_length(container, length); case THEMIS_KEY_EC_PUBLIC: return soter_ec_pub_key_check_length(container, length); default: return THEMIS_INVALID_PARAMETER; } return THEMIS_INVALID_PARAMETER; } themis_status_t themis_gen_sym_key(uint8_t* key, size_t* key_length) { if (key_length == NULL) { return THEMIS_INVALID_PARAMETER; } if (key == NULL || *key_length == 0) { *key_length = THEMIS_SYM_KEY_LENGTH; return THEMIS_BUFFER_TOO_SMALL; } /* soter_rand() wipes the key on failure, soter_wipe() not needed */ return soter_rand(key, *key_length); }
3,869
2,151
<gh_stars>1000+ // Copyright 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/chromeos/policy/component_active_directory_policy_retriever.h" #include "base/bind.h" #include "base/test/scoped_task_environment.h" #include "chromeos/dbus/dbus_thread_manager.h" #include "chromeos/dbus/fake_session_manager_client.h" #include "chromeos/dbus/session_manager_client.h" #include "components/policy/core/common/cloud/policy_builder.h" #include "components/policy/core/common/policy_test_utils.h" #include "components/policy/proto/device_management_backend.pb.h" #include "testing/gtest/include/gtest/gtest.h" namespace em = enterprise_management; namespace chromeos { class FakeSessionManagerClient; } namespace { constexpr char kExtensionId[] = "abcdefghabcdefghabcdefghabcdefgh"; constexpr char kFakePolicy[] = "fake_policy"; constexpr char kEmptyAccountId[] = ""; } // namespace namespace policy { using RetrieveResult = ComponentActiveDirectoryPolicyRetriever::RetrieveResult; using RetrieveCallback = ComponentActiveDirectoryPolicyRetriever::RetrieveCallback; using ResponseType = ComponentActiveDirectoryPolicyRetriever::ResponseType; class ComponentActiveDirectoryPolicyRetrieverTest : public testing::Test { protected: ComponentActiveDirectoryPolicyRetrieverTest() { auto session_manager_client = std::make_unique<chromeos::FakeSessionManagerClient>(); session_manager_client_ = session_manager_client.get(); chromeos::DBusThreadManager::GetSetterForTesting()->SetSessionManagerClient( std::move(session_manager_client)); } RetrieveCallback CreateRetrieveCallback() { return base::BindOnce( &ComponentActiveDirectoryPolicyRetrieverTest::OnPoliciesRetrieved, base::Unretained(this)); } void OnPoliciesRetrieved(std::vector<RetrieveResult> results) { callback_called_ = true; results_ = std::move(results); } chromeos::VoidDBusMethodCallback CreateStoredCallback() { return base::BindOnce( &ComponentActiveDirectoryPolicyRetrieverTest::OnPolicyStored, base::Unretained(this)); } void OnPolicyStored(bool success) { policy_stored_ = success; } base::test::ScopedTaskEnvironment scoped_task_environment_; std::vector<RetrieveResult> results_; bool policy_stored_ = false; bool callback_called_ = false; chromeos::FakeSessionManagerClient* session_manager_client_; // Not owned. }; TEST_F(ComponentActiveDirectoryPolicyRetrieverTest, RetrieveNoPolicy) { const std::vector<PolicyNamespace> empty_namespaces; EXPECT_FALSE(callback_called_); ComponentActiveDirectoryPolicyRetriever retriever( login_manager::ACCOUNT_TYPE_DEVICE, kEmptyAccountId, empty_namespaces, CreateRetrieveCallback()); retriever.Start(); scoped_task_environment_.RunUntilIdle(); EXPECT_TRUE(results_.empty()); EXPECT_TRUE(callback_called_); } TEST_F(ComponentActiveDirectoryPolicyRetrieverTest, RetrieveEmptyPolicy) { std::vector<PolicyNamespace> namespaces = { PolicyNamespace(POLICY_DOMAIN_EXTENSIONS, kExtensionId)}; ComponentActiveDirectoryPolicyRetriever retriever( login_manager::ACCOUNT_TYPE_DEVICE, kEmptyAccountId, namespaces, CreateRetrieveCallback()); retriever.Start(); scoped_task_environment_.RunUntilIdle(); ASSERT_EQ(1UL, results_.size()); EXPECT_EQ(namespaces[0], results_[0].ns); EXPECT_EQ(ResponseType::SUCCESS, results_[0].response); EXPECT_TRUE(results_[0].policy_fetch_response_blob.empty()); } TEST_F(ComponentActiveDirectoryPolicyRetrieverTest, RetrievePolicies) { // Build a policy fetch response blob (|session_manager_client_| needs one). ComponentActiveDirectoryPolicyBuilder builder; builder.set_payload(kFakePolicy); builder.Build(); const std::string policy_blob = builder.GetBlob(); // Store the fake extension policy. login_manager::PolicyDescriptor descriptor; descriptor.set_account_type(login_manager::ACCOUNT_TYPE_DEVICE); descriptor.set_domain(login_manager::POLICY_DOMAIN_EXTENSIONS); descriptor.set_component_id(kExtensionId); session_manager_client_->StorePolicy(descriptor, policy_blob, CreateStoredCallback()); scoped_task_environment_.RunUntilIdle(); EXPECT_TRUE(policy_stored_); // Retrieve the fake extension policy and make sure it matches. std::vector<PolicyNamespace> namespaces = { PolicyNamespace(POLICY_DOMAIN_EXTENSIONS, kExtensionId)}; ComponentActiveDirectoryPolicyRetriever retriever( login_manager::ACCOUNT_TYPE_DEVICE, kEmptyAccountId, namespaces, CreateRetrieveCallback()); retriever.Start(); scoped_task_environment_.RunUntilIdle(); ASSERT_EQ(1UL, results_.size()); EXPECT_EQ(namespaces[0], results_[0].ns); EXPECT_EQ(ResponseType::SUCCESS, results_[0].response); EXPECT_EQ(policy_blob, results_[0].policy_fetch_response_blob); } // Makes sure cancellation won't access invalid memory. TEST_F(ComponentActiveDirectoryPolicyRetrieverTest, CancelClean) { std::vector<PolicyNamespace> namespaces = { PolicyNamespace(POLICY_DOMAIN_EXTENSIONS, kExtensionId)}; auto retriever = std::make_unique<ComponentActiveDirectoryPolicyRetriever>( login_manager::ACCOUNT_TYPE_DEVICE, kEmptyAccountId, namespaces, CreateRetrieveCallback()); retriever->Start(); retriever.reset(); scoped_task_environment_.RunUntilIdle(); ASSERT_EQ(0UL, results_.size()); } } // namespace policy
1,829
1,006
<gh_stars>1000+ /**************************************************************************** * include/nuttx/rf/ioctl.h * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ****************************************************************************/ #ifndef __INCLUDE_NUTTX_RF_IOCTL_H #define __INCLUDE_NUTTX_RF_IOCTL_H /**************************************************************************** * Included Files ****************************************************************************/ #include <nuttx/config.h> #include <nuttx/fs/ioctl.h> /* Generic IOCTLs commands used for digital attenuators */ #define RFIOC_SETATT _RFIOC(0x0001) /* Set the attenuation, Arg: struct attenuator_control* */ #endif
337
315
<reponame>g-r-a-n-t/py-libp2p import pytest import trio from libp2p.host.exceptions import StreamFailure from libp2p.peer.peerinfo import info_from_p2p_addr from libp2p.tools.factories import HostFactory from libp2p.tools.utils import MAX_READ_LEN PROTOCOL_ID = "/chat/1.0.0" async def hello_world(host_a, host_b): hello_world_from_host_a = b"hello world from host a" hello_world_from_host_b = b"hello world from host b" async def stream_handler(stream): read = await stream.read(len(hello_world_from_host_b)) assert read == hello_world_from_host_b await stream.write(hello_world_from_host_a) await stream.close() host_a.set_stream_handler(PROTOCOL_ID, stream_handler) # Start a stream with the destination. # Multiaddress of the destination peer is fetched from the peerstore using 'peerId'. stream = await host_b.new_stream(host_a.get_id(), [PROTOCOL_ID]) await stream.write(hello_world_from_host_b) read = await stream.read(MAX_READ_LEN) assert read == hello_world_from_host_a await stream.close() async def connect_write(host_a, host_b): messages = ["data %d" % i for i in range(5)] received = [] async def stream_handler(stream): for message in messages: received.append((await stream.read(len(message))).decode()) host_a.set_stream_handler(PROTOCOL_ID, stream_handler) # Start a stream with the destination. # Multiaddress of the destination peer is fetched from the peerstore using 'peerId'. stream = await host_b.new_stream(host_a.get_id(), [PROTOCOL_ID]) for message in messages: await stream.write(message.encode()) # Reader needs time due to async reads await trio.sleep(2) await stream.close() assert received == messages async def connect_read(host_a, host_b): messages = [b"data %d" % i for i in range(5)] async def stream_handler(stream): for message in messages: await stream.write(message) await stream.close() host_a.set_stream_handler(PROTOCOL_ID, stream_handler) # Start a stream with the destination. # Multiaddress of the destination peer is fetched from the peerstore using 'peerId'. stream = await host_b.new_stream(host_a.get_id(), [PROTOCOL_ID]) received = [] for message in messages: received.append(await stream.read(len(message))) await stream.close() assert received == messages async def no_common_protocol(host_a, host_b): messages = [b"data %d" % i for i in range(5)] async def stream_handler(stream): for message in messages: await stream.write(message) await stream.close() host_a.set_stream_handler(PROTOCOL_ID, stream_handler) # try to creates a new new with a procotol not known by the other host with pytest.raises(StreamFailure): await host_b.new_stream(host_a.get_id(), ["/fakeproto/0.0.1"]) @pytest.mark.parametrize( "test", [(hello_world), (connect_write), (connect_read), (no_common_protocol)] ) @pytest.mark.trio async def test_chat(test, security_protocol): print("!@# ", security_protocol) async with HostFactory.create_batch_and_listen( 2, security_protocol=security_protocol ) as hosts: addr = hosts[0].get_addrs()[0] info = info_from_p2p_addr(addr) await hosts[1].connect(info) await test(hosts[0], hosts[1])
1,329
854
<reponame>rakhi2001/ecom7<gh_stars>100-1000 __________________________________________________________________________________________________ sample 48 ms submission class Solution: def findMin(self, nums: List[int]) -> int: l, r = 0, len(nums)-1 while l+1 < r: mid = (l+r)//2 if nums[mid] == nums[l]: l += 1 elif nums[mid] <= nums[r]: r = mid else: l = mid if nums[l] < nums[r]: return nums[l] else: return nums[r] __________________________________________________________________________________________________ sample 13216 kb submission class Solution: def findMin(self, nums: List[int]) -> int: if len(nums)==1: return nums[0] low, high = 0, len(nums) mid = (low + high) // 2 if nums[low] == nums[high-1]: return min(self.findMin(nums[low:mid]),self.findMin(nums[mid:high])) if nums[low] < nums[high-1]: return nums[low] if nums[low] > nums[high-1]: if nums[mid]<nums[high-1]: return self.findMin(nums[low:mid+1]) if nums[mid]==nums[high-1]: return min(self.findMin(nums[low:mid]),self.findMin(nums[mid:high])) else: return self.findMin(nums[mid:high]) __________________________________________________________________________________________________
748
575
// Copyright 2018 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 "components/exo/text_input.h" #include <memory> #include <string> #include "base/strings/utf_string_conversions.h" #include "components/exo/buffer.h" #include "components/exo/shell_surface.h" #include "components/exo/surface.h" #include "components/exo/test/exo_test_base.h" #include "components/exo/test/exo_test_helper.h" #include "testing/gmock/include/gmock/gmock.h" #include "ui/aura/window_tree_host.h" #include "ui/base/ime/composition_text.h" #include "ui/base/ime/input_method_observer.h" #include "ui/events/keycodes/dom/dom_code.h" #include "ui/views/widget/widget.h" using testing::_; namespace exo { namespace { class MockTextInputDelegate : public TextInput::Delegate { public: MockTextInputDelegate() = default; // TextInput::Delegate: MOCK_METHOD0(Activated, void()); MOCK_METHOD0(Deactivated, void()); MOCK_METHOD1(OnVirtualKeyboardVisibilityChanged, void(bool)); MOCK_METHOD1(SetCompositionText, void(const ui::CompositionText&)); MOCK_METHOD1(Commit, void(const std::u16string&)); MOCK_METHOD1(SetCursor, void(const gfx::Range&)); MOCK_METHOD1(DeleteSurroundingText, void(const gfx::Range&)); MOCK_METHOD1(SendKey, void(const ui::KeyEvent&)); MOCK_METHOD1(OnLanguageChanged, void(const std::string&)); MOCK_METHOD1(OnTextDirectionChanged, void(base::i18n::TextDirection direction)); private: DISALLOW_COPY_AND_ASSIGN(MockTextInputDelegate); }; class TestingInputMethodObserver : public ui::InputMethodObserver { public: explicit TestingInputMethodObserver(ui::InputMethod* input_method) : input_method_(input_method) { input_method_->AddObserver(this); } ~TestingInputMethodObserver() override { input_method_->RemoveObserver(this); } // ui::InputMethodObserver MOCK_METHOD0(OnFocus, void()); MOCK_METHOD0(OnBlur, void()); MOCK_METHOD1(OnCaretBoundsChanged, void(const ui::TextInputClient*)); MOCK_METHOD1(OnTextInputStateChanged, void(const ui::TextInputClient*)); MOCK_METHOD1(OnInputMethodDestroyed, void(const ui::InputMethod*)); MOCK_METHOD0(OnShowVirtualKeyboardIfEnabled, void()); private: ui::InputMethod* input_method_ = nullptr; DISALLOW_COPY_AND_ASSIGN(TestingInputMethodObserver); }; class TextInputTest : public test::ExoTestBase { public: TextInputTest() = default; void SetUp() override { test::ExoTestBase::SetUp(); text_input_ = std::make_unique<TextInput>(std::make_unique<MockTextInputDelegate>()); SetupSurface(); } void TearDown() override { TearDownSurface(); text_input_.reset(); test::ExoTestBase::TearDown(); } void SetupSurface() { gfx::Size buffer_size(32, 32); buffer_ = std::make_unique<Buffer>( exo_test_helper()->CreateGpuMemoryBuffer(buffer_size)); surface_ = std::make_unique<Surface>(); shell_surface_ = std::make_unique<ShellSurface>(surface_.get()); surface_->Attach(buffer_.get()); surface_->Commit(); gfx::Point origin(100, 100); shell_surface_->SetGeometry(gfx::Rect(origin, buffer_size)); } void TearDownSurface() { shell_surface_.reset(); surface_.reset(); buffer_.reset(); } protected: TextInput* text_input() { return text_input_.get(); } MockTextInputDelegate* delegate() { return static_cast<MockTextInputDelegate*>(text_input_->delegate()); } Surface* surface() { return surface_.get(); } ui::InputMethod* GetInputMethod() { return surface_->window()->GetHost()->GetInputMethod(); } void SetCompositionText(const std::string& utf8) { ui::CompositionText t; t.text = base::UTF8ToUTF16(utf8); t.selection = gfx::Range(1u); t.ime_text_spans.push_back( ui::ImeTextSpan(ui::ImeTextSpan::Type::kComposition, 0, t.text.size(), ui::ImeTextSpan::Thickness::kThick)); EXPECT_CALL(*delegate(), SetCompositionText(t)).Times(1); text_input()->SetCompositionText(t); } private: std::unique_ptr<TextInput> text_input_; std::unique_ptr<Buffer> buffer_; std::unique_ptr<Surface> surface_; std::unique_ptr<ShellSurface> shell_surface_; DISALLOW_COPY_AND_ASSIGN(TextInputTest); }; TEST_F(TextInputTest, Activate) { EXPECT_EQ(ui::TEXT_INPUT_TYPE_NONE, text_input()->GetTextInputType()); EXPECT_EQ(ui::TEXT_INPUT_MODE_DEFAULT, text_input()->GetTextInputMode()); EXPECT_CALL(*delegate(), Activated).Times(1); text_input()->Activate(surface()); EXPECT_EQ(ui::TEXT_INPUT_TYPE_TEXT, text_input()->GetTextInputType()); EXPECT_EQ(ui::TEXT_INPUT_MODE_TEXT, text_input()->GetTextInputMode()); EXPECT_EQ(0, text_input()->GetTextInputFlags()); EXPECT_CALL(*delegate(), Deactivated).Times(1); text_input()->Deactivate(); EXPECT_EQ(ui::TEXT_INPUT_TYPE_NONE, text_input()->GetTextInputType()); EXPECT_EQ(ui::TEXT_INPUT_MODE_DEFAULT, text_input()->GetTextInputMode()); } TEST_F(TextInputTest, ShowVirtualKeyboardIfEnabled) { TestingInputMethodObserver observer(GetInputMethod()); EXPECT_CALL(observer, OnTextInputStateChanged(text_input())).Times(1); EXPECT_CALL(*delegate(), Activated).Times(1); text_input()->Activate(surface()); EXPECT_CALL(observer, OnShowVirtualKeyboardIfEnabled) .WillOnce(testing::Invoke( [this]() { text_input()->OnKeyboardVisibilityChanged(true); })); EXPECT_CALL(*delegate(), OnVirtualKeyboardVisibilityChanged(true)).Times(1); text_input()->ShowVirtualKeyboardIfEnabled(); EXPECT_CALL(observer, OnTextInputStateChanged(nullptr)).Times(1); EXPECT_CALL(*delegate(), Deactivated).Times(1); text_input()->Deactivate(); } TEST_F(TextInputTest, ShowVirtualKeyboardIfEnabledBeforeActivated) { TestingInputMethodObserver observer(GetInputMethod()); // ShowVirtualKeyboardIfEnabled before activation. text_input()->ShowVirtualKeyboardIfEnabled(); EXPECT_CALL(observer, OnTextInputStateChanged(text_input())).Times(1); EXPECT_CALL(observer, OnShowVirtualKeyboardIfEnabled) .WillOnce(testing::Invoke( [this]() { text_input()->OnKeyboardVisibilityChanged(true); })); EXPECT_CALL(*delegate(), Activated).Times(1); EXPECT_CALL(*delegate(), OnVirtualKeyboardVisibilityChanged(true)).Times(1); text_input()->Activate(surface()); EXPECT_CALL(*delegate(), Deactivated).Times(1); } TEST_F(TextInputTest, SetTypeModeFlag) { TestingInputMethodObserver observer(GetInputMethod()); EXPECT_CALL(observer, OnTextInputStateChanged(text_input())).Times(1); EXPECT_CALL(*delegate(), Activated).Times(1); text_input()->Activate(surface()); EXPECT_EQ(ui::TEXT_INPUT_TYPE_TEXT, text_input()->GetTextInputType()); EXPECT_EQ(ui::TEXT_INPUT_MODE_TEXT, text_input()->GetTextInputMode()); EXPECT_EQ(0, text_input()->GetTextInputFlags()); EXPECT_TRUE(text_input()->ShouldDoLearning()); int flags = ui::TEXT_INPUT_FLAG_AUTOCOMPLETE_OFF | ui::TEXT_INPUT_FLAG_AUTOCAPITALIZE_NONE; EXPECT_CALL(observer, OnTextInputStateChanged(text_input())).Times(1); text_input()->SetTypeModeFlags(ui::TEXT_INPUT_TYPE_URL, ui::TEXT_INPUT_MODE_URL, flags, false); EXPECT_EQ(ui::TEXT_INPUT_TYPE_URL, text_input()->GetTextInputType()); EXPECT_EQ(ui::TEXT_INPUT_MODE_URL, text_input()->GetTextInputMode()); EXPECT_EQ(flags, text_input()->GetTextInputFlags()); EXPECT_FALSE(text_input()->ShouldDoLearning()); EXPECT_CALL(*delegate(), Deactivated).Times(1); } TEST_F(TextInputTest, CaretBounds) { TestingInputMethodObserver observer(GetInputMethod()); EXPECT_CALL(observer, OnTextInputStateChanged(text_input())).Times(1); EXPECT_CALL(*delegate(), Activated).Times(1); text_input()->Activate(surface()); gfx::Rect bounds(10, 10, 0, 16); EXPECT_CALL(observer, OnCaretBoundsChanged(text_input())).Times(1); text_input()->SetCaretBounds(bounds); EXPECT_EQ(bounds.size().ToString(), text_input()->GetCaretBounds().size().ToString()); gfx::Point origin = surface()->window()->GetBoundsInScreen().origin(); origin += bounds.OffsetFromOrigin(); EXPECT_EQ(origin.ToString(), text_input()->GetCaretBounds().origin().ToString()); EXPECT_CALL(*delegate(), Deactivated).Times(1); } TEST_F(TextInputTest, CompositionText) { SetCompositionText("composition"); ui::CompositionText empty; EXPECT_CALL(*delegate(), SetCompositionText(empty)).Times(1); text_input()->ClearCompositionText(); } TEST_F(TextInputTest, CompositionTextEmpty) { SetCompositionText(""); EXPECT_CALL(*delegate(), SetCompositionText(_)).Times(0); text_input()->ClearCompositionText(); } TEST_F(TextInputTest, CommitCompositionText) { SetCompositionText("composition"); EXPECT_CALL(*delegate(), Commit(base::UTF8ToUTF16("composition"))).Times(1); const uint32_t composition_text_length = text_input()->ConfirmCompositionText(/** keep_selection */ false); EXPECT_EQ(composition_text_length, static_cast<uint32_t>(11)); } TEST_F(TextInputTest, Commit) { std::u16string s = u"commit text"; EXPECT_CALL(*delegate(), Commit(s)).Times(1); text_input()->InsertText( s, ui::TextInputClient::InsertTextCursorBehavior::kMoveCursorAfterText); } TEST_F(TextInputTest, InsertChar) { text_input()->Activate(surface()); ui::KeyEvent ev(ui::ET_KEY_PRESSED, ui::VKEY_RETURN, 0); EXPECT_CALL(*delegate(), SendKey(testing::Ref(ev))).Times(1); text_input()->InsertChar(ev); } TEST_F(TextInputTest, InsertCharCtrlV) { text_input()->Activate(surface()); // CTRL+V is interpreted as non-IME consumed KeyEvent, so should // not be sent. ui::KeyEvent ev(ui::ET_KEY_PRESSED, ui::VKEY_V, ui::EF_CONTROL_DOWN); EXPECT_CALL(*delegate(), SendKey(_)).Times(0); text_input()->InsertChar(ev); } TEST_F(TextInputTest, InsertCharNormalKey) { text_input()->Activate(surface()); char16_t ch = 'x'; ui::KeyEvent ev(ch, ui::VKEY_X, ui::DomCode::NONE, 0); EXPECT_CALL(*delegate(), Commit(std::u16string(1, ch))).Times(1); EXPECT_CALL(*delegate(), SendKey(_)).Times(0); text_input()->InsertChar(ev); } TEST_F(TextInputTest, SurroundingText) { gfx::Range range; EXPECT_FALSE(text_input()->GetTextRange(&range)); EXPECT_FALSE(text_input()->GetCompositionTextRange(&range)); EXPECT_FALSE(text_input()->GetEditableSelectionRange(&range)); std::u16string got_text; EXPECT_FALSE(text_input()->GetTextFromRange(gfx::Range(0, 1), &got_text)); std::u16string text = base::UTF8ToUTF16("surrounding\xE3\x80\x80text"); text_input()->SetSurroundingText(text, 11, 12); EXPECT_TRUE(text_input()->GetTextRange(&range)); EXPECT_EQ(gfx::Range(0, text.size()).ToString(), range.ToString()); EXPECT_FALSE(text_input()->GetCompositionTextRange(&range)); EXPECT_TRUE(text_input()->GetEditableSelectionRange(&range)); EXPECT_EQ(gfx::Range(11, 12).ToString(), range.ToString()); EXPECT_TRUE(text_input()->GetTextFromRange(gfx::Range(11, 12), &got_text)); EXPECT_EQ(text.substr(11, 1), got_text); // DeleteSurroundingText receives the range in UTF8 -- so (11, 14) range is // expected. EXPECT_CALL(*delegate(), DeleteSurroundingText(gfx::Range(11, 14))).Times(1); text_input()->ExtendSelectionAndDelete(0, 0); size_t composition_size = std::string("composition").size(); SetCompositionText("composition"); EXPECT_TRUE(text_input()->GetCompositionTextRange(&range)); EXPECT_EQ(gfx::Range(11, 11 + composition_size).ToString(), range.ToString()); EXPECT_TRUE(text_input()->GetTextRange(&range)); EXPECT_EQ(gfx::Range(0, text.size() - 1 + composition_size).ToString(), range.ToString()); EXPECT_TRUE(text_input()->GetEditableSelectionRange(&range)); EXPECT_EQ(gfx::Range(11, 12).ToString(), range.ToString()); } TEST_F(TextInputTest, GetTextRange) { std::u16string text = u"surrounding text"; text_input()->SetSurroundingText(text, 11, 12); SetCompositionText("composition"); const struct { gfx::Range range; std::string expected; } kTestCases[] = { {gfx::Range(0, 3), "sur"}, {gfx::Range(10, 13), "gco"}, {gfx::Range(10, 23), "gcompositiont"}, {gfx::Range(12, 15), "omp"}, {gfx::Range(12, 23), "ompositiont"}, {gfx::Range(22, 25), "tex"}, }; for (auto& c : kTestCases) { std::u16string result; EXPECT_TRUE(text_input()->GetTextFromRange(c.range, &result)) << c.range.ToString(); EXPECT_EQ(base::UTF8ToUTF16(c.expected), result) << c.range.ToString(); } } } // anonymous namespace } // namespace exo
4,733
1,927
<reponame>alimy/scene /* * Copyright (C) 2019 ByteDance 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.bytedance.scene.utlity; import androidx.annotation.NonNull; import android.view.View; import android.view.ViewGroup; /** * Created by JiangQi on 8/2/18. */ public class AnimatorUtility { public static void resetViewStatus(@NonNull View view) { view.setTranslationX(0); view.setTranslationY(0); view.setScaleX(1.0f); view.setScaleY(1.0f); view.setRotation(0.0f); view.setRotationX(0.0f); view.setRotationY(0.0f); view.setAlpha(1.0f); view.clearAnimation(); } @NonNull public static AnimatorInfo captureViewStatus(@NonNull View view) { return new AnimatorInfo(view.getTranslationX(), view.getTranslationY(), view.getScaleX(), view.getScaleY(), view.getRotation(), view.getRotationX(), view.getRotationY(), view.getAlpha()); } public static void resetViewStatus(@NonNull View view, @NonNull AnimatorInfo animatorInfo) { view.setTranslationX(animatorInfo.translationX); view.setTranslationY(animatorInfo.translationY); view.setScaleX(animatorInfo.scaleX); view.setScaleY(animatorInfo.scaleY); view.setRotation(animatorInfo.rotation); view.setRotationX(animatorInfo.rotationX); view.setRotationY(animatorInfo.rotationY); view.setAlpha(animatorInfo.alpha); } public static void bringToFrontIfNeeded(@NonNull View view) { ViewGroup viewGroup = (ViewGroup) view.getParent(); int childCount = viewGroup.getChildCount(); int childIndex = viewGroup.indexOfChild(view); if (childIndex >= 0 && childIndex != childCount - 1) { view.bringToFront(); } } public static class AnimatorInfo { public final float translationX; public final float translationY; public final float scaleX; public final float scaleY; public final float rotation; public final float rotationX; public final float rotationY; public final float alpha; public AnimatorInfo(float translationX, float translationY, float scaleX, float scaleY, float rotation, float rotationX, float rotationY, float alpha) { this.translationX = translationX; this.translationY = translationY; this.scaleX = scaleX; this.scaleY = scaleY; this.rotation = rotation; this.rotationX = rotationX; this.rotationY = rotationY; this.alpha = alpha; } } }
1,395
348
<gh_stars>100-1000 {"nom":"Pierrefitte-Nestalas","dpt":"Hautes-Pyrénées","inscrits":973,"abs":232,"votants":741,"blancs":105,"nuls":33,"exp":603,"res":[{"panneau":"1","voix":418},{"panneau":"2","voix":185}]}
90
14,668
// Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "third_party/blink/renderer/core/svg/svg_path_query.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/blink/renderer/core/svg/svg_path_byte_stream.h" #include "third_party/blink/renderer/core/svg/svg_path_utilities.h" #include "ui/gfx/geometry/point_f.h" #include "ui/gfx/geometry/test/geometry_util.h" namespace blink { namespace { TEST(SVGPathQueryTest, PointAtLength_ArcDecomposedToMultipleCubics) { SVGPathByteStream path_stream; ASSERT_EQ(BuildByteStreamFromString("M56.2,66.2a174.8,174.8,0,1,0,276.0,-2.0", path_stream), SVGParseStatus::kNoError); constexpr float kStep = 7.80249691f; constexpr float kTolerance = 0.0005f; EXPECT_POINTF_NEAR(SVGPathQuery(path_stream).GetPointAtLength(0), gfx::PointF(56.200f, 66.200f), kTolerance); EXPECT_POINTF_NEAR(SVGPathQuery(path_stream).GetPointAtLength(kStep), gfx::PointF(51.594f, 72.497f), kTolerance); EXPECT_POINTF_NEAR(SVGPathQuery(path_stream).GetPointAtLength(2 * kStep), gfx::PointF(47.270f, 78.991f), kTolerance); EXPECT_POINTF_NEAR(SVGPathQuery(path_stream).GetPointAtLength(3 * kStep), gfx::PointF(43.239f, 85.671f), kTolerance); } } // namespace } // namespace blink
669
607
<reponame>kirill-grouchnikov/radiance<gh_stars>100-1000 package org.pushingpixels.radiance.demo.component.svg.tango.transcoded; import java.awt.*; import java.awt.geom.*; import java.awt.image.BufferedImage; import java.io.*; import java.lang.ref.WeakReference; import java.util.Base64; import java.util.Stack; import javax.imageio.ImageIO; import javax.swing.SwingUtilities; import javax.swing.plaf.UIResource; import org.pushingpixels.radiance.common.api.icon.RadianceIcon; import org.pushingpixels.radiance.common.api.icon.RadianceIconUIResource; /** * This class has been automatically generated using <a * href="https://github.com/kirill-grouchnikov/radiance">Radiance SVG transcoder</a>. */ public class Internet_group_chat implements RadianceIcon { private Shape shape = null; private GeneralPath generalPath = null; private Paint paint = null; private Stroke stroke = null; private Shape clip = null; private RadianceIcon.ColorFilter colorFilter = null; private Stack<AffineTransform> transformsStack = new Stack<>(); private void _paint0(Graphics2D g,float origAlpha) { // g.setComposite(AlphaComposite.getInstance(3, 1.0f * origAlpha)); // _0 g.setComposite(AlphaComposite.getInstance(3, 1.0f * origAlpha)); transformsStack.push(g.getTransform()); g.transform(new AffineTransform(1.0f, 0.0f, 0.0f, 1.0f, 10.75f, -6.5f)); // _0_0 g.setComposite(AlphaComposite.getInstance(3, 0.12f * origAlpha)); // _0_0_0 shape = new Ellipse2D.Double(3.59999942779541, 32.580997467041016, 31.6200008392334, 8.718000411987305); paint = new RadialGradientPaint(new Point2D.Double(29.5, 27.639999389648438), 11.52f, new Point2D.Double(29.5, 27.639999389648438), new float[] {0.0f,1.0f}, new Color[] {((colorFilter != null) ? colorFilter.filter(new Color(0, 0, 0, 255)) : new Color(0, 0, 0, 255)),((colorFilter != null) ? colorFilter.filter(new Color(0, 0, 0, 0)) : new Color(0, 0, 0, 0))}, MultipleGradientPaint.CycleMethod.NO_CYCLE, MultipleGradientPaint.ColorSpaceType.SRGB, new AffineTransform(1.3730000257492065f, 0.0f, 0.0f, 0.3785000145435333f, -21.09000015258789f, 26.469999313354492f)); g.setPaint(paint); g.fill(shape); g.setTransform(transformsStack.pop()); g.setComposite(AlphaComposite.getInstance(3, 0.12f * origAlpha)); // _0_1 shape = new Ellipse2D.Double(3.59999942779541, 32.580997467041016, 31.6200008392334, 8.718000411987305); paint = new RadialGradientPaint(new Point2D.Double(29.5, 27.639999389648438), 11.52f, new Point2D.Double(29.5, 27.639999389648438), new float[] {0.0f,1.0f}, new Color[] {((colorFilter != null) ? colorFilter.filter(new Color(0, 0, 0, 255)) : new Color(0, 0, 0, 255)),((colorFilter != null) ? colorFilter.filter(new Color(0, 0, 0, 0)) : new Color(0, 0, 0, 0))}, MultipleGradientPaint.CycleMethod.NO_CYCLE, MultipleGradientPaint.ColorSpaceType.SRGB, new AffineTransform(1.3730000257492065f, 0.0f, 0.0f, 0.3785000145435333f, -21.09000015258789f, 26.469999313354492f)); g.setPaint(paint); g.fill(shape); g.setComposite(AlphaComposite.getInstance(3, 1.0f * origAlpha)); transformsStack.push(g.getTransform()); g.transform(new AffineTransform(-1.0299999713897705f, 0.0f, 0.0f, 0.989799976348877f, 49.08000183105469f, -8.723999977111816f)); // _0_2 g.setComposite(AlphaComposite.getInstance(3, 1.0f * origAlpha)); // _0_2_0 g.setComposite(AlphaComposite.getInstance(3, 1.0f * origAlpha)); // _0_2_0_0 if (generalPath == null) { generalPath = new GeneralPath(); } else { generalPath.reset(); } generalPath.moveTo(31.64f, 17.39f); generalPath.lineTo(31.64f, 32.579998f); generalPath.curveTo(31.64f, 33.639f, 30.817f, 34.477997f, 29.778f, 34.477997f); generalPath.lineTo(16.068f, 34.477997f); generalPath.curveTo(15.237f, 35.590996f, 13.564001f, 37.406f, 9.641001f, 38.887997f); generalPath.curveTo(11.366001f, 36.822f, 11.468f, 35.428997f, 11.273001f, 34.477997f); generalPath.lineTo(8.464001f, 34.477997f); generalPath.curveTo(7.4250007f, 34.477997f, 6.5710006f, 33.638996f, 6.5710006f, 32.579998f); generalPath.lineTo(6.5710006f, 17.39f); generalPath.curveTo(6.5710006f, 16.331f, 7.4250007f, 15.459999f, 8.464001f, 15.459999f); generalPath.lineTo(29.784f, 15.459999f); generalPath.curveTo(30.823f, 15.459999f, 31.646f, 16.331f, 31.646f, 17.39f); generalPath.closePath(); shape = generalPath; paint = new LinearGradientPaint(new Point2D.Double(36.439998626708984, 19.989999771118164), new Point2D.Double(49.08000183105469, 35.47999954223633), new float[] {0.0f,1.0f}, new Color[] {((colorFilter != null) ? colorFilter.filter(new Color(245, 245, 245, 255)) : new Color(245, 245, 245, 255)),((colorFilter != null) ? colorFilter.filter(new Color(233, 233, 233, 255)) : new Color(233, 233, 233, 255))}, MultipleGradientPaint.CycleMethod.NO_CYCLE, MultipleGradientPaint.ColorSpaceType.SRGB, new AffineTransform(-1.0080000162124634f, 0.0f, 0.0f, 0.9876000285148621f, 61.880001068115234f, 0.2750000059604645f)); g.setPaint(paint); g.fill(shape); paint = (colorFilter != null) ? colorFilter.filter(new Color(120, 120, 120, 255)) : new Color(120, 120, 120, 255); stroke = new BasicStroke(0.99f,0,0,4.0f,null,0.0f); if (generalPath == null) { generalPath = new GeneralPath(); } else { generalPath.reset(); } generalPath.moveTo(31.64f, 17.39f); generalPath.lineTo(31.64f, 32.579998f); generalPath.curveTo(31.64f, 33.639f, 30.817f, 34.477997f, 29.778f, 34.477997f); generalPath.lineTo(16.068f, 34.477997f); generalPath.curveTo(15.237f, 35.590996f, 13.564001f, 37.406f, 9.641001f, 38.887997f); generalPath.curveTo(11.366001f, 36.822f, 11.468f, 35.428997f, 11.273001f, 34.477997f); generalPath.lineTo(8.464001f, 34.477997f); generalPath.curveTo(7.4250007f, 34.477997f, 6.5710006f, 33.638996f, 6.5710006f, 32.579998f); generalPath.lineTo(6.5710006f, 17.39f); generalPath.curveTo(6.5710006f, 16.331f, 7.4250007f, 15.459999f, 8.464001f, 15.459999f); generalPath.lineTo(29.784f, 15.459999f); generalPath.curveTo(30.823f, 15.459999f, 31.646f, 16.331f, 31.646f, 17.39f); generalPath.closePath(); shape = generalPath; g.setPaint(paint); g.setStroke(stroke); g.draw(shape); g.setComposite(AlphaComposite.getInstance(3, 1.0f * origAlpha)); // _0_2_0_1 paint = (colorFilter != null) ? colorFilter.filter(new Color(255, 255, 255, 255)) : new Color(255, 255, 255, 255); stroke = new BasicStroke(0.99f,0,0,4.0f,null,0.0f); if (generalPath == null) { generalPath = new GeneralPath(); } else { generalPath.reset(); } generalPath.moveTo(30.62f, 17.88f); generalPath.lineTo(30.62f, 32.079998f); generalPath.curveTo(30.62f, 33.039997f, 30.378f, 33.447998f, 29.436f, 33.447998f); generalPath.lineTo(15.536001f, 33.447998f); generalPath.curveTo(14.783001f, 34.457996f, 13.468001f, 36.044f, 12.025002f, 36.698997f); generalPath.curveTo(12.428001f, 35.531998f, 12.273002f, 34.562996f, 12.198002f, 33.447998f); generalPath.lineTo(8.791002f, 33.447998f); generalPath.curveTo(7.8490024f, 33.447998f, 7.5790024f, 33.039997f, 7.5790024f, 32.079998f); generalPath.lineTo(7.5790024f, 17.999998f); generalPath.curveTo(7.5790024f, 17.039999f, 7.8490024f, 16.451998f, 8.791002f, 16.451998f); generalPath.lineTo(29.391003f, 16.451998f); generalPath.curveTo(30.334003f, 16.451998f, 30.626003f, 16.912998f, 30.626003f, 17.873999f); generalPath.closePath(); shape = generalPath; g.setPaint(paint); g.setStroke(stroke); g.draw(shape); g.setTransform(transformsStack.pop()); g.setComposite(AlphaComposite.getInstance(3, 1.0f * origAlpha)); // _0_3 g.setComposite(AlphaComposite.getInstance(3, 1.0f * origAlpha)); // _0_3_0 g.setComposite(AlphaComposite.getInstance(3, 1.0f * origAlpha)); // _0_3_0_0 if (generalPath == null) { generalPath = new GeneralPath(); } else { generalPath.reset(); } generalPath.moveTo(31.64f, 17.39f); generalPath.lineTo(31.64f, 32.579998f); generalPath.curveTo(31.64f, 33.639f, 30.817f, 34.477997f, 29.778f, 34.477997f); generalPath.lineTo(16.068f, 34.477997f); generalPath.curveTo(15.237f, 35.590996f, 13.564001f, 37.406f, 9.641001f, 38.887997f); generalPath.curveTo(11.366001f, 36.822f, 11.468f, 35.428997f, 11.273001f, 34.477997f); generalPath.lineTo(8.464001f, 34.477997f); generalPath.curveTo(7.4250007f, 34.477997f, 6.5710006f, 33.638996f, 6.5710006f, 32.579998f); generalPath.lineTo(6.5710006f, 17.39f); generalPath.curveTo(6.5710006f, 16.331f, 7.4250007f, 15.459999f, 8.464001f, 15.459999f); generalPath.lineTo(29.784f, 15.459999f); generalPath.curveTo(30.823f, 15.459999f, 31.646f, 16.331f, 31.646f, 17.39f); generalPath.closePath(); shape = generalPath; paint = new LinearGradientPaint(new Point2D.Double(35.0, 10.960000038146973), new Point2D.Double(27.270000457763672, 24.139999389648438), new float[] {0.0f,1.0f}, new Color[] {((colorFilter != null) ? colorFilter.filter(new Color(245, 245, 245, 255)) : new Color(245, 245, 245, 255)),((colorFilter != null) ? colorFilter.filter(new Color(233, 233, 233, 255)) : new Color(233, 233, 233, 255))}, MultipleGradientPaint.CycleMethod.NO_CYCLE, MultipleGradientPaint.ColorSpaceType.SRGB, new AffineTransform(-0.9771999716758728f, 0.0f, 0.0f, 0.9958999752998352f, 50.599998474121094f, 9.116000175476074f)); g.setPaint(paint); g.fill(shape); paint = (colorFilter != null) ? colorFilter.filter(new Color(120, 120, 120, 255)) : new Color(120, 120, 120, 255); stroke = new BasicStroke(1.0f,0,0,4.0f,null,0.0f); if (generalPath == null) { generalPath = new GeneralPath(); } else { generalPath.reset(); } generalPath.moveTo(31.64f, 17.39f); generalPath.lineTo(31.64f, 32.579998f); generalPath.curveTo(31.64f, 33.639f, 30.817f, 34.477997f, 29.778f, 34.477997f); generalPath.lineTo(16.068f, 34.477997f); generalPath.curveTo(15.237f, 35.590996f, 13.564001f, 37.406f, 9.641001f, 38.887997f); generalPath.curveTo(11.366001f, 36.822f, 11.468f, 35.428997f, 11.273001f, 34.477997f); generalPath.lineTo(8.464001f, 34.477997f); generalPath.curveTo(7.4250007f, 34.477997f, 6.5710006f, 33.638996f, 6.5710006f, 32.579998f); generalPath.lineTo(6.5710006f, 17.39f); generalPath.curveTo(6.5710006f, 16.331f, 7.4250007f, 15.459999f, 8.464001f, 15.459999f); generalPath.lineTo(29.784f, 15.459999f); generalPath.curveTo(30.823f, 15.459999f, 31.646f, 16.331f, 31.646f, 17.39f); generalPath.closePath(); shape = generalPath; g.setPaint(paint); g.setStroke(stroke); g.draw(shape); g.setComposite(AlphaComposite.getInstance(3, 1.0f * origAlpha)); // _0_3_0_1 paint = (colorFilter != null) ? colorFilter.filter(new Color(255, 255, 255, 255)) : new Color(255, 255, 255, 255); stroke = new BasicStroke(1.0f,0,0,4.0f,null,0.0f); if (generalPath == null) { generalPath = new GeneralPath(); } else { generalPath.reset(); } generalPath.moveTo(30.62f, 17.88f); generalPath.lineTo(30.62f, 32.079998f); generalPath.curveTo(30.62f, 33.039997f, 30.378f, 33.447998f, 29.436f, 33.447998f); generalPath.lineTo(15.536001f, 33.447998f); generalPath.curveTo(14.783001f, 34.457996f, 13.468001f, 36.044f, 12.025002f, 36.698997f); generalPath.curveTo(12.428001f, 35.531998f, 12.273002f, 34.562996f, 12.198002f, 33.447998f); generalPath.lineTo(8.791002f, 33.447998f); generalPath.curveTo(7.8490024f, 33.447998f, 7.5790024f, 33.039997f, 7.5790024f, 32.079998f); generalPath.lineTo(7.5790024f, 17.999998f); generalPath.curveTo(7.5790024f, 17.039999f, 7.8490024f, 16.451998f, 8.791002f, 16.451998f); generalPath.lineTo(29.391003f, 16.451998f); generalPath.curveTo(30.334003f, 16.451998f, 30.626003f, 16.912998f, 30.626003f, 17.873999f); generalPath.closePath(); shape = generalPath; g.setPaint(paint); g.setStroke(stroke); g.draw(shape); } @SuppressWarnings("unused") private void innerPaint(Graphics2D g) { float origAlpha = 1.0f; Composite origComposite = g.getComposite(); if (origComposite instanceof AlphaComposite) { AlphaComposite origAlphaComposite = (AlphaComposite)origComposite; if (origAlphaComposite.getRule() == AlphaComposite.SRC_OVER) { origAlpha = origAlphaComposite.getAlpha(); } } _paint0(g, origAlpha); shape = null; generalPath = null; paint = null; stroke = null; clip = null; transformsStack.clear(); } /** * Returns the X of the bounding box of the original SVG image. * * @return The X of the bounding box of the original SVG image. */ public static double getOrigX() { return 3.59999942779541; } /** * Returns the Y of the bounding box of the original SVG image. * * @return The Y of the bounding box of the original SVG image. */ public static double getOrigY() { return 6.088356018066406; } /** * Returns the width of the bounding box of the original SVG image. * * @return The width of the bounding box of the original SVG image. */ public static double getOrigWidth() { return 42.37000274658203; } /** * Returns the height of the bounding box of the original SVG image. * * @return The height of the bounding box of the original SVG image. */ public static double getOrigHeight() { return 35.21063995361328; } /** The current width of this icon. */ private int width; /** The current height of this icon. */ private int height; /** * Creates a new transcoded SVG image. This is marked as private to indicate that app * code should be using the {@link #of(int, int)} method to obtain a pre-configured instance. */ private Internet_group_chat() { this.width = (int) getOrigWidth(); this.height = (int) getOrigHeight(); } @Override public int getIconHeight() { return height; } @Override public int getIconWidth() { return width; } @Override public synchronized void setDimension(Dimension newDimension) { this.width = newDimension.width; this.height = newDimension.height; } @Override public boolean supportsColorFilter() { return true; } @Override public void setColorFilter(ColorFilter colorFilter) { this.colorFilter = colorFilter; } @Override public synchronized void paintIcon(Component c, Graphics g, int x, int y) { Graphics2D g2d = (Graphics2D) g.create(); g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC); g2d.translate(x, y); double coef1 = (double) this.width / getOrigWidth(); double coef2 = (double) this.height / getOrigHeight(); double coef = Math.min(coef1, coef2); g2d.clipRect(0, 0, this.width, this.height); g2d.scale(coef, coef); g2d.translate(-getOrigX(), -getOrigY()); if (coef1 != coef2) { if (coef1 < coef2) { int extraDy = (int) ((getOrigWidth() - getOrigHeight()) / 2.0); g2d.translate(0, extraDy); } else { int extraDx = (int) ((getOrigHeight() - getOrigWidth()) / 2.0); g2d.translate(extraDx, 0); } } Graphics2D g2ForInner = (Graphics2D) g2d.create(); innerPaint(g2ForInner); g2ForInner.dispose(); g2d.dispose(); } /** * Returns a new instance of this icon with specified dimensions. * * @param width Required width of the icon * @param height Required height of the icon * @return A new instance of this icon with specified dimensions. */ public static RadianceIcon of(int width, int height) { Internet_group_chat base = new Internet_group_chat(); base.width = width; base.height = height; return base; } /** * Returns a new {@link UIResource} instance of this icon with specified dimensions. * * @param width Required width of the icon * @param height Required height of the icon * @return A new {@link UIResource} instance of this icon with specified dimensions. */ public static RadianceIconUIResource uiResourceOf(int width, int height) { Internet_group_chat base = new Internet_group_chat(); base.width = width; base.height = height; return new RadianceIconUIResource(base); } /** * Returns a factory that returns instances of this icon on demand. * * @return Factory that returns instances of this icon on demand. */ public static Factory factory() { return Internet_group_chat::new; } }
6,986
5,169
<filename>Specs/COPeoplePickerViewController/0.0.1/COPeoplePickerViewController.podspec.json { "name": "COPeoplePickerViewController", "version": "0.0.1", "platforms": { "ios": null }, "license": "MIT", "summary": "Tokenized People Picker. Re-implementation of the email address picker of iCal (work in progress).", "homepage": "https://github.com/eaigner/COPeoplePickerViewController", "authors": { "<NAME>": "<EMAIL>" }, "source": { "git": "https://github.com/eaigner/COPeoplePickerViewController.git", "commit": "<PASSWORD>" }, "source_files": "COPeoplePickerViewController/COPeoplePickerViewController.*", "frameworks": [ "AddressBook", "AddressBookUI", "QuartzCore" ], "requires_arc": true }
291
13,885
#include "draco/io/file_writer_factory.h" #include <vector> namespace draco { namespace { #define FILEWRITER_LOG_ERROR(error_string) \ do { \ fprintf(stderr, "%s:%d (%s): %s.\n", __FILE__, __LINE__, __func__, \ error_string); \ } while (false) std::vector<FileWriterFactory::OpenFunction> *GetFileWriterOpenFunctions() { static auto open_functions = new (std::nothrow) std::vector<FileWriterFactory::OpenFunction>(); return open_functions; } } // namespace bool FileWriterFactory::RegisterWriter(OpenFunction open_function) { if (open_function == nullptr) { return false; } auto open_functions = GetFileWriterOpenFunctions(); const size_t num_writers = open_functions->size(); open_functions->push_back(open_function); return open_functions->size() == num_writers + 1; } std::unique_ptr<FileWriterInterface> FileWriterFactory::OpenWriter( const std::string &file_name) { for (auto open_function : *GetFileWriterOpenFunctions()) { auto writer = open_function(file_name); if (writer == nullptr) { continue; } return writer; } FILEWRITER_LOG_ERROR("No file writer able to open output"); return nullptr; } } // namespace draco
571
1,056
/* * 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.netbeans.modules.profiler.nbimpl.providers; import com.sun.source.tree.Scope; import java.io.IOException; import java.util.concurrent.Callable; import java.util.concurrent.CountDownLatch; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JEditorPane; import javax.swing.SwingUtilities; import javax.swing.text.Document; import javax.swing.text.JTextComponent; import javax.swing.text.StyledDocument; import org.netbeans.api.editor.EditorRegistry; import org.netbeans.api.java.source.CompilationController; import org.netbeans.api.java.source.JavaSource; import org.netbeans.api.java.source.Task; import org.netbeans.api.project.Project; import org.netbeans.modules.editor.NbEditorUtilities; import org.netbeans.modules.profiler.api.EditorContext; import org.netbeans.modules.profiler.spi.EditorSupportProvider; import org.openide.DialogDisplayer; import org.openide.NotifyDescriptor; import org.openide.cookies.EditorCookie; import org.openide.filesystems.FileObject; import org.openide.loaders.DataObject; import org.openide.text.NbDocument; import org.openide.util.Exceptions; import org.openide.util.Lookup; import org.openide.util.NbBundle; import org.openide.util.UserQuestionException; import org.openide.util.lookup.ServiceProvider; import org.openide.windows.TopComponent; import org.openide.windows.WindowManager; /** * * @author <NAME> * @author <NAME> */ @ServiceProvider(service = EditorSupportProvider.class) public class ProjectEditorSupportImpl extends EditorSupportProvider { private static final Logger LOG = Logger.getLogger(ProjectEditorSupportImpl.class.getName()); private <T> T performOnAWT(final Callable<T> action) throws Exception { if (SwingUtilities.isEventDispatchThread()) { return action.call(); } else { final T[] rslt = (T[]) new Object[]{null}; final Exception[] exc = new Exception[1]; final CountDownLatch latch = new CountDownLatch(1); SwingUtilities.invokeLater(new Runnable() { @Override public void run() { try { rslt[0] = action.call(); } catch (Exception ex) { exc[0] = ex; } latch.countDown(); } }); try { latch.await(); } catch (InterruptedException ex) { Thread.currentThread().interrupt(); } if (exc[0] != null) { throw exc[0]; } return rslt[0]; } } @Override public boolean currentlyInJavaEditor() { // Get focused TopComponent TopComponent top1 = WindowManager.getDefault().getRegistry().getActivated(); if (top1 == null) { return false; } // Get most active editor JTextComponent editor = EditorRegistry.lastFocusedComponent(); if (editor == null) { return false; } // Check if Java source Document document = editor.getDocument(); if (document == null) { return false; } FileObject fileObject = NbEditorUtilities.getFileObject(document); if ((fileObject == null) || !fileObject.getExt().equalsIgnoreCase("java")) { // NOI18N return false; } // Get editor TopComponent TopComponent top2 = NbEditorUtilities.getOuterTopComponent(editor); if (top2 == null) { return false; } // Return whether focused TopComponent == editor TopComponent return top1 == top2; } @Override public EditorContext getMostActiveJavaEditorContext() { for (JTextComponent component : EditorRegistry.componentList()) { Document document = component.getDocument(); FileObject fileObject = NbEditorUtilities.getFileObject(document); if ((fileObject != null) && fileObject.getExt().equalsIgnoreCase("java")) { // NOI18N return new EditorContext(component, document, fileObject); } } return null; } @Override public FileObject getCurrentFile() { try { return performOnAWT(new Callable<FileObject>() { @Override public FileObject call() throws Exception { TopComponent tc = TopComponent.getRegistry().getActivated(); if (tc != null) { return tc.getLookup().lookup(FileObject.class); } return null; } }); } catch (Exception e) { Exceptions.printStackTrace(e); } return null; } @Override public int getCurrentOffset() { try { return performOnAWT(new Callable<Integer>() { @Override public Integer call() throws Exception { JTextComponent mostActiveEditor = EditorRegistry.lastFocusedComponent(); if ((mostActiveEditor != null) && (mostActiveEditor.getCaret() != null)) { return mostActiveEditor.getCaretPosition(); } return -1; } }); } catch (Exception e) { Exceptions.printStackTrace(e); } return -1; } @Override public int getLineForOffset(final FileObject file, final int offset) { try { if (offset == -1) { return -1; } DataObject dobj = DataObject.find(file); if (dobj == null) { return -1; } final EditorCookie ec = dobj.getLookup().lookup(EditorCookie.class); if (ec == null) { return -1; } return performOnAWT(new Callable<Integer>() { @Override public Integer call() throws Exception { StyledDocument doc = getDocument(ec); if (doc == null) { return -1; } return NbDocument.findLineNumber(doc, offset); } }); } catch (Exception e) { LOG.log(Level.WARNING, null, e); } return -1; } @Override public int getOffsetForLine(final FileObject file, final int line) { try { if (line == -1) { return -1; } DataObject dobj = DataObject.find(file); if (dobj == null) { return -1; } final EditorCookie ec = dobj.getLookup().lookup(EditorCookie.class); if (ec == null) { return -1; } return performOnAWT(new Callable<Integer>() { @Override public Integer call() throws Exception { StyledDocument doc = getDocument(ec); if (doc == null) { return -1; } try { return NbDocument.findLineOffset(doc, line); } catch (IndexOutOfBoundsException e) { // #225139, line number out of document bounds return -1; } } }); } catch (Exception e) { LOG.log(Level.WARNING, null, e); } return -1; } @Override public boolean isOffsetValid(final FileObject file, final int offset) { try { return performOnAWT(new Callable<Boolean>() { @Override public Boolean call() throws Exception { if (file == null) { return false; } return validateOffset(file, offset) != -1; } }); } catch (Exception e) { Exceptions.printStackTrace(e); } return false; } @Override public Lookup.Provider getCurrentProject() { try { return performOnAWT(new Callable<Lookup.Provider>() { @Override public Lookup.Provider call() throws Exception { TopComponent tc = TopComponent.getRegistry().getActivated(); if (tc != null) { return tc.getLookup().lookup(Project.class); } return null; } }); } catch (Exception e) { Exceptions.printStackTrace(e); } return null; } @Override public int[] getSelectionOffsets() { try { return performOnAWT(new Callable<int[]>() { @Override public int[] call() throws Exception { int[] indexes = new int[]{-1, -1}; TopComponent tc = TopComponent.getRegistry().getActivated(); if (tc != null) { EditorCookie ec = tc.getLookup().lookup(EditorCookie.class); if (ec != null) { for (JEditorPane pane : ec.getOpenedPanes()) { int selStart = pane.getSelectionStart(); if (selStart > -1) { indexes[0] = selStart; indexes[1] = pane.getSelectionEnd(); break; } } } } return indexes; } }); } catch (Exception e) { Exceptions.printStackTrace(e); } return new int[]{-1, -1}; } private static int validateOffset(FileObject editorDoc, final int toValidate) { final int[] validated = new int[]{-1}; JavaSource js = JavaSource.forFileObject(editorDoc); if (js != null) { try { js.runUserActionTask(new Task<CompilationController>() { public void run(CompilationController controller) throws Exception { controller.toPhase(JavaSource.Phase.RESOLVED); validated[0] = -1; // non-validated default Scope sc = controller.getTreeUtilities().scopeFor(toValidate); if (sc.getEnclosingClass() != null) { validated[0] = toValidate; } } }, true); } catch (IOException ex) { Exceptions.printStackTrace(ex); } } return validated[0]; } @NbBundle.Messages("TXT_Question=Question") private static StyledDocument getDocument(EditorCookie ec) throws IOException { StyledDocument doc; try { doc = ec.openDocument(); } catch (UserQuestionException uqe) { final Object value = DialogDisplayer.getDefault().notify( new NotifyDescriptor.Confirmation(uqe.getLocalizedMessage(), Bundle.TXT_Question(), NotifyDescriptor.YES_NO_OPTION)); if (value != NotifyDescriptor.YES_OPTION) { return null; } uqe.confirmed(); doc = ec.openDocument(); } return doc; } }
6,170
5,279
<filename>runners/samza/src/main/java/org/apache/beam/runners/samza/translation/TransformTranslator.java /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.beam.runners.samza.translation; import org.apache.beam.runners.core.construction.graph.PipelineNode; import org.apache.beam.runners.core.construction.graph.QueryablePipeline; import org.apache.beam.sdk.runners.TransformHierarchy; import org.apache.beam.sdk.transforms.PTransform; /** Interface of Samza translator for BEAM {@link PTransform}. */ public interface TransformTranslator<T extends PTransform<?, ?>> { /** Translates the Java {@link PTransform} into Samza API. */ default void translate(T transform, TransformHierarchy.Node node, TranslationContext ctx) { throw new UnsupportedOperationException( "Java translation is not supported for " + this.getClass().getSimpleName()); } /** * Translates the portable {@link org.apache.beam.model.pipeline.v1.RunnerApi.PTransform} into * Samza API. */ default void translatePortable( PipelineNode.PTransformNode transform, QueryablePipeline pipeline, PortableTranslationContext ctx) { throw new UnsupportedOperationException( "Portable translation is not supported for " + this.getClass().getSimpleName()); } }
582
335
# ***************************************************************************** # # Copyright (c) 2020, the pyEX authors. # # This file is part of the pyEX library, distributed under the terms of # the Apache License 2.0. The full license can be found in the LICENSE file. # from functools import wraps import pandas as pd from ..common import ( _EST, _expire, _get, _quoteSymbols, _raiseIfNotStr, _reindex, _toDatetime, ) @_expire(hour=8, tz=_EST) def spread(symbol, token="", version="stable", filter="", format="json"): """This returns an array of effective spread, eligible volume, and price improvement of a stock, by market. Unlike volume-by-venue, this will only return a venue if effective spread is not ‘N/A’. Values are sorted in descending order by effectiveSpread. Lower effectiveSpread and higher priceImprovement values are generally considered optimal. Effective spread is designed to measure marketable orders executed in relation to the market center’s quoted spread and takes into account hidden and midpoint liquidity available at each market center. Effective Spread is calculated by using eligible trade prices recorded to the consolidated tape and comparing those trade prices to the National Best Bid and Offer (“NBBO”) at the time of the execution. View the data disclaimer at the bottom of the stocks app for more information about how these values are calculated. 8am ET M-F Args: symbol (str): Ticker to request token (str): Access token version (str): API version filter (str): filters: https://iexcloud.io/docs/api/#filter-results format (str): return format, defaults to json Returns: dict or DataFrame: result """ _raiseIfNotStr(symbol) return _get( "stock/{symbol}/effective-spread".format(symbol=_quoteSymbols(symbol)), token=token, version=version, filter=filter, format=format, ) @wraps(spread) def spreadDF(*args, **kwargs): return _reindex(_toDatetime(pd.DataFrame(spread(*args, **kwargs))), "venue")
678
3,227
namespace CGAL { /*! \ingroup PkgSegmentDelaunayGraph2Ref The class `Segment_Delaunay_graph_storage_site_2` is a model for the concept `SegmentDelaunayGraphStorageSite_2`. \tparam Gt must be a model of the `SegmentDelaunayGraphStorageTraits_2` concept. \cgalModels `SegmentDelaunayGraphStorageSite_2` \sa `CGAL::Segment_Delaunay_graph_site_2<K>` */ template< typename St > class Segment_Delaunay_graph_storage_site_2 { public: /// \name Types /// The class `Segment_Delaunay_graph_storage_site_2` introduces the /// following type in addition to the types in the concept /// `SegmentDelaunayGraphStorageSite_2`. /// @{ /*! A type for the template parameter `St`. */ typedef St Storage_traits; /// @} }; /* end Segment_Delaunay_graph_storage_site_2 */ } /* end namespace CGAL */
281
1,150
# -*- coding: utf-8 -*- from django.core.signing import JSONSerializer as BaseJSONSerializer JSONSerializer = BaseJSONSerializer
42
1,056
<filename>ide/subversion/src/org/netbeans/modules/subversion/ui/copy/SwitchToAction.java /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.netbeans.modules.subversion.ui.copy; import java.awt.EventQueue; import java.io.File; import java.util.List; import java.util.concurrent.Callable; import org.netbeans.modules.subversion.FileInformation; import org.netbeans.modules.subversion.RepositoryFile; import org.netbeans.modules.subversion.Subversion; import org.netbeans.modules.subversion.client.SvnClient; import org.netbeans.modules.subversion.client.SvnClientExceptionHandler; import org.netbeans.modules.subversion.client.SvnProgressSupport; import org.netbeans.modules.subversion.ui.actions.ContextAction; import org.netbeans.modules.subversion.util.Context; import org.netbeans.modules.subversion.util.SvnUtils; import org.netbeans.modules.versioning.util.Utils; import org.openide.nodes.Node; import org.openide.util.NbBundle; import org.openide.util.RequestProcessor; import org.tigris.subversion.svnclientadapter.ISVNInfo; import org.tigris.subversion.svnclientadapter.SVNClientException; import org.tigris.subversion.svnclientadapter.SVNNodeKind; import org.tigris.subversion.svnclientadapter.SVNRevision; import org.tigris.subversion.svnclientadapter.SVNUrl; /** * * @author <NAME> */ public class SwitchToAction extends ContextAction { /** * Creates a new instance of SwitchToAction */ public SwitchToAction() { } @Override protected String getBaseName(Node[] activatedNodes) { return "CTL_MenuItem_Switch"; // NOI18N } @Override protected int getFileEnabledStatus() { return FileInformation.STATUS_MANAGED & ~FileInformation.STATUS_NOTVERSIONED_EXCLUDED & ~FileInformation.STATUS_NOTVERSIONED_NEWLOCALLY; } @Override protected int getDirectoryEnabledStatus() { return FileInformation.STATUS_MANAGED & ~FileInformation.STATUS_NOTVERSIONED_EXCLUDED & ~FileInformation.STATUS_NOTVERSIONED_NEWLOCALLY; } @Override protected boolean enable(Node[] nodes) { return super.enable(nodes) && nodes.length == 1; } @Override protected void performContextAction(final Node[] nodes) { if(!Subversion.getInstance().checkClientAvailable()) { return; } Context ctx = getContext(nodes); File[] roots = SvnUtils.getActionRoots(ctx); if(roots == null || roots.length == 0) return; File interestingFile; if(roots.length == 1) { interestingFile = roots[0]; } else { interestingFile = SvnUtils.getPrimaryFile(roots[0]); } SVNUrl rootUrl = null, fileUrl = null; try { rootUrl = SvnUtils.getRepositoryRootUrl(interestingFile); fileUrl = SvnUtils.getRepositoryUrl(interestingFile); } catch (SVNClientException ex) { if (rootUrl == null) { SvnClientExceptionHandler.notifyException(ex, true, true); return; } } final RepositoryFile repositoryFile = new RepositoryFile(rootUrl, fileUrl == null ? rootUrl : fileUrl, SVNRevision.HEAD); boolean hasChanges = Subversion.getInstance().getStatusCache().containsFiles(ctx, FileInformation.STATUS_LOCAL_CHANGE, true); final RequestProcessor rp = createRequestProcessor(ctx); final SwitchTo switchTo = new SwitchTo(repositoryFile, interestingFile, hasChanges); performSwitch(switchTo, rp, nodes, roots); } /** * Switches all files from the roots array to their respective urls given by the SwitchTo controller * @param switchTo * @param rp * @param nodes * @param roots */ private void performSwitch(final SwitchTo switchTo, final RequestProcessor rp, final Node[] nodes, final File[] roots) { if(!switchTo.showDialog()) { return; } rp.post(new Runnable() { @Override public void run() { if(!validateInput(roots[0], switchTo.getRepositoryFile())) { EventQueue.invokeLater(new Runnable() { @Override public void run() { performSwitch(switchTo, rp, nodes, roots); } }); } else { ContextAction.ProgressSupport support = new ContextAction.ProgressSupport(SwitchToAction.this, nodes) { @Override public void perform() { final ContextAction.ProgressSupport supp = this; try { SvnUtils.runWithoutIndexing(new Callable<Void>() { @Override public Void call () throws Exception { for (File root : roots) { RepositoryFile toRepositoryFile = switchTo.getRepositoryFile(); if (root.isFile() && roots.length > 1) { // change the filename ONLY for multi-file data objects, not for folders toRepositoryFile = toRepositoryFile.replaceLastSegment(root.getName(), 0); } performSwitch(toRepositoryFile, root, supp); } return null; } }, roots); } catch (SVNClientException ex) { SvnClientExceptionHandler.notifyException(ex, true, false); } } }; support.start(rp); } } }); } private boolean validateInput(File root, RepositoryFile toRepositoryFile) { boolean ret = false; SvnClient client; try { client = Subversion.getInstance().getClient(toRepositoryFile.getRepositoryUrl()); ISVNInfo info = client.getInfo(toRepositoryFile.getFileUrl()); if(info.getNodeKind() == SVNNodeKind.DIR && root.isFile()) { SvnClientExceptionHandler.annotate(NbBundle.getMessage(SwitchToAction.class, "LBL_SwitchFileToFolderError")); ret = false; } else if(info.getNodeKind() == SVNNodeKind.FILE && root.isDirectory()) { SvnClientExceptionHandler.annotate(NbBundle.getMessage(SwitchToAction.class, "LBL_SwitchFolderToFileError")); ret = false; } else { ret = true; } } catch (SVNClientException ex) { SvnClientExceptionHandler.notifyException(ex, true, true); return ret; } return ret; } static void performSwitch(final RepositoryFile toRepositoryFile, final File root, final SvnProgressSupport support) { File[][] split = Utils.splitFlatOthers(new File[] {root} ); boolean recursive; // there can be only 1 root file if(split[0].length > 0) { recursive = false; } else { recursive = true; } try { SvnClient client; try { client = Subversion.getInstance().getClient(toRepositoryFile.getRepositoryUrl()); } catch (SVNClientException ex) { SvnClientExceptionHandler.notifyException(ex, true, true); return; } // ... and switch client.switchToUrl(root, toRepositoryFile.getFileUrl(), toRepositoryFile.getRevision(), recursive); // the client doesn't notify as there is no output rom the cli. Lets emulate onNotify as from the client List<File> switchedFiles = SvnUtils.listManagedRecursively(root); File[] fileArray = switchedFiles.toArray(new File[switchedFiles.size()]); // the cache fires status change events to trigger the annotation refresh // unfortunatelly - we have to call the refresh explicitly for each file also // from this place as the branch label was changed evern if the files status didn't Subversion.getInstance().getStatusCache().getLabelsCache().flushFileLabels(fileArray); Subversion.getInstance().refreshAnnotations(fileArray); // refresh the inline diff Subversion.getInstance().versionedFilesChanged(); } catch (SVNClientException ex) { support.annotate(ex); } } }
4,445
709
<filename>runtime/basis/Posix/Process/termSig.c #include "platform.h" C_Signal_t Posix_Process_termSig (C_Status_t s) { return WTERMSIG (s); }
64
866
<reponame>Miouge1/cli {"format_version":"0.1","terraform_version":"0.12.18","variables":{"servicebus_queue_list":{"value":["something","somethingelse","somethingdifferent"]}},"planned_values":{"root_module":{"resources":[{"address":"azurerm_servicebus_queue.sb[\"something\"]","mode":"managed","type":"azurerm_servicebus_queue","name":"sb","index":"something","provider_name":"azurerm","schema_version":0,"values":{"dead_lettering_on_message_expiration":true,"default_message_ttl":"P14D","enable_batched_operations":null,"enable_express":false,"enable_partitioning":true,"location":null,"max_delivery_count":10,"name":"something","namespace_name":"testnamespace","requires_duplicate_detection":false,"requires_session":false,"resource_group_name":"testgroup","support_ordering":null}},{"address":"azurerm_servicebus_queue.sb[\"somethingdifferent\"]","mode":"managed","type":"azurerm_servicebus_queue","name":"sb","index":"somethingdifferent","provider_name":"azurerm","schema_version":0,"values":{"dead_lettering_on_message_expiration":true,"default_message_ttl":"P14D","enable_batched_operations":null,"enable_express":false,"enable_partitioning":true,"location":null,"max_delivery_count":10,"name":"somethingdifferent","namespace_name":"testnamespace","requires_duplicate_detection":false,"requires_session":false,"resource_group_name":"testgroup","support_ordering":null}},{"address":"azurerm_servicebus_queue.sb[\"somethingelse\"]","mode":"managed","type":"azurerm_servicebus_queue","name":"sb","index":"somethingelse","provider_name":"azurerm","schema_version":0,"values":{"dead_lettering_on_message_expiration":true,"default_message_ttl":"P14D","enable_batched_operations":null,"enable_express":false,"enable_partitioning":true,"location":null,"max_delivery_count":10,"name":"somethingelse","namespace_name":"testnamespace","requires_duplicate_detection":false,"requires_session":false,"resource_group_name":"testgroup","support_ordering":null}}]}},"resource_changes":[{"address":"azurerm_servicebus_queue.sb[\"something\"]","mode":"managed","type":"azurerm_servicebus_queue","name":"sb","index":"something","provider_name":"azurerm","change":{"actions":["create"],"before":null,"after":{"dead_lettering_on_message_expiration":true,"default_message_ttl":"P14D","enable_batched_operations":null,"enable_express":false,"enable_partitioning":true,"location":null,"max_delivery_count":10,"name":"something","namespace_name":"testnamespace","requires_duplicate_detection":false,"requires_session":false,"resource_group_name":"testgroup","support_ordering":null},"after_unknown":{"auto_delete_on_idle":true,"duplicate_detection_history_time_window":true,"id":true,"lock_duration":true,"max_size_in_megabytes":true}}},{"address":"azurerm_servicebus_queue.sb[\"somethingdifferent\"]","mode":"managed","type":"azurerm_servicebus_queue","name":"sb","index":"somethingdifferent","provider_name":"azurerm","change":{"actions":["create"],"before":null,"after":{"dead_lettering_on_message_expiration":true,"default_message_ttl":"P14D","enable_batched_operations":null,"enable_express":false,"enable_partitioning":true,"location":null,"max_delivery_count":10,"name":"somethingdifferent","namespace_name":"testnamespace","requires_duplicate_detection":false,"requires_session":false,"resource_group_name":"testgroup","support_ordering":null},"after_unknown":{"auto_delete_on_idle":true,"duplicate_detection_history_time_window":true,"id":true,"lock_duration":true,"max_size_in_megabytes":true}}},{"address":"azurerm_servicebus_queue.sb[\"somethingelse\"]","mode":"managed","type":"azurerm_servicebus_queue","name":"sb","index":"somethingelse","provider_name":"azurerm","change":{"actions":["create"],"before":null,"after":{"dead_lettering_on_message_expiration":true,"default_message_ttl":"P14D","enable_batched_operations":null,"enable_express":false,"enable_partitioning":true,"location":null,"max_delivery_count":10,"name":"somethingelse","namespace_name":"testnamespace","requires_duplicate_detection":false,"requires_session":false,"resource_group_name":"testgroup","support_ordering":null},"after_unknown":{"auto_delete_on_idle":true,"duplicate_detection_history_time_window":true,"id":true,"lock_duration":true,"max_size_in_megabytes":true}}}],"configuration":{"root_module":{"resources":[{"address":"azurerm_servicebus_queue.sb","mode":"managed","type":"azurerm_servicebus_queue","name":"sb","provider_config_key":"azurerm","expressions":{"dead_lettering_on_message_expiration":{"constant_value":true},"default_message_ttl":{"constant_value":"P14D"},"enable_partitioning":{"constant_value":true},"name":{"references":["each.value"]},"namespace_name":{"constant_value":"testnamespace"},"resource_group_name":{"constant_value":"testgroup"}},"schema_version":0,"for_each_expression":{"references":["var.servicebus_queue_list"]}}],"variables":{"servicebus_queue_list":{"default":["something","somethingelse","somethingdifferent"]}}}}}
1,438
379
<reponame>Ahzed11/mozart2<gh_stars>100-1000 // Copyright © 2013, Université catholique de Louvain // 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. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. #ifndef MOZART_MODBROWSER_H #define MOZART_MODBROWSER_H #include "../mozartcore.hh" #ifndef MOZART_GENERATOR namespace mozart { namespace builtins { //////////////////// // Browser module // //////////////////// class ModBrowser: public Module { public: ModBrowser(): Module("Browser") {} class IsRecordCVar: public Builtin<IsRecordCVar> { public: IsRecordCVar(): Builtin("isRecordCVar") {} static void call(VM vm, In value, Out result) { // TODO Update this when we have kinded variables result = build(vm, !value.isTransient() && RecordLike(value).isRecord(vm)); } }; class ChunkWidth: public Builtin<ChunkWidth> { public: ChunkWidth(): Builtin("chunkWidth") {} static void call(VM vm, In value, Out result) { result = build(vm, RecordLike(getChunkUnderlying(vm, value)).width(vm)); } }; class ChunkArity: public Builtin<ChunkArity> { public: ChunkArity(): Builtin("chunkArity") {} static void call(VM vm, In value, Out result) { result = RecordLike(getChunkUnderlying(vm, value)).arityList(vm); } }; private: static StableNode& getChunkUnderlying(VM vm, In value) { if (value.is<Chunk>()) return *value.as<Chunk>().getUnderlying(); else if (value.is<Object>()) return *value.as<Object>().getFeaturesRecord(); else if (value.isTransient()) waitFor(vm, value); else raiseTypeError(vm, "Chunk", value); } public: class ShortName: public Builtin<ShortName> { public: ShortName(): Builtin("shortName") {} static void call(VM vm, In longName, Out result) { // Keep it for compatibility, but this is nonsense ozVSLengthForBuffer(vm, longName); // for the type error result = build(vm, longName); } }; class GetsBoundB: public Builtin<GetsBoundB> { public: GetsBoundB(): Builtin("getsBoundB") {} static void call(VM vm, In variable, Out watcher) { watcher = Variable::build(vm); if (variable.isTransient() && !variable.is<FailedValue>()) { DataflowVariable(variable).addToSuspendList(vm, watcher); }; } }; class VarSpace: public Builtin<VarSpace> { public: VarSpace(): Builtin("varSpace") {} static void call(VM vm, In variable, Out result) { Space* space; while (variable.is<ReadOnly>()) variable = *variable.as<ReadOnly>().getUnderlying(); if (variable.is<OptVar>()) space = variable.as<OptVar>().home(); else if (variable.is<Variable>()) space = variable.as<Variable>().home(); else if (variable.is<ReadOnlyVariable>()) space = variable.as<ReadOnlyVariable>().home(); else space = nullptr; result = build(vm, (nativeint) space); } }; class ProcLoc: public Builtin<ProcLoc> { public: ProcLoc(): Builtin("procLoc") {} static void call(VM vm, In procedure, Out file, Out line, Out column) { atom_t printName; UnstableNode debugData; Callable(procedure).getDebugInfo(vm, printName, debugData); Dottable dotDebugData(debugData); file = dotDebugData.condSelect( vm, "file", "procedure"); line = dotDebugData.condSelect( vm, "line", "-"); column = dotDebugData.condSelect( vm, "column", "-"); } }; class Addr: public Builtin<Addr> { public: Addr(): Builtin("addr") {} static void call(VM vm, In entity, Out result) { result = build(vm, (nativeint) entity.getStableRef(vm)); } }; }; } } #endif // MOZART_GENERATOR #endif // MOZART_MODBROWSER_H
1,820
1,603
<filename>metadata-integration/java/datahub-protobuf/src/test/java/datahub/protobuf/visitors/dataset/DomainVisitorTest.java package datahub.protobuf.visitors.dataset; import com.linkedin.common.urn.Urn; import datahub.protobuf.model.ProtobufGraph; import org.junit.Test; import java.io.IOException; import java.util.List; import java.util.Set; import java.util.stream.Collectors; import static datahub.protobuf.TestFixtures.getTestProtobufGraph; import static datahub.protobuf.TestFixtures.getVisitContextBuilder; import static org.junit.jupiter.api.Assertions.assertEquals; public class DomainVisitorTest { @Test public void visitorTest() throws IOException { ProtobufGraph graph = getTestProtobufGraph("extended_protobuf", "messageA"); DomainVisitor test = new DomainVisitor(); assertEquals(Set.of(Urn.createFromTuple("domain", "engineering")), graph.accept(getVisitContextBuilder("extended_protobuf.MessageA"), List.of(test)).collect(Collectors.toSet())); } }
370
12,700
<gh_stars>1000+ #ifndef _ASM_BARRIER_H_ #define _ASM_BARRIER_H_ /* * asm-generic/barrier.h * * Copyright (C) 2016, Red Hat Inc, <NAME> <<EMAIL>> * * This work is licensed under the terms of the GNU LGPL, version 2. */ #ifndef mb #define mb() asm volatile("":::"memory") #endif #ifndef rmb #define rmb() asm volatile("":::"memory") #endif #ifndef wmb #define wmb() asm volatile("":::"memory") #endif #ifndef smp_mb #define smp_mb() mb() #endif #ifndef smp_rmb #define smp_rmb() rmb() #endif #ifndef smp_wmb #define smp_wmb() wmb() #endif #ifndef cpu_relax #define cpu_relax() asm volatile ("":::"memory") #endif #endif /* _ASM_BARRIER_H_ */
293
399
/* * Copyright(c) 2019 Intel Corporation * * This source code is subject to the terms of the BSD 2 Clause License and * the Alliance for Open Media Patent License 1.0. If the BSD 2 Clause License * was not distributed with this source code in the LICENSE file, you can * obtain it at https://www.aomedia.org/license/software-license. If the Alliance for Open * Media Patent License 1.0 was not distributed with this source code in the * PATENTS file, you can obtain it at https://www.aomedia.org/license/patent-license. */ #ifndef AOM_DSP_X86_CONVOLVE_AVX512_H_ #define AOM_DSP_X86_CONVOLVE_AVX512_H_ #include "convolve.h" #include "EbDefinitions.h" #include "EbInterPrediction.h" #include "EbMemory_AVX2.h" #include "EbMemory_SSE4_1.h" #include "synonyms.h" #include "synonyms_avx2.h" #include "synonyms_avx512.h" #if EN_AVX512_SUPPORT static INLINE __m512i svt_mm512_broadcast_i64x2(const __m128i v) { #ifdef _WIN32 // Work around of Visual Studio warning C4305: 'function': truncation from // 'int' to '__mmask8'. It's a flaw in header file zmmintrin.h. return _mm512_maskz_broadcast_i64x2((__mmask8)0xffff, v); #else return _mm512_broadcast_i64x2(v); #endif } static INLINE __m512i _mm512_setr_m256i(const __m256i src0, const __m256i src1) { return _mm512_inserti64x4(_mm512_castsi256_si512(src0), src1, 1); } static INLINE __m512i loadu_8bit_32x2_avx512(const void *const src, const ptrdiff_t strideInByte) { const __m256i src0 = _mm256_loadu_si256((__m256i *)src); const __m256i src1 = _mm256_loadu_si256((__m256i *)((uint8_t *)src + strideInByte)); return _mm512_setr_m256i(src0, src1); } static INLINE __m512i loadu_u8_32x2_avx512(const uint8_t *const src, const ptrdiff_t stride) { return loadu_8bit_32x2_avx512(src, sizeof(*src) * stride); } static INLINE __m512i loadu_s16_16x2_avx512(const int16_t *const src, const ptrdiff_t stride) { return loadu_8bit_32x2_avx512(src, sizeof(*src) * stride); } static INLINE void storeu_8bit_32x2_avx512(const __m512i src, void *const dst, const ptrdiff_t strideInByte) { const __m256i d0 = _mm512_castsi512_si256(src); const __m256i d1 = _mm512_extracti64x4_epi64(src, 1); _mm256_storeu_si256((__m256i *)dst, d0); _mm256_storeu_si256((__m256i *)((uint8_t *)dst + strideInByte), d1); } static INLINE void storeu_u8_32x2_avx512(const __m512i src, uint8_t *const dst, const ptrdiff_t stride) { storeu_8bit_32x2_avx512(src, dst, sizeof(*dst) * stride); } static INLINE void populate_coeffs_4tap_avx512(const __m128i coeffs_128, __m512i coeffs[2]) { const __m512i coeffs_512 = svt_mm512_broadcast_i64x2(coeffs_128); // coeffs 2 3 2 3 2 3 2 3 coeffs[0] = _mm512_shuffle_epi8(coeffs_512, _mm512_set1_epi16(0x0604u)); // coeffs 4 5 4 5 4 5 4 5 coeffs[1] = _mm512_shuffle_epi8(coeffs_512, _mm512_set1_epi16(0x0a08u)); } static INLINE void populate_coeffs_6tap_avx512(const __m128i coeffs_128, __m512i coeffs[3]) { const __m512i coeffs_512 = svt_mm512_broadcast_i64x2(coeffs_128); // coeffs 1 2 1 2 1 2 1 2 coeffs[0] = _mm512_shuffle_epi8(coeffs_512, _mm512_set1_epi16(0x0402u)); // coeffs 3 4 3 4 3 4 3 4 coeffs[1] = _mm512_shuffle_epi8(coeffs_512, _mm512_set1_epi16(0x0806u)); // coeffs 5 6 5 6 5 6 5 6 coeffs[2] = _mm512_shuffle_epi8(coeffs_512, _mm512_set1_epi16(0x0C0Au)); } static INLINE void populate_coeffs_8tap_avx512(const __m128i coeffs_128, __m512i coeffs[4]) { const __m512i coeffs_512 = svt_mm512_broadcast_i64x2(coeffs_128); // coeffs 0 1 0 1 0 1 0 1 coeffs[0] = _mm512_shuffle_epi8(coeffs_512, _mm512_set1_epi16(0x0200u)); // coeffs 2 3 2 3 2 3 2 3 coeffs[1] = _mm512_shuffle_epi8(coeffs_512, _mm512_set1_epi16(0x0604u)); // coeffs 4 5 4 5 4 5 4 5 coeffs[2] = _mm512_shuffle_epi8(coeffs_512, _mm512_set1_epi16(0x0a08u)); // coeffs 6 7 6 7 6 7 6 7 coeffs[3] = _mm512_shuffle_epi8(coeffs_512, _mm512_set1_epi16(0x0e0cu)); } static INLINE void prepare_half_coeffs_2tap_avx512(const InterpFilterParams *const filter_params, const int32_t subpel_q4, __m512i *const coeffs /* [1] */) { const int16_t *const filter = av1_get_interp_filter_subpel_kernel(*filter_params, subpel_q4 & SUBPEL_MASK); const __m128i coeffs_8 = _mm_cvtsi32_si128(*(const int32_t *)(filter + 3)); const __m512i filter_coeffs = _mm512_broadcastd_epi32(coeffs_8); // right shift all filter co-efficients by 1 to reduce the bits required. // This extra right shift will be taken care of at the end while rounding // the result. // Since all filter co-efficients are even, this change will not affect the // end result assert(_mm_test_all_zeros(_mm_and_si128(coeffs_8, _mm_set1_epi16(1)), _mm_set1_epi16((short)0xffff))); const __m512i coeffs_1 = _mm512_srai_epi16(filter_coeffs, 1); // coeffs 3 4 3 4 3 4 3 4 *coeffs = _mm512_shuffle_epi8(coeffs_1, _mm512_set1_epi16(0x0200u)); } static INLINE void prepare_half_coeffs_4tap_avx512(const InterpFilterParams *const filter_params, const int32_t subpel_q4, __m512i *const coeffs /* [2] */) { const int16_t *const filter = av1_get_interp_filter_subpel_kernel(*filter_params, subpel_q4 & SUBPEL_MASK); const __m128i coeffs_8 = _mm_loadu_si128((__m128i *)filter); // right shift all filter co-efficients by 1 to reduce the bits required. // This extra right shift will be taken care of at the end while rounding // the result. // Since all filter co-efficients are even, this change will not affect the // end result assert(_mm_test_all_zeros(_mm_and_si128(coeffs_8, _mm_set1_epi16(1)), _mm_set1_epi16((short)0xffff))); const __m128i coeffs_1 = _mm_srai_epi16(coeffs_8, 1); populate_coeffs_4tap_avx512(coeffs_1, coeffs); } static INLINE void prepare_half_coeffs_6tap_avx512(const InterpFilterParams *const filter_params, const int32_t subpel_q4, __m512i *const coeffs /* [3] */) { const int16_t *const filter = av1_get_interp_filter_subpel_kernel(*filter_params, subpel_q4 & SUBPEL_MASK); const __m128i coeffs_8 = _mm_loadu_si128((__m128i *)filter); // right shift all filter co-efficients by 1 to reduce the bits required. // This extra right shift will be taken care of at the end while rounding // the result. // Since all filter co-efficients are even, this change will not affect the // end result assert(_mm_test_all_zeros(_mm_and_si128(coeffs_8, _mm_set1_epi16(1)), _mm_set1_epi16((short)0xffff))); const __m128i coeffs_1 = _mm_srai_epi16(coeffs_8, 1); populate_coeffs_6tap_avx512(coeffs_1, coeffs); } SIMD_INLINE void prepare_half_coeffs_8tap_avx512(const InterpFilterParams *const filter_params, const int32_t subpel_q4, __m512i *const coeffs /* [4] */) { const int16_t *const filter = av1_get_interp_filter_subpel_kernel(*filter_params, subpel_q4 & SUBPEL_MASK); const __m128i coeffs_8 = _mm_loadu_si128((__m128i *)filter); // right shift all filter co-efficients by 1 to reduce the bits required. // This extra right shift will be taken care of at the end while rounding // the result. // Since all filter co-efficients are even, this change will not affect the // end result assert(_mm_test_all_zeros(_mm_and_si128(coeffs_8, _mm_set1_epi16(1)), _mm_set1_epi16((short)0xffff))); const __m128i coeffs_1 = _mm_srai_epi16(coeffs_8, 1); populate_coeffs_8tap_avx512(coeffs_1, coeffs); } static INLINE void prepare_coeffs_2tap_avx512(const InterpFilterParams *const filter_params, const int32_t subpel_q4, __m512i *const coeffs /* [1] */) { const int16_t *filter = av1_get_interp_filter_subpel_kernel(*filter_params, subpel_q4 & SUBPEL_MASK); const __m128i coeff_8 = _mm_cvtsi32_si128(*(const int32_t *)(filter + 3)); const __m512i coeff = _mm512_broadcastd_epi32(coeff_8); // coeffs 3 4 3 4 3 4 3 4 coeffs[0] = _mm512_shuffle_epi32(coeff, 0x00); } static INLINE void prepare_coeffs_4tap_avx512(const InterpFilterParams *const filter_params, const int32_t subpel_q4, __m512i *const coeffs /* [2] */) { const int16_t *filter = av1_get_interp_filter_subpel_kernel(*filter_params, subpel_q4 & SUBPEL_MASK); const __m128i coeff_8 = _mm_loadu_si128((__m128i *)filter); const __m512i coeff = svt_mm512_broadcast_i64x2(coeff_8); // coeffs 2 3 2 3 2 3 2 3 coeffs[0] = _mm512_shuffle_epi32(coeff, 0x55); // coeffs 4 5 4 5 4 5 4 5 coeffs[1] = _mm512_shuffle_epi32(coeff, 0xaa); } static INLINE void prepare_coeffs_6tap_avx512(const InterpFilterParams *const filter_params, const int32_t subpel_q4, __m512i *const coeffs /* [3] */) { const int16_t *const filter = av1_get_interp_filter_subpel_kernel(*filter_params, subpel_q4 & SUBPEL_MASK); const __m128i coeffs_8 = _mm_loadu_si128((__m128i *)filter); const __m512i coeff = svt_mm512_broadcast_i64x2(coeffs_8); // coeffs 1 2 1 2 1 2 1 2 coeffs[0] = _mm512_shuffle_epi8(coeff, _mm512_set1_epi32(0x05040302u)); // coeffs 3 4 3 4 3 4 3 4 coeffs[1] = _mm512_shuffle_epi8(coeff, _mm512_set1_epi32(0x09080706u)); // coeffs 5 6 5 6 5 6 5 6 coeffs[2] = _mm512_shuffle_epi8(coeff, _mm512_set1_epi32(0x0D0C0B0Au)); } static INLINE void prepare_coeffs_8tap_avx512(const InterpFilterParams *const filter_params, const int32_t subpel_q4, __m512i *const coeffs /* [4] */) { const int16_t *filter = av1_get_interp_filter_subpel_kernel(*filter_params, subpel_q4 & SUBPEL_MASK); const __m128i coeff_8 = _mm_loadu_si128((__m128i *)filter); const __m512i coeff = svt_mm512_broadcast_i64x2(coeff_8); // coeffs 0 1 0 1 0 1 0 1 coeffs[0] = _mm512_shuffle_epi32(coeff, 0x00); // coeffs 2 3 2 3 2 3 2 3 coeffs[1] = _mm512_shuffle_epi32(coeff, 0x55); // coeffs 4 5 4 5 4 5 4 5 coeffs[2] = _mm512_shuffle_epi32(coeff, 0xaa); // coeffs 6 7 6 7 6 7 6 7 coeffs[3] = _mm512_shuffle_epi32(coeff, 0xff); } static INLINE void load_16bit_32x7_avx512(const int16_t *const src, __m512i dst[7]) { dst[0] = loadu_s16_16x2_avx512(src + 0 * 16, 32); dst[1] = loadu_s16_16x2_avx512(src + 1 * 16, 32); dst[2] = loadu_s16_16x2_avx512(src + 4 * 16, 32); dst[3] = loadu_s16_16x2_avx512(src + 5 * 16, 32); dst[4] = loadu_s16_16x2_avx512(src + 8 * 16, 32); dst[5] = loadu_s16_16x2_avx512(src + 9 * 16, 32); dst[6] = loadu_s16_16x2_avx512(src + 12 * 16, 32); } SIMD_INLINE void load_16bit_4rows_avx512(const int16_t *const src, const ptrdiff_t stride, __m512i dst[8]) { dst[0] = zz_load_512(src + 0 * stride); dst[1] = zz_load_512(src + 1 * stride); dst[2] = zz_load_512(src + 2 * stride); dst[3] = zz_load_512(src + 3 * stride); } static INLINE void load_16bit_7rows_avx512(const int16_t *const src, const ptrdiff_t stride, __m512i dst[7]) { dst[0] = zz_load_512(src + 0 * stride); dst[1] = zz_load_512(src + 1 * stride); dst[2] = zz_load_512(src + 2 * stride); dst[3] = zz_load_512(src + 3 * stride); dst[4] = zz_load_512(src + 4 * stride); dst[5] = zz_load_512(src + 5 * stride); dst[6] = zz_load_512(src + 6 * stride); } SIMD_INLINE void loadu_unpack_16bit_5rows_avx512(const int16_t *const src, const ptrdiff_t stride, __m512i s_512[5], __m512i ss_512[5], __m512i tt_512[5]) { s_512[0] = _mm512_loadu_si512((__m512i *)(src + 0 * stride)); s_512[1] = _mm512_loadu_si512((__m512i *)(src + 1 * stride)); s_512[2] = _mm512_loadu_si512((__m512i *)(src + 2 * stride)); s_512[3] = _mm512_loadu_si512((__m512i *)(src + 3 * stride)); s_512[4] = _mm512_loadu_si512((__m512i *)(src + 4 * stride)); ss_512[0] = _mm512_unpacklo_epi16(s_512[0], s_512[1]); ss_512[1] = _mm512_unpacklo_epi16(s_512[2], s_512[3]); ss_512[3] = _mm512_unpackhi_epi16(s_512[0], s_512[1]); ss_512[4] = _mm512_unpackhi_epi16(s_512[2], s_512[3]); tt_512[0] = _mm512_unpacklo_epi16(s_512[1], s_512[2]); tt_512[1] = _mm512_unpacklo_epi16(s_512[3], s_512[4]); tt_512[3] = _mm512_unpackhi_epi16(s_512[1], s_512[2]); tt_512[4] = _mm512_unpackhi_epi16(s_512[3], s_512[4]); } SIMD_INLINE void loadu_unpack_16bit_32x3_avx512(const int16_t *const src, __m512i s_512[3], __m512i ss_512[3], __m512i tt_512[3]) { s_512[0] = loadu_s16_16x2_avx512(src + 0 * 16, 32); s_512[1] = loadu_s16_16x2_avx512(src + 1 * 16, 32); s_512[2] = loadu_s16_16x2_avx512(src + 4 * 16, 32); ss_512[0] = _mm512_unpacklo_epi16(s_512[0], s_512[1]); ss_512[2] = _mm512_unpackhi_epi16(s_512[0], s_512[1]); tt_512[0] = _mm512_unpacklo_epi16(s_512[1], s_512[2]); tt_512[2] = _mm512_unpackhi_epi16(s_512[1], s_512[2]); } SIMD_INLINE void loadu_unpack_16bit_32x5_avx512(const int16_t *const src, __m512i s_512[5], __m512i ss_512[5], __m512i tt_512[5]) { s_512[0] = loadu_s16_16x2_avx512(src + 0 * 16, 32); s_512[1] = loadu_s16_16x2_avx512(src + 1 * 16, 32); s_512[2] = loadu_s16_16x2_avx512(src + 4 * 16, 32); s_512[3] = loadu_s16_16x2_avx512(src + 5 * 16, 32); s_512[4] = loadu_s16_16x2_avx512(src + 8 * 16, 32); ss_512[0] = _mm512_unpacklo_epi16(s_512[0], s_512[1]); ss_512[1] = _mm512_unpacklo_epi16(s_512[2], s_512[3]); ss_512[3] = _mm512_unpackhi_epi16(s_512[0], s_512[1]); ss_512[4] = _mm512_unpackhi_epi16(s_512[2], s_512[3]); tt_512[0] = _mm512_unpacklo_epi16(s_512[1], s_512[2]); tt_512[1] = _mm512_unpacklo_epi16(s_512[3], s_512[4]); tt_512[3] = _mm512_unpackhi_epi16(s_512[1], s_512[2]); tt_512[4] = _mm512_unpackhi_epi16(s_512[3], s_512[4]); } static INLINE void convolve_8tap_unapck_avx512(const __m512i s[6], __m512i ss[7]) { ss[0] = _mm512_unpacklo_epi16(s[0], s[1]); ss[1] = _mm512_unpacklo_epi16(s[2], s[3]); ss[2] = _mm512_unpacklo_epi16(s[4], s[5]); ss[4] = _mm512_unpackhi_epi16(s[0], s[1]); ss[5] = _mm512_unpackhi_epi16(s[2], s[3]); ss[6] = _mm512_unpackhi_epi16(s[4], s[5]); } static INLINE __m512i convolve_2tap_avx512(const __m512i ss[1], const __m512i coeffs[1]) { return _mm512_maddubs_epi16(ss[0], coeffs[0]); } static INLINE __m512i convolve_4tap_avx512(const __m512i ss[2], const __m512i coeffs[2]) { const __m512i res_23 = _mm512_maddubs_epi16(ss[0], coeffs[0]); const __m512i res_45 = _mm512_maddubs_epi16(ss[1], coeffs[1]); return _mm512_add_epi16(res_23, res_45); } static INLINE __m512i convolve_6tap_avx512(const __m512i ss[3], const __m512i coeffs[3]) { const __m512i res_01 = _mm512_maddubs_epi16(ss[0], coeffs[0]); const __m512i res_23 = _mm512_maddubs_epi16(ss[1], coeffs[1]); const __m512i res_45 = _mm512_maddubs_epi16(ss[2], coeffs[2]); const __m512i res_0145 = _mm512_add_epi16(res_01, res_45); return _mm512_add_epi16(res_0145, res_23); } static INLINE __m512i convolve_8tap_avx512(const __m512i ss[4], const __m512i coeffs[4]) { const __m512i res_01 = _mm512_maddubs_epi16(ss[0], coeffs[0]); const __m512i res_23 = _mm512_maddubs_epi16(ss[1], coeffs[1]); const __m512i res_45 = _mm512_maddubs_epi16(ss[2], coeffs[2]); const __m512i res_67 = _mm512_maddubs_epi16(ss[3], coeffs[3]); const __m512i res_0145 = _mm512_add_epi16(res_01, res_45); const __m512i res_2367 = _mm512_add_epi16(res_23, res_67); return _mm512_add_epi16(res_0145, res_2367); } static INLINE __m512i convolve16_2tap_avx512(const __m512i ss[1], const __m512i coeffs[1]) { return _mm512_madd_epi16(ss[0], coeffs[0]); } static INLINE __m512i convolve16_4tap_avx512(const __m512i ss[2], const __m512i coeffs[2]) { const __m512i res_1 = _mm512_madd_epi16(ss[0], coeffs[0]); const __m512i res_2 = _mm512_madd_epi16(ss[1], coeffs[1]); return _mm512_add_epi32(res_1, res_2); } static INLINE __m512i convolve16_6tap_avx512(const __m512i ss[3], const __m512i coeffs[3]) { const __m512i res_01 = _mm512_madd_epi16(ss[0], coeffs[0]); const __m512i res_23 = _mm512_madd_epi16(ss[1], coeffs[1]); const __m512i res_45 = _mm512_madd_epi16(ss[2], coeffs[2]); const __m512i res_0123 = _mm512_add_epi32(res_01, res_23); return _mm512_add_epi32(res_0123, res_45); } static INLINE __m512i convolve16_8tap_avx512(const __m512i ss[4], const __m512i coeffs[4]) { const __m512i res_01 = _mm512_madd_epi16(ss[0], coeffs[0]); const __m512i res_23 = _mm512_madd_epi16(ss[1], coeffs[1]); const __m512i res_45 = _mm512_madd_epi16(ss[2], coeffs[2]); const __m512i res_67 = _mm512_madd_epi16(ss[3], coeffs[3]); const __m512i res_0123 = _mm512_add_epi32(res_01, res_23); const __m512i res_4567 = _mm512_add_epi32(res_45, res_67); return _mm512_add_epi32(res_0123, res_4567); } static INLINE __m512i sr_y_round_avx512(const __m512i src) { const __m512i round = _mm512_set1_epi16(32); const __m512i dst = _mm512_add_epi16(src, round); return _mm512_srai_epi16(dst, FILTER_BITS - 1); } static INLINE __m512i xy_x_round_avx512(const __m512i src) { const __m512i round = _mm512_set1_epi16(2); const __m512i dst = _mm512_add_epi16(src, round); return _mm512_srai_epi16(dst, 2); } static INLINE __m512i xy_y_round_avx512(const __m512i src) { const __m512i round = _mm512_set1_epi32(1024); const __m512i dst = _mm512_add_epi32(src, round); return _mm512_srai_epi32(dst, 11); } static INLINE __m512i xy_y_round_16_avx512(const __m512i r0, const __m512i r1) { const __m512i d0 = xy_y_round_avx512(r0); const __m512i d1 = xy_y_round_avx512(r1); return _mm512_packs_epi32(d0, d1); } static INLINE __m512i xy_y_round_32_avx512(const __m512i r[2]) { const __m512i r0 = xy_y_round_avx512(r[0]); const __m512i r1 = xy_y_round_avx512(r[1]); return _mm512_packs_epi32(r0, r1); } static INLINE __m512i xy_y_round_half_pel_avx512(const __m512i src) { const __m512i round = _mm512_set1_epi16(16); const __m512i dst = _mm512_add_epi16(src, round); return _mm512_srai_epi16(dst, 5); } static INLINE __m512i jnt_y_round_avx512(const __m512i src) { const __m512i round = _mm512_set1_epi16(2); const __m512i dst = _mm512_add_epi16(src, round); return _mm512_srai_epi16(dst, 2); } static INLINE __m512i jnt_avg_round_avx512(const __m512i src, const __m512i offset) { const __m512i dst = _mm512_add_epi16(src, offset); return _mm512_srai_epi16(dst, 2); } static INLINE __m512i jnt_no_avg_round_avx512(const __m512i src, const __m512i offset) { const __m512i dst = _mm512_add_epi16(src, offset); return _mm512_srli_epi16(dst, 2); } static INLINE void pack_store_32_avx512(const __m512i res, uint8_t *const dst) { const __m256i r0 = _mm512_castsi512_si256(res); const __m256i r1 = _mm512_extracti64x4_epi64(res, 1); pack_store_32_avx2(r0, r1, dst); } static INLINE void xy_y_pack_store_32x2_avx512(const __m512i res0, const __m512i res1, uint8_t *const dst, const ptrdiff_t stride) { const __m512i t = _mm512_packus_epi16(res0, res1); const __m512i d = _mm512_permutexvar_epi64(_mm512_setr_epi64(0, 4, 2, 6, 1, 5, 3, 7), t); storeu_u8_32x2_avx512(d, dst, stride); } static INLINE void xy_y_pack_store_64_avx512(const __m512i res0, const __m512i res1, uint8_t *const dst) { const __m512i d = _mm512_packus_epi16(res0, res1); // d = _mm512_permute4x64_epi64(d, 0xD8); _mm512_storeu_si512((__m512i *)dst, d); } static INLINE void xy_y_round_store_32x2_avx512(const __m512i r0[2], const __m512i r1[2], uint8_t *const dst, const ptrdiff_t stride) { const __m512i ra = xy_y_round_32_avx512(r0); const __m512i rb = xy_y_round_32_avx512(r1); xy_y_pack_store_32x2_avx512(ra, rb, dst, stride); } static INLINE void xy_y_round_store_64_avx512(const __m512i r0[2], const __m512i r1[2], uint8_t *const dst) { const __m512i ra = xy_y_round_32_avx512(r0); const __m512i rb = xy_y_round_32_avx512(r1); xy_y_pack_store_64_avx512(ra, rb, dst); } static INLINE void convolve_store_32x2_avx512(const __m512i res0, const __m512i res1, uint8_t *const dst, const ptrdiff_t dst_stride) { const __m512i d = _mm512_packus_epi16(res0, res1); storeu_u8_32x2_avx512(d, dst, dst_stride); } static INLINE void convolve_store_64_avx512(const __m512i res0, const __m512i res1, uint8_t *const dst) { const __m512i d = _mm512_packus_epi16(res0, res1); _mm512_storeu_si512((__m512i *)dst, d); } static INLINE void jnt_no_avg_store_32x2_avx512(const __m512i src0, const __m512i src1, ConvBufType *const dst, const ptrdiff_t stride) { const __m512i d0 = _mm512_permutex2var_epi64( src0, _mm512_setr_epi64(0, 1, 8, 9, 2, 3, 10, 11), src1); const __m512i d1 = _mm512_permutex2var_epi64( src0, _mm512_setr_epi64(4, 5, 12, 13, 6, 7, 14, 15), src1); _mm512_storeu_si512((__m512i *)dst, d0); _mm512_storeu_si512((__m512i *)(dst + stride), d1); } static INLINE void jnt_no_avg_store_64_avx512(const __m512i src0, const __m512i src1, ConvBufType *const dst) { const __m512i d0 = _mm512_permutex2var_epi64( src0, _mm512_setr_epi64(0, 1, 8, 9, 2, 3, 10, 11), src1); const __m512i d1 = _mm512_permutex2var_epi64( src0, _mm512_setr_epi64(4, 5, 12, 13, 6, 7, 14, 15), src1); _mm512_storeu_si512((__m512i *)dst, d0); _mm512_storeu_si512((__m512i *)(dst + 32), d1); } static INLINE void x_convolve_2tap_32x2_avx512(const uint8_t *const src, const ptrdiff_t src_stride, const __m512i coeffs[1], __m512i r[2]) { const __m512i s0_256 = loadu_u8_32x2_avx512(src, src_stride); const __m512i s1_256 = loadu_u8_32x2_avx512(src + 1, src_stride); const __m512i ss0 = _mm512_unpacklo_epi8(s0_256, s1_256); const __m512i ss1 = _mm512_unpackhi_epi8(s0_256, s1_256); r[0] = convolve_2tap_avx512(&ss0, coeffs); r[1] = convolve_2tap_avx512(&ss1, coeffs); } static INLINE void x_convolve_2tap_64_avx512(const uint8_t *const src, const __m512i coeffs[1], __m512i r[2]) { const __m512i s0 = _mm512_loadu_si512((__m512i *)src); const __m512i s1 = _mm512_loadu_si512((__m512i *)(src + 1)); const __m512i ss0 = _mm512_unpacklo_epi8(s0, s1); const __m512i ss1 = _mm512_unpackhi_epi8(s0, s1); r[0] = convolve_2tap_avx512(&ss0, coeffs); r[1] = convolve_2tap_avx512(&ss1, coeffs); } static INLINE __m512i x_convolve_4tap_avx512(const __m512i data, const __m512i coeffs[2], const __m512i filt[2]) { __m512i ss[2]; ss[0] = _mm512_shuffle_epi8(data, filt[0]); ss[1] = _mm512_shuffle_epi8(data, filt[1]); return convolve_4tap_avx512(ss, coeffs); } static INLINE __m512i x_convolve_6tap_avx512(const __m512i data, const __m512i coeffs[3], const __m512i filt[3]) { __m512i ss[3]; ss[0] = _mm512_shuffle_epi8(data, filt[0]); ss[1] = _mm512_shuffle_epi8(data, filt[1]); ss[2] = _mm512_shuffle_epi8(data, filt[2]); return convolve_6tap_avx512(ss, coeffs); } static INLINE __m512i x_convolve_8tap_avx512(const __m512i data, const __m512i coeffs[4], const __m512i filt[4]) { __m512i ss[4]; ss[0] = _mm512_shuffle_epi8(data, filt[0]); ss[1] = _mm512_shuffle_epi8(data, filt[1]); ss[2] = _mm512_shuffle_epi8(data, filt[2]); ss[3] = _mm512_shuffle_epi8(data, filt[3]); return convolve_8tap_avx512(ss, coeffs); } static INLINE void x_convolve_6tap_32x2_avx512(const uint8_t *const src, const ptrdiff_t src_stride, const __m512i coeffs[3], const __m512i filt[3], __m512i r[2]) { const __m512i s0_512 = loadu_u8_32x2_avx512(src, src_stride); const __m512i s1_512 = loadu_u8_32x2_avx512(src + 8, src_stride); r[0] = x_convolve_6tap_avx512(s0_512, coeffs, filt); r[1] = x_convolve_6tap_avx512(s1_512, coeffs, filt); } static INLINE void x_convolve_6tap_64_avx512(const uint8_t *const src, const __m512i coeffs[3], const __m512i filt[3], __m512i r[2]) { const __m512i s0_512 = _mm512_loadu_si512((__m512i *)src); const __m512i s1_512 = _mm512_loadu_si512((__m512i *)(src + 8)); r[0] = x_convolve_6tap_avx512(s0_512, coeffs, filt); r[1] = x_convolve_6tap_avx512(s1_512, coeffs, filt); } SIMD_INLINE void x_convolve_8tap_32x2_avx512(const uint8_t *const src, const ptrdiff_t src_stride, const __m512i coeffs[4], const __m512i filt[4], __m512i r[2]) { const __m512i s0_512 = loadu_u8_32x2_avx512(src, src_stride); const __m512i s1_512 = loadu_u8_32x2_avx512(src + 8, src_stride); r[0] = x_convolve_8tap_avx512(s0_512, coeffs, filt); r[1] = x_convolve_8tap_avx512(s1_512, coeffs, filt); } SIMD_INLINE void x_convolve_8tap_64_avx512(const uint8_t *const src, const __m512i coeffs[4], const __m512i filt[4], __m512i r[2]) { const __m512i s0_512 = _mm512_loadu_si512((__m512i *)src); const __m512i s1_512 = _mm512_loadu_si512((__m512i *)(src + 8)); r[0] = x_convolve_8tap_avx512(s0_512, coeffs, filt); r[1] = x_convolve_8tap_avx512(s1_512, coeffs, filt); } static INLINE void y_convolve_2tap_32x2_avx512(const uint8_t *const src, const ptrdiff_t stride, const __m512i coeffs[1], __m256i *const s0_256, __m512i r[2]) { const __m256i s1_256 = _mm256_loadu_si256((__m256i *)src); const __m512i s0_512 = _mm512_setr_m256i(*s0_256, s1_256); *s0_256 = _mm256_loadu_si256((__m256i *)(src + stride)); const __m512i s1_512 = _mm512_setr_m256i(s1_256, *s0_256); const __m512i ss0 = _mm512_unpacklo_epi8(s0_512, s1_512); const __m512i ss1 = _mm512_unpackhi_epi8(s0_512, s1_512); r[0] = convolve_2tap_avx512(&ss0, coeffs); r[1] = convolve_2tap_avx512(&ss1, coeffs); } static INLINE void y_convolve_2tap_64_avx512(const uint8_t *const src, const __m512i coeffs[1], const __m512i s0, __m512i *const s1, __m512i r[2]) { *s1 = _mm512_loadu_si512((__m512i *)src); const __m512i ss0 = _mm512_unpacklo_epi8(s0, *s1); const __m512i ss1 = _mm512_unpackhi_epi8(s0, *s1); r[0] = convolve_2tap_avx512(&ss0, coeffs); r[1] = convolve_2tap_avx512(&ss1, coeffs); } static INLINE void y_convolve_4tap_32x2_avx512(const uint8_t *const src, const ptrdiff_t stride, const __m512i coeffs[2], __m256i s_256[3], __m512i ss_512[4], __m512i r[2]) { s_256[1] = _mm256_loadu_si256((__m256i *)(src + 1 * stride)); const __m512i s0_512 = _mm512_setr_m256i(s_256[2], s_256[1]); s_256[2] = _mm256_loadu_si256((__m256i *)(src + 2 * stride)); const __m512i s1_512 = _mm512_setr_m256i(s_256[1], s_256[2]); ss_512[1] = _mm512_unpacklo_epi8(s0_512, s1_512); ss_512[3] = _mm512_unpackhi_epi8(s0_512, s1_512); r[0] = convolve_4tap_avx512(ss_512 + 0, coeffs); r[1] = convolve_4tap_avx512(ss_512 + 2, coeffs); } static INLINE void y_convolve_6tap_32x2_avx512(const uint8_t *const src, const ptrdiff_t stride, const __m512i coeffs[3], __m256i s_256[5], __m512i ss_512[6], __m512i r[2]) { s_256[3] = _mm256_loadu_si256((__m256i *)(src + 3 * stride)); const __m512i s0_512 = _mm512_setr_m256i(s_256[4], s_256[3]); s_256[4] = _mm256_loadu_si256((__m256i *)(src + 4 * stride)); const __m512i s1_512 = _mm512_setr_m256i(s_256[3], s_256[4]); ss_512[2] = _mm512_unpacklo_epi8(s0_512, s1_512); ss_512[5] = _mm512_unpackhi_epi8(s0_512, s1_512); r[0] = convolve_6tap_avx512(ss_512 + 0, coeffs); r[1] = convolve_6tap_avx512(ss_512 + 3, coeffs); } static INLINE void y_convolve_6tap_64x2_avx512(const uint8_t *const src, const ptrdiff_t stride, const __m512i coeffs[3], __m512i s_512[6], __m512i ss_512[6], __m512i tt_512[6], __m512i r[4]) { s_512[5] = _mm512_loadu_si512((__m512i *)(src + 3 * stride)); ss_512[2] = _mm512_unpacklo_epi8(s_512[4], s_512[5]); ss_512[5] = _mm512_unpackhi_epi8(s_512[4], s_512[5]); s_512[4] = _mm512_loadu_si512((__m512i *)(src + 4 * stride)); tt_512[2] = _mm512_unpacklo_epi8(s_512[5], s_512[4]); tt_512[5] = _mm512_unpackhi_epi8(s_512[5], s_512[4]); r[0] = convolve_6tap_avx512(ss_512 + 0, coeffs); r[1] = convolve_6tap_avx512(ss_512 + 3, coeffs); r[2] = convolve_6tap_avx512(tt_512 + 0, coeffs); r[3] = convolve_6tap_avx512(tt_512 + 3, coeffs); } static INLINE void y_convolve_8tap_32x2_avx512(const uint8_t *const src, const ptrdiff_t stride, const __m512i coeffs[4], __m256i s_256[7], __m512i ss_512[8], __m512i r[2]) { s_256[5] = _mm256_loadu_si256((__m256i *)(src + 5 * stride)); const __m512i s0_512 = _mm512_setr_m256i(s_256[6], s_256[5]); s_256[6] = _mm256_loadu_si256((__m256i *)(src + 6 * stride)); const __m512i s1_512 = _mm512_setr_m256i(s_256[5], s_256[6]); ss_512[3] = _mm512_unpacklo_epi8(s0_512, s1_512); ss_512[7] = _mm512_unpackhi_epi8(s0_512, s1_512); r[0] = convolve_8tap_avx512(ss_512 + 0, coeffs); r[1] = convolve_8tap_avx512(ss_512 + 4, coeffs); } static INLINE void y_convolve_8tap_64x2_avx512(const uint8_t *const src, const ptrdiff_t stride, const __m512i coeffs[4], __m512i s_512[8], __m512i ss_512[8], __m512i tt_512[8], __m512i r[4]) { s_512[7] = _mm512_loadu_si512((__m512i *)(src + 7 * stride)); ss_512[3] = _mm512_unpacklo_epi8(s_512[6], s_512[7]); ss_512[7] = _mm512_unpackhi_epi8(s_512[6], s_512[7]); s_512[6] = _mm512_loadu_si512((__m512i *)(src + 8 * stride)); tt_512[3] = _mm512_unpacklo_epi8(s_512[7], s_512[6]); tt_512[7] = _mm512_unpackhi_epi8(s_512[7], s_512[6]); r[0] = convolve_8tap_avx512(ss_512 + 0, coeffs); r[1] = convolve_8tap_avx512(ss_512 + 4, coeffs); r[2] = convolve_8tap_avx512(tt_512 + 0, coeffs); r[3] = convolve_8tap_avx512(tt_512 + 4, coeffs); } static INLINE void xy_x_convolve_2tap_32x2_avx512(const uint8_t *const src, const ptrdiff_t stride, const __m512i coeffs[1], __m512i r[2]) { const __m512i s0 = loadu_u8_32x2_avx512(src, stride); const __m512i s1 = loadu_u8_32x2_avx512(src + 1, stride); const __m512i ss0 = _mm512_unpacklo_epi8(s0, s1); const __m512i ss1 = _mm512_unpackhi_epi8(s0, s1); r[0] = convolve_2tap_avx512(&ss0, coeffs); r[1] = convolve_2tap_avx512(&ss1, coeffs); } static INLINE void xy_x_convolve_2tap_64_avx512(const uint8_t *const src, const __m512i coeffs[1], __m512i r[2]) { const __m512i s0 = _mm512_loadu_si512((__m512i *)src); const __m512i s1 = _mm512_loadu_si512((__m512i *)(src + 1)); const __m512i ss0 = _mm512_unpacklo_epi8(s0, s1); const __m512i ss1 = _mm512_unpackhi_epi8(s0, s1); r[0] = convolve_2tap_avx512(&ss0, coeffs); r[1] = convolve_2tap_avx512(&ss1, coeffs); } static INLINE void xy_x_2tap_32x2_avx512(const uint8_t *const src, const ptrdiff_t src_stride, const __m512i coeffs[1], int16_t *const dst) { __m512i r[2]; xy_x_convolve_2tap_32x2_avx512(src, src_stride, coeffs, r); const __m512i d0 = xy_x_round_avx512(r[0]); const __m512i d1 = xy_x_round_avx512(r[1]); // const __m512i d0 = _mm512_inserti64x4(t0, _mm512_castsi512_si256(t1), 1); // const __m512i d1 = _mm512_inserti64x4(t1, _mm512_extracti64x4_epi64(t0, // 1), 0); zz_store_512(dst, d0); zz_store_512(dst + 32, d1); } static INLINE void xy_x_store_64_avx512(const __m512i d[2], int16_t *const dst) { const __m512i d0 = xy_x_round_avx512(d[0]); const __m512i d1 = xy_x_round_avx512(d[1]); // const __m512i d0 = _mm512_inserti64x4(t0, _mm512_castsi512_si256(t1), 1); // const __m512i d1 = _mm512_inserti64x4(t1, _mm512_extracti64x4_epi64(t0, // 1), 0); zz_store_512(dst, d0); zz_store_512(dst + 32, d1); } static INLINE void xy_x_2tap_64_avx512(const uint8_t *const src, const __m512i coeffs[1], int16_t *const dst) { __m512i d[2]; xy_x_convolve_2tap_64_avx512(src, coeffs, d); xy_x_store_64_avx512(d, dst); } static INLINE void xy_x_6tap_32x2_avx512(const uint8_t *const src, const ptrdiff_t src_stride, const __m512i coeffs[3], const __m512i filt[3], int16_t *const dst) { __m512i d[2]; x_convolve_6tap_32x2_avx512(src, src_stride, coeffs, filt, d); xy_x_store_64_avx512(d, dst); } static INLINE void xy_x_6tap_64_avx512(const uint8_t *const src, const __m512i coeffs[3], const __m512i filt[3], int16_t *const dst) { __m512i d[2]; x_convolve_6tap_64_avx512(src, coeffs, filt, d); xy_x_store_64_avx512(d, dst); } static INLINE void xy_x_8tap_32x2_avx512(const uint8_t *const src, const ptrdiff_t src_stride, const __m512i coeffs[4], const __m512i filt[4], int16_t *const dst) { __m512i d[2]; x_convolve_8tap_32x2_avx512(src, src_stride, coeffs, filt, d); xy_x_store_64_avx512(d, dst); } static INLINE void xy_x_8tap_64_avx512(const uint8_t *const src, const __m512i coeffs[4], const __m512i filt[4], int16_t *const dst) { __m512i d[2]; x_convolve_8tap_64_avx512(src, coeffs, filt, d); xy_x_store_64_avx512(d, dst); } static INLINE void xy_y_convolve_2tap_32_avx512(const __m512i s0, const __m512i s1, const __m512i coeffs[1], __m512i r[2]) { const __m512i ss0 = _mm512_unpacklo_epi16(s0, s1); const __m512i ss1 = _mm512_unpackhi_epi16(s0, s1); r[0] = convolve16_2tap_avx512(&ss0, coeffs); r[1] = convolve16_2tap_avx512(&ss1, coeffs); } static INLINE void xy_y_convolve_2tap_32x2_avx512(const int16_t *const src, __m512i s[2], const __m512i coeffs[1], __m512i r[4]) { s[1] = loadu_s16_16x2_avx512(src + 16, 32); xy_y_convolve_2tap_32_avx512(s[0], s[1], coeffs, r + 0); s[0] = loadu_s16_16x2_avx512(src + 64, 32); xy_y_convolve_2tap_32_avx512(s[1], s[0], coeffs, r + 2); } static INLINE void xy_y_convolve_2tap_64_avx512(const int16_t *const src, const __m512i s0[2], __m512i s1[2], const __m512i coeffs[1], __m512i r[4]) { s1[0] = zz_load_512(src); s1[1] = zz_load_512(src + 32); xy_y_convolve_2tap_32_avx512(s0[0], s1[0], coeffs, r + 0); xy_y_convolve_2tap_32_avx512(s0[1], s1[1], coeffs, r + 2); } static INLINE void xy_y_convolve_2tap_64_all_avx512(const int16_t *const src, const __m512i s0[2], __m512i s1[2], const __m512i coeffs[1], uint8_t *const dst) { __m512i r[4]; xy_y_convolve_2tap_64_avx512(src, s0, s1, coeffs, r); xy_y_round_store_64_avx512(r + 0, r + 2, dst); } static INLINE void xy_y_convolve_2tap_half_pel_32x2_avx512(const int16_t *const src, __m512i s[2], __m512i r[2]) { s[1] = loadu_s16_16x2_avx512(src, 32); r[0] = _mm512_add_epi16(s[0], s[1]); s[0] = loadu_s16_16x2_avx512(src + 48, 32); r[1] = _mm512_add_epi16(s[1], s[0]); } static INLINE void xy_y_convolve_2tap_half_pel_64_avx512(const int16_t *const src, const __m512i s0[2], __m512i s1[2], __m512i r[2]) { s1[0] = zz_load_512(src); s1[1] = zz_load_512(src + 32); r[0] = _mm512_add_epi16(s0[0], s1[0]); r[1] = _mm512_add_epi16(s0[1], s1[1]); } static INLINE void xy_y_convolve_2tap_half_pel_64_all_avx512(const int16_t *const src, const __m512i s0[2], __m512i s1[2], uint8_t *const dst) { __m512i r[2]; xy_y_convolve_2tap_half_pel_64_avx512(src, s0, s1, r); r[0] = xy_y_round_half_pel_avx512(r[0]); r[1] = xy_y_round_half_pel_avx512(r[1]); xy_y_pack_store_64_avx512(r[0], r[1], dst); } static INLINE void xy_y_convolve_4tap_32_avx512(const __m512i ss[4], const __m512i coeffs[2], __m512i r[2]) { r[0] = convolve16_4tap_avx512(ss, coeffs); r[1] = convolve16_4tap_avx512(ss + 2, coeffs); } static INLINE void xy_y_convolve_4tap_width32x2_avx512(const int16_t *const src, __m512i s_512[4], __m512i ss_512[4], __m512i tt_512[4], const __m512i coeffs[2], __m512i r[4]) { s_512[3] = loadu_s16_16x2_avx512(src + 5 * 16, 32); ss_512[1] = _mm512_unpacklo_epi16(s_512[2], s_512[3]); ss_512[3] = _mm512_unpackhi_epi16(s_512[2], s_512[3]); s_512[2] = loadu_s16_16x2_avx512(src + 8 * 16, 32); tt_512[1] = _mm512_unpacklo_epi16(s_512[3], s_512[2]); tt_512[3] = _mm512_unpackhi_epi16(s_512[3], s_512[2]); xy_y_convolve_4tap_32_avx512(ss_512, coeffs, r + 0); xy_y_convolve_4tap_32_avx512(tt_512, coeffs, r + 2); ss_512[0] = ss_512[1]; ss_512[2] = ss_512[3]; tt_512[0] = tt_512[1]; tt_512[2] = tt_512[3]; } static INLINE void xy_y_convolve_6tap_32_avx512(const __m512i ss[6], const __m512i coeffs[3], __m512i r[2]) { r[0] = convolve16_6tap_avx512(ss, coeffs); r[1] = convolve16_6tap_avx512(ss + 3, coeffs); } SIMD_INLINE void xy_y_convolve_6tap_width32x2_avx512(const int16_t *const src, const __m512i coeffs[3], __m512i s_512[6], __m512i ss_512[6], __m512i tt_512[6], __m512i r[4]) { s_512[5] = loadu_s16_16x2_avx512(src + 9 * 16, 32); ss_512[2] = _mm512_unpacklo_epi16(s_512[4], s_512[5]); ss_512[5] = _mm512_unpackhi_epi16(s_512[4], s_512[5]); s_512[4] = loadu_s16_16x2_avx512(src + 12 * 16, 32); tt_512[2] = _mm512_unpacklo_epi16(s_512[5], s_512[4]); tt_512[5] = _mm512_unpackhi_epi16(s_512[5], s_512[4]); xy_y_convolve_6tap_32_avx512(ss_512, coeffs, r + 0); xy_y_convolve_6tap_32_avx512(tt_512, coeffs, r + 2); ss_512[0] = ss_512[1]; ss_512[1] = ss_512[2]; ss_512[3] = ss_512[4]; ss_512[4] = ss_512[5]; tt_512[0] = tt_512[1]; tt_512[1] = tt_512[2]; tt_512[3] = tt_512[4]; tt_512[4] = tt_512[5]; } static INLINE void xy_y_convolve_6tap_32x2_avx512(const int16_t *const src, const ptrdiff_t stride, __m512i s_512[6], __m512i ss_512[6], __m512i tt_512[6], const __m512i coeffs[3], __m512i r[4]) { s_512[5] = _mm512_loadu_si512((__m512i *)(src + 5 * stride)); ss_512[2] = _mm512_unpacklo_epi16(s_512[4], s_512[5]); ss_512[5] = _mm512_unpackhi_epi16(s_512[4], s_512[5]); s_512[4] = _mm512_loadu_si512((__m512i *)(src + 6 * stride)); tt_512[2] = _mm512_unpacklo_epi16(s_512[5], s_512[4]); tt_512[5] = _mm512_unpackhi_epi16(s_512[5], s_512[4]); xy_y_convolve_6tap_32_avx512(ss_512, coeffs, r + 0); xy_y_convolve_6tap_32_avx512(tt_512, coeffs, r + 2); ss_512[0] = ss_512[1]; ss_512[1] = ss_512[2]; ss_512[3] = ss_512[4]; ss_512[4] = ss_512[5]; tt_512[0] = tt_512[1]; tt_512[1] = tt_512[2]; tt_512[3] = tt_512[4]; tt_512[4] = tt_512[5]; } SIMD_INLINE void xy_y_convolve_8tap_32_avx512(const __m512i *const ss, const __m512i coeffs[4], __m512i r[2]) { r[0] = convolve16_8tap_avx512(ss, coeffs); r[1] = convolve16_8tap_avx512(ss + 4, coeffs); } SIMD_INLINE void xy_y_convolve_8tap_width32x2_avx512(const int16_t *const src, const __m512i coeffs[4], __m512i s_512[8], __m512i ss_512[8], __m512i tt_512[8], __m512i r[4]) { s_512[7] = loadu_s16_16x2_avx512(src + 13 * 16, 32); ss_512[3] = _mm512_unpacklo_epi16(s_512[6], s_512[7]); ss_512[7] = _mm512_unpackhi_epi16(s_512[6], s_512[7]); s_512[6] = loadu_s16_16x2_avx512(src + 16 * 16, 32); tt_512[3] = _mm512_unpacklo_epi16(s_512[7], s_512[6]); tt_512[7] = _mm512_unpackhi_epi16(s_512[7], s_512[6]); xy_y_convolve_8tap_32_avx512(ss_512, coeffs, r + 0); xy_y_convolve_8tap_32_avx512(tt_512, coeffs, r + 2); ss_512[0] = ss_512[1]; ss_512[1] = ss_512[2]; ss_512[2] = ss_512[3]; ss_512[4] = ss_512[5]; ss_512[5] = ss_512[6]; ss_512[6] = ss_512[7]; tt_512[0] = tt_512[1]; tt_512[1] = tt_512[2]; tt_512[2] = tt_512[3]; tt_512[4] = tt_512[5]; tt_512[5] = tt_512[6]; tt_512[6] = tt_512[7]; } SIMD_INLINE void xy_y_convolve_8tap_32x2_avx512(const int16_t *const src, const ptrdiff_t stride, const __m512i coeffs[4], __m512i s_512[8], __m512i ss_512[8], __m512i tt_512[8], __m512i r[4]) { s_512[7] = zz_load_512(src + 7 * stride); ss_512[3] = _mm512_unpacklo_epi16(s_512[6], s_512[7]); ss_512[7] = _mm512_unpackhi_epi16(s_512[6], s_512[7]); s_512[6] = zz_load_512(src + 8 * stride); tt_512[3] = _mm512_unpacklo_epi16(s_512[7], s_512[6]); tt_512[7] = _mm512_unpackhi_epi16(s_512[7], s_512[6]); xy_y_convolve_8tap_32_avx512(ss_512, coeffs, r + 0); xy_y_convolve_8tap_32_avx512(tt_512, coeffs, r + 2); ss_512[0] = ss_512[1]; ss_512[1] = ss_512[2]; ss_512[2] = ss_512[3]; ss_512[4] = ss_512[5]; ss_512[5] = ss_512[6]; ss_512[6] = ss_512[7]; tt_512[0] = tt_512[1]; tt_512[1] = tt_512[2]; tt_512[2] = tt_512[3]; tt_512[4] = tt_512[5]; tt_512[5] = tt_512[6]; tt_512[6] = tt_512[7]; } static INLINE __m512i jnt_comp_avg_convolve_32_avx512(const __m512i res, const __m512i dst, const __m512i factor, const __m512i offset) { __m512i d[2]; d[0] = _mm512_unpacklo_epi16(dst, res); d[1] = _mm512_unpackhi_epi16(dst, res); d[0] = _mm512_madd_epi16(d[0], factor); d[1] = _mm512_madd_epi16(d[1], factor); d[0] = _mm512_add_epi32(d[0], offset); d[1] = _mm512_add_epi32(d[1], offset); d[0] = _mm512_srai_epi32(d[0], 8); d[1] = _mm512_srai_epi32(d[1], 8); return _mm512_packs_epi32(d[0], d[1]); } static INLINE void jnt_comp_avg_round_store_32_kernel_avx512(const __m512i res, const __m512i factor, const __m512i offset, const ConvBufType *const dst, uint8_t *const dst8) { __m512i d; d = _mm512_loadu_si512((__m512i *)dst); d = jnt_comp_avg_convolve_32_avx512(res, d, factor, offset); pack_store_32_avx512(d, dst8); } static INLINE void jnt_loadu_u16_8x4x2_avx512(const ConvBufType *const src, const ptrdiff_t stride, __m512i d[2]) { const __m512i s0 = _mm512_loadu_si512((__m512i *)(src + 0 * stride)); const __m512i s1 = _mm512_loadu_si512((__m512i *)(src + 1 * stride)); d[0] = _mm512_permutex2var_epi64(s0, _mm512_setr_epi64(0, 1, 4, 5, 8, 9, 12, 13), s1); d[1] = _mm512_permutex2var_epi64(s0, _mm512_setr_epi64(2, 3, 6, 7, 10, 11, 14, 15), s1); } SIMD_INLINE void jnt_comp_avg_round_store_32x2_avx512( const __m512i res[2], const __m512i factor, const __m512i offset, const ConvBufType *const dst, const ptrdiff_t dst_stride, uint8_t *const dst8, const ptrdiff_t dst8_stride) { __m512i r[2], d[2]; r[0] = jnt_y_round_avx512(res[0]); r[1] = jnt_y_round_avx512(res[1]); jnt_loadu_u16_8x4x2_avx512(dst, dst_stride, d); d[0] = jnt_comp_avg_convolve_32_avx512(r[0], d[0], factor, offset); d[1] = jnt_comp_avg_convolve_32_avx512(r[1], d[1], factor, offset); convolve_store_32x2_avx512(d[0], d[1], dst8, dst8_stride); } SIMD_INLINE void jnt_comp_avg_round_store_64_avx512(const __m512i res[2], const __m512i factor, const __m512i offset, const ConvBufType *const dst, uint8_t *const dst8) { __m512i r[2], d[2]; r[0] = jnt_y_round_avx512(res[0]); r[1] = jnt_y_round_avx512(res[1]); jnt_loadu_u16_8x4x2_avx512(dst, 32, d); d[0] = jnt_comp_avg_convolve_32_avx512(r[0], d[0], factor, offset); d[1] = jnt_comp_avg_convolve_32_avx512(r[1], d[1], factor, offset); convolve_store_64_avx512(d[0], d[1], dst8); } static INLINE __m512i jnt_avg_32_avx512(const __m512i res, const __m512i dst) { const __m512i d = _mm512_add_epi16(res, dst); return _mm512_srai_epi16(d, 5); } static INLINE __m512i jnt_copy_load_src_32_avx512(const uint8_t *const src) { const __m256i s8 = _mm256_loadu_si256((__m256i *)src); const __m512i s16 = _mm512_cvtepu8_epi16(s8); return _mm512_slli_epi16(s16, LEFT_SHIFT); } static INLINE void jnt_copy_comp_avg_32_avx512(const uint8_t *const src, const __m512i factor_512, const __m512i offset_comp_avg_512, const ConvBufType *const dst, uint8_t *const dst8) { const __m512i res = jnt_copy_load_src_32_avx512(src); jnt_comp_avg_round_store_32_kernel_avx512(res, factor_512, offset_comp_avg_512, dst, dst8); } static INLINE void jnt_avg_round_store_32x2_avx512(const __m512i res[2], const __m512i offset, const ConvBufType *const dst, const ptrdiff_t dst_stride, uint8_t *const dst8, const ptrdiff_t dst8_stride) { __m512i r[2], d[2]; r[0] = jnt_avg_round_avx512(res[0], offset); r[1] = jnt_avg_round_avx512(res[1], offset); jnt_loadu_u16_8x4x2_avx512(dst, dst_stride, d); d[0] = jnt_avg_32_avx512(r[0], d[0]); d[1] = jnt_avg_32_avx512(r[1], d[1]); convolve_store_32x2_avx512(d[0], d[1], dst8, dst8_stride); } static INLINE void jnt_avg_round_store_64_avx512(const __m512i res[2], const __m512i offset, const ConvBufType *const dst, uint8_t *const dst8) { __m512i r[2], d[2]; r[0] = jnt_avg_round_avx512(res[0], offset); r[1] = jnt_avg_round_avx512(res[1], offset); jnt_loadu_u16_8x4x2_avx512(dst, 32, d); d[0] = jnt_avg_32_avx512(r[0], d[0]); d[1] = jnt_avg_32_avx512(r[1], d[1]); convolve_store_64_avx512(d[0], d[1], dst8); } static INLINE void jnt_no_avg_round_store_32x2_avx512(const __m512i res[2], const __m512i offset, ConvBufType *const dst, const ptrdiff_t dst_stride) { __m512i d[2]; d[0] = jnt_no_avg_round_avx512(res[0], offset); d[1] = jnt_no_avg_round_avx512(res[1], offset); jnt_no_avg_store_32x2_avx512(d[0], d[1], dst, dst_stride); } static INLINE void jnt_no_avg_round_store_64_avx512(const __m512i res[2], const __m512i offset, ConvBufType *const dst) { __m512i d[2]; d[0] = jnt_no_avg_round_avx512(res[0], offset); d[1] = jnt_no_avg_round_avx512(res[1], offset); jnt_no_avg_store_64_avx512(d[0], d[1], dst); } #endif // EN_AVX512_SUPPORT #endif // AOM_DSP_X86_CONVOLVE_AVX512_H_
29,621
370
#define DINT #include <../Source/umf_realloc.c>
20
965
<filename>docs/atl/codesnippet/CPP/specifying-property-pages_1.h class ATL_NO_VTABLE CMyCtrl : OtherInterfaces public ISpecifyPropertyPagesImpl<CMyCtrl> { public: BEGIN_COM_MAP(CMyCtrl) OtherComMapEntries COM_INTERFACE_ENTRY(ISpecifyPropertyPages) END_COM_MAP() BEGIN_PROP_MAP(CMyCtrl) OtherPropMapEntries PROP_PAGE(CLSID_DatePage) PROP_PAGE(CLSID_StockColorPage) END_PROP_MAP() // Remainder of class declaration omitted.
182
1,947
<gh_stars>1000+ /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ // Do not edit this file. It is machine generated. { "WrongNumberOfParametersProvidedReferToTheUsageOfThisScript": "Yanlış sayıda parametre sağlandı. Lütfen doğru kullanım için bu betiğin kullanımına başvurun." }
137
337
<filename>j2k/testData/fileOrElement/class/emptyClass.java //class final class A {}
28
5,169
<filename>Specs/1/9/4/iiwi/0.1.1/iiwi.podspec.json { "name": "iiwi", "version": "0.1.1", "summary": "iiwi simplifies usage of Core Data", "description": "iiwi is a simple library which helps set up Core Data in application. It relies on NSPersistentContainer and provides implementation of base repositories. Repository allows CRUD operations. There is also convenienece solution for fetching enitities based on generic primary key.", "homepage": "https://github.com/rogowskimark/iiwi", "license": { "type": "MIT", "file": "LICENSE" }, "authors": { "rogowskimark": "<EMAIL>" }, "source": { "git": "https://github.com/rogowskimark/iiwi.git", "tag": "0.1.1" }, "swift_versions": "4.2", "platforms": { "ios": "11.0" }, "source_files": "iiwi/Classes/**/*", "swift_version": "4.2" }
321
743
<gh_stars>100-1000 { // Use IntelliSense to find out which attributes exist for C# debugging // Use hover for the description of the existing attributes // For further information visit https://github.com/OmniSharp/omnisharp-vscode/blob/master/debugger-launchjson.md "version": "0.2.0", "configurations": [ { "type": "chrome", "request": "launch", "name": "Debug Designer", "url": "http://localhost:8001", "webRoot": "${workspaceFolder}/source/nodejs/adaptivecards-designer" },{ "name": ".NET Core Attach", "type": "coreclr", "request": "attach", "processId": "${command:pickProcess}" } ] }
257
816
<gh_stars>100-1000 package geb.textmatching; import java.util.Arrays; class AnyTextMatcher extends CompositeTextMatcher { public AnyTextMatcher(TextMatcher[] matchers) { super(matchers); } @Override public boolean matches(String text) { return Arrays.stream(matchers).anyMatch(m -> m.matches(text)); } }
131
434
<reponame>Hidden-black/jishaku #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ MIT License Copyright (c) 2021 <NAME> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ import os import pkg_resources from jinja2 import Environment from jinja2.environment import Template from jinja2.loaders import BaseLoader ENVIRONMENT = Environment(loader=BaseLoader()) with open('dist_summary.jinja2', 'r', encoding='utf-8') as fp: template: Template = ENVIRONMENT.from_string(fp.read()) with open('dist/DIST_SUMMARY.md', 'w', encoding='utf-8') as fp: output = template.render( env=os.getenv, package=pkg_resources.get_distribution('jishaku'), ) # Jinja loves obliterating trailing newlines if not output.endswith('\n'): output += '\n' fp.write(output)
557
2,989
<reponame>tb-soft/databus package com.linkedin.databus.util; import com.linkedin.databus2.test.TestUtil; import java.io.File; import java.util.List; import org.apache.log4j.Level; import org.jboss.netty.logging.InternalLoggerFactory; import org.jboss.netty.logging.Log4JLoggerFactory; import org.testng.Assert; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import com.linkedin.databus.core.util.FileUtils; import com.linkedin.databus.core.util.InvalidConfigException; public class TestSchemaMetaDataManager { @Test /** * Steps: * 1. Construct a Schema-registry directory with expected meta-files for some example sources and have a backup. * 2. Instantiate a SchemaMetaDataManager * 3. Call public getter APIs to fetch srcIds and sourceNames and validate they are expected. * 4. Call store() and ensure the persisted matches with the backup. * 5. Add a new source. Validate the new sourceId is expected. * 6. Call public getter APIs to fetch srcIds and sourceNames and validate they are expected. * * @throws Exception */ public void testSchemaMetaDataManager() throws Exception { File schema_dir = FileUtils.createTempDir("dir_testSchemaMetaDataManager"); // Input contents String[] idNameMapContents = { "1:com.linkedin.events.example.person", "2:com.linkedin.events.example.address", "3:com.linkedin.events.example.date", "10:com.linkedin.events.another_example.zipcode", }; String[] dbToSrcMapContents = { "{", " \"another_example\" : [ \"com.linkedin.events.another_example.zipcode\" ],", " \"example\" : [ \"com.linkedin.events.example.address\", \"com.linkedin.events.example.date\", \"com.linkedin.events.example.person\" ]", "}" }; String dbToSrcFile1 = schema_dir.getAbsolutePath() + "/physical_logical_src_map.json"; String idNameMapFile1 = schema_dir.getAbsolutePath() + "/idToName.map"; FileUtils.storeLinesToTempFile(dbToSrcFile1,dbToSrcMapContents); FileUtils.storeLinesToTempFile(idNameMapFile1, idNameMapContents); File newSchemaDir = FileUtils.createTempDir("dir_testSchemaMetaDataManager_backup"); String dbToSrcFile2 = newSchemaDir.getAbsolutePath() + "/physical_logical_src_map.json"; String idNameMapFile2 = newSchemaDir.getAbsolutePath() + "/idToName.map"; Runtime.getRuntime().exec("cp " + dbToSrcFile1 + " " + dbToSrcFile2 ); Runtime.getRuntime().exec("cp " + idNameMapFile1 + " " + idNameMapFile2 ); SchemaMetaDataManager mgr = new SchemaMetaDataManager(schema_dir.getAbsolutePath()); //Validate Managed Sources List<String> sources = mgr.getManagedSourcesForDB("another_example"); Assert.assertEquals( sources.size(), 1, "Number of Sources"); Assert.assertEquals(sources.get(0),"com.linkedin.events.another_example.zipcode","Number of Sources"); sources = mgr.getManagedSourcesForDB("example"); Assert.assertEquals(sources.size(),3, "Number of Sources"); Assert.assertEquals( sources.get(0), "com.linkedin.events.example.person", "Source 1"); Assert.assertEquals( sources.get(1), "com.linkedin.events.example.address", "Source 2"); Assert.assertEquals( sources.get(2), "com.linkedin.events.example.date","Source 3"); Assert.assertNull(mgr.getManagedSourcesForDB("unknown_source"),"Unknown Source"); //Validate getSrcId Assert.assertEquals( mgr.getSrcId("com.linkedin.events.another_example.zipcode"),10,"ZipCode SrcId"); Assert.assertEquals( mgr.getSrcId("com.linkedin.events.example.person"),1, "Person SrcId"); Assert.assertEquals( mgr.getSrcId("com.linkedin.events.example.address"), 2, "Address SrcId"); Assert.assertEquals( mgr.getSrcId("com.linkedin.events.example.date"),3, "Date SrcId"); //unknown SrcName boolean exception = false; try { mgr.getSrcId("Unknown SrcId"); } catch (RuntimeException re) { exception = true; } Assert.assertTrue(exception, "Got exception ?"); //Store to meta-files and compare to expected files. mgr.store(); FileUtils.compareTwoTextFiles(dbToSrcFile1, dbToSrcFile2); FileUtils.compareTwoTextFiles(idNameMapFile1, idNameMapFile2); // Adding new source short srcId = mgr.updateAndGetNewSrcId("another_example", "com.linkedin.events.another_example.city"); Assert.assertEquals(srcId,11,"New SrcId "); sources = mgr.getManagedSourcesForDB("another_example"); Assert.assertEquals( sources.size(), 2, "Number of Sources"); Assert.assertEquals(sources.get(0),"com.linkedin.events.another_example.zipcode","Zipcode Sources"); Assert.assertEquals(sources.get(1),"com.linkedin.events.another_example.city","City Source "); Assert.assertEquals( mgr.getSrcId("com.linkedin.events.another_example.city"),11,"City SrcId"); sources = mgr.getManagedSourcesForDB("example"); Assert.assertEquals(sources.size(),3, "Number of Sources"); Assert.assertEquals( sources.get(0), "com.linkedin.events.example.person", "Source 1"); Assert.assertEquals( sources.get(1), "com.linkedin.events.example.address", "Source 2"); Assert.assertEquals( sources.get(2), "com.linkedin.events.example.date","Source 3"); Assert.assertNull(mgr.getManagedSourcesForDB("unknown_source"),"Unknown Source"); System.out.println(mgr.getDbToSrcMap()); } @Test public void testDuplicateSourceId() throws Exception { File schema_dir = FileUtils.createTempDir("dir_testSchemaMetaDataManager"); // Input contents String[] idNameMapContents = { "1:com.linkedin.events.example.person", "2:com.linkedin.events.example.address", "3:com.linkedin.events.example.date", "2:com.linkedin.events.another_example.zipcode", }; String[] dbToSrcMapContents = { "{", " \"another_example\" : [ \"com.linkedin.events.another_example.zipcode\" ],", " \"example\" : [ \"com.linkedin.events.example.address\", \"com.linkedin.events.example.date\", \"com.linkedin.events.example.person\" ]", "}" }; String dbToSrcFile1 = schema_dir.getAbsolutePath() + "/physical_logical_src_map.json"; String idNameMapFile1 = schema_dir.getAbsolutePath() + "/idToName.map"; FileUtils.storeLinesToTempFile(dbToSrcFile1,dbToSrcMapContents); FileUtils.storeLinesToTempFile(idNameMapFile1, idNameMapContents); File newSchemaDir = FileUtils.createTempDir("dir_testSchemaMetaDataManager_backup"); String dbToSrcFile2 = newSchemaDir.getAbsolutePath() + "/physical_logical_src_map.json"; String idNameMapFile2 = newSchemaDir.getAbsolutePath() + "/idToName.map"; Runtime.getRuntime().exec("cp " + dbToSrcFile1 + " " + dbToSrcFile2 ); Runtime.getRuntime().exec("cp " + idNameMapFile1 + " " + idNameMapFile2 ); SchemaMetaDataManager mgr = null; //unknown SrcName boolean exception = false; try { mgr = new SchemaMetaDataManager(schema_dir.getAbsolutePath()); } catch (RuntimeException re) { exception = true; } Assert.assertTrue(exception, "Got exception ?"); } @Test public void testDuplicateSourceName() throws Exception { File schema_dir = FileUtils.createTempDir("dir_testSchemaMetaDataManager"); // Input contents String[] idNameMapContents = { "1:com.linkedin.events.example.person", "2:com.linkedin.events.example.address", "3:com.linkedin.events.example.address", "4:com.linkedin.events.another_example.zipcode", }; String[] dbToSrcMapContents = { "{", " \"another_example\" : [ \"com.linkedin.events.another_example.zipcode\" ],", " \"example\" : [ \"com.linkedin.events.example.address\", \"com.linkedin.events.example.date\", \"com.linkedin.events.example.person\" ]", "}" }; String dbToSrcFile1 = schema_dir.getAbsolutePath() + "/physical_logical_src_map.json"; String idNameMapFile1 = schema_dir.getAbsolutePath() + "/idToName.map"; FileUtils.storeLinesToTempFile(dbToSrcFile1,dbToSrcMapContents); FileUtils.storeLinesToTempFile(idNameMapFile1, idNameMapContents); File newSchemaDir = FileUtils.createTempDir("dir_testSchemaMetaDataManager_backup"); String dbToSrcFile2 = newSchemaDir.getAbsolutePath() + "/physical_logical_src_map.json"; String idNameMapFile2 = newSchemaDir.getAbsolutePath() + "/idToName.map"; Runtime.getRuntime().exec("cp " + dbToSrcFile1 + " " + dbToSrcFile2 ); Runtime.getRuntime().exec("cp " + idNameMapFile1 + " " + idNameMapFile2 ); SchemaMetaDataManager mgr = null; //unknown SrcName boolean exception = false; try { mgr = new SchemaMetaDataManager(schema_dir.getAbsolutePath()); } catch (RuntimeException re) { exception = true; } Assert.assertTrue(exception, "Got exception ?"); } @BeforeClass public void setUpClass() throws InvalidConfigException { //setup logging TestUtil.setupLogging(true, null, Level.INFO); InternalLoggerFactory.setDefaultFactory(new Log4JLoggerFactory()); } }
4,073
2,350
#pragma once #include "GameFramework/HUD.h" #include "UnrealEnginePython.h" #include "PyHUD.generated.h" UCLASS(BlueprintType, Blueprintable) class UNREALENGINEPYTHON_API APyHUD : public AHUD { GENERATED_BODY() public: // Sets default values for this component's properties APyHUD(); ~APyHUD(); // Called when the game starts virtual void BeginPlay() override; // Called every frame virtual void Tick(float DeltaSeconds) override; virtual void DrawHUD() override; UPROPERTY(EditAnywhere , Category = "Python") FString PythonModule; UPROPERTY(EditAnywhere, Category = "Python") FString PythonClass; UPROPERTY(EditAnywhere, Category = "Python") bool PythonTickForceDisabled; UPROPERTY(EditAnywhere, Category = "Python") bool PythonDisableAutoBinding; UFUNCTION(BlueprintCallable, Category = "Python") void CallPythonHUDMethod(FString method_name, FString args); UFUNCTION(BlueprintCallable, Category = "Python") bool CallPythonHUDMethodBool(FString method_name, FString args); UFUNCTION(BlueprintCallable, Category = "Python") FString CallPythonHUDMethodString(FString method_name, FString args); private: PyObject *py_hud_instance; // mapped uobject, required for debug and advanced reflection ue_PyUObject *py_uobject; };
408
809
{ "js": [ "src/paste.js", "src/wordpastehandler.js", "src/oembedpastehandler.js", "src/genericpastehandler.js" ] }
60
397
#pragma once #define DESKTOP_ALL (DESKTOP_CREATEMENU | DESKTOP_CREATEWINDOW | \ DESKTOP_ENUMERATE | DESKTOP_HOOKCONTROL | \ DESKTOP_JOURNALPLAYBACK | DESKTOP_JOURNALRECORD | \ DESKTOP_READOBJECTS | DESKTOP_SWITCHDESKTOP | \ DESKTOP_WRITEOBJECTS | DELETE | \ READ_CONTROL | WRITE_DAC |\ WRITE_OWNER) #define WINSTA_ALL (WINSTA_ACCESSCLIPBOARD | WINSTA_ACCESSGLOBALATOMS | \ WINSTA_CREATEDESKTOP | WINSTA_ENUMDESKTOPS | \ WINSTA_ENUMERATE | WINSTA_EXITWINDOWS | \ WINSTA_READATTRIBUTES | WINSTA_READSCREEN | \ WINSTA_WRITEATTRIBUTES | DELETE |\ READ_CONTROL | WRITE_DAC | \ WRITE_OWNER) #define GENERIC_ACCESS (GENERIC_READ | GENERIC_WRITE |GENERIC_EXECUTE | GENERIC_ALL)
323
2,082
from typing import Type from auto_labeling_pipeline.labels import ( ClassificationLabels, Labels, Seq2seqLabels, SequenceLabels, ) from auto_labeling_pipeline.mappings import MappingTemplate from auto_labeling_pipeline.models import RequestModelFactory from auto_labeling_pipeline.pipeline import pipeline from auto_labeling_pipeline.postprocessing import PostProcessor from .labels import create_labels from auto_labeling.models import AutoLabelingConfig def get_label_collection(task_type: str) -> Type[Labels]: return {"Category": ClassificationLabels, "Span": SequenceLabels, "Text": Seq2seqLabels}[task_type] def execute_pipeline(data: str, config: AutoLabelingConfig): label_collection = get_label_collection(config.task_type) model = RequestModelFactory.create(model_name=config.model_name, attributes=config.model_attrs) template = MappingTemplate(label_collection=label_collection, template=config.template) post_processor = PostProcessor(config.label_mapping) labels = pipeline(text=data, request_model=model, mapping_template=template, post_processing=post_processor) labels = create_labels(config.task_type, labels) return labels
374
801
<gh_stars>100-1000 // // MPVariant.h // HelloMixpanel // // Created by <NAME> on 28/4/14. // Copyright (c) 2014 Mixpanel. All rights reserved. // #import <Foundation/Foundation.h> @interface MPVariant : NSObject <NSCoding> @property (nonatomic) NSUInteger ID; @property (nonatomic) NSUInteger experimentID; /*! Whether this specific variant is currently running on the device. This property will not be restored on unarchive, as the variant will need to be run again once the app is restarted. */ @property (nonatomic, readonly) BOOL running; /*! Whether the variant should not run anymore. Variants are marked as finished when we no longer see them in a decide response. They will continue running (ie their changes will be visible) until the next time the app starts. */ @property (nonatomic, readonly) BOOL finished; + (MPVariant *)variantWithJSONObject:(NSDictionary *)object; - (void)addActionsFromJSONObject:(NSArray *)actions andExecute:(BOOL)exec; - (void)addActionFromJSONObject:(NSDictionary *)object andExecute:(BOOL)exec; - (void)addTweaksFromJSONObject:(NSArray *)tweaks andExecute:(BOOL)exec; - (void)addTweakFromJSONObject:(NSDictionary *)object andExecute:(BOOL)exec; - (void)removeActionWithName:(NSString *)name; /*! Executes the variant, including all of its actions and tweaks. This immediately applies the changes associated with this variant. */ - (void)execute; /*! Stops the variant, including all of its actions and tweaks. This immediately applies the reverse of this variant. including reversing all actions and tweaks to their original values. */ - (void)stop; /*! Sets the finished flag on this variant, does not take any actions. The finished flag marks this variant as one that should not be run anymore the next time the app opens, but we leave it running so that the UI doesn't change during the user session. */ - (void)finish; /*! Unsets the finished flag on this variant, does not take any actions. If the finished flag is unset, the variant will continue to run the next time the app starts. */ - (void)restart; @end @interface MPVariantAction : NSObject <NSCoding> @end @interface MPVariantTweak : NSObject <NSCoding> @end
636