max_stars_count
int64
301
224k
text
stringlengths
6
1.05M
token_count
int64
3
727k
65,488
[{ "code": "invalid-transition", "message": "Transitions can only be applied to DOM elements, not components", "start": { "line": 7, "column": 8, "character": 87 }, "end": { "line": 7, "column": 14, "character": 93 }, "pos": 87 }]
106
12,718
// -*- C++ -*- //===----------------------------------------------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #ifndef _LIBCPP___ALGORITHM_FOR_EACH_H #define _LIBCPP___ALGORITHM_FOR_EACH_H #include <__config> #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER) #pragma GCC system_header #endif _LIBCPP_PUSH_MACROS #include <__undef_macros> _LIBCPP_BEGIN_NAMESPACE_STD template <class _InputIterator, class _Function> inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17 _Function for_each(_InputIterator __first, _InputIterator __last, _Function __f) { for (; __first != __last; ++__first) __f(*__first); return __f; } _LIBCPP_END_NAMESPACE_STD _LIBCPP_POP_MACROS #endif // _LIBCPP___ALGORITHM_FOR_EACH_H
532
372
<reponame>mdbloice/systemds # ------------------------------------------------------------- # # 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. # # ------------------------------------------------------------- # Autogenerated By : src/main/python/generator/generator.py # Autogenerated From : scripts/builtin/gridSearch.dml from typing import Dict, Iterable from systemds.operator import OperationNode, Matrix, Frame, List, MultiReturn, Scalar from systemds.script_building.dag import OutputType from systemds.utils.consts import VALID_INPUT_TYPES def gridSearch(X: Matrix, y: Matrix, train: str, predict: str, params: List, paramValues: List, **kwargs: Dict[str, VALID_INPUT_TYPES]): """ :param train: Name ft of the train function to call via ft(trainArgs) :param predict: Name fp of the loss function to call via fp((predictArgs,B)) :param numB: Maximum number of parameters in model B (pass the max because the size :param may: parameters like icpt or multi-class classification) :param columnvectors: hyper-parameters in 'params' :param gridSearch: hyper-parameter by name, if :param not: an empty list, the lm parameters are used :param gridSearch: trained models at the end, if :param not: an empty list, list(X, y) is used instead :param cv: flag enabling k-fold cross validation, otherwise training loss :param cvk: if cv=TRUE, specifies the the number of folds, otherwise ignored :param verbose: flag for verbose debug output :return: 'OperationNode' containing returned as a column-major linearized column vector """ params_dict = {'X': X, 'y': y, 'train': train, 'predict': predict, 'params': params, 'paramValues': paramValues} params_dict.update(kwargs) vX_0 = Matrix(X.sds_context, '') vX_1 = Frame(X.sds_context, '') output_nodes = [vX_0, vX_1, ] op = MultiReturn(X.sds_context, 'gridSearch', output_nodes, named_input_nodes=params_dict) vX_0._unnamed_input_nodes = [op] vX_1._unnamed_input_nodes = [op] return op
943
313
//------------------------------------------------------------------------------ // GxB_init: initialize GraphBLAS and declare malloc/calloc/realloc/free to use //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, <NAME>, (c) 2017-2022, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // GrB_init (or GxB_init) must called before any other GraphBLAS operation. // GrB_finalize must be called as the last GraphBLAS operation. GxB_init is // identical to GrB_init, except that it allows the user application to define // the malloc/calloc/realloc/free functions that SuiteSparse:GraphBLAS will // use. The functions cannot be modified once GraphBLAS starts. // The calloc and realloc function pointers are optional and can be NULL. If // calloc is NULL, it is not used, and malloc/memset are used instead. If // realloc is NULL, it is not used, and malloc/memcpy/free are used instead. // Examples: // // To use GraphBLAS with the ANSI C11 functions (or to another library // linked in that replaces them): // // // either use: // GrB_init (mode) ; // // or use this (but not both): // GxB_init (mode, malloc, calloc, realloc, free) ; // // To use GraphBLAS from within a mexFunction: // // #include "mex.h" // GxB_init (mode, mxMalloc, mxCalloc, mxRealloc, mxFree) ; // // To use the C interface to the Intel TBB scalable allocators: // // #include "tbb/scalable_allocator.h" // GxB_init (mode, scalable_malloc, scalable_calloc, scalable_realloc, // scalable_free) ; // // To use CUDA and its RMM memory manager: // // GxB_init (mode, rmm_malloc, rmm_calloc, rmm_realloc, rmm_free) ; // // mode is GrB_BLOCKING or GrB_NONBLOCKING #if for_comments_only compute_system = rmm_wrap_initialize (mode, initpoolsize, maxpoolsize) ; create RMM instance query the GPU(s) available, set their context compute_system: holds 4 RMM contexts, 4 GPUs, how big they are ... p = rmm_wrap_malloc (42) ; // needs the GPUs to be warmed up ... // option: GxB_init (GrB_NONBLOCKING, rmm_wrap_malloc, rmm_wrap_calloc, rmm_wrap_realloc, rmm_wrap_free) ; // use GrB just on the CPU cores GrB_Matrix_new (&C, ...) GrB_mxm (...) GxB_set (GxB_CUDA_SYSTEM_CONTEXT, compute_system) ; // use the GPUs ... GxB_set (GxB_NTHREDS, 4) ; // use 4 cpu threads GxB_get (GxB_CUDA_NGPUS, &ngpus) // use GrB just on the GPU 2 GxB_set (GxB_CUDA_SET_DEVICE, 2) ; GrB_mxm (C, ...) GxB_set (C, GxB_SPARSITY, GxB_SPARSE + GxB_HYPERSPARE) ; GxB_Matrix_Option_set GrB_mxm (C, ...) ... GxB_set (GxB_CUDA, true) ; // 0 seconds, GPUs already warmed up ... GxB_set (GxB_CUDA, false) ; ... GxB_set (GxB_CUDA, true) ; // 0 seconds GxB_set (GxB_GPUS, [0 2]) ; ... GrB_finalize ( ) ; rmm_wrap_free (p) ; rmm_wrap_finalize ( ) ; #endif // // To use user-provided malloc and free functions, but not calloc/realloc: // // GxB_init (mode, my_malloc, NULL, NULL, my_free) ; #include "GB.h" GrB_Info GxB_init // start up GraphBLAS and also define malloc, etc ( GrB_Mode mode, // blocking or non-blocking mode // pointers to memory management functions void * (* user_malloc_function ) (size_t), // required void * (* user_calloc_function ) (size_t, size_t), // no longer used void * (* user_realloc_function ) (void *, size_t), // optional, can be NULL void (* user_free_function ) (void *) // required ) { //-------------------------------------------------------------------------- // check inputs //-------------------------------------------------------------------------- GB_CONTEXT ("GxB_init (mode, malloc, calloc, realloc, free)") ; if (user_malloc_function == NULL || user_free_function == NULL) { // only malloc and free are required. calloc and/or realloc may be // NULL return (GrB_NULL_POINTER) ; } //-------------------------------------------------------------------------- // initialize GraphBLAS //-------------------------------------------------------------------------- return (GB_init (mode, // blocking or non-blocking mode user_malloc_function, // user-defined malloc, required user_realloc_function, // user-defined realloc, may be NULL user_free_function, // user-defined free, required Context)) ; }
1,764
606
/* # Copyright 2021 Hewlett Packard Enterprise Development LP # # 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. */ #if defined(HAVE_CONFIG_H) #include <config.h> #endif #include <string.h> #include <ctype.h> #if defined(NETPERF_STANDALONE_DEBUG) #include <stdio.h> #endif #include <stdlib.h> #include <net/if.h> #include <devid.h> #include <libdevinfo.h> char * find_interface_slot(char *interface_name) { return strdup("Not Implemented"); } static char interface_match[IFNAMSIZ]; static int found_vendor = 0; static int found_device = 0; static int found_subvendor = 0; static int found_subdevice = 0; static char * set_interface_match(char *interface_name) { int i; char *nukeit; strncpy(interface_match,interface_name,IFNAMSIZ); interface_match[IFNAMSIZ-1] = 0; /* strip away the logical interface information if present we "know" thanks to the above that we will find a null character to get us out of the loop */ for (nukeit = strchr(interface_match,':'); (NULL != nukeit) && (*nukeit != 0); nukeit++) { *nukeit = 0; } if (strlen(interface_match) == 0) return NULL; else return interface_match; } /* take the binding name for our found node and try to break it up into pci ids. return the number of IDs we found */ static int parse_binding_name(char *binding_name) { char *my_copy; char *vend; char *dev; char *subvend; char *subdev; int count; int i; /* we cannot handle "class" :) */ if (NULL != strstr(binding_name,"class")) return 0; my_copy = strdup(binding_name); if (NULL == my_copy) return 0; /* we assume something of the form: pci14e4,164c or perhaps pci14e4,164c.103c.7038.12 or pciex8086,105e.108e.105e.6 or where we ass-u-me that the first four hex digits before the comma are the vendor ID, the next four after the comma are the device id, the next four after the period are the subvendor id and the next four after the next dot are the subdevice id. we have absolutely no idea what the digits after a third dot might be. of course these: pciex108e,abcd.108e.0.1 pci14e4,164c.12 are somewhat perplexing also. Can we ass-u-me that the id's will always be presented as four character hex? Until we learn to the contrary, that is what will be ass-u-me-d here and so we will naturally ignore those things, which might be revision numbers raj 2008-03-20 */ vend = strtok(my_copy,","); if (NULL == vend) { count = 0; } else { /* take only the last four characters */ if (strlen(vend) < 5) { count = 0; } else { /* OK, we could just update vend I suppose, but for some reason I felt the need to blank-out the leading cruft... */ for (i = 0; i < strlen(vend) - 4; i++) vend[i] = ' '; found_vendor = strtol(vend,NULL,16); /* ok, now check for device */ dev = strtok(NULL,"."); if ((NULL == dev) || (strlen(dev) != 4)) { /* we give-up after vendor */ count = 1; } else { found_device = strtol(dev,NULL,16); /* ok, now check for subvendor */ subvend = strtok(NULL,"."); if ((NULL == subvend) || (strlen(subvend) != 4)) { /* give-up after device */ count = 2; } else { found_subvendor = strtol(subvend,NULL,16); /* ok, now check for subdevice */ subdev = strtok(NULL,"."); if ((NULL == subdev) || (strlen(subdev) != 4)) { /* give-up after subvendor */ count = 3; } else { found_subdevice = strtol(subdev,NULL,16); count = 4; } } } } } return count; } static int check_node(di_node_t node, void *arg) { char *nodename; char *minorname; char *propname; char *bindingname; di_minor_t minor; di_prop_t prop; int *ints; #ifdef NETPERF_STANDALONE_DEBUG nodename = di_devfs_path(node); /* printf("Checking node named %s\n",nodename); */ di_devfs_path_free(nodename); #endif minor = DI_MINOR_NIL; while ((minor = di_minor_next(node,minor)) != DI_MINOR_NIL) { /* check for a match with the interface_match */ minorname = di_minor_name(minor); #ifdef NETPERF_STANDALONE_DEBUG /* printf("\tminor name %s\n",minorname); */ #endif /* do they match? */ if (strcmp(minorname,interface_match) == 0) { /* found a match */ bindingname = di_binding_name(node); #ifdef NETPERF_STANDALONE_DEBUG printf("FOUND A MATCH ON %s under node %s with binding name %s\n",interface_match, nodename, bindingname); #endif if (parse_binding_name(bindingname) == 4) { /* we are done */ return DI_WALK_TERMINATE; } /* ok, getting here means we didn't find all the names we seek, so try taking a look at the properties of the node. we know that at least one driver is kind enough to set them in there... and if we find it, we will allow that to override anything we may have already found */ prop = DI_PROP_NIL; while ((prop = di_prop_next(node,prop)) != DI_PROP_NIL) { propname = di_prop_name(prop); #ifdef NETPERF_STANDALONE_DEBUG printf("\t\tproperty name %s\n",propname); #endif /* only bother checking the name if the type is what we expect and we can get the ints */ if ((di_prop_type(prop) == DI_PROP_TYPE_INT) && (di_prop_ints(prop,&ints) > 0)) { if (strcmp(propname,"subsystem-vendor-id") == 0) found_subvendor = ints[0]; else if (strcmp(propname,"subsystem-id") == 0) found_subdevice = ints[0]; else if (strcmp(propname,"vendor-id") == 0) found_vendor = ints[0]; else if (strcmp(propname,"device-id") == 0) found_device = ints[0]; } } /* since we found a match on the name, we are done now */ return DI_WALK_TERMINATE; } } return DI_WALK_CONTINUE; } void find_interface_ids(char *interface_name, int *vendor, int *device, int *sub_vend, int *sub_dev) { di_node_t root; char *interface_match; /* so we have "failure values" ready if need be */ *vendor = 0; *device = 0; *sub_vend = 0; *sub_dev = 0; interface_match = set_interface_match(interface_name); if (NULL == interface_match) return; /* get the root of all devices, and hope they aren't evil */ root = di_init("/", DINFOCPYALL); if (DI_NODE_NIL == root) return; /* now we start trapsing merrily around the tree */ di_walk_node(root, DI_WALK_CLDFIRST,NULL,check_node); di_fini(root); *vendor = found_vendor; *device = found_device; *sub_vend = found_subvendor; *sub_dev = found_subdevice; return; } #if defined(NETPERF_STANDALONE_DEBUG) int main(int argc, char *argv[]) { char *slot; int vendor; int device; int subvendor; int subdevice; if (argc != 2) { fprintf(stderr,"%s <interface>\n",argv[0]); return -1; } slot = find_interface_slot(argv[1]); find_interface_ids(argv[1], &vendor, &device, &subvendor, &subdevice); printf("%s in in slot %s: vendor %4x device %4x subvendor %4x subdevice %4x\n", argv[1], slot, vendor, device, subvendor, subdevice); return 0; } #endif
3,133
348
<reponame>chamberone/Leaflet.PixiOverlay<gh_stars>100-1000 {"nom":"Villers-Bocage","circ":"6ème circonscription","dpt":"Calvados","inscrits":2074,"abs":1032,"votants":1042,"blancs":45,"nuls":12,"exp":985,"res":[{"nuance":"REM","nom":"<NAME>","voix":399},{"nuance":"FN","nom":"<NAME>","voix":155},{"nuance":"UDI","nom":"<NAME>","voix":83},{"nuance":"FI","nom":"<NAME>","voix":83},{"nuance":"DVD","nom":"Mme <NAME>","voix":66},{"nuance":"DVD","nom":"M. <NAME>","voix":59},{"nuance":"ECO","nom":"Mme <NAME>","voix":41},{"nuance":"DLF","nom":"<NAME>","voix":27},{"nuance":"RDG","nom":"Mme <NAME>","voix":19},{"nuance":"COM","nom":"Mme <NAME>","voix":16},{"nuance":"EXG","nom":"Mme <NAME>","voix":15},{"nuance":"EXD","nom":"<NAME>","voix":7},{"nuance":"DIV","nom":"Mme <NAME>","voix":7},{"nuance":"DVG","nom":"<NAME>","voix":6},{"nuance":"DVG","nom":"M. <NAME>","voix":2}]}
354
350
<reponame>zqn1996-alan/talkback<gh_stars>100-1000 /* * Copyright 2020 Google 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.google.android.accessibility.brailleime.tutorial; import android.animation.Animator; import android.animation.ValueAnimator; import android.content.Context; import android.graphics.Canvas; import android.graphics.ColorFilter; import android.graphics.Paint; import android.graphics.PixelFormat; import android.graphics.drawable.Drawable; import com.google.android.accessibility.brailleime.R; import com.google.android.accessibility.brailleime.Utils; /** Drawable that draws a flashing dot. */ class TapMeAnimationDrawable extends Drawable { private static final int ANIMATION_DURATION_MS = 1200; private static final int START_DELAY_DURATION_MS = 1000; private final Paint circlePaint; private final ValueAnimator animator; TapMeAnimationDrawable(Context context) { circlePaint = new Paint(); circlePaint.setColor(context.getColor(R.color.text_highlight_color)); // These values are the scale parameters of radius vary in the animation. animator = ValueAnimator.ofFloat(0f, 1f, 0f, 1f, 0f); animator.setDuration(ANIMATION_DURATION_MS); animator.addUpdateListener(animation -> invalidateSelf()); animator.addListener( new Animator.AnimatorListener() { @Override public void onAnimationStart(Animator animator) {} @Override public void onAnimationEnd(Animator animator) { animator.setStartDelay(START_DELAY_DURATION_MS); // This might not be a good solution but it works, do not start animator because // Robolectric tests run on main thread also, otherwise animator will repeat in endless // loop and cause the test timeout. if (!Utils.isRobolectric()) { animator.start(); } } @Override public void onAnimationCancel(Animator animator) {} @Override public void onAnimationRepeat(Animator animator) {} }); animator.start(); } @Override public void draw(Canvas canvas) { float radius = (float) animator.getAnimatedValue() * getBounds().height() / 2f; canvas.drawCircle(getBounds().width() / 2f, getBounds().height() / 2f, radius, circlePaint); } @Override public void setAlpha(int alpha) { circlePaint.setAlpha(alpha); } @Override public void setColorFilter(ColorFilter colorFilter) {} @Override public int getOpacity() { return PixelFormat.TRANSPARENT; } }
1,057
14,668
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "third_party/blink/renderer/core/animation/property_handle.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/blink/renderer/core/svg_names.h" namespace blink { using svg_names::kAmplitudeAttr; using svg_names::kExponentAttr; class PropertyHandleTest : public testing::Test {}; TEST_F(PropertyHandleTest, Equality) { AtomicString name_a = "--a"; AtomicString name_b = "--b"; EXPECT_TRUE(PropertyHandle(GetCSSPropertyOpacity()) == PropertyHandle(GetCSSPropertyOpacity())); EXPECT_FALSE(PropertyHandle(GetCSSPropertyOpacity()) != PropertyHandle(GetCSSPropertyOpacity())); EXPECT_FALSE(PropertyHandle(GetCSSPropertyOpacity()) == PropertyHandle(GetCSSPropertyTransform())); EXPECT_TRUE(PropertyHandle(GetCSSPropertyOpacity()) != PropertyHandle(GetCSSPropertyTransform())); EXPECT_FALSE(PropertyHandle(GetCSSPropertyOpacity()) == PropertyHandle(name_a)); EXPECT_TRUE(PropertyHandle(GetCSSPropertyOpacity()) != PropertyHandle(name_a)); EXPECT_FALSE(PropertyHandle(GetCSSPropertyOpacity()) == PropertyHandle(kAmplitudeAttr)); EXPECT_TRUE(PropertyHandle(GetCSSPropertyOpacity()) != PropertyHandle(kAmplitudeAttr)); EXPECT_FALSE(PropertyHandle(name_a) == PropertyHandle(GetCSSPropertyOpacity())); EXPECT_TRUE(PropertyHandle(name_a) != PropertyHandle(GetCSSPropertyOpacity())); EXPECT_FALSE(PropertyHandle(name_a) == PropertyHandle(GetCSSPropertyTransform())); EXPECT_TRUE(PropertyHandle(name_a) != PropertyHandle(GetCSSPropertyTransform())); EXPECT_TRUE(PropertyHandle(name_a) == PropertyHandle(name_a)); EXPECT_FALSE(PropertyHandle(name_a) != PropertyHandle(name_a)); EXPECT_FALSE(PropertyHandle(name_a) == PropertyHandle(name_b)); EXPECT_TRUE(PropertyHandle(name_a) != PropertyHandle(name_b)); EXPECT_FALSE(PropertyHandle(name_a) == PropertyHandle(kAmplitudeAttr)); EXPECT_TRUE(PropertyHandle(name_a) != PropertyHandle(kAmplitudeAttr)); EXPECT_FALSE(PropertyHandle(kAmplitudeAttr) == PropertyHandle(GetCSSPropertyOpacity())); EXPECT_TRUE(PropertyHandle(kAmplitudeAttr) != PropertyHandle(GetCSSPropertyOpacity())); EXPECT_FALSE(PropertyHandle(kAmplitudeAttr) == PropertyHandle(name_a)); EXPECT_TRUE(PropertyHandle(kAmplitudeAttr) != PropertyHandle(name_a)); EXPECT_TRUE(PropertyHandle(kAmplitudeAttr) == PropertyHandle(kAmplitudeAttr)); EXPECT_FALSE(PropertyHandle(kAmplitudeAttr) != PropertyHandle(kAmplitudeAttr)); EXPECT_FALSE(PropertyHandle(kAmplitudeAttr) == PropertyHandle(kExponentAttr)); EXPECT_TRUE(PropertyHandle(kAmplitudeAttr) != PropertyHandle(kExponentAttr)); } TEST_F(PropertyHandleTest, Hash) { AtomicString name_a = "--a"; AtomicString name_b = "--b"; EXPECT_TRUE(PropertyHandle(GetCSSPropertyOpacity()).GetHash() == PropertyHandle(GetCSSPropertyOpacity()).GetHash()); EXPECT_FALSE(PropertyHandle(GetCSSPropertyOpacity()).GetHash() == PropertyHandle(name_a).GetHash()); EXPECT_FALSE(PropertyHandle(GetCSSPropertyOpacity()).GetHash() == PropertyHandle(GetCSSPropertyTransform()).GetHash()); EXPECT_FALSE(PropertyHandle(GetCSSPropertyOpacity()).GetHash() == PropertyHandle(kAmplitudeAttr).GetHash()); EXPECT_FALSE(PropertyHandle(name_a).GetHash() == PropertyHandle(GetCSSPropertyOpacity()).GetHash()); EXPECT_TRUE(PropertyHandle(name_a).GetHash() == PropertyHandle(name_a).GetHash()); EXPECT_FALSE(PropertyHandle(name_a).GetHash() == PropertyHandle(name_b).GetHash()); EXPECT_FALSE(PropertyHandle(name_a).GetHash() == PropertyHandle(kExponentAttr).GetHash()); EXPECT_FALSE(PropertyHandle(kAmplitudeAttr).GetHash() == PropertyHandle(GetCSSPropertyOpacity()).GetHash()); EXPECT_FALSE(PropertyHandle(kAmplitudeAttr).GetHash() == PropertyHandle(name_a).GetHash()); EXPECT_TRUE(PropertyHandle(kAmplitudeAttr).GetHash() == PropertyHandle(kAmplitudeAttr).GetHash()); EXPECT_FALSE(PropertyHandle(kAmplitudeAttr).GetHash() == PropertyHandle(kExponentAttr).GetHash()); } TEST_F(PropertyHandleTest, Accessors) { AtomicString name = "--x"; EXPECT_TRUE(PropertyHandle(GetCSSPropertyOpacity()).IsCSSProperty()); EXPECT_TRUE(PropertyHandle(name).IsCSSProperty()); EXPECT_FALSE(PropertyHandle(kAmplitudeAttr).IsCSSProperty()); EXPECT_FALSE(PropertyHandle(GetCSSPropertyOpacity()).IsSVGAttribute()); EXPECT_FALSE(PropertyHandle(name).IsSVGAttribute()); EXPECT_TRUE(PropertyHandle(kAmplitudeAttr).IsSVGAttribute()); EXPECT_FALSE(PropertyHandle(GetCSSPropertyOpacity()).IsCSSCustomProperty()); EXPECT_TRUE(PropertyHandle(name).IsCSSCustomProperty()); EXPECT_FALSE(PropertyHandle(kAmplitudeAttr).IsCSSCustomProperty()); EXPECT_EQ( CSSPropertyID::kOpacity, PropertyHandle(GetCSSPropertyOpacity()).GetCSSProperty().PropertyID()); EXPECT_EQ(CSSPropertyID::kVariable, PropertyHandle(name).GetCSSProperty().PropertyID()); EXPECT_EQ(name, PropertyHandle(name).CustomPropertyName()); EXPECT_EQ(kAmplitudeAttr, PropertyHandle(kAmplitudeAttr).SvgAttribute()); EXPECT_EQ(name, PropertyHandle(name).GetCSSPropertyName().ToAtomicString()); EXPECT_EQ(CSSPropertyID::kOpacity, PropertyHandle(GetCSSPropertyOpacity()).GetCSSPropertyName().Id()); EXPECT_EQ( CSSPropertyID::kColor, PropertyHandle(GetCSSPropertyColor(), true).GetCSSPropertyName().Id()); } } // namespace blink
2,180
12,824
/* * Scala (https://www.scala-lang.org) * * Copyright EPFL and Lightbend, Inc. * * Licensed under Apache License 2.0 * (http://www.apache.org/licenses/LICENSE-2.0). * * See the NOTICE file distributed with this work for * additional information regarding copyright ownership. */ package scala.runtime; public final class VolatileByteRef implements java.io.Serializable { private static final long serialVersionUID = -100666928446877072L; volatile public byte elem; public VolatileByteRef(byte elem) { this.elem = elem; } public String toString() { return java.lang.Byte.toString(elem); } public static VolatileByteRef create(byte e) { return new VolatileByteRef(e); } public static VolatileByteRef zero() { return new VolatileByteRef((byte)0); } }
246
3,102
// RUN: %clang_cc1 -Wall %s -I %S/Inputs -isystem %S/Inputs/SystemHeaderPrefix -verify // RUN: %clang_cc1 %s -E -o - -I %S/Inputs -isystem %S/Inputs/SystemHeaderPrefix | FileCheck %s #include <noline.h> #include <line-directive-in-system.h> // [email protected]:* {{type specifier missing, defaults to 'int'}} #include "line-directive.h" // This tests that "#line" directives in system headers preserve system // header-ness just like GNU line markers that don't have filenames. This was // PR30752. // CHECK: # {{[0-9]+}} "{{.*}}system-header-line-directive.c" 2 // CHECK: # 1 "{{.*}}noline.h" 1 3 // CHECK: foo(); // CHECK: # 4 "{{.*}}system-header-line-directive.c" 2 // CHECK: # 1 "{{.*}}line-directive-in-system.h" 1 3 // The "3" below indicates that "foo.h" is considered a system header. // CHECK: # 1 "foo.h" 3 // CHECK: foo(); // CHECK: # {{[0-9]+}} "{{.*}}system-header-line-directive.c" 2 // CHECK: # 1 "{{.*}}line-directive.h" 1 // CHECK: # 10 "foo.h"{{$}}
393
335
<filename>R/Redecoration_noun.json { "word": "Redecoration", "definitions": [ "The process of applying paint or wallpaper in a room or building again, typically in a different style from before." ], "parts-of-speech": "Noun" }
89
5,169
<reponame>Gantios/Specs { "name": "BlazeHTMLCell", "version": "0.0.4", "summary": "HTML-cell addition to Blaze", "license": "MIT", "description": "Useful HTML-cell addition to Blaze, using DTCoreText and TTTAttributedLabel for performance and link checking", "homepage": "https://github.com/BobDG/Blaze-HTMLCell", "authors": { "<NAME>": "<EMAIL>" }, "source": { "git": "https://github.com/BobDG/Blaze-HTMLCell.git", "tag": "0.0.4" }, "source_files": "BlazeHTMLCell/*.{h,m}", "platforms": { "ios": null }, "requires_arc": "true", "dependencies": { "Blaze": [ ], "DTCoreText": [ ], "TTTAttributedLabel": [ ] } }
298
460
<reponame>dyzmapl/BumpTop // Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef _BT_CAMERA_ZOOM_GESTURE_ #define _BT_CAMERA_ZOOM_GESTURE_ #include "BT_Gesture.h" class CameraZoomGesture : public Gesture { private: static const float MINIMUM_PATH_LENGTH; static const float MINIMUM_LINGERING_ZOOM_SPEED; static const float MAXIMUM_TOLERANCE_ANGLE; // whether to reset "_original" variables because a finger has lifted and repositioned bool _recalculateInitials; float _originalDistanceBetweenPoints; Vec3 _originalCamEye, _camDirection; void calculateInitials(TouchPoint & firstFingerEndPoint, TouchPoint & secondFingerEndPoint); protected: virtual Detected isRecognizedImpl(GestureContext *gestureContext); virtual bool processGestureImpl(GestureContext *gestureContext); virtual void clearGesture(); public: CameraZoomGesture(); }; #endif /* _BT_CAMERA_ZOOM_GESTURE_ */
504
15,577
/// c++ sample dictionary library #include <cstdint> #include <functional> #include <iostream> #include <memory> #include <sstream> #include <vector> namespace ClickHouseLibrary { using CString = const char *; using ColumnName = CString; using ColumnNames = ColumnName[]; struct CStrings { CString * data = nullptr; uint64_t size = 0; }; struct VectorUInt64 { const uint64_t * data = nullptr; uint64_t size = 0; }; struct ColumnsUInt64 { VectorUInt64 * data = nullptr; uint64_t size = 0; }; struct Field { const void * data = nullptr; uint64_t size = 0; }; struct Row { const Field * data = nullptr; uint64_t size = 0; }; struct Table { const Row * data = nullptr; uint64_t size = 0; uint64_t error_code = 0; // 0 = ok; !0 = error, with message in error_string const char * error_string = nullptr; }; enum LogLevel { FATAL = 1, CRITICAL, ERROR, WARNING, NOTICE, INFORMATION, DEBUG, TRACE, }; void log(LogLevel level, CString msg); } #define LOG(logger, message) \ do \ { \ std::stringstream builder; \ builder << message; \ (logger)(ClickHouseLibrary::INFORMATION, builder.str().c_str()); \ } while (false) struct LibHolder { std::function<void(ClickHouseLibrary::LogLevel, ClickHouseLibrary::CString)> log; }; struct DataHolder { std::vector<std::vector<uint64_t>> dataHolder; // Actual data storage std::vector<std::vector<ClickHouseLibrary::Field>> fieldHolder; // Pointers and sizes of data std::unique_ptr<ClickHouseLibrary::Row[]> rowHolder; ClickHouseLibrary::Table ctable; // Result data prepared for transfer via c-style interface LibHolder * lib = nullptr; size_t num_rows; size_t num_cols; }; template <typename T> void MakeColumnsFromVector(T * ptr) { if (ptr->dataHolder.empty()) { LOG(ptr->lib->log, "generating null values, cols: " << ptr->num_cols); std::vector<ClickHouseLibrary::Field> fields; for (size_t i = 0; i < ptr->num_cols; ++i) fields.push_back({nullptr, 0}); ptr->fieldHolder.push_back(fields); } else { for (const auto & row : ptr->dataHolder) { std::vector<ClickHouseLibrary::Field> fields; for (const auto & field : row) fields.push_back({&field, sizeof(field)}); ptr->fieldHolder.push_back(fields); } } const auto rows_num = ptr->fieldHolder.size(); ptr->rowHolder = std::make_unique<ClickHouseLibrary::Row[]>(rows_num); size_t i = 0; for (auto & row : ptr->fieldHolder) { ptr->rowHolder[i].size = row.size(); ptr->rowHolder[i].data = row.data(); ++i; } ptr->ctable.size = rows_num; ptr->ctable.data = ptr->rowHolder.get(); } extern "C" { void * ClickHouseDictionary_v3_loadIds(void * data_ptr, ClickHouseLibrary::CStrings * settings, ClickHouseLibrary::CStrings * columns, const struct ClickHouseLibrary::VectorUInt64 * ids) { auto ptr = static_cast<DataHolder *>(data_ptr); if (ids) LOG(ptr->lib->log, "loadIds lib call ptr=" << data_ptr << " => " << ptr << " size=" << ids->size); if (!ptr) return nullptr; if (settings) { LOG(ptr->lib->log, "settings passed: " << settings->size); for (size_t i = 0; i < settings->size; ++i) { LOG(ptr->lib->log, "setting " << i << " :" << settings->data[i]); } } if (columns) { LOG(ptr->lib->log, "columns passed:" << columns->size); for (size_t i = 0; i < columns->size; ++i) { LOG(ptr->lib->log, "column " << i << " :" << columns->data[i]); } } if (ids) { LOG(ptr->lib->log, "ids passed: " << ids->size); for (size_t i = 0; i < ids->size; ++i) { LOG(ptr->lib->log, "id " << i << " :" << ids->data[i] << " generating."); ptr->dataHolder.emplace_back(std::vector<uint64_t>{ids->data[i], ids->data[i] + 100, ids->data[i] + 200, ids->data[i] + 300}); } } MakeColumnsFromVector(ptr); return static_cast<void *>(&ptr->ctable); } void * ClickHouseDictionary_v3_loadAll(void * data_ptr, ClickHouseLibrary::CStrings * settings, ClickHouseLibrary::CStrings * /*columns*/) { auto ptr = static_cast<DataHolder *>(data_ptr); LOG(ptr->lib->log, "loadAll lib call ptr=" << data_ptr << " => " << ptr); if (!ptr) return nullptr; size_t num_rows = 0, num_cols = 4; std::string test_type; std::vector<std::string> settings_values; if (settings) { LOG(ptr->lib->log, "settings size: " << settings->size); for (size_t i = 0; i < settings->size; ++i) { std::string setting_name = settings->data[i]; std::string setting_value = settings->data[++i]; LOG(ptr->lib->log, "setting " + std::to_string(i) + " name " + setting_name + " value " + setting_value); if (setting_name == "num_rows") num_rows = std::atoi(setting_value.data()); else if (setting_name == "num_cols") num_cols = std::atoi(setting_value.data()); else if (setting_name == "test_type") test_type = setting_value; else { LOG(ptr->lib->log, "Adding setting " + setting_name); settings_values.push_back(setting_value); } } } if (test_type == "test_simple") { for (size_t i = 0; i < 10; ++i) { LOG(ptr->lib->log, "id " << i << " :" << " generating."); ptr->dataHolder.emplace_back(std::vector<uint64_t>{i, i + 10, i + 20, i + 30}); } } else if (test_type == "test_many_rows" && num_rows) { for (size_t i = 0; i < num_rows; ++i) { ptr->dataHolder.emplace_back(std::vector<uint64_t>{i, i, i, i}); } } ptr->num_cols = num_cols; ptr->num_rows = num_rows; MakeColumnsFromVector(ptr); return static_cast<void *>(&ptr->ctable); } void * ClickHouseDictionary_v3_loadKeys(void * data_ptr, ClickHouseLibrary::CStrings * settings, ClickHouseLibrary::Table * requested_keys) { auto ptr = static_cast<DataHolder *>(data_ptr); LOG(ptr->lib->log, "loadKeys lib call ptr=" << data_ptr << " => " << ptr); if (settings) { LOG(ptr->lib->log, "settings passed: " << settings->size); for (size_t i = 0; i < settings->size; ++i) { LOG(ptr->lib->log, "setting " << i << " :" << settings->data[i]); } } if (requested_keys) { LOG(ptr->lib->log, "requested_keys columns passed: " << requested_keys->size); for (size_t i = 0; i < requested_keys->size; ++i) { LOG(ptr->lib->log, "requested_keys at column " << i << " passed: " << requested_keys->data[i].size); ptr->dataHolder.emplace_back(std::vector<uint64_t>{i, i + 100, i + 200, i + 300}); } } MakeColumnsFromVector(ptr); return static_cast<void *>(&ptr->ctable); } void * ClickHouseDictionary_v3_libNew( ClickHouseLibrary::CStrings * /*settings*/, void (*logFunc)(ClickHouseLibrary::LogLevel, ClickHouseLibrary::CString)) { auto lib_ptr = new LibHolder; lib_ptr->log = logFunc; return lib_ptr; } void ClickHouseDictionary_v3_libDelete(void * lib_ptr) { auto ptr = static_cast<LibHolder *>(lib_ptr); delete ptr; return; } void * ClickHouseDictionary_v3_dataNew(void * lib_ptr) { auto data_ptr = new DataHolder; data_ptr->lib = static_cast<decltype(data_ptr->lib)>(lib_ptr); return data_ptr; } void ClickHouseDictionary_v3_dataDelete(void * /*lib_ptr*/, void * data_ptr) { auto ptr = static_cast<DataHolder *>(data_ptr); delete ptr; return; } }
3,766
1,350
/** * Copyright Microsoft Corporation * * 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.microsoft.windowsazure.services.blob.models; /** * A wrapper class for the response returned from a Blob Service REST API Lease * Blob operation. This is returned by calls to implementations of * {@link com.microsoft.windowsazure.services.blob.BlobContract#acquireLease(String, String)}, * {@link com.microsoft.windowsazure.services.blob.BlobContract#acquireLease(String, String, AcquireLeaseOptions)}, * {@link com.microsoft.windowsazure.services.blob.BlobContract#renewLease(String, String, String, BlobServiceOptions)}, * and {@link com.microsoft.windowsazure.services.blob.BlobContract#renewLease(String, String, String)}. * <p> * See the <a * href="http://msdn.microsoft.com/en-us/library/windowsazure/ee691972.aspx" * >Lease Blob</a> documentation on MSDN for details of the underlying Blob * Service REST API operation. */ public class AcquireLeaseResult { private String leaseId; /** * Gets the lease ID of the blob. * <p> * This value is used when updating or deleting a blob with an active lease, * and when renewing or releasing the lease. * * @return A {@link String} containing the server-assigned lease ID for the * blob. */ public String getLeaseId() { return leaseId; } /** * Reserved for internal use. Sets the lease ID of the blob from the * <strong>x-ms-lease-id</strong> header of the response. * <p> * This method is invoked by the API to set the value from the Blob Service * REST API operation response returned by the server. * * @param leaseId * A {@link String} containing the server-assigned lease ID for * the blob. */ public void setLeaseId(String leaseId) { this.leaseId = leaseId; } }
786
515
<filename>stella-gateway-formas-pagamento/src/main/java/br/com/caelum/stella/gateway/bb/RespostaInicialFormularioSonda.java<gh_stars>100-1000 package br.com.caelum.stella.gateway.bb; /** * Classe para poder parsear o xml de entrada do formulario sonda e servir de base para criar a BBFormularioSondaReturn * @author <NAME> * */ class RespostaInicialFormularioSonda { private String refTran; private String valor; private String idConv; private String tpPagamento; private String situacao; private String dataPagamento; public RespostaInicialFormularioSonda(String refTran, String valor, String idConv, String tpPagamento, String situacao, String dataPagamento) { super(); this.refTran = refTran; this.valor = valor; this.idConv = idConv; this.tpPagamento = tpPagamento; this.situacao = situacao; this.dataPagamento = dataPagamento; } public RespostaInicialFormularioSonda() { super(); // TODO Auto-generated constructor stub } public String getRefTran() { return refTran; } public void setRefTran(String refTran) { this.refTran = refTran; } public String getValor() { return valor; } public void setValor(String valor) { this.valor = valor; } public String getIdConv() { return idConv; } public void setIdConv(String idConv) { this.idConv = idConv; } public String getTpPagamento() { return tpPagamento; } public void setTpPagamento(String tpPagamento) { this.tpPagamento = tpPagamento; } public String getSituacao() { return situacao; } public void setSituacao(String situacao) { this.situacao = situacao; } public String getDataPagamento() { return dataPagamento; } public void setDataPagamento(String dataPagamento) { this.dataPagamento = dataPagamento; } }
827
972
<gh_stars>100-1000 package com.hannesdorfmann.fragmentargs.processor; import org.junit.Test; import static com.hannesdorfmann.fragmentargs.processor.CompileTest.assertClassCompilesWithoutError; public class InnerClassTest { @Test public void innerClass() { assertClassCompilesWithoutError("ClassWithInnerClass.java", "ClassWithInnerClassBuilder.java"); } @Test public void innerClassWithProtectedField() { assertClassCompilesWithoutError("InnerClassWithProtectedField.java", "InnerClassWithProtectedFieldBuilder.java"); } }
194
2,453
// // Generated by class-dump 3.5 (64 bit) (Debug version compiled Sep 30 2020 21:18:12). // // Copyright (C) 1997-2019 <NAME>. // #import <IDESourceEditor/_TtC15IDESourceEditor23DVTSourceEditorLandmark.h> @interface _TtC15IDESourceEditor23DVTSourceEditorLandmark (IDESourceEditor) - (unsigned long long)landmarkItemType; - (BOOL)needsUpdate; - (id)landmarkItemTypeName; - (struct _NSRange)landmarkItemNameRange; - (struct _NSRange)landmarkItemRange; - (id)landmarkItemName; - (id)childLandmarkItems; - (long long)numberOfChildLandmarkItems; - (id)parentLandmarkItem; @end
208
381
<reponame>nanjekyejoannah/pypy #include "operators.h" // for testing the case of virtual operator== v_opeq_base::v_opeq_base(int val) : m_val(val) {} v_opeq_base::~v_opeq_base() {} bool v_opeq_base::operator==(const v_opeq_base& other) { return m_val == other.m_val; } v_opeq_derived::v_opeq_derived(int val) : v_opeq_base(val) {} v_opeq_derived::~v_opeq_derived() {} bool v_opeq_derived::operator==(const v_opeq_derived& other) { return m_val != other.m_val; }
206
811
<reponame>mitsuhiko/lol-html { "description": "Selectors - Parsing: Numbers in classes (css3-modsel-175a)", "selectors": { "p": "css3-modsel-175a.expected0.html" }, "src": "css3-modsel-175a.src.html" }
92
892
{ "schema_version": "1.2.0", "id": "GHSA-hvp2-hchp-m52h", "modified": "2022-05-13T01:16:02Z", "published": "2022-05-13T01:16:02Z", "aliases": [ "CVE-2013-3200" ], "details": "The USB drivers in the kernel-mode drivers in Microsoft Windows XP SP2 and SP3, Windows Server 2003 SP2, Windows Vista SP2, Windows Server 2008 SP2 and R2 SP1, Windows 7 SP1, Windows 8, Windows Server 2012, and Windows RT allow physically proximate attackers to execute arbitrary code by connecting a crafted USB device, aka \"Windows USB Descriptor Vulnerability.\"", "severity": [ ], "affected": [ ], "references": [ { "type": "ADVISORY", "url": "https://nvd.nist.gov/vuln/detail/CVE-2013-3200" }, { "type": "WEB", "url": "https://docs.microsoft.com/en-us/security-updates/securitybulletins/2013/ms13-081" }, { "type": "WEB", "url": "https://oval.cisecurity.org/repository/search/definition/oval%3Aorg.mitre.oval%3Adef%3A18630" }, { "type": "WEB", "url": "http://www.us-cert.gov/ncas/alerts/TA13-288A" } ], "database_specific": { "cwe_ids": [ "CWE-94" ], "severity": "HIGH", "github_reviewed": false } }
527
921
// Copyright 2016-2021 <NAME> // Licensed under the Apache License, version 2.0 // See accompanying file LICENSE or https://www.apache.org/licenses/LICENSE-2.0 #ifndef LIBCURV_SSTATE_H #define LIBCURV_SSTATE_H namespace curv { struct Context; struct Frame; struct System; // Shared state while scanning/analysing/evaluating a source file. // Referenced by Scanner, Environ (analysis) and Frame (evaluation). struct Source_State { System& system_; // If file_frame_ != nullptr, then we are processing a source file due to // an evaluation-time call to `file`, and this is the Frame of the `file` // call. It's used to add a stack trace to analysis time errors. Frame* file_frame_; // Have we already emitted a 'deprecated' warning for this topic? // Used to prevent an avalanche of warning messages. bool var_deprecated_ = false; bool paren_empty_list_deprecated_ = false; bool paren_list_deprecated_ = false; bool not_deprecated_ = false; bool dot_string_deprecated_ = false; bool string_colon_deprecated_ = false; bool where_deprecated_ = false; bool bracket_index_deprecated_ = false; bool at_deprecated_ = false; Source_State(System& sys, Frame* ff) : system_(sys), file_frame_(ff) {} void deprecate(bool Source_State::*, int, const Context&, String_Ref); static const char dot_string_deprecated_msg[]; }; } // namespace curv #endif // header guard
475
190,993
/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/lite/delegates/gpu/gl/compiler/rename.h" #include <algorithm> #include <utility> #include <vector> #include "absl/container/flat_hash_map.h" #include "absl/strings/str_cat.h" #include "absl/strings/str_join.h" #include "absl/strings/str_split.h" #include "tensorflow/lite/delegates/gpu/common/status.h" #include "tensorflow/lite/delegates/gpu/gl/compiler/object_accessor.h" #include "tensorflow/lite/delegates/gpu/gl/compiler/preprocessor.h" #include "tensorflow/lite/delegates/gpu/gl/compiler/variable_accessor.h" #include "tensorflow/lite/delegates/gpu/gl/object.h" #include "tensorflow/lite/delegates/gpu/gl/variable.h" namespace tflite { namespace gpu { namespace gl { namespace { // Rewrites names of all variables according to returned values from the // given NameFunctor. class VariableRewriter : public InlineRewrite { public: VariableRewriter(const std::string& inline_delimiter, const NameFunctor& name_func) : inline_delimiter_(inline_delimiter), name_func_(name_func) {} RewriteStatus Rewrite(absl::string_view input, std::string* output) final { auto ref = variable_accessor_internal::Parse(input); if (ref.name.empty()) { absl::StrAppend(output, "INVALID_SYNTAX"); return RewriteStatus::ERROR; } auto it = name_to_variable_.find(std::string(ref.name.data(), ref.name.size())); if (it == name_to_variable_.end()) { return RewriteStatus::NOT_RECOGNIZED; } // reconstruct access using the new name. absl::StrAppend(output, inline_delimiter_, it->second.name); if (!ref.index.empty()) { absl::StrAppend(output, "[", ref.index, "]"); } absl::StrAppend(output, ref.field, inline_delimiter_); return RewriteStatus::SUCCESS; } // Return true if variable was successfully added. bool AddVariable(Variable&& variable) { std::string old_name = variable.name; variable.name = name_func_(old_name); return name_to_variable_.insert({old_name, std::move(variable)}).second; } // Returns a collection of uniform parameters with updated names. std::vector<Variable> GetUniformParameters() const { std::vector<Variable> variables; variables.reserve(name_to_variable_.size()); for (const auto& variable : name_to_variable_) { variables.push_back(variable.second); } return variables; } private: const std::string inline_delimiter_; const NameFunctor name_func_; absl::flat_hash_map<std::string, Variable> name_to_variable_; }; // Rewrites names of all objects according to returned values from the // given NameFunctor. class ObjectRewriter : public InlineRewrite { public: ObjectRewriter(const std::string& inline_delimiter, const NameFunctor& name_func) : inline_delimiter_(inline_delimiter), name_func_(name_func) {} RewriteStatus Rewrite(absl::string_view input, std::string* output) final { // Splits 'a = b' into {'a','b'}. std::pair<absl::string_view, absl::string_view> n = absl::StrSplit(input, absl::MaxSplits('=', 1), absl::SkipWhitespace()); if (n.first.empty()) { return RewriteStatus::NOT_RECOGNIZED; } if (n.second.empty()) { return RewriteRead(absl::StripAsciiWhitespace(n.first), output); } return RewriteWrite(absl::StripAsciiWhitespace(n.first), absl::StripAsciiWhitespace(n.second), output); } // Return true if an object was successfully added. bool AddObject(const std::string& name, Object object) { std::string new_name = name_func_(name); return name_to_object_.insert({name, {new_name, std::move(object)}}).second; } // Returns a collection of registered objects with updated names. std::vector<std::pair<std::string, Object>> GetObjects() const { std::vector<std::pair<std::string, Object>> objects; objects.reserve(name_to_object_.size()); for (const auto& o : name_to_object_) { objects.push_back(o.second); } return objects; } private: RewriteStatus RewriteRead(absl::string_view location, std::string* output) { auto element = object_accessor_internal::ParseElement(location); if (element.object_name.empty()) { absl::StrAppend(output, "UNABLE_TO_PARSE_INDEXED_ELEMENT"); return RewriteStatus::ERROR; } auto it = name_to_object_.find( std::string(element.object_name.data(), element.object_name.size())); if (it == name_to_object_.end()) { return RewriteStatus::NOT_RECOGNIZED; } absl::StrAppend(output, inline_delimiter_, it->second.first, "[", absl::StrJoin(element.indices, ","), "]", inline_delimiter_); return RewriteStatus::SUCCESS; } RewriteStatus RewriteWrite(absl::string_view location, absl::string_view value, std::string* output) { // name[index1, index2...] = value auto element = object_accessor_internal::ParseElement(location); if (element.object_name.empty()) { absl::StrAppend(output, "UNABLE_TO_PARSE_INDEXED_ELEMENT"); return RewriteStatus::ERROR; } auto it = name_to_object_.find( std::string(element.object_name.data(), element.object_name.size())); if (it == name_to_object_.end()) { return RewriteStatus::NOT_RECOGNIZED; } absl::StrAppend(output, inline_delimiter_, it->second.first, "[", absl::StrJoin(element.indices, ","), "] = ", value, inline_delimiter_); return RewriteStatus::SUCCESS; } const std::string inline_delimiter_; const NameFunctor name_func_; absl::flat_hash_map<std::string, std::pair<std::string, Object>> name_to_object_; }; } // namespace absl::Status Rename(const NameFunctor& name_func, GeneratedCode* code) { VariableRewriter variable_rewriter("$", name_func); ObjectRewriter object_rewriter("$", name_func); for (auto&& uniform_parameter : code->parameters) { if (!variable_rewriter.AddVariable(std::move(uniform_parameter))) { return absl::InternalError("Variable name already exists"); } } for (auto&& object : code->objects) { if (!object_rewriter.AddObject(object.first, std::move(object.second))) { return absl::InternalError("Object name already exists"); } } TextPreprocessor preprocessor('$', /*keep_unknown_rewrites=*/true); preprocessor.AddRewrite(&variable_rewriter); preprocessor.AddRewrite(&object_rewriter); std::string source_code; RETURN_IF_ERROR(preprocessor.Rewrite(code->source_code, &source_code)); code->source_code = source_code; code->parameters = variable_rewriter.GetUniformParameters(); code->objects = object_rewriter.GetObjects(); return absl::OkStatus(); } } // namespace gl } // namespace gpu } // namespace tflite
2,731
956
<gh_stars>100-1000 /* SPDX-License-Identifier: BSD-3-Clause * Copyright(c) 2018 Intel Corporation */ #include "ifcvf.h" #include "ifcvf_osdep.h" STATIC void * get_cap_addr(struct ifcvf_hw *hw, struct ifcvf_pci_cap *cap) { u8 bar = cap->bar; u32 length = cap->length; u32 offset = cap->offset; if (bar > IFCVF_PCI_MAX_RESOURCE - 1) { DEBUGOUT("invalid bar: %u\n", bar); return NULL; } if (offset + length < offset) { DEBUGOUT("offset(%u) + length(%u) overflows\n", offset, length); return NULL; } if (offset + length > hw->mem_resource[cap->bar].len) { DEBUGOUT("offset(%u) + length(%u) overflows bar length(%u)", offset, length, (u32)hw->mem_resource[cap->bar].len); return NULL; } return hw->mem_resource[bar].addr + offset; } int ifcvf_init_hw(struct ifcvf_hw *hw, PCI_DEV *dev) { int ret; u8 pos; struct ifcvf_pci_cap cap; ret = PCI_READ_CONFIG_BYTE(dev, &pos, PCI_CAPABILITY_LIST); if (ret < 0) { DEBUGOUT("failed to read pci capability list\n"); return -1; } while (pos) { ret = PCI_READ_CONFIG_RANGE(dev, (u32 *)&cap, sizeof(cap), pos); if (ret < 0) { DEBUGOUT("failed to read cap at pos: %x", pos); break; } if (cap.cap_vndr != PCI_CAP_ID_VNDR) goto next; DEBUGOUT("cfg type: %u, bar: %u, offset: %u, " "len: %u\n", cap.cfg_type, cap.bar, cap.offset, cap.length); switch (cap.cfg_type) { case IFCVF_PCI_CAP_COMMON_CFG: hw->common_cfg = get_cap_addr(hw, &cap); break; case IFCVF_PCI_CAP_NOTIFY_CFG: PCI_READ_CONFIG_DWORD(dev, &hw->notify_off_multiplier, pos + sizeof(cap)); hw->notify_base = get_cap_addr(hw, &cap); hw->notify_region = cap.bar; break; case IFCVF_PCI_CAP_ISR_CFG: hw->isr = get_cap_addr(hw, &cap); break; case IFCVF_PCI_CAP_DEVICE_CFG: hw->dev_cfg = get_cap_addr(hw, &cap); break; } next: pos = cap.cap_next; } hw->lm_cfg = hw->mem_resource[4].addr; if (hw->common_cfg == NULL || hw->notify_base == NULL || hw->isr == NULL || hw->dev_cfg == NULL) { DEBUGOUT("capability incomplete\n"); return -1; } DEBUGOUT("capability mapping:\ncommon cfg: %p\n" "notify base: %p\nisr cfg: %p\ndevice cfg: %p\n" "multiplier: %u\n", hw->common_cfg, hw->dev_cfg, hw->isr, hw->notify_base, hw->notify_off_multiplier); return 0; } STATIC u8 ifcvf_get_status(struct ifcvf_hw *hw) { return IFCVF_READ_REG8(&hw->common_cfg->device_status); } STATIC void ifcvf_set_status(struct ifcvf_hw *hw, u8 status) { IFCVF_WRITE_REG8(status, &hw->common_cfg->device_status); } STATIC void ifcvf_reset(struct ifcvf_hw *hw) { ifcvf_set_status(hw, 0); /* flush status write */ while (ifcvf_get_status(hw)) msec_delay(1); } STATIC void ifcvf_add_status(struct ifcvf_hw *hw, u8 status) { if (status != 0) status |= ifcvf_get_status(hw); ifcvf_set_status(hw, status); ifcvf_get_status(hw); } u64 ifcvf_get_features(struct ifcvf_hw *hw) { u32 features_lo, features_hi; struct ifcvf_pci_common_cfg *cfg = hw->common_cfg; IFCVF_WRITE_REG32(0, &cfg->device_feature_select); features_lo = IFCVF_READ_REG32(&cfg->device_feature); IFCVF_WRITE_REG32(1, &cfg->device_feature_select); features_hi = IFCVF_READ_REG32(&cfg->device_feature); return ((u64)features_hi << 32) | features_lo; } STATIC void ifcvf_set_features(struct ifcvf_hw *hw, u64 features) { struct ifcvf_pci_common_cfg *cfg = hw->common_cfg; IFCVF_WRITE_REG32(0, &cfg->guest_feature_select); IFCVF_WRITE_REG32(features & ((1ULL << 32) - 1), &cfg->guest_feature); IFCVF_WRITE_REG32(1, &cfg->guest_feature_select); IFCVF_WRITE_REG32(features >> 32, &cfg->guest_feature); } STATIC int ifcvf_config_features(struct ifcvf_hw *hw) { u64 host_features; host_features = ifcvf_get_features(hw); hw->req_features &= host_features; ifcvf_set_features(hw, hw->req_features); ifcvf_add_status(hw, IFCVF_CONFIG_STATUS_FEATURES_OK); if (!(ifcvf_get_status(hw) & IFCVF_CONFIG_STATUS_FEATURES_OK)) { DEBUGOUT("failed to set FEATURES_OK status\n"); return -1; } return 0; } STATIC void io_write64_twopart(u64 val, u32 *lo, u32 *hi) { IFCVF_WRITE_REG32(val & ((1ULL << 32) - 1), lo); IFCVF_WRITE_REG32(val >> 32, hi); } STATIC int ifcvf_hw_enable(struct ifcvf_hw *hw) { struct ifcvf_pci_common_cfg *cfg; u8 *lm_cfg; u32 i; u16 notify_off; cfg = hw->common_cfg; lm_cfg = hw->lm_cfg; IFCVF_WRITE_REG16(0, &cfg->msix_config); if (IFCVF_READ_REG16(&cfg->msix_config) == IFCVF_MSI_NO_VECTOR) { DEBUGOUT("msix vec alloc failed for device config\n"); return -1; } for (i = 0; i < hw->nr_vring; i++) { IFCVF_WRITE_REG16(i, &cfg->queue_select); io_write64_twopart(hw->vring[i].desc, &cfg->queue_desc_lo, &cfg->queue_desc_hi); io_write64_twopart(hw->vring[i].avail, &cfg->queue_avail_lo, &cfg->queue_avail_hi); io_write64_twopart(hw->vring[i].used, &cfg->queue_used_lo, &cfg->queue_used_hi); IFCVF_WRITE_REG16(hw->vring[i].size, &cfg->queue_size); *(u32 *)(lm_cfg + IFCVF_LM_RING_STATE_OFFSET + (i / 2) * IFCVF_LM_CFG_SIZE + (i % 2) * 4) = (u32)hw->vring[i].last_avail_idx | ((u32)hw->vring[i].last_used_idx << 16); IFCVF_WRITE_REG16(i + 1, &cfg->queue_msix_vector); if (IFCVF_READ_REG16(&cfg->queue_msix_vector) == IFCVF_MSI_NO_VECTOR) { DEBUGOUT("queue %u, msix vec alloc failed\n", i); return -1; } notify_off = IFCVF_READ_REG16(&cfg->queue_notify_off); hw->notify_addr[i] = (void *)((u8 *)hw->notify_base + notify_off * hw->notify_off_multiplier); IFCVF_WRITE_REG16(1, &cfg->queue_enable); } return 0; } STATIC void ifcvf_hw_disable(struct ifcvf_hw *hw) { u32 i; struct ifcvf_pci_common_cfg *cfg; u32 ring_state; cfg = hw->common_cfg; IFCVF_WRITE_REG16(IFCVF_MSI_NO_VECTOR, &cfg->msix_config); for (i = 0; i < hw->nr_vring; i++) { IFCVF_WRITE_REG16(i, &cfg->queue_select); IFCVF_WRITE_REG16(0, &cfg->queue_enable); IFCVF_WRITE_REG16(IFCVF_MSI_NO_VECTOR, &cfg->queue_msix_vector); ring_state = *(u32 *)(hw->lm_cfg + IFCVF_LM_RING_STATE_OFFSET + (i / 2) * IFCVF_LM_CFG_SIZE + (i % 2) * 4); hw->vring[i].last_avail_idx = (u16)(ring_state >> 16); hw->vring[i].last_used_idx = (u16)(ring_state >> 16); } } int ifcvf_start_hw(struct ifcvf_hw *hw) { ifcvf_reset(hw); ifcvf_add_status(hw, IFCVF_CONFIG_STATUS_ACK); ifcvf_add_status(hw, IFCVF_CONFIG_STATUS_DRIVER); if (ifcvf_config_features(hw) < 0) return -1; if (ifcvf_hw_enable(hw) < 0) return -1; ifcvf_add_status(hw, IFCVF_CONFIG_STATUS_DRIVER_OK); return 0; } void ifcvf_stop_hw(struct ifcvf_hw *hw) { ifcvf_hw_disable(hw); ifcvf_reset(hw); } void ifcvf_enable_logging(struct ifcvf_hw *hw, u64 log_base, u64 log_size) { u8 *lm_cfg; lm_cfg = hw->lm_cfg; *(u32 *)(lm_cfg + IFCVF_LM_BASE_ADDR_LOW) = log_base & IFCVF_32_BIT_MASK; *(u32 *)(lm_cfg + IFCVF_LM_BASE_ADDR_HIGH) = (log_base >> 32) & IFCVF_32_BIT_MASK; *(u32 *)(lm_cfg + IFCVF_LM_END_ADDR_LOW) = (log_base + log_size) & IFCVF_32_BIT_MASK; *(u32 *)(lm_cfg + IFCVF_LM_END_ADDR_HIGH) = ((log_base + log_size) >> 32) & IFCVF_32_BIT_MASK; *(u32 *)(lm_cfg + IFCVF_LM_LOGGING_CTRL) = IFCVF_LM_ENABLE_VF; } void ifcvf_disable_logging(struct ifcvf_hw *hw) { u8 *lm_cfg; lm_cfg = hw->lm_cfg; *(u32 *)(lm_cfg + IFCVF_LM_LOGGING_CTRL) = IFCVF_LM_DISABLE; } void ifcvf_notify_queue(struct ifcvf_hw *hw, u16 qid) { IFCVF_WRITE_REG16(qid, hw->notify_addr[qid]); } u8 ifcvf_get_notify_region(struct ifcvf_hw *hw) { return hw->notify_region; } u64 ifcvf_get_queue_notify_off(struct ifcvf_hw *hw, int qid) { return (u8 *)hw->notify_addr[qid] - (u8 *)hw->mem_resource[hw->notify_region].addr; }
3,775
359
/** * Copyright 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. */ #ifndef __TOUPLE_H__ #define __TOUPLE_H__ #include "expr.h" #include "param.h" typedef struct touple { expr_list * values; param_list * dims; unsigned int line_no; } touple; touple * touple_new(expr_list * values, param_list * dims); void touple_delete(touple * value); #endif /* __TOUPLE_H__ */
417
1,359
<filename>src/main/java/com/kalessil/phpStorm/phpInspectionsEA/utils/analytics/AnalyticsUtil.java package com.kalessil.phpStorm.phpInspectionsEA.utils.analytics; /* * This file is part of the Php Inspections (EA Extended) package. * * (c) <NAME> <<EMAIL>> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import org.apache.http.client.fluent.Request; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.io.IOException; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.stream.Collectors; final public class AnalyticsUtil { private final static Set<String> stopList = new HashSet<>(); static { /* ugly, but: PhpStorm 2016 compatibility + reducing crash-reports rate */ stopList.add("com.jetbrains.php.lang.parser.PhpParserException"); stopList.add("com.intellij.openapi.diagnostic.RuntimeExceptionWithAttachments"); stopList.add("com.intellij.openapi.progress.ProcessCanceledException"); stopList.add("com.intellij.util.indexing.StorageException"); stopList.add("com.intellij.psi.stubs.UpToDateStubIndexMismatch"); stopList.add("java.util.ConcurrentModificationException"); stopList.add("java.lang.OutOfMemoryError"); stopList.add("com.intellij.psi.impl.source.FileTrees"); stopList.add("OpenapiEquivalenceUtil.java"); stopList.add("OpenapiResolveUtil.java"); } final static private String COLLECTOR_ID = "UA-16483983-8"; final static private String COLLECTOR_URL = "https://www.google-analytics.com/collect"; /* or /debug/collect */ private static final String pluginNamespace = "com.kalessil.phpStorm.phpInspectionsEA"; public static void registerLoggedException(@Nullable String version, @Nullable String uuid, @Nullable Throwable error) { if (error != null) { /* ignore IO-errors, that's not something we can handle */ final Throwable cause = error.getCause(); if (stopList.contains(error.getClass().getName()) || error instanceof IOException || cause instanceof IOException) { return; } /* report plugin failure location and trace top: to understand is it internals or the plugin */ final StackTraceElement[] stackTrace = error.getStackTrace(); final List<StackTraceElement> related = Arrays.stream(stackTrace) .filter(element -> element.getClassName().contains(pluginNamespace)) .collect(Collectors.toList()); if (!related.isEmpty()) { final StackTraceElement entryPoint = related.get(0); if (!stopList.contains(entryPoint.getFileName()) && !stopList.contains(stackTrace[0].getClassName())) { final String description = String.format( "[%s:%s@%s] %s::%s#%s: %s|%s", entryPoint.getFileName(), entryPoint.getLineNumber(), version, stackTrace[0].getClassName(), stackTrace[0].getMethodName(), stackTrace[0].getLineNumber(), error.getMessage(), error.getClass().getName() ); invokeExceptionReporting(uuid, description); } related.clear(); } } } static private void invokeExceptionReporting(@Nullable String uuid, @NotNull String description) { new Thread(() -> { /* See https://developers.google.com/analytics/devguides/collection/analyticsjs/exceptions */ final StringBuilder payload = new StringBuilder(); payload .append("v=1") // Version. .append("&tid=").append(COLLECTOR_ID) // Tracking ID / Property ID. .append("&cid=").append(uuid) // Anonymous Client ID. .append("&t=exception") // Exception hit type. .append("&exd=").append(description) // Exception description. .append("&exf=1") // Exception is fatal? ; try { Request.Post(COLLECTOR_URL) .bodyByteArray(payload.toString().getBytes()) .connectTimeout(3000) .execute(); } catch (Exception failed) { /* we do nothing here - this happens in background and not mission critical */ } }).start(); } }
2,281
321
<gh_stars>100-1000 // // WLRAppDelegate.h // WLRRoute // // Created by Neo on 12/18/2016. // Copyright (c) 2016 Neo. All rights reserved. // @import UIKit; @class WLRRouter; @interface WLRAppDelegate : UIResponder <UIApplicationDelegate> @property (strong, nonatomic) UIWindow *window; @property(nonatomic,strong)WLRRouter * router; @end
131
345
import os import unittest import unittest.mock from programy.bot import Bot from programy.clients.polling.twitter.client import TwitterBotClient from programy.clients.polling.twitter.config import TwitterConfiguration from programy.storage.config import FileStorageConfiguration from programy.storage.factory import StorageFactory from programy.storage.stores.file.config import FileStoreConfiguration from programy.storage.stores.file.engine import FileStorageEngine from programy.clients.render.text import TextRenderer from programytest.clients.arguments import MockArgumentParser class MockMessage(object): def __init__(self, id, sender_id, text): self.id = id self.sender_id = sender_id self.text = text class MockTwitterApi(object): def __init__(self): self._mock_direct_messages = [] self._destroyed_friendships = [] self._messages_sent_to = [] self._followers = [] self._friends_ids = [] self._statuses = [] self._user = None self._status = None def direct_messages(self, since_id=-1): return self._mock_direct_messages def destroy_friendship(self, friend_id): self._destroyed_friendships.append(friend_id) def send_direct_message(self, id, text): self._messages_sent_to.append(id) def followers(self): return self._followers def friends_ids(self): return self._friends_ids def home_timeline(self, since_id=-1): return self._statuses def get_user(self, userid): return self._user def update_status(self, status): self._status = status class MockBot(Bot): def __init__(self, config): Bot.__init__(self, config) self._answer = "" def ask_question(self, clientid: str, text: str, srai=False, responselogger=None): return self._answer class MockTwitterBotClient(TwitterBotClient): def __init__(self, argument_parser=None): self._response = None TwitterBotClient.__init__(self, argument_parser) def _create_api(self, consumer_key, consumer_secret, access_token, access_token_secret): return MockTwitterApi() def load_license_keys(self): self._license_keys.add_key("TWITTER_USERNAME", "username") self._license_keys.add_key("TWITTER_CONSUMER_KEY", "consumer_key") self._license_keys.add_key("TWITTER_CONSUMER_SECRET", "consumer_secret") self._license_keys.add_key("TWITTER_ACCESS_TOKEN", "access_token") self._license_keys.add_key("TWITTER_ACCESS_TOKEN_SECRET", "access_secret") def ask_question(self, userid, question): return self._response class TwitterBotClientTests(unittest.TestCase): def test_twitter_init(self): arguments = MockArgumentParser() client = MockTwitterBotClient(arguments) self.assertIsNotNone(client.get_client_configuration()) self.assertIsInstance(client.get_client_configuration(), TwitterConfiguration) self.assertEqual("ProgramY AIML2.0 Twitter Client", client.get_description()) self.assertEqual("username", client._username) self.assertEqual(8, client._username_len) self.assertEqual("consumer_key", client._consumer_key) self.assertEqual("consumer_secret", client._consumer_secret) self.assertEqual("access_token", client._access_token) self.assertEqual("access_secret", client._access_token_secret) self.assertFalse(client._render_callback()) self.assertIsInstance(client.renderer, TextRenderer)
1,345
4,901
<reponame>VSaliy/j2objc<filename>jre_emul/android/platform/libcore/ojluni/src/test/java/time/tck/java/time/temporal/TCKWeekFields.java /* * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* * Copyright (c) 2008-2012, <NAME> & <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 JSR-310 nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package tck.java.time.temporal; import static java.time.format.ResolverStyle.LENIENT; import static java.time.format.ResolverStyle.SMART; import static java.time.format.ResolverStyle.STRICT; import static java.time.temporal.ChronoField.DAY_OF_MONTH; import static java.time.temporal.ChronoField.DAY_OF_WEEK; import static java.time.temporal.ChronoField.DAY_OF_YEAR; import static java.time.temporal.ChronoField.MONTH_OF_YEAR; import static java.time.temporal.ChronoField.YEAR; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; import java.io.IOException; import java.time.DateTimeException; import java.time.DayOfWeek; import java.time.LocalDate; import java.time.format.DateTimeFormatter; import java.time.format.DateTimeFormatterBuilder; import java.time.temporal.ChronoUnit; import java.time.temporal.TemporalField; import java.time.temporal.ValueRange; import java.time.temporal.WeekFields; import com.tngtech.java.junit.dataprovider.DataProvider; import com.tngtech.java.junit.dataprovider.DataProviderRunner; import com.tngtech.java.junit.dataprovider.UseDataProvider; import org.junit.runner.RunWith; import org.junit.Test; import tck.java.time.AbstractTCKTest; /** * Test WeekFields. */ @RunWith(DataProviderRunner.class) public class TCKWeekFields extends AbstractTCKTest { @Test @UseDataProvider("data_weekFields") public void test_of_DayOfWeek_int_singleton(DayOfWeek firstDayOfWeek, int minDays) { WeekFields week = WeekFields.of(firstDayOfWeek, minDays); assertEquals("Incorrect firstDayOfWeek", week.getFirstDayOfWeek(), firstDayOfWeek); assertEquals("Incorrect MinimalDaysInFirstWeek", week.getMinimalDaysInFirstWeek(), minDays); assertSame(WeekFields.of(firstDayOfWeek, minDays), week); } //----------------------------------------------------------------------- @Test @UseDataProvider("data_weekFields") public void test_basics(DayOfWeek firstDayOfWeek, int minDays) { WeekFields week = WeekFields.of(firstDayOfWeek, minDays); assertEquals(week.dayOfWeek().isDateBased(), true); assertEquals(week.dayOfWeek().isTimeBased(), false); assertEquals(week.weekOfMonth().isDateBased(), true); assertEquals(week.weekOfMonth().isTimeBased(), false); assertEquals(week.weekOfYear().isDateBased(), true); assertEquals(week.weekOfYear().isTimeBased(), false); assertEquals(week.weekOfWeekBasedYear().isDateBased(), true); assertEquals(week.weekOfWeekBasedYear().isTimeBased(), false); assertEquals(week.weekBasedYear().isDateBased(), true); assertEquals(week.weekBasedYear().isTimeBased(), false); } //----------------------------------------------------------------------- @Test public void test_dayOfWeekField_simpleGet() { LocalDate date = LocalDate.of(2000, 1, 10); // Known to be ISO Monday assertEquals(date.get(WeekFields.ISO.dayOfWeek()), 1); assertEquals(date.get(WeekFields.of(DayOfWeek.MONDAY, 1).dayOfWeek()), 1); assertEquals(date.get(WeekFields.of(DayOfWeek.MONDAY, 7).dayOfWeek()), 1); assertEquals(date.get(WeekFields.SUNDAY_START.dayOfWeek()), 2); assertEquals(date.get(WeekFields.of(DayOfWeek.SUNDAY, 1).dayOfWeek()), 2); assertEquals(date.get(WeekFields.of(DayOfWeek.SUNDAY, 7).dayOfWeek()), 2); assertEquals(date.get(WeekFields.of(DayOfWeek.SATURDAY, 1).dayOfWeek()), 3); assertEquals(date.get(WeekFields.of(DayOfWeek.FRIDAY, 1).dayOfWeek()), 4); assertEquals(date.get(WeekFields.of(DayOfWeek.TUESDAY, 1).dayOfWeek()), 7); } @Test public void test_dayOfWeekField_simpleSet() { LocalDate date = LocalDate.of(2000, 1, 10); // Known to be ISO Monday assertEquals(date.with(WeekFields.ISO.dayOfWeek(), 2), LocalDate.of(2000, 1, 11)); assertEquals(date.with(WeekFields.ISO.dayOfWeek(), 7), LocalDate.of(2000, 1, 16)); assertEquals(date.with(WeekFields.SUNDAY_START.dayOfWeek(), 3), LocalDate.of(2000, 1, 11)); assertEquals(date.with(WeekFields.SUNDAY_START.dayOfWeek(), 7), LocalDate.of(2000, 1, 15)); assertEquals(date.with(WeekFields.of(DayOfWeek.SATURDAY, 1).dayOfWeek(), 4), LocalDate.of(2000, 1, 11)); assertEquals(date.with(WeekFields.of(DayOfWeek.TUESDAY, 1).dayOfWeek(), 1), LocalDate.of(2000, 1, 4)); } @Test @UseDataProvider("data_weekFields") public void test_dayOfWeekField(DayOfWeek firstDayOfWeek, int minDays) { LocalDate day = LocalDate.of(2000, 1, 10); // Known to be ISO Monday WeekFields week = WeekFields.of(firstDayOfWeek, minDays); TemporalField f = week.dayOfWeek(); for (int i = 1; i <= 7; i++) { assertEquals(day.get(f), (7 + day.getDayOfWeek().getValue() - firstDayOfWeek.getValue()) % 7 + 1); day = day.plusDays(1); } } @Test @UseDataProvider("data_weekFields") public void test_weekOfMonthField(DayOfWeek firstDayOfWeek, int minDays) { LocalDate day = LocalDate.of(2012, 12, 31); // Known to be ISO Monday WeekFields week = WeekFields.of(firstDayOfWeek, minDays); TemporalField dowField = week.dayOfWeek(); TemporalField womField = week.weekOfMonth(); for (int i = 1; i <= 15; i++) { int actualDOW = day.get(dowField); int actualWOM = day.get(womField); // Verify that the combination of day of week and week of month can be used // to reconstruct the same date. LocalDate day1 = day.withDayOfMonth(1); int offset = - (day1.get(dowField) - 1); int week1 = day1.get(womField); if (week1 == 0) { // week of the 1st is partial; start with first full week offset += 7; } offset += actualDOW - 1; offset += (actualWOM - 1) * 7; LocalDate result = day1.plusDays(offset); assertEquals("Incorrect dayOfWeek or weekOfMonth: " + String.format("%s, ISO Dow: %s, offset: %s, actualDOW: %s, actualWOM: %s, expected: %s, result: %s%n", week, day.getDayOfWeek(), offset, actualDOW, actualWOM, day, result), result, day); day = day.plusDays(1); } } @Test @UseDataProvider("data_weekFields") public void test_weekOfYearField(DayOfWeek firstDayOfWeek, int minDays) { LocalDate day = LocalDate.of(2012, 12, 31); // Known to be ISO Monday WeekFields week = WeekFields.of(firstDayOfWeek, minDays); TemporalField dowField = week.dayOfWeek(); TemporalField woyField = week.weekOfYear(); for (int i = 1; i <= 15; i++) { int actualDOW = day.get(dowField); int actualWOY = day.get(woyField); // Verify that the combination of day of week and week of month can be used // to reconstruct the same date. LocalDate day1 = day.withDayOfYear(1); int offset = - (day1.get(dowField) - 1); int week1 = day1.get(woyField); if (week1 == 0) { // week of the 1st is partial; start with first full week offset += 7; } offset += actualDOW - 1; offset += (actualWOY - 1) * 7; LocalDate result = day1.plusDays(offset); assertEquals("Incorrect dayOfWeek or weekOfYear " + String.format("%s, ISO Dow: %s, offset: %s, actualDOW: %s, actualWOM: %s, expected: %s, result: %s%n", week, day.getDayOfWeek(), offset, actualDOW, actualWOY, day, result), result, day); day = day.plusDays(1); } } /** * Verify that the date can be reconstructed from the DOW, WeekOfWeekBasedYear, * and WeekBasedYear for every combination of start of week * and minimal days in week. * @param firstDayOfWeek the first day of the week * @param minDays the minimum number of days in the week */ @Test @UseDataProvider("data_weekFields") public void test_weekOfWeekBasedYearField(DayOfWeek firstDayOfWeek, int minDays) { LocalDate day = LocalDate.of(2012, 12, 31); // Known to be ISO Monday WeekFields weekDef = WeekFields.of(firstDayOfWeek, minDays); TemporalField dowField = weekDef.dayOfWeek(); TemporalField wowbyField = weekDef.weekOfWeekBasedYear(); TemporalField yowbyField = weekDef.weekBasedYear(); for (int i = 1; i <= 15; i++) { int actualDOW = day.get(dowField); int actualWOWBY = day.get(wowbyField); int actualYOWBY = day.get(yowbyField); // Verify that the combination of day of week and week of month can be used // to reconstruct the same date. LocalDate day1 = LocalDate.of(actualYOWBY, 1, 1); DayOfWeek isoDOW = day1.getDayOfWeek(); int dow = (7 + isoDOW.getValue() - firstDayOfWeek.getValue()) % 7 + 1; int weekStart = Math.floorMod(1 - dow, 7); if (weekStart + 1 > weekDef.getMinimalDaysInFirstWeek()) { // The previous week has the minimum days in the current month to be a 'week' weekStart -= 7; } weekStart += actualDOW - 1; weekStart += (actualWOWBY - 1) * 7; LocalDate result = day1.plusDays(weekStart); assertEquals("Incorrect dayOfWeek or weekOfYear " + String.format("%s, ISO Dow: %s, weekStart: %s, actualDOW: %s, actualWOWBY: %s, YearOfWBY: %d, expected day: %s, result: %s%n", weekDef, day.getDayOfWeek(), weekStart, actualDOW, actualWOWBY, actualYOWBY, day, result), result, day); day = day.plusDays(1); } } @Test @UseDataProvider("data_weekFields") public void test_fieldRanges(DayOfWeek firstDayOfWeek, int minDays) { WeekFields weekDef = WeekFields.of(firstDayOfWeek, minDays); TemporalField womField = weekDef.weekOfMonth(); TemporalField woyField = weekDef.weekOfYear(); LocalDate day = LocalDate.of(2012, 11, 30); LocalDate endDay = LocalDate.of(2013, 1, 2); while (day.isBefore(endDay)) { LocalDate last = day.with(DAY_OF_MONTH, day.lengthOfMonth()); int lastWOM = last.get(womField); LocalDate first = day.with(DAY_OF_MONTH, 1); int firstWOM = first.get(womField); ValueRange rangeWOM = day.range(womField); assertEquals("Range min should be same as WeekOfMonth for first day of month: " + first + ", " + weekDef, rangeWOM.getMinimum(), firstWOM); assertEquals("Range max should be same as WeekOfMonth for last day of month: " + last + ", " + weekDef, rangeWOM.getMaximum(), lastWOM); last = day.with(DAY_OF_YEAR, day.lengthOfYear()); int lastWOY = last.get(woyField); first = day.with(DAY_OF_YEAR, 1); int firstWOY = first.get(woyField); ValueRange rangeWOY = day.range(woyField); assertEquals("Range min should be same as WeekOfYear for first day of Year: " + day + ", " + weekDef, rangeWOY.getMinimum(), firstWOY); assertEquals("Range max should be same as WeekOfYear for last day of Year: " + day + ", " + weekDef, rangeWOY.getMaximum(), lastWOY); day = day.plusDays(1); } } //----------------------------------------------------------------------- // withDayOfWeek() //----------------------------------------------------------------------- @Test @UseDataProvider("data_weekFields") public void test_withDayOfWeek(DayOfWeek firstDayOfWeek, int minDays) { LocalDate day = LocalDate.of(2012, 12, 15); // Safely in the middle of a month WeekFields week = WeekFields.of(firstDayOfWeek, minDays); TemporalField dowField = week.dayOfWeek(); TemporalField womField = week.weekOfMonth(); TemporalField woyField = week.weekOfYear(); int wom = day.get(womField); int woy = day.get(woyField); for (int dow = 1; dow <= 7; dow++) { LocalDate result = day.with(dowField, dow); assertEquals(String.format("Incorrect new Day of week: %s", result), result.get(dowField), dow); assertEquals("Week of Month should not change", result.get(womField), wom); assertEquals("Week of Year should not change", result.get(woyField), woy); } } @Test @UseDataProvider("data_weekFields") public void test_rangeWeekOfWeekBasedYear(DayOfWeek firstDayOfWeek, int minDays) { WeekFields weekFields = WeekFields.of(firstDayOfWeek, minDays); TemporalField dowField = weekFields.dayOfWeek(); TemporalField wowByField = weekFields.weekOfWeekBasedYear(); LocalDate day1 = LocalDate.of(2012, 1, weekFields.getMinimalDaysInFirstWeek()); day1 = day1.with(wowByField, 1).with(dowField, 1); LocalDate day2 = LocalDate.of(2013, 1, weekFields.getMinimalDaysInFirstWeek()); day2 = day2.with(wowByField, 1).with(dowField, 1); int expectedWeeks = (int)ChronoUnit.DAYS.between(day1, day2) / 7; ValueRange range = day1.range(wowByField); assertEquals("Range incorrect", range.getMaximum(), expectedWeeks); } @Test @UseDataProvider("data_weekFields") public void test_withWeekOfWeekBasedYear(DayOfWeek firstDayOfWeek, int minDays) { LocalDate day = LocalDate.of(2012, 12, 31); WeekFields week = WeekFields.of(firstDayOfWeek, minDays); TemporalField dowField = week.dayOfWeek(); TemporalField wowbyField = week.weekOfWeekBasedYear(); TemporalField yowbyField = week.weekBasedYear(); int dowExpected = (day.get(dowField) - 1) % 7 + 1; LocalDate dowDate = day.with(dowField, dowExpected); int dowResult = dowDate.get(dowField); assertEquals("Localized DayOfWeek not correct; " + day + " -->" + dowDate, dowResult, dowExpected); int weekExpected = day.get(wowbyField) + 1; ValueRange range = day.range(wowbyField); weekExpected = ((weekExpected - 1) % (int)range.getMaximum()) + 1; LocalDate weekDate = day.with(wowbyField, weekExpected); int weekResult = weekDate.get(wowbyField); assertEquals("Localized WeekOfWeekBasedYear not correct; " + day + " -->" + weekDate, weekResult, weekExpected); int yearExpected = day.get(yowbyField) + 1; LocalDate yearDate = day.with(yowbyField, yearExpected); int yearResult = yearDate.get(yowbyField); assertEquals("Localized WeekBasedYear not correct; " + day + " --> " + yearDate, yearResult, yearExpected); range = yearDate.range(wowbyField); weekExpected = Math.min(day.get(wowbyField), (int)range.getMaximum()); int weekActual = yearDate.get(wowbyField); assertEquals("Localized WeekOfWeekBasedYear week should not change; " + day + " --> " + yearDate + ", actual: " + weekActual + ", weekExpected: " + weekExpected, weekActual, weekExpected); } //----------------------------------------------------------------------- @Test @UseDataProvider("data_weekFields") public void test_parse_resolve_localizedWom(DayOfWeek firstDayOfWeek, int minDays) { LocalDate date = LocalDate.of(2012, 12, 15); WeekFields week = WeekFields.of(firstDayOfWeek, minDays); TemporalField womField = week.weekOfMonth(); for (int i = 1; i <= 60; i++) { DateTimeFormatter f = new DateTimeFormatterBuilder() .appendValue(YEAR).appendLiteral(':') .appendValue(MONTH_OF_YEAR).appendLiteral(':') .appendValue(womField).appendLiteral(':') .appendValue(DAY_OF_WEEK).toFormatter().withResolverStyle(SMART); String str = date.getYear() + ":" + date.getMonthValue() + ":" + date.get(womField) + ":" + date.get(DAY_OF_WEEK); LocalDate parsed = LocalDate.parse(str, f); assertEquals(" ::" + str + "::" + i, parsed, date); date = date.plusDays(1); } } @Test @UseDataProvider("data_weekFields") public void test_parse_resolve_localizedWom_lenient(DayOfWeek firstDayOfWeek, int minDays) { LocalDate date = LocalDate.of(2012, 12, 15); WeekFields week = WeekFields.of(firstDayOfWeek, minDays); TemporalField womField = week.weekOfMonth(); for (int i = 1; i <= 60; i++) { DateTimeFormatter f = new DateTimeFormatterBuilder() .appendValue(YEAR).appendLiteral(':') .appendValue(MONTH_OF_YEAR).appendLiteral(':') .appendValue(womField).appendLiteral(':') .appendValue(DAY_OF_WEEK).toFormatter().withResolverStyle(LENIENT); int wom = date.get(womField); int dow = date.get(DAY_OF_WEEK); for (int j = wom - 10; j < wom + 10; j++) { String str = date.getYear() + ":" + date.getMonthValue() + ":" + j + ":" + dow; LocalDate parsed = LocalDate.parse(str, f); assertEquals(" ::" + str + ": :" + i + "::" + j, parsed, date.plusWeeks(j - wom)); } date = date.plusDays(1); } } @Test @UseDataProvider("data_weekFields") public void test_parse_resolve_localizedWom_strict(DayOfWeek firstDayOfWeek, int minDays) { WeekFields week = WeekFields.of(firstDayOfWeek, minDays); TemporalField womField = week.weekOfMonth(); DateTimeFormatter f = new DateTimeFormatterBuilder() .appendValue(YEAR).appendLiteral(':') .appendValue(MONTH_OF_YEAR).appendLiteral(':') .appendValue(womField).appendLiteral(':') .appendValue(DAY_OF_WEEK).toFormatter().withResolverStyle(STRICT); String str = "2012:1:0:1"; try { LocalDate date = LocalDate.parse(str, f); assertEquals(date.getYear(), 2012); assertEquals(date.getMonthValue(), 1); assertEquals(date.get(womField), 0); assertEquals(date.get(DAY_OF_WEEK), 1); } catch (DateTimeException ex) { // expected } } //----------------------------------------------------------------------- @Test @UseDataProvider("data_weekFields") public void test_parse_resolve_localizedWomDow(DayOfWeek firstDayOfWeek, int minDays) { LocalDate date = LocalDate.of(2012, 12, 15); WeekFields week = WeekFields.of(firstDayOfWeek, minDays); TemporalField dowField = week.dayOfWeek(); TemporalField womField = week.weekOfMonth(); for (int i = 1; i <= 15; i++) { DateTimeFormatter f = new DateTimeFormatterBuilder() .appendValue(YEAR).appendLiteral(':') .appendValue(MONTH_OF_YEAR).appendLiteral(':') .appendValue(womField).appendLiteral(':') .appendValue(dowField).toFormatter(); String str = date.getYear() + ":" + date.getMonthValue() + ":" + date.get(womField) + ":" + date.get(dowField); LocalDate parsed = LocalDate.parse(str, f); assertEquals(" :: " + str + " " + i, parsed, date); date = date.plusDays(1); } } @Test @UseDataProvider("data_weekFields") public void test_parse_resolve_localizedWomDow_lenient(DayOfWeek firstDayOfWeek, int minDays) { LocalDate date = LocalDate.of(2012, 12, 15); WeekFields week = WeekFields.of(firstDayOfWeek, minDays); TemporalField dowField = week.dayOfWeek(); TemporalField womField = week.weekOfMonth(); for (int i = 1; i <= 60; i++) { DateTimeFormatter f = new DateTimeFormatterBuilder() .appendValue(YEAR).appendLiteral(':') .appendValue(MONTH_OF_YEAR).appendLiteral(':') .appendValue(womField).appendLiteral(':') .appendValue(dowField).toFormatter().withResolverStyle(LENIENT); int wom = date.get(womField); int dow = date.get(dowField); for (int j = wom - 10; j < wom + 10; j++) { String str = date.getYear() + ":" + date.getMonthValue() + ":" + j + ":" + dow; LocalDate parsed = LocalDate.parse(str, f); assertEquals(" ::" + str + ": :" + i + "::" + j, parsed, date.plusWeeks(j - wom)); } date = date.plusDays(1); } } //----------------------------------------------------------------------- @Test @UseDataProvider("data_weekFields") public void test_parse_resolve_localizedWoy(DayOfWeek firstDayOfWeek, int minDays) { LocalDate date = LocalDate.of(2012, 12, 15); WeekFields week = WeekFields.of(firstDayOfWeek, minDays); TemporalField woyField = week.weekOfYear(); for (int i = 1; i <= 60; i++) { DateTimeFormatter f = new DateTimeFormatterBuilder() .appendValue(YEAR).appendLiteral(':') .appendValue(woyField).appendLiteral(':') .appendValue(DAY_OF_WEEK).toFormatter(); String str = date.getYear() + ":" + date.get(woyField) + ":" + date.get(DAY_OF_WEEK); LocalDate parsed = LocalDate.parse(str, f); assertEquals(" :: " + str + " " + i, parsed, date); date = date.plusDays(1); } } @Test @UseDataProvider("data_weekFields") public void test_parse_resolve_localizedWoy_lenient(DayOfWeek firstDayOfWeek, int minDays) { LocalDate date = LocalDate.of(2012, 12, 15); WeekFields week = WeekFields.of(firstDayOfWeek, minDays); TemporalField woyField = week.weekOfYear(); for (int i = 1; i <= 60; i++) { DateTimeFormatter f = new DateTimeFormatterBuilder() .appendValue(YEAR).appendLiteral(':') .appendValue(woyField).appendLiteral(':') .appendValue(DAY_OF_WEEK).toFormatter().withResolverStyle(LENIENT); int woy = date.get(woyField); int dow = date.get(DAY_OF_WEEK); for (int j = woy - 60; j < woy + 60; j++) { String str = date.getYear() + ":" + j + ":" + dow; LocalDate parsed = LocalDate.parse(str, f); assertEquals(" ::" + str + ": :" + i + "::" + j, parsed, date.plusWeeks(j - woy)); } date = date.plusDays(1); } } @Test @UseDataProvider("data_weekFields") public void test_parse_resolve_localizedWoy_strict(DayOfWeek firstDayOfWeek, int minDays) { WeekFields week = WeekFields.of(firstDayOfWeek, minDays); TemporalField woyField = week.weekOfYear(); DateTimeFormatter f = new DateTimeFormatterBuilder() .appendValue(YEAR).appendLiteral(':') .appendValue(woyField).appendLiteral(':') .appendValue(DAY_OF_WEEK).toFormatter().withResolverStyle(STRICT); String str = "2012:0:1"; try { LocalDate date = LocalDate.parse(str, f); assertEquals(date.getYear(), 2012); assertEquals(date.get(woyField), 0); assertEquals(date.get(DAY_OF_WEEK), 1); } catch (DateTimeException ex) { // expected } } //----------------------------------------------------------------------- @Test @UseDataProvider("data_weekFields") public void test_parse_resolve_localizedWoyDow(DayOfWeek firstDayOfWeek, int minDays) { LocalDate date = LocalDate.of(2012, 12, 15); WeekFields week = WeekFields.of(firstDayOfWeek, minDays); TemporalField dowField = week.dayOfWeek(); TemporalField woyField = week.weekOfYear(); for (int i = 1; i <= 60; i++) { DateTimeFormatter f = new DateTimeFormatterBuilder() .appendValue(YEAR).appendLiteral(':') .appendValue(MONTH_OF_YEAR).appendLiteral(':') .appendValue(woyField).appendLiteral(':') .appendValue(dowField).toFormatter(); String str = date.getYear() + ":" + date.getMonthValue() + ":" + date.get(woyField) + ":" + date.get(dowField); LocalDate parsed = LocalDate.parse(str, f); assertEquals(" :: " + str + " " + i, parsed, date); date = date.plusDays(1); } } @Test @UseDataProvider("data_weekFields") public void test_parse_resolve_localizedWoyDow_lenient(DayOfWeek firstDayOfWeek, int minDays) { LocalDate date = LocalDate.of(2012, 12, 15); WeekFields week = WeekFields.of(firstDayOfWeek, minDays); TemporalField dowField = week.dayOfWeek(); TemporalField woyField = week.weekOfYear(); for (int i = 1; i <= 60; i++) { DateTimeFormatter f = new DateTimeFormatterBuilder() .appendValue(YEAR).appendLiteral(':') .appendValue(woyField).appendLiteral(':') .appendValue(dowField).toFormatter().withResolverStyle(LENIENT); int woy = date.get(woyField); int dow = date.get(dowField); for (int j = woy - 60; j < woy + 60; j++) { String str = date.getYear() + ":" + j + ":" + dow; LocalDate parsed = LocalDate.parse(str, f); assertEquals(" ::" + str + ": :" + i + "::" + j, parsed, date.plusWeeks(j - woy)); } date = date.plusDays(1); } } //----------------------------------------------------------------------- @Test @UseDataProvider("data_weekFields") public void test_parse_resolve_localizedWoWBY(DayOfWeek firstDayOfWeek, int minDays) { LocalDate date = LocalDate.of(2012, 12, 31); WeekFields week = WeekFields.of(firstDayOfWeek, minDays); TemporalField wowbyField = week.weekOfWeekBasedYear(); TemporalField yowbyField = week.weekBasedYear(); for (int i = 1; i <= 60; i++) { DateTimeFormatter f = new DateTimeFormatterBuilder() .appendValue(yowbyField).appendLiteral(':') .appendValue(wowbyField).appendLiteral(':') .appendValue(DAY_OF_WEEK).toFormatter(); String str = date.get(yowbyField) + ":" + date.get(wowbyField) + ":" + date.get(DAY_OF_WEEK); LocalDate parsed = LocalDate.parse(str, f); assertEquals(" :: " + str + " " + i, parsed, date); date = date.plusDays(1); } } @Test @UseDataProvider("data_weekFields") public void test_parse_resolve_localizedWoWBY_lenient(DayOfWeek firstDayOfWeek, int minDays) { LocalDate date = LocalDate.of(2012, 12, 31); WeekFields week = WeekFields.of(firstDayOfWeek, minDays); TemporalField wowbyField = week.weekOfWeekBasedYear(); TemporalField yowbyField = week.weekBasedYear(); for (int i = 1; i <= 60; i++) { DateTimeFormatter f = new DateTimeFormatterBuilder() .appendValue(yowbyField).appendLiteral(':') .appendValue(wowbyField).appendLiteral(':') .appendValue(DAY_OF_WEEK).toFormatter().withResolverStyle(LENIENT); int wowby = date.get(wowbyField); int dow = date.get(DAY_OF_WEEK); for (int j = wowby - 60; j < wowby + 60; j++) { String str = date.get(yowbyField) + ":" + j + ":" + dow; LocalDate parsed = LocalDate.parse(str, f); assertEquals(" ::" + str + ": :" + i + "::" + j, parsed, date.plusWeeks(j - wowby)); } date = date.plusDays(1); } } @Test @UseDataProvider("data_weekFields") public void test_parse_resolve_localizedWoWBY_strict(DayOfWeek firstDayOfWeek, int minDays) { WeekFields week = WeekFields.of(firstDayOfWeek, minDays); TemporalField wowbyField = week.weekOfWeekBasedYear(); TemporalField yowbyField = week.weekBasedYear(); DateTimeFormatter f = new DateTimeFormatterBuilder() .appendValue(yowbyField).appendLiteral(':') .appendValue(wowbyField).appendLiteral(':') .appendValue(DAY_OF_WEEK).toFormatter().withResolverStyle(STRICT); String str = "2012:0:1"; try { LocalDate date = LocalDate.parse(str, f); assertEquals(date.get(yowbyField), 2012); assertEquals(date.get(wowbyField), 0); assertEquals(date.get(DAY_OF_WEEK), 1); } catch (DateTimeException ex) { // expected } } //----------------------------------------------------------------------- @Test @UseDataProvider("data_weekFields") public void test_parse_resolve_localizedWoWBYDow(DayOfWeek firstDayOfWeek, int minDays) { LocalDate date = LocalDate.of(2012, 12, 31); WeekFields week = WeekFields.of(firstDayOfWeek, minDays); TemporalField dowField = week.dayOfWeek(); TemporalField wowbyField = week.weekOfWeekBasedYear(); TemporalField yowbyField = week.weekBasedYear(); for (int i = 1; i <= 60; i++) { DateTimeFormatter f = new DateTimeFormatterBuilder() .appendValue(yowbyField).appendLiteral(':') .appendValue(wowbyField).appendLiteral(':') .appendValue(dowField).toFormatter(); String str = date.get(yowbyField) + ":" + date.get(wowbyField) + ":" + date.get(dowField); LocalDate parsed = LocalDate.parse(str, f); assertEquals(" :: " + str + " " + i, parsed, date); date = date.plusDays(1); } } @Test @UseDataProvider("data_weekFields") public void test_parse_resolve_localizedWoWBYDow_lenient(DayOfWeek firstDayOfWeek, int minDays) { LocalDate date = LocalDate.of(2012, 12, 31); WeekFields week = WeekFields.of(firstDayOfWeek, minDays); TemporalField dowField = week.dayOfWeek(); TemporalField wowbyField = week.weekOfWeekBasedYear(); TemporalField yowbyField = week.weekBasedYear(); for (int i = 1; i <= 60; i++) { DateTimeFormatter f = new DateTimeFormatterBuilder() .appendValue(yowbyField).appendLiteral(':') .appendValue(wowbyField).appendLiteral(':') .appendValue(dowField).toFormatter().withResolverStyle(LENIENT); int wowby = date.get(wowbyField); int dow = date.get(dowField); for (int j = wowby - 60; j < wowby + 60; j++) { String str = date.get(yowbyField) + ":" + j + ":" + dow; LocalDate parsed = LocalDate.parse(str, f); assertEquals(" ::" + str + ": :" + i + "::" + j, parsed, date.plusWeeks(j - wowby)); } date = date.plusDays(1); } } //----------------------------------------------------------------------- @DataProvider public static Object[][] data_weekFields() { Object[][] objects = new Object[49][]; int i = 0; for (DayOfWeek firstDayOfWeek : DayOfWeek.values()) { for (int minDays = 1; minDays <= 7; minDays++) { objects[i++] = new Object[] {firstDayOfWeek, minDays}; } } return objects; } //----------------------------------------------------------------------- @DataProvider public static Object[][] provider_WeekBasedYearData() { return new Object[][] { {WeekFields.of(DayOfWeek.SUNDAY, 1), 2008, 52, 7, LocalDate.of(2008, 12, 27)}, {WeekFields.of(DayOfWeek.SUNDAY, 1), 2009, 1, 1, LocalDate.of(2008, 12, 28)}, {WeekFields.of(DayOfWeek.SUNDAY, 1), 2009, 1, 2, LocalDate.of(2008, 12, 29)}, {WeekFields.of(DayOfWeek.SUNDAY, 1), 2009, 1, 3, LocalDate.of(2008, 12, 30)}, {WeekFields.of(DayOfWeek.SUNDAY, 1), 2009, 1, 4, LocalDate.of(2008, 12, 31)}, {WeekFields.of(DayOfWeek.SUNDAY, 1), 2009, 1, 5, LocalDate.of(2009, 1, 1)}, {WeekFields.of(DayOfWeek.SUNDAY, 1), 2009, 2, 1, LocalDate.of(2009, 1, 4)}, {WeekFields.of(DayOfWeek.SUNDAY, 1), 2009, 2, 2, LocalDate.of(2009, 1, 5)}, {WeekFields.of(DayOfWeek.SUNDAY, 1), 2009, 2, 3, LocalDate.of(2009, 1, 6)}, }; } @Test @UseDataProvider("provider_WeekBasedYearData") public void test_weekBasedYears(WeekFields weekDef, int weekBasedYear, int weekOfWeekBasedYear, int dayOfWeek, LocalDate date) { TemporalField dowField = weekDef.dayOfWeek(); TemporalField wowbyField = weekDef.weekOfWeekBasedYear(); TemporalField yowbyField = weekDef.weekBasedYear(); assertEquals("DayOfWeek mismatch", date.get(dowField), dayOfWeek); assertEquals("Week of WeekBasedYear mismatch", date.get(wowbyField), weekOfWeekBasedYear); assertEquals("Year of WeekBasedYear mismatch", date.get(yowbyField), weekBasedYear); } //----------------------------------------------------------------------- @DataProvider public static Object[][] data_week() { return new Object[][] { {LocalDate.of(1969, 12, 29), DayOfWeek.MONDAY, 1, 1970}, {LocalDate.of(2012, 12, 23), DayOfWeek.SUNDAY, 51, 2012}, {LocalDate.of(2012, 12, 24), DayOfWeek.MONDAY, 52, 2012}, {LocalDate.of(2012, 12, 27), DayOfWeek.THURSDAY, 52, 2012}, {LocalDate.of(2012, 12, 28), DayOfWeek.FRIDAY, 52, 2012}, {LocalDate.of(2012, 12, 29), DayOfWeek.SATURDAY, 52, 2012}, {LocalDate.of(2012, 12, 30), DayOfWeek.SUNDAY, 52, 2012}, {LocalDate.of(2012, 12, 31), DayOfWeek.MONDAY, 1, 2013}, {LocalDate.of(2013, 1, 1), DayOfWeek.TUESDAY, 1, 2013}, {LocalDate.of(2013, 1, 2), DayOfWeek.WEDNESDAY, 1, 2013}, {LocalDate.of(2013, 1, 6), DayOfWeek.SUNDAY, 1, 2013}, {LocalDate.of(2013, 1, 7), DayOfWeek.MONDAY, 2, 2013}, }; } //----------------------------------------------------------------------- // WEEK_OF_WEEK_BASED_YEAR // Validate with the same data used by IsoFields. //----------------------------------------------------------------------- @Test @UseDataProvider("data_week") public void test_WOWBY(LocalDate date, DayOfWeek dow, int week, int wby) { WeekFields weekDef = WeekFields.ISO; TemporalField dowField = weekDef.dayOfWeek(); TemporalField wowbyField = weekDef.weekOfWeekBasedYear(); TemporalField yowbyField = weekDef.weekBasedYear(); assertEquals(date.get(dowField), dow.getValue()); assertEquals(date.get(wowbyField), week); assertEquals(date.get(yowbyField), wby); } //----------------------------------------------------------------------- // equals() and hashCode(). //----------------------------------------------------------------------- @Test public void test_equals() { WeekFields weekDef_iso = WeekFields.ISO; WeekFields weekDef_sundayStart = WeekFields.SUNDAY_START; assertTrue(weekDef_iso.equals(WeekFields.of(DayOfWeek.MONDAY, 4))); assertTrue(weekDef_sundayStart.equals(WeekFields.of(DayOfWeek.SUNDAY, 1))); assertEquals(weekDef_iso.hashCode(), WeekFields.of(DayOfWeek.MONDAY, 4).hashCode()); assertEquals(weekDef_sundayStart.hashCode(), WeekFields.of(DayOfWeek.SUNDAY, 1).hashCode()); assertFalse(weekDef_iso.equals(weekDef_sundayStart)); assertNotEquals(weekDef_iso.hashCode(), weekDef_sundayStart.hashCode()); } }
16,847
14,668
// 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 "services/network/public/cpp/server/http_connection.h" #include <utility> #include "base/check.h" #include "net/socket/stream_socket.h" #include "services/network/public/cpp/server/web_socket.h" namespace network { namespace server { HttpConnection::HttpConnection( int id, mojo::PendingRemote<mojom::TCPConnectedSocket> socket, mojo::ScopedDataPipeConsumerHandle socket_receive_handle, mojo::ScopedDataPipeProducerHandle socket_send_handle, const net::IPEndPoint& peer_addr) : id_(id), socket_(std::move(socket)), socket_receive_handle_(std::move(socket_receive_handle)), receive_pipe_watcher_(FROM_HERE, mojo::SimpleWatcher::ArmingPolicy::AUTOMATIC), socket_send_handle_(std::move(socket_send_handle)), send_pipe_watcher_(FROM_HERE, mojo::SimpleWatcher::ArmingPolicy::AUTOMATIC), peer_addr_(peer_addr) {} HttpConnection::~HttpConnection() = default; void HttpConnection::SetWebSocket(std::unique_ptr<WebSocket> web_socket) { DCHECK(!web_socket_); web_socket_ = std::move(web_socket); } } // namespace server } // namespace network
508
690
<gh_stars>100-1000 package com.artemis.link; import com.artemis.ComponentType; import com.artemis.Entity; import com.artemis.World; import com.artemis.annotations.EntityId; import com.artemis.annotations.LinkPolicy; import com.artemis.utils.Bag; import com.artemis.utils.IntBag; import com.artemis.utils.reflect.Annotation; import com.artemis.utils.reflect.ClassReflection; import com.artemis.utils.reflect.Field; import static com.artemis.annotations.LinkPolicy.Policy.SKIP; import static com.artemis.utils.reflect.ReflectionUtil.isGenericType; class LinkFactory { private static final int NULL_REFERENCE = 0; private static final int SINGLE_REFERENCE = 1; private static final int MULTI_REFERENCE = 2; private final Bag<LinkSite> links = new Bag<LinkSite>(); private final World world; private final ReflexiveMutators reflexiveMutators; public LinkFactory(World world) { this.world = world; reflexiveMutators = new ReflexiveMutators(world); } static int getReferenceTypeId(Field f) { Class type = f.getType(); if (Entity.class == type) return SINGLE_REFERENCE; if (isGenericType(f, Bag.class, Entity.class)) return MULTI_REFERENCE; boolean explicitEntityId = f.getDeclaredAnnotation(EntityId.class) != null; if (int.class == type && explicitEntityId) return SINGLE_REFERENCE; if (IntBag.class == type && explicitEntityId) return MULTI_REFERENCE; return NULL_REFERENCE; } Bag<LinkSite> create(ComponentType ct) { Class<?> type = ct.getType(); Field[] fields = ClassReflection.getDeclaredFields(type); links.clear(); for (int i = 0; fields.length > i; i++) { Field f = fields[i]; int referenceTypeId = getReferenceTypeId(f); if (referenceTypeId != NULL_REFERENCE && (SKIP != getPolicy(f))) { if (SINGLE_REFERENCE == referenceTypeId) { UniLinkSite ls = new UniLinkSite(world, ct, f); if (!configureMutator(ls)) reflexiveMutators.withMutator(ls); links.add(ls); } else if (MULTI_REFERENCE == referenceTypeId) { MultiLinkSite ls = new MultiLinkSite(world, ct, f); if (!configureMutator(ls)) reflexiveMutators.withMutator(ls); links.add(ls); } } } return links; } static LinkPolicy.Policy getPolicy(Field f) { Annotation annotation = f.getDeclaredAnnotation(LinkPolicy.class); if (annotation != null) { LinkPolicy lp = annotation.getAnnotation(LinkPolicy.class); return lp != null ? lp.value() : null; } return null; } private boolean configureMutator(UniLinkSite linkSite) { UniFieldMutator mutator = MutatorUtil.getGeneratedMutator(linkSite); if (mutator != null) { mutator.setWorld(world); linkSite.fieldMutator = mutator; return true; } else { return false; } } private boolean configureMutator(MultiLinkSite linkSite) { MultiFieldMutator mutator = MutatorUtil.getGeneratedMutator(linkSite); if (mutator != null) { mutator.setWorld(world); linkSite.fieldMutator = mutator; return true; } else { return false; } } static class ReflexiveMutators { final EntityFieldMutator entityField; final IntFieldMutator intField; final IntBagFieldMutator intBagField; final EntityBagFieldMutator entityBagField; public ReflexiveMutators(World world) { entityField = new EntityFieldMutator(); entityField.setWorld(world); intField = new IntFieldMutator(); intField.setWorld(world); intBagField = new IntBagFieldMutator(); intBagField.setWorld(world); entityBagField = new EntityBagFieldMutator(); entityBagField.setWorld(world); } UniLinkSite withMutator(UniLinkSite linkSite) { if (linkSite.fieldMutator != null) return linkSite; Class type = linkSite.field.getType(); if (Entity.class == type) { linkSite.fieldMutator = entityField; } else if (int.class == type) { linkSite.fieldMutator = intField; } else { throw new RuntimeException("unexpected '" + type + "', on " + linkSite.type); } return linkSite; } MultiLinkSite withMutator(MultiLinkSite linkSite) { if (linkSite.fieldMutator != null) return linkSite; Class type = linkSite.field.getType(); if (IntBag.class == type) { linkSite.fieldMutator = intBagField; } else if (Bag.class == type) { linkSite.fieldMutator = entityBagField; } else { throw new RuntimeException("unexpected '" + type + "', on " + linkSite.type); } return linkSite; } } }
1,657
926
<filename>library/modules/Designations.cpp #include "DataDefs.h" #include "Error.h" #include "modules/Designations.h" #include "modules/Job.h" #include "modules/Maps.h" #include "df/job.h" #include "df/map_block.h" #include "df/plant.h" #include "df/plant_tree_info.h" #include "df/plant_tree_tile.h" #include "df/tile_dig_designation.h" #include "df/world.h" using namespace DFHack; using namespace df::enums; using df::global::world; static df::map_block *getPlantBlock(const df::plant *plant) { if (!world) return nullptr; return Maps::getTileBlock(Designations::getPlantDesignationTile(plant)); } df::coord Designations::getPlantDesignationTile(const df::plant *plant) { CHECK_NULL_POINTER(plant); if (!plant->tree_info) return plant->pos; int dimx = plant->tree_info->dim_x; int dimy = plant->tree_info->dim_y; int cx = dimx / 2; int cy = dimy / 2; // Find the southeast trunk tile int x = cx; int y = cy; while (x + 1 < dimx && y + 1 < dimy) { if (plant->tree_info->body[0][(y * dimx) + (x + 1)].bits.trunk) ++x; else if (plant->tree_info->body[0][((y + 1) * dimx) + x].bits.trunk) ++y; else break; } return df::coord(plant->pos.x - cx + x, plant->pos.y - cy + y, plant->pos.z); } bool Designations::isPlantMarked(const df::plant *plant) { CHECK_NULL_POINTER(plant); df::coord des_pos = getPlantDesignationTile(plant); df::map_block *block = Maps::getTileBlock(des_pos); if (!block) return false; if (block->designation[des_pos.x % 16][des_pos.y % 16].bits.dig == tile_dig_designation::Default) return true; for (auto *link = world->jobs.list.next; link; link = link->next) { df::job *job = link->item; if (!job) continue; if (job->job_type != job_type::FellTree && job->job_type != job_type::GatherPlants) continue; if (job->pos == des_pos) return true; } return false; } bool Designations::canMarkPlant(const df::plant *plant) { CHECK_NULL_POINTER(plant); if (!getPlantBlock(plant)) return false; return !isPlantMarked(plant); } bool Designations::markPlant(const df::plant *plant) { CHECK_NULL_POINTER(plant); if (canMarkPlant(plant)) { df::coord des_pos = getPlantDesignationTile(plant); df::map_block *block = Maps::getTileBlock(des_pos); block->designation[des_pos.x % 16][des_pos.y % 16].bits.dig = tile_dig_designation::Default; block->flags.bits.designated = true; return true; } else { return false; } } bool Designations::canUnmarkPlant(const df::plant *plant) { CHECK_NULL_POINTER(plant); if (!getPlantBlock(plant)) return false; return isPlantMarked(plant); } bool Designations::unmarkPlant(const df::plant *plant) { CHECK_NULL_POINTER(plant); if (canUnmarkPlant(plant)) { df::coord des_pos = getPlantDesignationTile(plant); df::map_block *block = Maps::getTileBlock(des_pos); block->designation[des_pos.x % 16][des_pos.y % 16].bits.dig = tile_dig_designation::No; block->flags.bits.designated = true; auto *link = world->jobs.list.next; while (link) { auto *next = link->next; df::job *job = link->item; if (job && (job->job_type == job_type::FellTree || job->job_type == job_type::GatherPlants) && job->pos == des_pos) { Job::removeJob(job); } link = next; } return true; } else { return false; } }
1,714
965
class ATL_NO_VTABLE CNoAggClass : public CComObjectRoot, public CComCoClass<CNoAggClass, &CLSID_NoAggClass> { public: CNoAggClass() { } DECLARE_NOT_AGGREGATABLE(CNoAggClass) };
87
190,993
<filename>tensorflow/cc/experimental/libtf/impl/none.h /* Copyright 2021 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #ifndef TENSORFLOW_CC_EXPERIMENTAL_LIBTF_IMPL_NONE_H_ #define TENSORFLOW_CC_EXPERIMENTAL_LIBTF_IMPL_NONE_H_ #include <iosfwd> #include <utility> namespace tf { namespace libtf { namespace impl { /// @brief The Singleton `None` class. /// /// This class is not user-constructible. To create a `None` instance, use /// None::GetInstance(). class None final { public: /// Retrieves the `None` instance. /// /// @return Returns the `None` singleton. static None& GetInstance(); /// Equality operator. bool operator==(const None& other) const { return true; } /// Overload AbslHashValue. template <typename H> friend H AbslHashValue(H h, const None& n) { return H::combine(std::move(h), 34559); } private: // Private contructor. None() {} }; // Defined in iostream.cc. std::ostream& operator<<(std::ostream& o, const None& none); } // namespace impl } // namespace libtf } // namespace tf #endif // TENSORFLOW_CC_EXPERIMENTAL_LIBTF_IMPL_NONE_H_
535
421
<reponame>hamarb123/dotnet-api-docs //<snippet1> using namespace System; using namespace System::IO; using namespace System::Collections; using namespace System::Runtime::Serialization::Formatters::Binary; using namespace System::Runtime::Serialization; ref class SingletonSerializationHelper; // There should be only one instance of this type per AppDomain. [Serializable] public ref class Singleton sealed: public ISerializable { private: // This is the one instance of this type. static Singleton^ theOneObject = gcnew Singleton; public: // Here are the instance fields. String^ someString; Int32 someNumber; private: // Private constructor allowing this type to construct the singleton. Singleton() { // Do whatever is necessary to initialize the singleton. someString = "This is a String* field"; someNumber = 123; } public: // A method returning a reference to the singleton. static Singleton^ GetSingleton() { return theOneObject; } // A method called when serializing a Singleton. [System::Security::Permissions::SecurityPermissionAttribute (System::Security::Permissions::SecurityAction::LinkDemand, Flags=System::Security::Permissions::SecurityPermissionFlag::SerializationFormatter)] virtual void GetObjectData( SerializationInfo^ info, StreamingContext context ) { // Instead of serializing this Object*, we will // serialize a SingletonSerializationHelp instead. info->SetType( SingletonSerializationHelper::typeid ); // No other values need to be added. } // NOTE: ISerializable*'s special constructor is NOT necessary // because it's never called }; [Serializable] private ref class SingletonSerializationHelper sealed: public IObjectReference { public: // This Object* has no fields (although it could). // GetRealObject is called after this Object* is deserialized virtual Object^ GetRealObject( StreamingContext context ) { // When deserialiing this Object*, return a reference to // the singleton Object* instead. return Singleton::GetSingleton(); } }; [STAThread] int main() { FileStream^ fs = gcnew FileStream( "DataFile.dat",FileMode::Create ); try { // Construct a BinaryFormatter and use it // to serialize the data to the stream. BinaryFormatter^ formatter = gcnew BinaryFormatter; // Create an array with multiple elements refering to // the one Singleton Object*. array<Singleton^>^a1 = {Singleton::GetSingleton(),Singleton::GetSingleton()}; // This displays S"True". Console::WriteLine( "Do both array elements refer to the same Object? {0}", (a1[ 0 ] == a1[ 1 ]) ); // Serialize the array elements. formatter->Serialize( fs, a1 ); // Deserialize the array elements. fs->Position = 0; array<Singleton^>^a2 = (array<Singleton^>^)formatter->Deserialize( fs ); // This displays S"True". Console::WriteLine( "Do both array elements refer to the same Object? {0}", (a2[ 0 ] == a2[ 1 ]) ); // This displays S"True". Console::WriteLine( "Do all array elements refer to the same Object? {0}", (a1[ 0 ] == a2[ 0 ]) ); } catch ( SerializationException^ e ) { Console::WriteLine( "Failed to serialize. Reason: {0}", e->Message ); throw; } finally { fs->Close(); } return 0; } //</snippet1>
1,274
1,305
<filename>src/org/example/source/javax/swing/JFrame.java /* * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved. * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. * * * * * * * * * * * * * * * * * * * * */ package javax.swing; import java.awt.AWTEvent; import java.awt.BorderLayout; import java.awt.Component; import java.awt.Container; import java.awt.Frame; import java.awt.Graphics; import java.awt.GraphicsConfiguration; import java.awt.HeadlessException; import java.awt.Image; import java.awt.LayoutManager; import java.awt.event.WindowEvent; import javax.accessibility.Accessible; import javax.accessibility.AccessibleContext; import javax.accessibility.AccessibleState; import javax.accessibility.AccessibleStateSet; /** * An extended version of <code>java.awt.Frame</code> that adds support for * the JFC/Swing component architecture. * You can find task-oriented documentation about using <code>JFrame</code> * in <em>The Java Tutorial</em>, in the section * <a href="https://docs.oracle.com/javase/tutorial/uiswing/components/frame.html">How to Make Frames</a>. * * <p> * The <code>JFrame</code> class is slightly incompatible with <code>Frame</code>. * Like all other JFC/Swing top-level containers, * a <code>JFrame</code> contains a <code>JRootPane</code> as its only child. * The <b>content pane</b> provided by the root pane should, * as a rule, contain * all the non-menu components displayed by the <code>JFrame</code>. * This is different from the AWT <code>Frame</code> case. * As a convenience, the {@code add}, {@code remove}, and {@code setLayout} * methods of this class are overridden, so that they delegate calls * to the corresponding methods of the {@code ContentPane}. * For example, you can add a child component to a frame as follows: * <pre> * frame.add(child); * </pre> * And the child will be added to the contentPane. * The content pane will * always be non-null. Attempting to set it to null will cause the JFrame * to throw an exception. The default content pane will have a BorderLayout * manager set on it. * Refer to {@link javax.swing.RootPaneContainer} * for details on adding, removing and setting the <code>LayoutManager</code> * of a <code>JFrame</code>. * <p> * Unlike a <code>Frame</code>, a <code>JFrame</code> has some notion of how to * respond when the user attempts to close the window. The default behavior * is to simply hide the JFrame when the user closes the window. To change the * default behavior, you invoke the method * {@link #setDefaultCloseOperation}. * To make the <code>JFrame</code> behave the same as a <code>Frame</code> * instance, use * <code>setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE)</code>. * <p> * For more information on content panes * and other features that root panes provide, * see <a href="https://docs.oracle.com/javase/tutorial/uiswing/components/toplevel.html">Using Top-Level Containers</a> in <em>The Java Tutorial</em>. * <p> * In a multi-screen environment, you can create a <code>JFrame</code> * on a different screen device. See {@link java.awt.Frame} for more * information. * <p> * <strong>Warning:</strong> Swing is not thread safe. For more * information see <a * href="package-summary.html#threading">Swing's Threading * Policy</a>. * <p> * <strong>Warning:</strong> * Serialized objects of this class will not be compatible with * future Swing releases. The current serialization support is * appropriate for short term storage or RMI between applications running * the same version of Swing. As of 1.4, support for long term storage * of all JavaBeans&trade; * has been added to the <code>java.beans</code> package. * Please see {@link java.beans.XMLEncoder}. * * @see JRootPane * @see #setDefaultCloseOperation * @see java.awt.event.WindowListener#windowClosing * @see javax.swing.RootPaneContainer * * @beaninfo * attribute: isContainer true * attribute: containerDelegate getContentPane * description: A toplevel window which can be minimized to an icon. * * @author <NAME> * @author <NAME> * @author <NAME> */ public class JFrame extends Frame implements WindowConstants, Accessible, RootPaneContainer, TransferHandler.HasGetTransferHandler { /** * The exit application default window close operation. If a window * has this set as the close operation and is closed in an applet, * a <code>SecurityException</code> may be thrown. * It is recommended you only use this in an application. * <p> * @since 1.3 */ public static final int EXIT_ON_CLOSE = 3; /** * Key into the AppContext, used to check if should provide decorations * by default. */ private static final Object defaultLookAndFeelDecoratedKey = new StringBuffer("JFrame.defaultLookAndFeelDecorated"); private int defaultCloseOperation = HIDE_ON_CLOSE; /** * The <code>TransferHandler</code> for this frame. */ private TransferHandler transferHandler; /** * The <code>JRootPane</code> instance that manages the * <code>contentPane</code> * and optional <code>menuBar</code> for this frame, as well as the * <code>glassPane</code>. * * @see JRootPane * @see RootPaneContainer */ protected JRootPane rootPane; /** * If true then calls to <code>add</code> and <code>setLayout</code> * will be forwarded to the <code>contentPane</code>. This is initially * false, but is set to true when the <code>JFrame</code> is constructed. * * @see #isRootPaneCheckingEnabled * @see #setRootPaneCheckingEnabled * @see javax.swing.RootPaneContainer */ protected boolean rootPaneCheckingEnabled = false; /** * Constructs a new frame that is initially invisible. * <p> * This constructor sets the component's locale property to the value * returned by <code>JComponent.getDefaultLocale</code>. * * @exception HeadlessException if GraphicsEnvironment.isHeadless() * returns true. * @see java.awt.GraphicsEnvironment#isHeadless * @see Component#setSize * @see Component#setVisible * @see JComponent#getDefaultLocale */ public JFrame() throws HeadlessException { super(); frameInit(); } /** * Creates a <code>Frame</code> in the specified * <code>GraphicsConfiguration</code> of * a screen device and a blank title. * <p> * This constructor sets the component's locale property to the value * returned by <code>JComponent.getDefaultLocale</code>. * * @param gc the <code>GraphicsConfiguration</code> that is used * to construct the new <code>Frame</code>; * if <code>gc</code> is <code>null</code>, the system * default <code>GraphicsConfiguration</code> is assumed * @exception IllegalArgumentException if <code>gc</code> is not from * a screen device. This exception is always thrown when * GraphicsEnvironment.isHeadless() returns true. * @see java.awt.GraphicsEnvironment#isHeadless * @see JComponent#getDefaultLocale * @since 1.3 */ public JFrame(GraphicsConfiguration gc) { super(gc); frameInit(); } /** * Creates a new, initially invisible <code>Frame</code> with the * specified title. * <p> * This constructor sets the component's locale property to the value * returned by <code>JComponent.getDefaultLocale</code>. * * @param title the title for the frame * @exception HeadlessException if GraphicsEnvironment.isHeadless() * returns true. * @see java.awt.GraphicsEnvironment#isHeadless * @see Component#setSize * @see Component#setVisible * @see JComponent#getDefaultLocale */ public JFrame(String title) throws HeadlessException { super(title); frameInit(); } /** * Creates a <code>JFrame</code> with the specified title and the * specified <code>GraphicsConfiguration</code> of a screen device. * <p> * This constructor sets the component's locale property to the value * returned by <code>JComponent.getDefaultLocale</code>. * * @param title the title to be displayed in the * frame's border. A <code>null</code> value is treated as * an empty string, "". * @param gc the <code>GraphicsConfiguration</code> that is used * to construct the new <code>JFrame</code> with; * if <code>gc</code> is <code>null</code>, the system * default <code>GraphicsConfiguration</code> is assumed * @exception IllegalArgumentException if <code>gc</code> is not from * a screen device. This exception is always thrown when * GraphicsEnvironment.isHeadless() returns true. * @see java.awt.GraphicsEnvironment#isHeadless * @see JComponent#getDefaultLocale * @since 1.3 */ public JFrame(String title, GraphicsConfiguration gc) { super(title, gc); frameInit(); } /** Called by the constructors to init the <code>JFrame</code> properly. */ protected void frameInit() { enableEvents(AWTEvent.KEY_EVENT_MASK | AWTEvent.WINDOW_EVENT_MASK); setLocale( JComponent.getDefaultLocale() ); setRootPane(createRootPane()); setBackground(UIManager.getColor("control")); setRootPaneCheckingEnabled(true); if (JFrame.isDefaultLookAndFeelDecorated()) { boolean supportsWindowDecorations = UIManager.getLookAndFeel().getSupportsWindowDecorations(); if (supportsWindowDecorations) { setUndecorated(true); getRootPane().setWindowDecorationStyle(JRootPane.FRAME); } } sun.awt.SunToolkit.checkAndSetPolicy(this); } /** * Called by the constructor methods to create the default * <code>rootPane</code>. */ protected JRootPane createRootPane() { JRootPane rp = new JRootPane(); // NOTE: this uses setOpaque vs LookAndFeel.installProperty as there // is NO reason for the RootPane not to be opaque. For painting to // work the contentPane must be opaque, therefor the RootPane can // also be opaque. rp.setOpaque(true); return rp; } /** * Processes window events occurring on this component. * Hides the window or disposes of it, as specified by the setting * of the <code>defaultCloseOperation</code> property. * * @param e the window event * @see #setDefaultCloseOperation * @see java.awt.Window#processWindowEvent */ protected void processWindowEvent(final WindowEvent e) { super.processWindowEvent(e); if (e.getID() == WindowEvent.WINDOW_CLOSING) { switch (defaultCloseOperation) { case HIDE_ON_CLOSE: setVisible(false); break; case DISPOSE_ON_CLOSE: dispose(); break; case EXIT_ON_CLOSE: // This needs to match the checkExit call in // setDefaultCloseOperation System.exit(0); break; case DO_NOTHING_ON_CLOSE: default: } } } /** * Sets the operation that will happen by default when * the user initiates a "close" on this frame. * You must specify one of the following choices: * <br><br> * <ul> * <li><code>DO_NOTHING_ON_CLOSE</code> * (defined in <code>WindowConstants</code>): * Don't do anything; require the * program to handle the operation in the <code>windowClosing</code> * method of a registered <code>WindowListener</code> object. * * <li><code>HIDE_ON_CLOSE</code> * (defined in <code>WindowConstants</code>): * Automatically hide the frame after * invoking any registered <code>WindowListener</code> * objects. * * <li><code>DISPOSE_ON_CLOSE</code> * (defined in <code>WindowConstants</code>): * Automatically hide and dispose the * frame after invoking any registered <code>WindowListener</code> * objects. * * <li><code>EXIT_ON_CLOSE</code> * (defined in <code>JFrame</code>): * Exit the application using the <code>System</code> * <code>exit</code> method. Use this only in applications. * </ul> * <p> * The value is set to <code>HIDE_ON_CLOSE</code> by default. Changes * to the value of this property cause the firing of a property * change event, with property name "defaultCloseOperation". * <p> * <b>Note</b>: When the last displayable window within the * Java virtual machine (VM) is disposed of, the VM may * terminate. See <a href="../../java/awt/doc-files/AWTThreadIssues.html"> * AWT Threading Issues</a> for more information. * * @param operation the operation which should be performed when the * user closes the frame * @exception IllegalArgumentException if defaultCloseOperation value * isn't one of the above valid values * @see #addWindowListener * @see #getDefaultCloseOperation * @see WindowConstants * @throws SecurityException * if <code>EXIT_ON_CLOSE</code> has been specified and the * <code>SecurityManager</code> will * not allow the caller to invoke <code>System.exit</code> * @see java.lang.Runtime#exit(int) * * @beaninfo * preferred: true * bound: true * enum: DO_NOTHING_ON_CLOSE WindowConstants.DO_NOTHING_ON_CLOSE * HIDE_ON_CLOSE WindowConstants.HIDE_ON_CLOSE * DISPOSE_ON_CLOSE WindowConstants.DISPOSE_ON_CLOSE * EXIT_ON_CLOSE WindowConstants.EXIT_ON_CLOSE * description: The frame's default close operation. */ public void setDefaultCloseOperation(int operation) { if (operation != DO_NOTHING_ON_CLOSE && operation != HIDE_ON_CLOSE && operation != DISPOSE_ON_CLOSE && operation != EXIT_ON_CLOSE) { throw new IllegalArgumentException("defaultCloseOperation must be one of: DO_NOTHING_ON_CLOSE, HIDE_ON_CLOSE, DISPOSE_ON_CLOSE, or EXIT_ON_CLOSE"); } if (operation == EXIT_ON_CLOSE) { SecurityManager security = System.getSecurityManager(); if (security != null) { security.checkExit(0); } } if (this.defaultCloseOperation != operation) { int oldValue = this.defaultCloseOperation; this.defaultCloseOperation = operation; firePropertyChange("defaultCloseOperation", oldValue, operation); } } /** * Returns the operation that occurs when the user * initiates a "close" on this frame. * * @return an integer indicating the window-close operation * @see #setDefaultCloseOperation */ public int getDefaultCloseOperation() { return defaultCloseOperation; } /** * Sets the {@code transferHandler} property, which is a mechanism to * support transfer of data into this component. Use {@code null} * if the component does not support data transfer operations. * <p> * If the system property {@code suppressSwingDropSupport} is {@code false} * (the default) and the current drop target on this component is either * {@code null} or not a user-set drop target, this method will change the * drop target as follows: If {@code newHandler} is {@code null} it will * clear the drop target. If not {@code null} it will install a new * {@code DropTarget}. * <p> * Note: When used with {@code JFrame}, {@code TransferHandler} only * provides data import capability, as the data export related methods * are currently typed to {@code JComponent}. * <p> * Please see * <a href="https://docs.oracle.com/javase/tutorial/uiswing/dnd/index.html"> * How to Use Drag and Drop and Data Transfer</a>, a section in * <em>The Java Tutorial</em>, for more information. * * @param newHandler the new {@code TransferHandler} * * @see TransferHandler * @see #getTransferHandler * @see java.awt.Component#setDropTarget * @since 1.6 * * @beaninfo * bound: true * hidden: true * description: Mechanism for transfer of data into the component */ public void setTransferHandler(TransferHandler newHandler) { TransferHandler oldHandler = transferHandler; transferHandler = newHandler; SwingUtilities.installSwingDropTargetAsNecessary(this, transferHandler); firePropertyChange("transferHandler", oldHandler, newHandler); } /** * Gets the <code>transferHandler</code> property. * * @return the value of the <code>transferHandler</code> property * * @see TransferHandler * @see #setTransferHandler * @since 1.6 */ public TransferHandler getTransferHandler() { return transferHandler; } /** * Just calls <code>paint(g)</code>. This method was overridden to * prevent an unnecessary call to clear the background. * * @param g the Graphics context in which to paint */ public void update(Graphics g) { paint(g); } /** * Sets the menubar for this frame. * @param menubar the menubar being placed in the frame * * @see #getJMenuBar * * @beaninfo * hidden: true * description: The menubar for accessing pulldown menus from this frame. */ public void setJMenuBar(JMenuBar menubar) { getRootPane().setMenuBar(menubar); } /** * Returns the menubar set on this frame. * @return the menubar for this frame * * @see #setJMenuBar */ public JMenuBar getJMenuBar() { return getRootPane().getMenuBar(); } /** * Returns whether calls to <code>add</code> and * <code>setLayout</code> are forwarded to the <code>contentPane</code>. * * @return true if <code>add</code> and <code>setLayout</code> * are forwarded; false otherwise * * @see #addImpl * @see #setLayout * @see #setRootPaneCheckingEnabled * @see javax.swing.RootPaneContainer */ protected boolean isRootPaneCheckingEnabled() { return rootPaneCheckingEnabled; } /** * Sets whether calls to <code>add</code> and * <code>setLayout</code> are forwarded to the <code>contentPane</code>. * * @param enabled true if <code>add</code> and <code>setLayout</code> * are forwarded, false if they should operate directly on the * <code>JFrame</code>. * * @see #addImpl * @see #setLayout * @see #isRootPaneCheckingEnabled * @see javax.swing.RootPaneContainer * @beaninfo * hidden: true * description: Whether the add and setLayout methods are forwarded */ protected void setRootPaneCheckingEnabled(boolean enabled) { rootPaneCheckingEnabled = enabled; } /** * Adds the specified child <code>Component</code>. * This method is overridden to conditionally forward calls to the * <code>contentPane</code>. * By default, children are added to the <code>contentPane</code> instead * of the frame, refer to {@link javax.swing.RootPaneContainer} for * details. * * @param comp the component to be enhanced * @param constraints the constraints to be respected * @param index the index * @exception IllegalArgumentException if <code>index</code> is invalid * @exception IllegalArgumentException if adding the container's parent * to itself * @exception IllegalArgumentException if adding a window to a container * * @see #setRootPaneCheckingEnabled * @see javax.swing.RootPaneContainer */ protected void addImpl(Component comp, Object constraints, int index) { if(isRootPaneCheckingEnabled()) { getContentPane().add(comp, constraints, index); } else { super.addImpl(comp, constraints, index); } } /** * Removes the specified component from the container. If * <code>comp</code> is not the <code>rootPane</code>, this will forward * the call to the <code>contentPane</code>. This will do nothing if * <code>comp</code> is not a child of the <code>JFrame</code> or * <code>contentPane</code>. * * @param comp the component to be removed * @throws NullPointerException if <code>comp</code> is null * @see #add * @see javax.swing.RootPaneContainer */ public void remove(Component comp) { if (comp == rootPane) { super.remove(comp); } else { getContentPane().remove(comp); } } /** * Sets the <code>LayoutManager</code>. * Overridden to conditionally forward the call to the * <code>contentPane</code>. * Refer to {@link javax.swing.RootPaneContainer} for * more information. * * @param manager the <code>LayoutManager</code> * @see #setRootPaneCheckingEnabled * @see javax.swing.RootPaneContainer */ public void setLayout(LayoutManager manager) { if(isRootPaneCheckingEnabled()) { getContentPane().setLayout(manager); } else { super.setLayout(manager); } } /** * Returns the <code>rootPane</code> object for this frame. * @return the <code>rootPane</code> property * * @see #setRootPane * @see RootPaneContainer#getRootPane */ public JRootPane getRootPane() { return rootPane; } /** * Sets the <code>rootPane</code> property. * This method is called by the constructor. * @param root the <code>rootPane</code> object for this frame * * @see #getRootPane * * @beaninfo * hidden: true * description: the RootPane object for this frame. */ protected void setRootPane(JRootPane root) { if(rootPane != null) { remove(rootPane); } rootPane = root; if(rootPane != null) { boolean checkingEnabled = isRootPaneCheckingEnabled(); try { setRootPaneCheckingEnabled(false); add(rootPane, BorderLayout.CENTER); } finally { setRootPaneCheckingEnabled(checkingEnabled); } } } /** * {@inheritDoc} */ public void setIconImage(Image image) { super.setIconImage(image); } /** * Returns the <code>contentPane</code> object for this frame. * @return the <code>contentPane</code> property * * @see #setContentPane * @see RootPaneContainer#getContentPane */ public Container getContentPane() { return getRootPane().getContentPane(); } /** * Sets the <code>contentPane</code> property. * This method is called by the constructor. * <p> * Swing's painting architecture requires an opaque <code>JComponent</code> * in the containment hierarchy. This is typically provided by the * content pane. If you replace the content pane it is recommended you * replace it with an opaque <code>JComponent</code>. * * @param contentPane the <code>contentPane</code> object for this frame * * @exception java.awt.IllegalComponentStateException (a runtime * exception) if the content pane parameter is <code>null</code> * @see #getContentPane * @see RootPaneContainer#setContentPane * @see JRootPane * * @beaninfo * hidden: true * description: The client area of the frame where child * components are normally inserted. */ public void setContentPane(Container contentPane) { getRootPane().setContentPane(contentPane); } /** * Returns the <code>layeredPane</code> object for this frame. * @return the <code>layeredPane</code> property * * @see #setLayeredPane * @see RootPaneContainer#getLayeredPane */ public JLayeredPane getLayeredPane() { return getRootPane().getLayeredPane(); } /** * Sets the <code>layeredPane</code> property. * This method is called by the constructor. * @param layeredPane the <code>layeredPane</code> object for this frame * * @exception java.awt.IllegalComponentStateException (a runtime * exception) if the layered pane parameter is <code>null</code> * @see #getLayeredPane * @see RootPaneContainer#setLayeredPane * * @beaninfo * hidden: true * description: The pane that holds the various frame layers. */ public void setLayeredPane(JLayeredPane layeredPane) { getRootPane().setLayeredPane(layeredPane); } /** * Returns the <code>glassPane</code> object for this frame. * @return the <code>glassPane</code> property * * @see #setGlassPane * @see RootPaneContainer#getGlassPane */ public Component getGlassPane() { return getRootPane().getGlassPane(); } /** * Sets the <code>glassPane</code> property. * This method is called by the constructor. * @param glassPane the <code>glassPane</code> object for this frame * * @see #getGlassPane * @see RootPaneContainer#setGlassPane * * @beaninfo * hidden: true * description: A transparent pane used for menu rendering. */ public void setGlassPane(Component glassPane) { getRootPane().setGlassPane(glassPane); } /** * {@inheritDoc} * * @since 1.6 */ public Graphics getGraphics() { JComponent.getGraphicsInvoked(this); return super.getGraphics(); } /** * Repaints the specified rectangle of this component within * <code>time</code> milliseconds. Refer to <code>RepaintManager</code> * for details on how the repaint is handled. * * @param time maximum time in milliseconds before update * @param x the <i>x</i> coordinate * @param y the <i>y</i> coordinate * @param width the width * @param height the height * @see RepaintManager * @since 1.6 */ public void repaint(long time, int x, int y, int width, int height) { if (RepaintManager.HANDLE_TOP_LEVEL_PAINT) { RepaintManager.currentManager(this).addDirtyRegion( this, x, y, width, height); } else { super.repaint(time, x, y, width, height); } } /** * Provides a hint as to whether or not newly created <code>JFrame</code>s * should have their Window decorations (such as borders, widgets to * close the window, title...) provided by the current look * and feel. If <code>defaultLookAndFeelDecorated</code> is true, * the current <code>LookAndFeel</code> supports providing window * decorations, and the current window manager supports undecorated * windows, then newly created <code>JFrame</code>s will have their * Window decorations provided by the current <code>LookAndFeel</code>. * Otherwise, newly created <code>JFrame</code>s will have their * Window decorations provided by the current window manager. * <p> * You can get the same effect on a single JFrame by doing the following: * <pre> * JFrame frame = new JFrame(); * frame.setUndecorated(true); * frame.getRootPane().setWindowDecorationStyle(JRootPane.FRAME); * </pre> * * @param defaultLookAndFeelDecorated A hint as to whether or not current * look and feel should provide window decorations * @see javax.swing.LookAndFeel#getSupportsWindowDecorations * @since 1.4 */ public static void setDefaultLookAndFeelDecorated(boolean defaultLookAndFeelDecorated) { if (defaultLookAndFeelDecorated) { SwingUtilities.appContextPut(defaultLookAndFeelDecoratedKey, Boolean.TRUE); } else { SwingUtilities.appContextPut(defaultLookAndFeelDecoratedKey, Boolean.FALSE); } } /** * Returns true if newly created <code>JFrame</code>s should have their * Window decorations provided by the current look and feel. This is only * a hint, as certain look and feels may not support this feature. * * @return true if look and feel should provide Window decorations. * @since 1.4 */ public static boolean isDefaultLookAndFeelDecorated() { Boolean defaultLookAndFeelDecorated = (Boolean) SwingUtilities.appContextGet(defaultLookAndFeelDecoratedKey); if (defaultLookAndFeelDecorated == null) { defaultLookAndFeelDecorated = Boolean.FALSE; } return defaultLookAndFeelDecorated.booleanValue(); } /** * Returns a string representation of this <code>JFrame</code>. * This method * is intended to be used only for debugging purposes, and the * content and format of the returned string may vary between * implementations. The returned string may be empty but may not * be <code>null</code>. * * @return a string representation of this <code>JFrame</code> */ protected String paramString() { String defaultCloseOperationString; if (defaultCloseOperation == HIDE_ON_CLOSE) { defaultCloseOperationString = "HIDE_ON_CLOSE"; } else if (defaultCloseOperation == DISPOSE_ON_CLOSE) { defaultCloseOperationString = "DISPOSE_ON_CLOSE"; } else if (defaultCloseOperation == DO_NOTHING_ON_CLOSE) { defaultCloseOperationString = "DO_NOTHING_ON_CLOSE"; } else if (defaultCloseOperation == 3) { defaultCloseOperationString = "EXIT_ON_CLOSE"; } else defaultCloseOperationString = ""; String rootPaneString = (rootPane != null ? rootPane.toString() : ""); String rootPaneCheckingEnabledString = (rootPaneCheckingEnabled ? "true" : "false"); return super.paramString() + ",defaultCloseOperation=" + defaultCloseOperationString + ",rootPane=" + rootPaneString + ",rootPaneCheckingEnabled=" + rootPaneCheckingEnabledString; } ///////////////// // Accessibility support //////////////// /** The accessible context property. */ protected AccessibleContext accessibleContext = null; /** * Gets the AccessibleContext associated with this JFrame. * For JFrames, the AccessibleContext takes the form of an * AccessibleJFrame. * A new AccessibleJFrame instance is created if necessary. * * @return an AccessibleJFrame that serves as the * AccessibleContext of this JFrame */ public AccessibleContext getAccessibleContext() { if (accessibleContext == null) { accessibleContext = new AccessibleJFrame(); } return accessibleContext; } /** * This class implements accessibility support for the * <code>JFrame</code> class. It provides an implementation of the * Java Accessibility API appropriate to frame user-interface * elements. */ protected class AccessibleJFrame extends AccessibleAWTFrame { // AccessibleContext methods /** * Get the accessible name of this object. * * @return the localized name of the object -- can be null if this * object does not have a name */ public String getAccessibleName() { if (accessibleName != null) { return accessibleName; } else { if (getTitle() == null) { return super.getAccessibleName(); } else { return getTitle(); } } } /** * Get the state of this object. * * @return an instance of AccessibleStateSet containing the current * state set of the object * @see AccessibleState */ public AccessibleStateSet getAccessibleStateSet() { AccessibleStateSet states = super.getAccessibleStateSet(); if (isResizable()) { states.add(AccessibleState.RESIZABLE); } if (getFocusOwner() != null) { states.add(AccessibleState.ACTIVE); } // FIXME: [[[WDW - should also return ICONIFIED and ICONIFIABLE // if we can ever figure these out]]] return states; } } // inner class AccessibleJFrame }
13,120
710
<reponame>johncollinsai/post-high-frequency-data # This file is part of Patsy # Copyright (C) 2011-2013 <NAME> <<EMAIL>> # See file LICENSE.txt for license information. # Some generic utilities. __all__ = ["atleast_2d_column_default", "uniqueify_list", "widest_float", "widest_complex", "wide_dtype_for", "widen", "repr_pretty_delegate", "repr_pretty_impl", "SortAnythingKey", "safe_scalar_isnan", "safe_isnan", "iterable", "have_pandas", "have_pandas_categorical", "have_pandas_categorical_dtype", "pandas_Categorical_from_codes", "pandas_Categorical_categories", "pandas_Categorical_codes", "safe_is_pandas_categorical_dtype", "safe_is_pandas_categorical", "safe_issubdtype", "no_pickling", "assert_no_pickling", "safe_string_eq", ] import sys import numpy as np import six from six.moves import cStringIO as StringIO from .compat import optional_dep_ok try: import pandas except ImportError: have_pandas = False else: have_pandas = True # Pandas versions < 0.9.0 don't have Categorical # Can drop this guard whenever we drop support for such older versions of # pandas. have_pandas_categorical = (have_pandas and hasattr(pandas, "Categorical")) if not have_pandas: have_pandas_categorical_dtype = False _pandas_is_categorical_dtype = None else: if hasattr(pandas, "api"): # This is available starting in pandas v0.19.0 have_pandas_categorical_dtype = True _pandas_is_categorical_dtype = pandas.api.types.is_categorical_dtype else: # This is needed for pandas v0.18.0 and earlier _pandas_is_categorical_dtype = getattr(pandas.core.common, "is_categorical_dtype", None) have_pandas_categorical_dtype = (_pandas_is_categorical_dtype is not None) # Passes through Series and DataFrames, call np.asarray() on everything else def asarray_or_pandas(a, copy=False, dtype=None, subok=False): if have_pandas: if isinstance(a, (pandas.Series, pandas.DataFrame)): # The .name attribute on Series is discarded when passing through # the constructor: # https://github.com/pydata/pandas/issues/1578 extra_args = {} if hasattr(a, "name"): extra_args["name"] = a.name return a.__class__(a, copy=copy, dtype=dtype, **extra_args) return np.array(a, copy=copy, dtype=dtype, subok=subok) def test_asarray_or_pandas(): import warnings assert type(asarray_or_pandas([1, 2, 3])) is np.ndarray with warnings.catch_warnings() as w: warnings.filterwarnings('ignore', 'the matrix subclass', PendingDeprecationWarning) assert type(asarray_or_pandas(np.matrix([[1, 2, 3]]))) is np.ndarray assert type(asarray_or_pandas( np.matrix([[1, 2, 3]]), subok=True)) is np.matrix assert w is None a = np.array([1, 2, 3]) assert asarray_or_pandas(a) is a a_copy = asarray_or_pandas(a, copy=True) assert np.array_equal(a, a_copy) a_copy[0] = 100 assert not np.array_equal(a, a_copy) assert np.allclose(asarray_or_pandas([1, 2, 3], dtype=float), [1.0, 2.0, 3.0]) assert asarray_or_pandas([1, 2, 3], dtype=float).dtype == np.dtype(float) a_view = asarray_or_pandas(a, dtype=a.dtype) a_view[0] = 99 assert a[0] == 99 global have_pandas if have_pandas: s = pandas.Series([1, 2, 3], name="A", index=[10, 20, 30]) s_view1 = asarray_or_pandas(s) assert s_view1.name == "A" assert np.array_equal(s_view1.index, [10, 20, 30]) s_view1[10] = 101 assert s[10] == 101 s_copy = asarray_or_pandas(s, copy=True) assert s_copy.name == "A" assert np.array_equal(s_copy.index, [10, 20, 30]) assert np.array_equal(s_copy, s) s_copy[10] = 100 assert not np.array_equal(s_copy, s) assert asarray_or_pandas(s, dtype=float).dtype == np.dtype(float) s_view2 = asarray_or_pandas(s, dtype=s.dtype) assert s_view2.name == "A" assert np.array_equal(s_view2.index, [10, 20, 30]) s_view2[10] = 99 assert s[10] == 99 df = pandas.DataFrame([[1, 2, 3]], columns=["A", "B", "C"], index=[10]) df_view1 = asarray_or_pandas(df) df_view1.loc[10, "A"] = 101 assert np.array_equal(df_view1.columns, ["A", "B", "C"]) assert np.array_equal(df_view1.index, [10]) assert df.loc[10, "A"] == 101 df_copy = asarray_or_pandas(df, copy=True) assert np.array_equal(df_copy, df) assert np.array_equal(df_copy.columns, ["A", "B", "C"]) assert np.array_equal(df_copy.index, [10]) df_copy.loc[10, "A"] = 100 assert not np.array_equal(df_copy, df) df_converted = asarray_or_pandas(df, dtype=float) assert df_converted["A"].dtype == np.dtype(float) assert np.allclose(df_converted, df) assert np.array_equal(df_converted.columns, ["A", "B", "C"]) assert np.array_equal(df_converted.index, [10]) df_view2 = asarray_or_pandas(df, dtype=df["A"].dtype) assert np.array_equal(df_view2.columns, ["A", "B", "C"]) assert np.array_equal(df_view2.index, [10]) # This actually makes a copy, not a view, because of a pandas bug: # https://github.com/pydata/pandas/issues/1572 assert np.array_equal(df, df_view2) # df_view2[0][0] = 99 # assert df[0][0] == 99 had_pandas = have_pandas try: have_pandas = False assert (type(asarray_or_pandas(pandas.Series([1, 2, 3]))) is np.ndarray) assert (type(asarray_or_pandas(pandas.DataFrame([[1, 2, 3]]))) is np.ndarray) finally: have_pandas = had_pandas # Like np.atleast_2d, but this converts lower-dimensional arrays into columns, # instead of rows. It also converts ndarray subclasses into basic ndarrays, # which makes it easier to guarantee correctness. However, there are many # places in the code where we want to preserve pandas indexing information if # present, so there is also an option def atleast_2d_column_default(a, preserve_pandas=False): if preserve_pandas and have_pandas: if isinstance(a, pandas.Series): return pandas.DataFrame(a) elif isinstance(a, pandas.DataFrame): return a # fall through a = np.asarray(a) a = np.atleast_1d(a) if a.ndim <= 1: a = a.reshape((-1, 1)) assert a.ndim >= 2 return a def test_atleast_2d_column_default(): import warnings assert np.all(atleast_2d_column_default([1, 2, 3]) == [[1], [2], [3]]) assert atleast_2d_column_default(1).shape == (1, 1) assert atleast_2d_column_default([1]).shape == (1, 1) assert atleast_2d_column_default([[1]]).shape == (1, 1) assert atleast_2d_column_default([[[1]]]).shape == (1, 1, 1) assert atleast_2d_column_default([1, 2, 3]).shape == (3, 1) assert atleast_2d_column_default([[1], [2], [3]]).shape == (3, 1) with warnings.catch_warnings() as w: warnings.filterwarnings('ignore', 'the matrix subclass', PendingDeprecationWarning) assert type(atleast_2d_column_default(np.matrix(1))) == np.ndarray assert w is None global have_pandas if have_pandas: assert (type(atleast_2d_column_default(pandas.Series([1, 2]))) == np.ndarray) assert (type(atleast_2d_column_default(pandas.DataFrame([[1], [2]]))) == np.ndarray) assert (type(atleast_2d_column_default(pandas.Series([1, 2]), preserve_pandas=True)) == pandas.DataFrame) assert (type(atleast_2d_column_default(pandas.DataFrame([[1], [2]]), preserve_pandas=True)) == pandas.DataFrame) s = pandas.Series([10, 11, 12], name="hi", index=["a", "b", "c"]) df = atleast_2d_column_default(s, preserve_pandas=True) assert isinstance(df, pandas.DataFrame) assert np.all(df.columns == ["hi"]) assert np.all(df.index == ["a", "b", "c"]) with warnings.catch_warnings() as w: warnings.filterwarnings('ignore', 'the matrix subclass', PendingDeprecationWarning) assert (type(atleast_2d_column_default(np.matrix(1), preserve_pandas=True)) == np.ndarray) assert w is None assert (type(atleast_2d_column_default([1, 2, 3], preserve_pandas=True)) == np.ndarray) if have_pandas: had_pandas = have_pandas try: have_pandas = False assert (type(atleast_2d_column_default(pandas.Series([1, 2]), preserve_pandas=True)) == np.ndarray) assert (type(atleast_2d_column_default(pandas.DataFrame([[1], [2]]), preserve_pandas=True)) == np.ndarray) finally: have_pandas = had_pandas # A version of .reshape() that knows how to down-convert a 1-column # pandas.DataFrame into a pandas.Series. Useful for code that wants to be # agnostic between 1d and 2d data, with the pattern: # new_a = atleast_2d_column_default(a, preserve_pandas=True) # # do stuff to new_a, which can assume it's always 2 dimensional # return pandas_friendly_reshape(new_a, a.shape) def pandas_friendly_reshape(a, new_shape): if not have_pandas: return a.reshape(new_shape) if not isinstance(a, pandas.DataFrame): return a.reshape(new_shape) # we have a DataFrame. Only supported reshapes are no-op, and # single-column DataFrame -> Series. if new_shape == a.shape: return a if len(new_shape) == 1 and a.shape[1] == 1: if new_shape[0] != a.shape[0]: raise ValueError("arrays have incompatible sizes") return a[a.columns[0]] raise ValueError("cannot reshape a DataFrame with shape %s to shape %s" % (a.shape, new_shape)) def test_pandas_friendly_reshape(): import pytest global have_pandas assert np.allclose(pandas_friendly_reshape(np.arange(10).reshape(5, 2), (2, 5)), np.arange(10).reshape(2, 5)) if have_pandas: df = pandas.DataFrame({"x": [1, 2, 3]}, index=["a", "b", "c"]) noop = pandas_friendly_reshape(df, (3, 1)) assert isinstance(noop, pandas.DataFrame) assert np.array_equal(noop.index, ["a", "b", "c"]) assert np.array_equal(noop.columns, ["x"]) squozen = pandas_friendly_reshape(df, (3,)) assert isinstance(squozen, pandas.Series) assert np.array_equal(squozen.index, ["a", "b", "c"]) assert squozen.name == "x" pytest.raises(ValueError, pandas_friendly_reshape, df, (4,)) pytest.raises(ValueError, pandas_friendly_reshape, df, (1, 3)) pytest.raises(ValueError, pandas_friendly_reshape, df, (3, 3)) had_pandas = have_pandas try: have_pandas = False # this will try to do a reshape directly, and DataFrames *have* no # reshape method pytest.raises(AttributeError, pandas_friendly_reshape, df, (3,)) finally: have_pandas = had_pandas def uniqueify_list(seq): seq_new = [] seen = set() for obj in seq: if obj not in seen: seq_new.append(obj) seen.add(obj) return seq_new def test_to_uniqueify_list(): assert uniqueify_list([1, 2, 3]) == [1, 2, 3] assert uniqueify_list([1, 3, 3, 2, 3, 1]) == [1, 3, 2] assert uniqueify_list([3, 2, 1, 4, 1, 2, 3]) == [3, 2, 1, 4] for float_type in ("float128", "float96", "float64"): if hasattr(np, float_type): widest_float = getattr(np, float_type) break else: # pragma: no cover assert False for complex_type in ("complex256", "complex196", "complex128"): if hasattr(np, complex_type): widest_complex = getattr(np, complex_type) break else: # pragma: no cover assert False def wide_dtype_for(arr): arr = np.asarray(arr) if (safe_issubdtype(arr.dtype, np.integer) or safe_issubdtype(arr.dtype, np.floating)): return widest_float elif safe_issubdtype(arr.dtype, np.complexfloating): return widest_complex raise ValueError("cannot widen a non-numeric type %r" % (arr.dtype,)) def widen(arr): return np.asarray(arr, dtype=wide_dtype_for(arr)) def test_wide_dtype_for_and_widen(): assert np.allclose(widen([1, 2, 3]), [1, 2, 3]) assert widen([1, 2, 3]).dtype == widest_float assert np.allclose(widen([1.0, 2.0, 3.0]), [1, 2, 3]) assert widen([1.0, 2.0, 3.0]).dtype == widest_float assert np.allclose(widen([1+0j, 2, 3]), [1, 2, 3]) assert widen([1+0j, 2, 3]).dtype == widest_complex import pytest pytest.raises(ValueError, widen, ["hi"]) class PushbackAdapter(object): def __init__(self, it): self._it = it self._pushed = [] def __iter__(self): return self def push_back(self, obj): self._pushed.append(obj) def next(self): if self._pushed: return self._pushed.pop() else: # May raise StopIteration return six.advance_iterator(self._it) __next__ = next def peek(self): try: obj = six.advance_iterator(self) except StopIteration: raise ValueError("no more data") self.push_back(obj) return obj def has_more(self): try: self.peek() except ValueError: return False else: return True def test_PushbackAdapter(): it = PushbackAdapter(iter([1, 2, 3, 4])) assert it.has_more() assert six.advance_iterator(it) == 1 it.push_back(0) assert six.advance_iterator(it) == 0 assert six.advance_iterator(it) == 2 assert it.peek() == 3 it.push_back(10) assert it.peek() == 10 it.push_back(20) assert it.peek() == 20 assert it.has_more() assert list(it) == [20, 10, 3, 4] assert not it.has_more() # The IPython pretty-printer gives very nice output that is difficult to get # otherwise, e.g., look how much more readable this is than if it were all # smooshed onto one line: # # ModelDesc(input_code='y ~ x*asdf', # lhs_terms=[Term([EvalFactor('y')])], # rhs_terms=[Term([]), # Term([EvalFactor('x')]), # Term([EvalFactor('asdf')]), # Term([EvalFactor('x'), EvalFactor('asdf')])], # ) # # But, we don't want to assume it always exists; nor do we want to be # re-writing every repr function twice, once for regular repr and once for # the pretty printer. So, here's an ugly fallback implementation that can be # used unconditionally to implement __repr__ in terms of _pretty_repr_. # # Pretty printer docs: # http://ipython.org/ipython-doc/dev/api/generated/IPython.lib.pretty.html class _MiniPPrinter(object): def __init__(self): self._out = StringIO() self.indentation = 0 def text(self, text): self._out.write(text) def breakable(self, sep=" "): self._out.write(sep) def begin_group(self, _, text): self.text(text) def end_group(self, _, text): self.text(text) def pretty(self, obj): if hasattr(obj, "_repr_pretty_"): obj._repr_pretty_(self, False) else: self.text(repr(obj)) def getvalue(self): return self._out.getvalue() def _mini_pretty(obj): printer = _MiniPPrinter() printer.pretty(obj) return printer.getvalue() def repr_pretty_delegate(obj): # If IPython is already loaded, then might as well use it. (Most commonly # this will occur if we are in an IPython session, but somehow someone has # called repr() directly. This can happen for example if printing an # container like a namedtuple that IPython lacks special code for # pretty-printing.) But, if IPython is not already imported, we do not # attempt to import it. This makes patsy itself faster to import (as of # Nov. 2012 I measured the extra overhead from loading IPython as ~4 # seconds on a cold cache), it prevents IPython from automatically # spawning a bunch of child processes (!) which may not be what you want # if you are not otherwise using IPython, and it avoids annoying the # pandas people who have some hack to tell whether you are using IPython # in their test suite (see patsy bug #12). if optional_dep_ok and "IPython" in sys.modules: from IPython.lib.pretty import pretty return pretty(obj) else: return _mini_pretty(obj) def repr_pretty_impl(p, obj, args, kwargs=[]): name = obj.__class__.__name__ p.begin_group(len(name) + 1, "%s(" % (name,)) started = [False] def new_item(): if started[0]: p.text(",") p.breakable() started[0] = True for arg in args: new_item() p.pretty(arg) for label, value in kwargs: new_item() p.begin_group(len(label) + 1, "%s=" % (label,)) p.pretty(value) p.end_group(len(label) + 1, "") p.end_group(len(name) + 1, ")") def test_repr_pretty(): assert repr_pretty_delegate("asdf") == "'asdf'" printer = _MiniPPrinter() class MyClass(object): pass repr_pretty_impl(printer, MyClass(), ["a", 1], [("foo", "bar"), ("asdf", "asdf")]) assert printer.getvalue() == "MyClass('a', 1, foo='bar', asdf='asdf')" # In Python 3, objects of different types are not generally comparable, so a # list of heterogeneous types cannot be sorted. This implements a Python 2 # style comparison for arbitrary types. (It works on Python 2 too, but just # gives you the built-in ordering.) To understand why this is tricky, consider # this example: # a = 1 # type 'int' # b = 1.5 # type 'float' # class gggg: # pass # c = gggg() # sorted([a, b, c]) # The fallback ordering sorts by class name, so according to the fallback # ordering, we have b < c < a. But, of course, a and b are comparable (even # though they're of different types), so we also have a < b. This is # inconsistent. There is no general solution to this problem (which I guess is # why Python 3 stopped trying), but the worst offender is all the different # "numeric" classes (int, float, complex, decimal, rational...), so as a # special-case, we sort all numeric objects to the start of the list. # (In Python 2, there is also a similar special case for str and unicode, but # we don't have to worry about that for Python 3.) class SortAnythingKey(object): def __init__(self, obj): self.obj = obj def _python_lt(self, other_obj): # On Py2, < never raises an error, so this is just <. (Actually it # does raise a TypeError for comparing complex to numeric, but not for # comparisons of complex to other types. Sigh. Whatever.) # On Py3, this returns a bool if available, and otherwise returns # NotImplemented try: return self.obj < other_obj except TypeError: return NotImplemented def __lt__(self, other): assert isinstance(other, SortAnythingKey) result = self._python_lt(other.obj) if result is not NotImplemented: return result # Okay, that didn't work, time to fall back. # If one of these is a number, then it is smaller. if self._python_lt(0) is not NotImplemented: return True if other._python_lt(0) is not NotImplemented: return False # Also check ==, since it may well be defined for otherwise # unorderable objects, and if so then we should be consistent with # it: if self.obj == other.obj: return False # Otherwise, we break ties based on class name and memory position return ((self.obj.__class__.__name__, id(self.obj)) < (other.obj.__class__.__name__, id(other.obj))) def test_SortAnythingKey(): assert sorted([20, 10, 0, 15], key=SortAnythingKey) == [0, 10, 15, 20] assert sorted([10, -1.5], key=SortAnythingKey) == [-1.5, 10] assert sorted([10, "a", 20.5, "b"], key=SortAnythingKey) == [10, 20.5, "a", "b"] class a(object): pass class b(object): pass class z(object): pass a_obj = a() b_obj = b() z_obj = z() o_obj = object() assert (sorted([z_obj, a_obj, 1, b_obj, o_obj], key=SortAnythingKey) == [1, a_obj, b_obj, o_obj, z_obj]) # NaN checking functions that work on arbitrary objects, on old Python # versions (math.isnan is only in 2.6+), etc. def safe_scalar_isnan(x): try: return np.isnan(float(x)) except (TypeError, ValueError, NotImplementedError): return False safe_isnan = np.vectorize(safe_scalar_isnan, otypes=[bool]) def test_safe_scalar_isnan(): assert not safe_scalar_isnan(True) assert not safe_scalar_isnan(None) assert not safe_scalar_isnan("sadf") assert not safe_scalar_isnan((1, 2, 3)) assert not safe_scalar_isnan(np.asarray([1, 2, 3])) assert not safe_scalar_isnan([np.nan]) assert safe_scalar_isnan(np.nan) assert safe_scalar_isnan(np.float32(np.nan)) assert safe_scalar_isnan(float(np.nan)) def test_safe_isnan(): assert np.array_equal(safe_isnan([1, True, None, np.nan, "asdf"]), [False, False, False, True, False]) assert safe_isnan(np.nan).ndim == 0 assert safe_isnan(np.nan) assert not safe_isnan(None) # raw isnan raises a *different* error for strings than for objects: assert not safe_isnan("asdf") def iterable(obj): try: iter(obj) except Exception: return False return True def test_iterable(): assert iterable("asdf") assert iterable([]) assert iterable({"a": 1}) assert not iterable(1) assert not iterable(iterable) ##### Handling Pandas's categorical stuff is horrible and hateful # Basically they decided that they didn't like how numpy does things, so their # categorical stuff is *kinda* like how numpy would do it (e.g. they have a # special ".dtype" attribute to mark categorical data), so by default you'll # find yourself using the same code paths to handle pandas categorical data # and other non-categorical data. BUT, all the idioms for detecting # categorical data blow up with errors if you try them with real numpy dtypes, # and all numpy's idioms for detecting non-categorical types blow up with # errors if you try them with pandas categorical stuff. So basically they have # just poisoned all code that touches dtypes; the old numpy stuff is unsafe, # and you must use special code like below. # # Also there are hoops to jump through to handle both the old style # (Categorical objects) and new-style (Series with dtype="category"). # Needed to support pandas < 0.15 def pandas_Categorical_from_codes(codes, categories): assert have_pandas_categorical # Old versions of pandas sometimes fail to coerce this to an array and # just return it directly from .labels (?!). codes = np.asarray(codes) if hasattr(pandas.Categorical, "from_codes"): return pandas.Categorical.from_codes(codes, categories) else: return pandas.Categorical(codes, categories) def test_pandas_Categorical_from_codes(): if not have_pandas_categorical: return c = pandas_Categorical_from_codes([1, 1, 0, -1], ["a", "b"]) assert np.all(np.asarray(c)[:-1] == ["b", "b", "a"]) assert np.isnan(np.asarray(c)[-1]) # Needed to support pandas < 0.15 def pandas_Categorical_categories(cat): # In 0.15+, a categorical Series has a .cat attribute which is similar to # a Categorical object, and Categorical objects are what have .categories # and .codes attributes. if hasattr(cat, "cat"): cat = cat.cat if hasattr(cat, "categories"): return cat.categories else: return cat.levels # Needed to support pandas < 0.15 def pandas_Categorical_codes(cat): # In 0.15+, a categorical Series has a .cat attribute which is a # Categorical object, and Categorical objects are what have .categories / # .codes attributes. if hasattr(cat, "cat"): cat = cat.cat if hasattr(cat, "codes"): return cat.codes else: return cat.labels def test_pandas_Categorical_accessors(): if not have_pandas_categorical: return c = pandas_Categorical_from_codes([1, 1, 0, -1], ["a", "b"]) assert np.all(pandas_Categorical_categories(c) == ["a", "b"]) assert np.all(pandas_Categorical_codes(c) == [1, 1, 0, -1]) if have_pandas_categorical_dtype: s = pandas.Series(c) assert np.all(pandas_Categorical_categories(s) == ["a", "b"]) assert np.all(pandas_Categorical_codes(s) == [1, 1, 0, -1]) # Needed to support pandas >= 0.15 (!) def safe_is_pandas_categorical_dtype(dt): if not have_pandas_categorical_dtype: return False return _pandas_is_categorical_dtype(dt) # Needed to support pandas >= 0.15 (!) def safe_is_pandas_categorical(data): if not have_pandas_categorical: return False if isinstance(data, pandas.Categorical): return True if hasattr(data, "dtype"): return safe_is_pandas_categorical_dtype(data.dtype) return False def test_safe_is_pandas_categorical(): assert not safe_is_pandas_categorical(np.arange(10)) if have_pandas_categorical: c_obj = pandas.Categorical(["a", "b"]) assert safe_is_pandas_categorical(c_obj) if have_pandas_categorical_dtype: s_obj = pandas.Series(["a", "b"], dtype="category") assert safe_is_pandas_categorical(s_obj) # Needed to support pandas >= 0.15 (!) # Calling np.issubdtype on a pandas categorical will blow up -- the officially # recommended solution is to replace every piece of code like # np.issubdtype(foo.dtype, bool) # with code like # isinstance(foo.dtype, np.dtype) and np.issubdtype(foo.dtype, bool) # or # not pandas.is_categorical_dtype(foo.dtype) and issubdtype(foo.dtype, bool) # We do the latter (with extra hoops) because the isinstance check is not # safe. See # https://github.com/pydata/pandas/issues/9581 # https://github.com/pydata/pandas/issues/9581#issuecomment-77099564 def safe_issubdtype(dt1, dt2): if safe_is_pandas_categorical_dtype(dt1): return False return np.issubdtype(dt1, dt2) def test_safe_issubdtype(): assert safe_issubdtype(int, np.integer) assert safe_issubdtype(np.dtype(float), np.floating) assert not safe_issubdtype(int, np.floating) assert not safe_issubdtype(np.dtype(float), np.integer) if have_pandas_categorical_dtype: bad_dtype = pandas.Series(["a", "b"], dtype="category") assert not safe_issubdtype(bad_dtype, np.integer) def no_pickling(*args, **kwargs): raise NotImplementedError( "Sorry, pickling not yet supported. " "See https://github.com/pydata/patsy/issues/26 if you want to " "help.") def assert_no_pickling(obj): import pickle import pytest pytest.raises(NotImplementedError, pickle.dumps, obj) # Use like: # if safe_string_eq(constraints, "center"): # ... # where 'constraints' might be a string or an array. (If it's an array, then # we can't use == becaues it might broadcast and ugh.) def safe_string_eq(obj, value): if isinstance(obj, six.string_types): return obj == value else: return False def test_safe_string_eq(): assert safe_string_eq("foo", "foo") assert not safe_string_eq("foo", "bar") if not six.PY3: assert safe_string_eq(unicode("foo"), "foo") assert not safe_string_eq(np.empty((2, 2)), "foo")
12,701
1,670
<reponame>developer-guy/go-gitlab<gh_stars>1000+ { "event_name": "group_rename", "created_at": "2017-10-30T15:09:00Z", "updated_at": "2017-11-01T10:23:52Z", "name": "<NAME>", "path": "better-name", "full_path": "parent-group/better-name", "group_id": 64, "owner_name": null, "owner_email": null, "old_path": "old-name", "old_full_path": "parent-group/old-name" }
173
355
package com.github.lindenb.jvarkit.tools.bam2graphics; import java.io.IOException; import java.nio.file.Path; import java.util.ArrayList; import java.util.List; import org.testng.Assert; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import com.github.lindenb.jvarkit.tests.AlsoTest; import com.github.lindenb.jvarkit.tools.tests.TestSupport; import com.github.lindenb.jvarkit.util.jcommander.LauncherTest; @AlsoTest(LauncherTest.class) public class Bam2RasterTest { private final TestSupport support = new TestSupport(); @DataProvider(name="rf_regions") public Object[][] getDataRegions() throws IOException { return new Object[][] { {"RF01:1-100"}, {"RF02:1-100"}, {"RF03:1-100"} } ; } private void run(final String rgn,Path out) throws IOException{ final List<String> args= new ArrayList<>(); args.add("-R"); args.add(support.resource("rotavirus_rf.fa")); args.add("-r"); args.add(rgn); args.add("-o"); args.add(out.toString()); for(int i=1;i<=5;i++) args.add(support.resource("S"+i+".bam")); Assert.assertEquals(new Bam2Raster().instanceMain(args),0); } @Test(dataProvider="rf_regions") public void test01(final String rgn) throws IOException { try { final Path imgOut = support.createTmpPath(".png"); run(rgn,imgOut); support.assertIsNotEmpty(imgOut); } finally { support.removeTmpFiles(); } } @Test(dataProvider="rf_regions") public void testZip(final String rgn) throws IOException { try { final Path imgOut = support.createTmpPath(".zip"); run(rgn,imgOut); support.assertZip(imgOut); } finally { support.removeTmpFiles(); } } }
658
7,857
<reponame>sharingcookies/nodegui<gh_stars>1000+ #pragma once #include <QTextEdit> #include "Extras/Export/export.h" #include "QtWidgets/QTextEdit/qtextedit_macro.h" #include "core/NodeWidget/nodewidget.h" class DLL_EXPORT NTextEdit : public QTextEdit, public NodeWidget { Q_OBJECT NODEWIDGET_IMPLEMENTATIONS(QTextEdit) public: using QTextEdit::QTextEdit; // inherit all constructors of QTextEdit virtual void connectSignalsToEventEmitter() { QTEXTEDIT_SIGNALS // Qt Connects: Implement all signal connects here } };
197
2,962
<filename>storio-sqlite/src/test/java/com/pushtorefresh/storio3/sqlite/design/ExecuteSQLOperationDesignTest.java package com.pushtorefresh.storio3.sqlite.design; import com.pushtorefresh.storio3.sqlite.queries.RawQuery; import org.junit.Test; import io.reactivex.Flowable; import static io.reactivex.BackpressureStrategy.MISSING; public class ExecuteSQLOperationDesignTest extends OperationDesignTest { @Test public void execSqlBlocking() { Object nothing = storIOSQLite() .executeSQL() .withQuery(RawQuery.builder() .query("ALTER TABLE users ...") .build()) .prepare() .executeAsBlocking(); } @Test public void execSqlAsRxFlowable() { Flowable<Object> flowable = storIOSQLite() .executeSQL() .withQuery(RawQuery.builder() .query("DROP TABLE users") .build()) .prepare() .asRxFlowable(MISSING); } }
529
437
<reponame>yangzhongchao1011/MMM-Remote-Control { "TITLE": "Menú Magic Mirror", "EDIT_MENU_NAME": "Editar Vista", "SHUTDOWN_MENU_NAME": "Encendre/Apagar", "CONFIGURE_MENU_NAME": "Editar config.js", "VIEW_MIRROR": "MagicMirror<sup>2</sup>", "BACK": "Endarrera", "BRIGHTNESS": "Brillantor", "REFRESHMM" : "Recarregar Navegador", "MONITOROFF": "Apagar monitor", "MONITORON": "Encendre monitor", "MONITORTIMED": "Encendre monitor breument", "RESTART": "Reiniciar RPi", "RESTARTMM": "Recarregar MagicMirror<sup>2</sup>", "SHUTDOWN": "Apagar RPi", "FULLSCREEN": "Pantalla sencera", "MINIMIZE": "Minimitzar Navegador", "DEVTOOLS": "Obrir Eines per desenvolupadors", "SHOWALL": "Mostrar Tots", "HIDEALL": "Amagar Tots", "ADD_MODULE": "Afegir mòdul", "SEARCH": "Buscar &hellip;", "INSTALLED": "Instal.lat", "DOWNLOAD": "Descarrega", "DOWNLOADING": "Descarregant &hellip;", "CODE_LINK": "Veure còdig", "BY": "per", "ADD_THIS": "Afegir aquest mòdul", "HELP": "Veure Readme", "MENU": "Menú", "RESET": "Reset", "NO_HEADER": "(sense capcelera)", "NO_POSITION": "(invisible)", "ADD_ENTRY": "Afegir entrada", "NEW_ENTRY_NAME": "(nom de la nova entrada)", "DELETE_ENTRY": "Esborrar", "UNSAVED_CHANGES": "Canvis sense guardar", "OK": "Ok", "DISCARD": "Descartar canvis", "CANCEL": "Cancel.lar", "NO_MODULES_LOADED": "No hi han móduls carregats.", "SAVE": "Guardar", "EXPERIMENTAL": "Aquesta es una funciò experimental, pot corrompre el teu arxiu config. Fes còpia de seguretat primer, per si de cas!<br>Vols continuar?", "PANIC": "No m'importa.", "NO_RISK_NO_FUN": "Qui no arrisca no pisca!", "CONFIRM_SHUTDOWN": "El sistema s'apagarà.", "CONFIRM_RESTART": "El sistema es recarregarà.", "LOAD_ERROR": "Si ves este mensaje, un error ha ocurrido cargando el archivo javascript. Si us plau, revisa aquest enllaç per veure si es un problema amb el teu navegador:", "ISSUE_LINK": "Pàgina de problemes de Github", "DONE": "Fet.", "ERROR": "Error!", "LOADING": "Carregant &hellip;", "LOCKSTRING_WARNING": "Aquest mòdul ha estat ocultat per LIST_OF_MODULES, no pot ser mostrat.", "FORCE_SHOW": "Fes-ho igualment.", "UPDATE_MENU_NAME" : "Actualitzacions", "UPDATEMM" : "Actualitza MagicMirror<sup>2</sup>", "UPDATE_AVAILABLE" : "Actualitzaciò disponible", "ALERT_MENU_NAME" : "Alertes / Notificacions", "SENDALERT" : "Envia alerta", "HIDEALERT" : "Oculta alerta", "FORM_TYPE" : "Tipus:", "FORM_ALERT" : "Alerta", "FORM_NOTIFICATION" : "Notificaciò", "FORM_TITLE" : "Títol:", "FORM_TITLE_PLACEHOLDER" : "Introdueix títol...", "FORM_MESSAGE" : "Missatge:", "FORM_MESSAGE_PLACEHOLDER" : "Introdueix missatge...", "FORM_SECONDS" : "Segons:", "RESPONSE_ERROR": "No ha funcionat. Comprova els MM logs per més detalls", "MODULE_CONTROLS": "Controls de mòduls", "CUSTOM_MENU": "El meu Menú Personalitzat" }
1,436
1,179
<filename>example/shippingindex_demo.py # encoding: UTF-8 from opendatatools import shippingindex if __name__ == "__main__": df, msg = shippingindex.get_index_list() print(df) for index, row in df.iterrows(): code = row['index'] df_data, msg = shippingindex.get_index_data(code) print(df_data)
136
347
package org.ovirt.engine.ui.common.uicommon.model; import java.util.List; import org.ovirt.engine.ui.uicommonweb.models.SearchableListModel; /** * Provider of {@link SearchableListModel} instances. * * @param <T> * List model item type. * @param <M> * List model type. */ public interface SearchableModelProvider<T, M extends SearchableListModel> extends ModelProvider<M> { /** * Updates the item selection of the model. * @param items The list of items to select. */ void setSelectedItems(List<T> items); /** * Implement this method if you wish to do anything additional when manually refreshing. */ void onManualRefresh(); }
249
471
import logging from datetime import datetime import attr from nose.tools import nottest from nose.plugins import Plugin import dimagi.utils.couch from dimagi.utils.couch.cache.cache_core import get_redis_client from ..locks import TestRedisClient log = logging.getLogger(__name__) class RedisLockTimeoutPlugin(Plugin): """A plugin that causes blocking redis locks to error on lock timeout""" name = "test-redis-locks" enabled = True def configure(self, options, conf): """Do not call super (always enabled)""" self.get_client = TestRedisClient(get_test_lock) def begin(self): """Patch redis client used for locks before any tests are run The patch will remain in effect for the duration of the test process. Tests (e.g., using `reentrant_redis_locks`) may override this patch temporarily on an as-needed basis. """ dimagi.utils.couch.get_redis_client = self.get_client def stopTest(self, case): get = dimagi.utils.couch.get_redis_client assert get == self.get_client, f"redis client patch broke ({get})" @nottest def get_test_lock(key, **kw): timeout = kw["timeout"] lock = get_redis_client().lock(key, **kw) return TestLock(key, lock, timeout) @attr.s class TestLock: name = attr.ib() lock = attr.ib(repr=False) timeout = attr.ib() def acquire(self, **kw): start = datetime.now() log.info("acquire %s", self) try: return self.lock.acquire(**kw) finally: elapsed = datetime.now() - start if elapsed.total_seconds() > self.timeout / 2: self.release() raise TimeoutError(f"locked for {elapsed} (timeout={self.timeout}s)") def release(self): log.info("release %s", self) self.lock.release() def __enter__(self): self.acquire(blocking=True) def __exit__(self, *exc_info): self.release() class TimeoutError(Exception): """Error raised when lock timeout is approached during tests"""
820
3,651
<reponame>aberdev/orientdb package com.orientechnologies.orient.core.metadata.security; import org.junit.Assert; import org.junit.Test; public class OSecurityResourceTest { @Test public void testParse() { Assert.assertEquals( OSecurityResourceClass.ALL_CLASSES, OSecurityResource.parseResource("database.class.*")); Assert.assertEquals( OSecurityResourceProperty.ALL_PROPERTIES, OSecurityResource.parseResource("database.class.*.*")); Assert.assertEquals( OSecurityResourceCluster.ALL_CLUSTERS, OSecurityResource.parseResource("database.cluster.*")); Assert.assertEquals( OSecurityResourceFunction.ALL_FUNCTIONS, OSecurityResource.parseResource("database.function.*")); Assert.assertTrue( OSecurityResource.parseResource("database.class.Person") instanceof OSecurityResourceClass); Assert.assertEquals( "Person", ((OSecurityResourceClass) OSecurityResource.parseResource("database.class.Person")) .getClassName()); Assert.assertTrue( OSecurityResource.parseResource("database.class.Person.name") instanceof OSecurityResourceProperty); Assert.assertEquals( "Person", ((OSecurityResourceProperty) OSecurityResource.parseResource("database.class.Person.name")) .getClassName()); Assert.assertEquals( "name", ((OSecurityResourceProperty) OSecurityResource.parseResource("database.class.Person.name")) .getPropertyName()); Assert.assertTrue( OSecurityResource.parseResource("database.class.*.name") instanceof OSecurityResourceProperty); Assert.assertTrue( OSecurityResource.parseResource("database.cluster.person") instanceof OSecurityResourceCluster); Assert.assertEquals( "person", ((OSecurityResourceCluster) OSecurityResource.parseResource("database.cluster.person")) .getClusterName()); Assert.assertTrue( OSecurityResource.parseResource("database.function.foo") instanceof OSecurityResourceFunction); Assert.assertEquals( OSecurityResourceDatabaseOp.BYPASS_RESTRICTED, OSecurityResource.parseResource("database.bypassRestricted")); Assert.assertEquals( OSecurityResourceDatabaseOp.COMMAND, OSecurityResource.parseResource("database.command")); Assert.assertEquals( OSecurityResourceDatabaseOp.COMMAND_GREMLIN, OSecurityResource.parseResource("database.command.gremlin")); Assert.assertEquals( OSecurityResourceDatabaseOp.COPY, OSecurityResource.parseResource("database.copy")); Assert.assertEquals( OSecurityResourceDatabaseOp.CREATE, OSecurityResource.parseResource("database.create")); Assert.assertEquals( OSecurityResourceDatabaseOp.DB, OSecurityResource.parseResource("database")); Assert.assertEquals( OSecurityResourceDatabaseOp.DROP, OSecurityResource.parseResource("database.drop")); Assert.assertEquals( OSecurityResourceDatabaseOp.EXISTS, OSecurityResource.parseResource("database.exists")); Assert.assertEquals( OSecurityResourceDatabaseOp.FREEZE, OSecurityResource.parseResource("database.freeze")); Assert.assertEquals( OSecurityResourceDatabaseOp.PASS_THROUGH, OSecurityResource.parseResource("database.passthrough")); Assert.assertEquals( OSecurityResourceDatabaseOp.RELEASE, OSecurityResource.parseResource("database.release")); Assert.assertEquals( OSecurityResourceDatabaseOp.HOOK_RECORD, OSecurityResource.parseResource("database.hook.record")); Assert.assertNotEquals( OSecurityResourceDatabaseOp.DB, OSecurityResource.parseResource("database.command")); Assert.assertEquals( OSecurityResourceServerOp.SERVER, OSecurityResource.parseResource("server")); Assert.assertEquals( OSecurityResourceServerOp.REMOVE, OSecurityResource.parseResource("server.remove")); Assert.assertEquals( OSecurityResourceServerOp.STATUS, OSecurityResource.parseResource("server.status")); Assert.assertEquals( OSecurityResourceServerOp.ADMIN, OSecurityResource.parseResource("server.admin")); try { OSecurityResource.parseResource("database.class.person.foo.bar"); Assert.fail(); } catch (Exception e) { } try { OSecurityResource.parseResource("database.cluster.person.foo"); Assert.fail(); } catch (Exception e) { } try { OSecurityResource.parseResource("database.function.foo.bar"); Assert.fail(); } catch (Exception e) { } try { OSecurityResource.parseResource("database.foo"); Assert.fail(); } catch (Exception e) { } try { OSecurityResource.parseResource("server.foo"); Assert.fail(); } catch (Exception e) { } } @Test public void testCache() { OSecurityResource person = OSecurityResource.getInstance("database.class.Person"); OSecurityResource person2 = OSecurityResource.getInstance("database.class.Person"); Assert.assertTrue(person == person2); } }
1,871
619
<reponame>moredu/upm /* * Authors: <NAME> <<EMAIL>> * <NAME> <<EMAIL>> * Copyright (c) 2014 Intel Corporation. * * This program and the accompanying materials are made available under the * terms of the The MIT License which is available at * https://opensource.org/licenses/MIT. * * SPDX-License-Identifier: MIT */ #include <iostream> #include <string> #include <stdexcept> #include <stdlib.h> #include <time.h> #include "stepmotor.hpp" using namespace upm; using namespace std; StepMotor::StepMotor (int dirPin, int stePin, int steps, int enPin) : m_dirPinCtx(dirPin), m_stePinCtx(stePin), m_enPinCtx(0), m_steps(steps) { m_name = "StepMotor"; setSpeed(60); setPosition(0); if (m_dirPinCtx.dir(mraa::DIR_OUT) != mraa::SUCCESS) { throw std::runtime_error(string(__FUNCTION__) + ": Could not initialize dirPin as output"); return; } m_dirPinCtx.write(0); if (m_stePinCtx.dir(mraa::DIR_OUT) != mraa::SUCCESS) { throw std::runtime_error(string(__FUNCTION__) + ": Could not initialize stePin as output"); return; } m_stePinCtx.write(0); if (enPin >= 0) { m_enPinCtx = new mraa::Gpio(enPin); if(m_enPinCtx->dir(mraa::DIR_OUT) != mraa::SUCCESS) { throw std::runtime_error(string(__FUNCTION__) + ": Could not initialize enPin as output"); return; } enable(true); } } StepMotor::~StepMotor () { if (m_enPinCtx) delete m_enPinCtx; } void StepMotor::enable (bool flag) { if (m_enPinCtx) { m_enPinCtx->write(flag); } else { throw std::runtime_error(string(__FUNCTION__) + ": Enable pin not defined"); } } void StepMotor::setSpeed (int speed) { if (speed > 0) { m_delay = 60000000 / (speed * m_steps); } else { throw std::invalid_argument(string(__FUNCTION__) + ": Parameter must be greater than 0"); } } mraa::Result StepMotor::step (int ticks) { if (ticks < 0) { return stepBackward(abs(ticks)); } else { return stepForward(ticks); } } mraa::Result StepMotor::stepForward (int ticks) { dirForward(); for (int i = 0; i < ticks; i++) { move(); m_position++; delayus(m_delay - MINPULSE_US - OVERHEAD_US); } return mraa::SUCCESS; } mraa::Result StepMotor::stepBackward (int ticks) { dirBackward(); for (int i = 0; i < ticks; i++) { move(); m_position--; delayus(m_delay - MINPULSE_US - OVERHEAD_US); } return mraa::SUCCESS; } void StepMotor::setPosition (int pos) { m_position = pos; } int StepMotor::getPosition () { return m_position; } int StepMotor::getStep () { return m_position < 0 ? m_steps + m_position % m_steps : m_position % m_steps; } void StepMotor::move () { m_stePinCtx.write(1); delayus(MINPULSE_US); m_stePinCtx.write(0); } mraa::Result StepMotor::dirForward () { mraa::Result error = m_dirPinCtx.write(HIGH); if (error != mraa::SUCCESS) { throw std::runtime_error(string(__FUNCTION__) + ": Could not write to dirPin"); } return error; } mraa::Result StepMotor::dirBackward () { mraa::Result error = m_dirPinCtx.write(LOW); if (error != mraa::SUCCESS) { throw std::runtime_error(string(__FUNCTION__) + ": Could not write to dirPin"); } return error; } void upm::StepMotor::delayus (int us) { int diff = 0; struct timespec gettime_now; clock_gettime(CLOCK_REALTIME, &gettime_now); int start = gettime_now.tv_nsec; while (diff < us * 1000) { clock_gettime(CLOCK_REALTIME, &gettime_now); diff = gettime_now.tv_nsec - start; if (diff < 0) diff += 1000000000; } }
2,026
728
tpl_dict = { 'meta_docstring': 'with jupyter wigets', 'html_header': r""" {%- if "widgets" in nb.metadata -%} <script src="https://unpkg.com/[email protected].*/dist/embed.js"></script> {%- endif-%} <script src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.1.10/require.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script> """, 'html_footer': r""" {% set mimetype = 'application/vnd.jupyter.widget-state+json'%} {% if mimetype in nb.metadata.get("widgets",{})%} <script type="{{ mimetype }}"> {{ nb.metadata.widgets[mimetype] | json_dumps }} </script> {% endif %} """ }
290
10,016
<gh_stars>1000+ /* * Zed Attack Proxy (ZAP) and its related class files. * * ZAP is an HTTP/HTTPS proxy for assessing web application security. * * Copyright 2014 The ZAP Development Team * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.zaproxy.zap.eventBus; import static java.util.Arrays.asList; import static java.util.Collections.emptySet; import java.security.InvalidParameterException; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import java.util.function.Consumer; import java.util.function.Predicate; import java.util.stream.Stream; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; /** * A very simple event bus * * @author simon */ public class SimpleEventBus implements EventBus { private Map<String, RegisteredPublisher> nameToPublisher = new HashMap<>(); private List<RegisteredConsumer> danglingConsumers = new ArrayList<>(); /** * The {@code Lock} for registration management (register and unregister) of publishers and * consumers. */ private final Lock regMgmtLock = new ReentrantLock(true); private static Logger log = LogManager.getLogger(SimpleEventBus.class); @Override public void registerPublisher(EventPublisher publisher, String... eventTypes) { if (publisher == null) { throw new InvalidParameterException("Publisher must not be null"); } if (eventTypes == null || eventTypes.length == 0) { throw new InvalidParameterException("At least one event type must be specified"); } regMgmtLock.lock(); try { String publisherName = publisher.getPublisherName(); if (nameToPublisher.get(publisherName) != null) { throw new InvalidParameterException( "Publisher with name " + publisherName + " already registered by " + nameToPublisher .get(publisherName) .getPublisher() .getClass() .getCanonicalName()); } log.debug("registerPublisher " + publisherName); RegisteredPublisher regProd = new RegisteredPublisher(publisher, new HashSet<>(asList(eventTypes))); List<RegisteredConsumer> consumers = new ArrayList<>(); // Check to see if there are any cached consumers moveConsumers( danglingConsumers, consumer -> consumer.getPublisherName().equals(publisherName), consumers::add); regProd.addConsumers(consumers); nameToPublisher.put(publisherName, regProd); } finally { regMgmtLock.unlock(); } } private static void moveConsumers( Collection<RegisteredConsumer> source, Predicate<RegisteredConsumer> condition, Consumer<RegisteredConsumer> sink) { source.removeIf( item -> { if (condition.test(item)) { sink.accept(item); return true; } return false; }); } @Override public void unregisterPublisher(EventPublisher publisher) { if (publisher == null) { throw new InvalidParameterException("Publisher must not be null"); } regMgmtLock.lock(); try { String publisherName = publisher.getPublisherName(); log.debug("unregisterPublisher " + publisherName); if (nameToPublisher.remove(publisherName) == null) { throw new InvalidParameterException( "Publisher with name " + publisherName + " not registered"); } } finally { regMgmtLock.unlock(); } } @Override public void registerConsumer(EventConsumer consumer, String publisherName) { registerConsumer(consumer, publisherName, (String[]) null); } @Override public void registerConsumer( EventConsumer consumer, String publisherName, String... eventTypes) { if (consumer == null) { throw new InvalidParameterException("Consumer must not be null"); } Set<String> eventTypesSet = eventTypes == null ? emptySet() : new HashSet<>(asList(eventTypes)); regMgmtLock.lock(); try { log.debug( "registerConsumer " + consumer.getClass().getCanonicalName() + " for " + publisherName); RegisteredPublisher publisher = nameToPublisher.get(publisherName); if (publisher == null) { // Cache until the publisher registers danglingConsumers.add( new RegisteredConsumer(consumer, eventTypesSet, publisherName)); } else { publisher.addConsumer(new RegisteredConsumer(consumer, eventTypesSet)); } } finally { regMgmtLock.unlock(); } } @Override public void unregisterConsumer(EventConsumer consumer) { if (consumer == null) { throw new InvalidParameterException("Consumer must not be null"); } regMgmtLock.lock(); try { log.debug("unregisterConsumer " + consumer.getClass().getCanonicalName()); nameToPublisher.values().forEach(publisher -> publisher.removeConsumer(consumer)); // Check to see if its cached waiting for a publisher removeDanglingConsumer(consumer); } finally { regMgmtLock.unlock(); } } private void removeDanglingConsumer(EventConsumer consumer) { danglingConsumers.removeIf( registeredConsumer -> registeredConsumer.getConsumer().equals(consumer)); } @Override public void unregisterConsumer(EventConsumer consumer, String publisherName) { if (consumer == null) { throw new InvalidParameterException("Consumer must not be null"); } regMgmtLock.lock(); try { log.debug( "unregisterConsumer " + consumer.getClass().getCanonicalName() + " for " + publisherName); RegisteredPublisher publisher = nameToPublisher.get(publisherName); if (publisher == null) { // Check to see if its cached waiting for the publisher removeDanglingConsumer(consumer); } else { publisher.removeConsumer(consumer); } } finally { regMgmtLock.unlock(); } } @Override public void publishSyncEvent(EventPublisher publisher, Event event) { if (publisher == null) { throw new InvalidParameterException("Publisher must not be null"); } String publisherName = publisher.getPublisherName(); String eventType = event.getEventType(); RegisteredPublisher regPublisher = nameToPublisher.get(publisherName); if (regPublisher == null) { throw new InvalidParameterException("Publisher not registered: " + publisherName); } log.debug("publishSyncEvent " + eventType + " from " + publisherName); if (!regPublisher.isEventRegistered(eventType)) { throw new InvalidParameterException( "Event type: " + eventType + " not registered for publisher: " + publisherName); } regPublisher .getConsumers() .filter(consumer -> consumer.wantsEvent(eventType)) .forEach( regCon -> { try { regCon.getConsumer().eventReceived(event); } catch (Exception e) { log.error(e.getMessage(), e); } }); } @Override public Set<String> getPublisherNames() { return Collections.unmodifiableSet(this.nameToPublisher.keySet()); } @Override public Set<String> getEventTypesForPublisher(String publisherName) { RegisteredPublisher publisher = nameToPublisher.get(publisherName); if (publisher != null) { return Collections.unmodifiableSet(publisher.getEventTypes()); } return Collections.emptySet(); } private static class RegisteredConsumer { private EventConsumer consumer; private Set<String> eventTypes = new HashSet<>(); private String publisherName; RegisteredConsumer(EventConsumer consumer, Set<String> eventTypes) { this.consumer = consumer; this.eventTypes.addAll(eventTypes); } RegisteredConsumer(EventConsumer consumer, Set<String> eventTypes, String publisherName) { this(consumer, eventTypes); this.publisherName = publisherName; } EventConsumer getConsumer() { return consumer; } boolean wantsEvent(String eventType) { return eventTypes.isEmpty() || eventTypes.contains(eventType); } String getPublisherName() { return publisherName; } } private static class RegisteredPublisher { private EventPublisher publisher; private Set<String> eventTypes = new HashSet<>(); private List<RegisteredConsumer> consumers = new CopyOnWriteArrayList<>(); RegisteredPublisher(EventPublisher publisher, Set<String> eventTypes) { this.publisher = publisher; this.eventTypes.addAll(eventTypes); } EventPublisher getPublisher() { return publisher; } boolean isEventRegistered(String eventType) { return eventTypes.contains(eventType); } Stream<RegisteredConsumer> getConsumers() { return consumers.stream(); } void addConsumer(RegisteredConsumer consumer) { consumers.add(consumer); } void addConsumers(List<RegisteredConsumer> registeredConsumers) { consumers.addAll(registeredConsumers); } void removeConsumer(EventConsumer consumer) { consumers.removeIf( registeredConsumer -> registeredConsumer.getConsumer().equals(consumer)); } public Set<String> getEventTypes() { return eventTypes; } } }
4,987
5,169
{ "name": "BreinifyApi", "version": "2.0.9", "summary": "Breinify´s DigitalDNA API puts dynamic behavior-based, people-driven data right at your fingertips", "description": "Breinifys DigitalDNA API puts dynamic behavior-based, people-driven data right at your fingertips. We believe that in many situations, a critical component of a great user experience is personalization. With all the data available on the web it should be easy to provide a unique experience to every visitor, and yet, sometimes you may find yourself wondering why it is so difficult.", "homepage": "https://github.com/Breinify/brein-api-library-ios", "license": { "type": "MIT", "file": "LICENSE" }, "authors": { "Breinify Inc.": "<EMAIL>" }, "source": { "git": "https://github.com/Breinify/brein-api-library-ios.git", "tag": "2.0.9" }, "swift_versions": "5.0", "platforms": { "ios": "9.0" }, "source_files": "BreinifyApi/**/*.swift", "swift_version": "5.0" }
340
1,545
# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from bookkeeper.common.util import __PYTHON3__ from bookkeeper.common.util import new_hostname_with_port if __PYTHON3__: from urllib.parse import urlparse else: from urlparse import urlparse class ServiceURI(object): def __init__(self, service_uri): self.uri = urlparse(service_uri) self.service_name = self.uri.scheme self.service_user = self.uri.username self.service_path = self.uri.path if __PYTHON3__: self.service_hosts = list(map(lambda x: new_hostname_with_port(x), self.uri.netloc.split(','))) else: self.service_hosts = map(lambda x: new_hostname_with_port(x), self.uri.netloc.split(',')) self.service_location = ','.join(self.service_hosts)
458
805
// util/text-utils.h // Copyright 2009-2011 Saarland University; Microsoft Corporation // See ../../COPYING for clarification regarding multiple authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED // WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABLITY OR NON-INFRINGEMENT. // See the Apache 2 License for the specific language governing permissions and // limitations under the License. #ifndef KALDI_UTIL_TEXT_UTILS_H_ #define KALDI_UTIL_TEXT_UTILS_H_ #include <errno.h> #include <string> #include <algorithm> #include <map> #include <set> #include <vector> #include <limits> #include "base/kaldi-common.h" namespace kaldi { /// Split a string using any of the single character delimiters. /// If omit_empty_strings == true, the output will contain any /// nonempty strings after splitting on any of the /// characters in the delimiter. If omit_empty_strings == false, /// the output will contain n+1 strings if there are n characters /// in the set "delim" within the input string. In this case /// the empty string is split to a single empty string. void SplitStringToVector(const std::string &full, const char *delim, bool omit_empty_strings, std::vector<std::string> *out); /// Joins the elements of a vector of strings into a single string using /// "delim" as the delimiter. If omit_empty_strings == true, any empty strings /// in the vector are skipped. A vector of empty strings results in an empty /// string on the output. void JoinVectorToString(const std::vector<std::string> &vec_in, const char *delim, bool omit_empty_strings, std::string *str_out); /** \brief Split a string (e.g. 1:2:3) into a vector of integers. \param [in] delim String containing a list of characters, any of which is allowed as a delimiter. \param [in] omit_empty_strings If true, empty strings between delimiters are allowed and will not produce an output integer; if false, instances of characters in 'delim' that are consecutive or at the start or end of the string would be an error. You'll normally want this to be true if 'delim' consists of spaces, and false otherwise. \param [out] out The output list of integers. */ template<class I> bool SplitStringToIntegers(const std::string &full, const char *delim, bool omit_empty_strings, // typically false [but // should probably be true // if "delim" is spaces]. std::vector<I> *out) { KALDI_ASSERT(out != NULL); KALDI_ASSERT_IS_INTEGER_TYPE(I); if (*(full.c_str()) == '\0') { out->clear(); return true; } std::vector<std::string> split; SplitStringToVector(full, delim, omit_empty_strings, &split); out->resize(split.size()); for (size_t i = 0; i < split.size(); i++) { const char *this_str = split[i].c_str(); char *end = NULL; int64 j = 0; j = KALDI_STRTOLL(this_str, &end); if (end == this_str || *end != '\0') { out->clear(); return false; } else { I jI = static_cast<I>(j); if (static_cast<int64>(jI) != j) { // output type cannot fit this integer. out->clear(); return false; } (*out)[i] = jI; } } return true; } // This is defined for F = float and double. template<class F> bool SplitStringToFloats(const std::string &full, const char *delim, bool omit_empty_strings, // typically false std::vector<F> *out); /// Converts a string into an integer via strtoll and returns false if there was /// any kind of problem (i.e. the string was not an integer or contained extra /// non-whitespace junk, or the integer was too large to fit into the type it is /// being converted into). Only sets *out if everything was OK and it returns /// true. template<class Int> bool ConvertStringToInteger(const std::string &str, Int *out) { KALDI_ASSERT_IS_INTEGER_TYPE(Int); const char *this_str = str.c_str(); char *end = NULL; errno = 0; int64 i = KALDI_STRTOLL(this_str, &end); if (end != this_str) while (isspace(*end)) end++; if (end == this_str || *end != '\0' || errno != 0) return false; Int iInt = static_cast<Int>(i); if (static_cast<int64>(iInt) != i || (i < 0 && !std::numeric_limits<Int>::is_signed)) { return false; } *out = iInt; return true; } /// ConvertStringToReal converts a string into either float or double /// and returns false if there was any kind of problem (i.e. the string /// was not a floating point number or contained extra non-whitespace junk). /// Be careful- this function will successfully read inf's or nan's. template <typename T> bool ConvertStringToReal(const std::string &str, T *out); /// Removes the beginning and trailing whitespaces from a string void Trim(std::string *str); /// Removes leading and trailing white space from the string, then splits on the /// first section of whitespace found (if present), putting the part before the /// whitespace in "first" and the rest in "rest". If there is no such space, /// everything that remains after removing leading and trailing whitespace goes /// in "first". void SplitStringOnFirstSpace(const std::string &line, std::string *first, std::string *rest); /// Returns true if "token" is nonempty, and all characters are /// printable and whitespace-free. bool IsToken(const std::string &token); /// Returns true if "line" is free of \n characters and unprintable /// characters, and does not contain leading or trailing whitespace. bool IsLine(const std::string &line); /** This function returns true when two text strings are approximately equal, and false when they are not. The definition of 'equal' is normal string equality, except that two substrings like "0.31134" and "0.311341" would be considered equal. 'decimal_places_tolerance' controls how many digits after the '.' have to match up. E.g. StringsApproxEqual("hello 0.23 there", "hello 0.24 there", 2) would return false because there is a difference in the 2nd decimal, but with an argument of 1 it would return true. */ bool StringsApproxEqual(const std::string &a, const std::string &b, int32 decimal_places_check = 2); } // namespace kaldi #endif // KALDI_UTIL_TEXT_UTILS_H_
2,693
312
<reponame>patrickwyler/rdf4j /******************************************************************************* * Copyright (c) 2015 Eclipse RDF4J contributors, Aduna, and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Distribution License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/org/documents/edl-v10.php. *******************************************************************************/ package org.eclipse.rdf4j.common.logging; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; /** * Log record interface */ public interface LogRecord { SimpleDateFormat ISO8601_TIMESTAMP_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss,SSS"); /** * Get log level * * @return log level enumeration */ LogLevel getLevel(); /** * Get date time * * @return date */ Date getTime(); /** * Get thread name * * @return thread name */ String getThreadName(); /** * Get message * * @return text */ String getMessage(); /** * Get stack trace as list of strings * * @return list of strings */ List<String> getStackTrace(); }
360
450
//===- BM188xVisitor.cpp --------------------------------------------------===// // // The ONNC Project // // See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "BM188xVisitor.h" using namespace onnc; using namespace onnc::BM188X; //===----------------------------------------------------------------------===// // BM188xVisitor //===----------------------------------------------------------------------===// bool BM188xVisitor::classof(const ComputeVisitor* pVisitor) { if (nullptr != pVisitor) return (pVisitor->getVisitorID() == id()); return false; }
185
1,405
package com.tencent.tmsecure.module.update; import com.tencent.tmsecure.common.BaseEntity; public class UpdateInfo extends BaseEntity { public Object data1; public Object data2; public String fileName; public int flag; public int type; public String url; }
93
10,002
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #pragma once #include "INarratorAnnouncementHost.h" // Declaration of the NarratorAnnouncementHostFactory class. // This class exists to hide the construction of a concrete INarratorAnnouncementHost. // Depending on the version of the OS the app is running on, the factory will return // an announcement host appropriate for that version. namespace CalculatorApp::ViewModel::Common::Automation { class NarratorAnnouncementHostFactory { public: static INarratorAnnouncementHost ^ MakeHost(); private: NarratorAnnouncementHostFactory() { } static int Initialize(); static void RegisterHosts(); static INarratorAnnouncementHost ^ GetHostProducer(); private: static int s_init; static INarratorAnnouncementHost ^ s_hostProducer; static std::vector<INarratorAnnouncementHost ^> s_hosts; }; }
334
5,169
<gh_stars>1000+ { "name": "WTLStickerPanel", "version": "1.0.1", "summary": "A simple sticker panel", "description": "WTLStickerPanel is a view for select sticker to post to comment area.", "homepage": "https://github.com/daarkfish/WTLStickerPanel", "license": { "type": "MIT", "file": "LICENSE" }, "authors": { "daarkfish": "<EMAIL>" }, "source": { "git": "https://github.com/daarkfish/WTLStickerPanel.git", "tag": "1.0.1" }, "platforms": { "ios": "8.0" }, "requires_arc": true, "source_files": "WTLStickerPanel/Classes/**/*", "resource_bundles": { "WTLStickerPanel": [ "WTLStickerPanel/Classes/*.xib" ] }, "frameworks": [ "UIKit", "MapKit" ], "dependencies": { "YYWebImage": [ ] } }
346
575
// Copyright 2021 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.chrome.browser.share.long_screenshots.bitmap_generation; import android.content.Context; import android.graphics.Rect; import androidx.annotation.VisibleForTesting; import org.chromium.chrome.browser.tab.Tab; import org.chromium.content_public.browser.RenderCoordinates; import org.chromium.ui.display.DisplayAndroid; /** * Responsible for calculating and tracking the bounds of the capture and composited * LongScreenshot Entries. */ public class ScreenshotBoundsManager { private static final int NUM_VIEWPORTS_CAPTURE_ABOVE = 4; private static final int NUM_VIEWPORTS_CAPTURE_BELOW = 6; private Tab mTab; private Rect mCaptureRect; private int mClipHeightScaled; private int mCurrYStartPosition; /** * @param context An instance of current Android {@link Context}. * @param tab Tab to generate the bitmap for. */ public ScreenshotBoundsManager(Context context, Tab tab) { mTab = tab; calculateClipHeightScaled(context); calculateCaptureBounds(); } private ScreenshotBoundsManager(Context context, Tab tab, int clipHeight) { mTab = tab; mClipHeightScaled = clipHeight; calculateCaptureBounds(); } /** * To only be used for testing purposes. * * @param context An instance of current Android {@link Context}. * @param tab Tab to generate the bitmap for. * @param clipHeight The height of the device. * @return an instance of ScreenshotBoundsManager. */ @VisibleForTesting public static ScreenshotBoundsManager createForTests(Context context, Tab tab, int clipHeight) { return new ScreenshotBoundsManager(context, tab, clipHeight); } /** * Calculates the height of the phone used to determine the height of the bitmaps. */ private void calculateClipHeightScaled(Context context) { DisplayAndroid displayAndroid = DisplayAndroid.getNonMultiDisplay(context); RenderCoordinates coords = RenderCoordinates.fromWebContents(mTab.getWebContents()); mClipHeightScaled = (int) Math.floor(displayAndroid.getDisplayHeight() * coords.getPageScaleFactor()); } /** * Defines the bounds of the capture. */ private void calculateCaptureBounds() { RenderCoordinates coords = RenderCoordinates.fromWebContents(mTab.getWebContents()); int pageScaleFactor = coords.getPageScaleFactorInt() == 0 ? 1 : coords.getPageScaleFactorInt(); // The current position the user has scrolled to. mCurrYStartPosition = coords.getScrollYPixInt() / pageScaleFactor; int startYAxis = mCurrYStartPosition - (NUM_VIEWPORTS_CAPTURE_ABOVE * mClipHeightScaled); startYAxis = startYAxis < 0 ? 0 : startYAxis; int endYAxis = mCurrYStartPosition + (NUM_VIEWPORTS_CAPTURE_BELOW * mClipHeightScaled); int maxY = coords.getContentHeightPixInt() / pageScaleFactor; endYAxis = endYAxis > maxY ? maxY : endYAxis; mCaptureRect = new Rect(0, startYAxis, 0, endYAxis); } /** * @return The bounds of the capture. */ public Rect getCaptureBounds() { return mCaptureRect; } /** * Gets the bounds of the initial entry to be used for compositing. * @return the compositing bounds of the first entry. */ public Rect getInitialEntryBounds() { return calculateClipBoundsBelow(mCurrYStartPosition); } /** * Defines the bounds of the capture and compositing. Only the starting height is needed. The * entire width is always captured. * * @param yAxisRef Where on the scrolled page the capture and compositing should start. */ public Rect calculateClipBoundsAbove(int yAxisRef) { if (yAxisRef <= mCaptureRect.top) { // Already at the top of the capture return null; } int startYAxis = yAxisRef - mClipHeightScaled; startYAxis = startYAxis < 0 ? 0 : startYAxis; startYAxis = startYAxis < mCaptureRect.top ? mCaptureRect.top : startYAxis; return new Rect(0, startYAxis, 0, yAxisRef); } /** * Defines the bounds of the capture and compositing. Only the starting height is needed. The * entire width is always captured. * * @param yAxisRef Where on the scrolled page the capture and compositing should start. */ public Rect calculateClipBoundsBelow(int yAxisRef) { if (yAxisRef >= mCaptureRect.bottom) { // Already at the bottom of the capture return null; } // TODO(tgupta): Address the case where the Y axis supersedes the length of the page. int endYAxis = yAxisRef + mClipHeightScaled; endYAxis = endYAxis > mCaptureRect.bottom ? mCaptureRect.bottom : endYAxis; return new Rect(0, yAxisRef, 0, endYAxis); } /** * Calculates the bounds passed in relative to the bounds of the capture. Since 6x the viewport * size is captured, the composite bounds needs to be adjusted to be relative to the captured * page. For example, let's say that the top Y-axis of the capture rectangle is 100 relative to * the top of the website. The Y-axis of the composite rectangle is 150 relative to the top of * the website. Then the relative top Y-axis to be used for compositing should be 50 where the * top is assumed to the top of the capture. * * @param compositeRect The bounds relative to the webpage * @return The bounds relative to the capture. */ public Rect calculateBoundsRelativeToCapture(Rect compositeRect) { int startY = compositeRect.top - mCaptureRect.top; startY = (startY < 0) ? 0 : startY; int endY = compositeRect.bottom - mCaptureRect.top; endY = (endY > mCaptureRect.height()) ? mCaptureRect.height() : endY; return new Rect(0, startY, 0, endY); } }
2,221
5,964
/* * Copyright 2010 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "GrDrawTarget.h" #include "GrAARectRenderer.h" #include "GrBatch.h" #include "GrCaps.h" #include "GrGpu.h" #include "GrPath.h" #include "GrPipeline.h" #include "GrMemoryPool.h" #include "GrRectBatch.h" #include "GrRenderTarget.h" #include "GrResourceProvider.h" #include "GrRenderTargetPriv.h" #include "GrSurfacePriv.h" #include "GrTemplates.h" #include "GrTexture.h" #include "GrVertexBuffer.h" #include "SkStrokeRec.h" //////////////////////////////////////////////////////////////////////////////// GrDrawTarget::GrDrawTarget(GrGpu* gpu, GrResourceProvider* resourceProvider) : fGpu(SkRef(gpu)) , fCaps(SkRef(gpu->caps())) , fResourceProvider(resourceProvider) , fGpuTraceMarkerCount(0) , fFlushing(false) { } GrDrawTarget::~GrDrawTarget() { fGpu->unref(); fCaps->unref(); } //////////////////////////////////////////////////////////////////////////////// bool GrDrawTarget::setupDstReadIfNecessary(const GrPipelineBuilder& pipelineBuilder, const GrProcOptInfo& colorPOI, const GrProcOptInfo& coveragePOI, GrXferProcessor::DstTexture* dstTexture, const SkRect* drawBounds) { if (!pipelineBuilder.willXPNeedDstTexture(*this->caps(), colorPOI, coveragePOI)) { return true; } GrRenderTarget* rt = pipelineBuilder.getRenderTarget(); if (this->caps()->textureBarrierSupport()) { if (GrTexture* rtTex = rt->asTexture()) { // The render target is a texture, so we can read from it directly in the shader. The XP // will be responsible to detect this situation and request a texture barrier. dstTexture->setTexture(rtTex); dstTexture->setOffset(0, 0); return true; } } SkIRect copyRect; pipelineBuilder.clip().getConservativeBounds(rt, &copyRect); if (drawBounds) { SkIRect drawIBounds; drawBounds->roundOut(&drawIBounds); if (!copyRect.intersect(drawIBounds)) { #ifdef SK_DEBUG GrCapsDebugf(fCaps, "Missed an early reject. " "Bailing on draw from setupDstReadIfNecessary.\n"); #endif return false; } } else { #ifdef SK_DEBUG //SkDebugf("No dev bounds when dst copy is made.\n"); #endif } // MSAA consideration: When there is support for reading MSAA samples in the shader we could // have per-sample dst values by making the copy multisampled. GrSurfaceDesc desc; if (!this->getGpu()->initCopySurfaceDstDesc(rt, &desc)) { desc.fOrigin = kDefault_GrSurfaceOrigin; desc.fFlags = kRenderTarget_GrSurfaceFlag; desc.fConfig = rt->config(); } desc.fWidth = copyRect.width(); desc.fHeight = copyRect.height(); SkAutoTUnref<GrTexture> copy( fResourceProvider->refScratchTexture(desc, GrTextureProvider::kApprox_ScratchTexMatch)); if (!copy) { SkDebugf("Failed to create temporary copy of destination texture.\n"); return false; } SkIPoint dstPoint = {0, 0}; this->copySurface(copy, rt, copyRect, dstPoint); dstTexture->setTexture(copy); dstTexture->setOffset(copyRect.fLeft, copyRect.fTop); return true; } void GrDrawTarget::flush() { if (fFlushing) { return; } fFlushing = true; this->getGpu()->saveActiveTraceMarkers(); this->onFlush(); this->getGpu()->restoreActiveTraceMarkers(); fFlushing = false; this->reset(); } void GrDrawTarget::drawBatch(GrPipelineBuilder* pipelineBuilder, GrBatch* batch) { SkASSERT(pipelineBuilder); // TODO some kind of checkdraw, but not at this level // Setup clip GrScissorState scissorState; GrPipelineBuilder::AutoRestoreFragmentProcessors arfp; GrPipelineBuilder::AutoRestoreStencil ars; if (!this->setupClip(pipelineBuilder, &arfp, &ars, &scissorState, &batch->bounds())) { return; } // Batch bounds are tight, so for dev copies // TODO move this into setupDstReadIfNecessary when paths are in batch SkRect bounds = batch->bounds(); bounds.outset(0.5f, 0.5f); GrDrawTarget::PipelineInfo pipelineInfo(pipelineBuilder, &scissorState, batch, &bounds, this); if (pipelineInfo.mustSkipDraw()) { return; } this->onDrawBatch(batch, pipelineInfo); } static const GrStencilSettings& winding_path_stencil_settings() { GR_STATIC_CONST_SAME_STENCIL_STRUCT(gSettings, kIncClamp_StencilOp, kIncClamp_StencilOp, kAlwaysIfInClip_StencilFunc, 0xFFFF, 0xFFFF, 0xFFFF); return *GR_CONST_STENCIL_SETTINGS_PTR_FROM_STRUCT_PTR(&gSettings); } static const GrStencilSettings& even_odd_path_stencil_settings() { GR_STATIC_CONST_SAME_STENCIL_STRUCT(gSettings, kInvert_StencilOp, kInvert_StencilOp, kAlwaysIfInClip_StencilFunc, 0xFFFF, 0xFFFF, 0xFFFF); return *GR_CONST_STENCIL_SETTINGS_PTR_FROM_STRUCT_PTR(&gSettings); } void GrDrawTarget::getPathStencilSettingsForFilltype(GrPathRendering::FillType fill, const GrStencilAttachment* sb, GrStencilSettings* outStencilSettings) { switch (fill) { default: SkFAIL("Unexpected path fill."); case GrPathRendering::kWinding_FillType: *outStencilSettings = winding_path_stencil_settings(); break; case GrPathRendering::kEvenOdd_FillType: *outStencilSettings = even_odd_path_stencil_settings(); break; } this->clipMaskManager()->adjustPathStencilParams(sb, outStencilSettings); } void GrDrawTarget::stencilPath(GrPipelineBuilder* pipelineBuilder, const GrPathProcessor* pathProc, const GrPath* path, GrPathRendering::FillType fill) { // TODO: extract portions of checkDraw that are relevant to path stenciling. SkASSERT(path); SkASSERT(this->caps()->shaderCaps()->pathRenderingSupport()); SkASSERT(pipelineBuilder); // Setup clip GrScissorState scissorState; GrPipelineBuilder::AutoRestoreFragmentProcessors arfp; GrPipelineBuilder::AutoRestoreStencil ars; if (!this->setupClip(pipelineBuilder, &arfp, &ars, &scissorState, NULL)) { return; } // set stencil settings for path GrStencilSettings stencilSettings; GrRenderTarget* rt = pipelineBuilder->getRenderTarget(); GrStencilAttachment* sb = rt->renderTargetPriv().attachStencilAttachment(); this->getPathStencilSettingsForFilltype(fill, sb, &stencilSettings); this->onStencilPath(*pipelineBuilder, pathProc, path, scissorState, stencilSettings); } void GrDrawTarget::drawPath(GrPipelineBuilder* pipelineBuilder, const GrPathProcessor* pathProc, const GrPath* path, GrPathRendering::FillType fill) { // TODO: extract portions of checkDraw that are relevant to path rendering. SkASSERT(path); SkASSERT(this->caps()->shaderCaps()->pathRenderingSupport()); SkASSERT(pipelineBuilder); SkRect devBounds = path->getBounds(); pathProc->viewMatrix().mapRect(&devBounds); // Setup clip GrScissorState scissorState; GrPipelineBuilder::AutoRestoreFragmentProcessors arfp; GrPipelineBuilder::AutoRestoreStencil ars; if (!this->setupClip(pipelineBuilder, &arfp, &ars, &scissorState, &devBounds)) { return; } // set stencil settings for path GrStencilSettings stencilSettings; GrRenderTarget* rt = pipelineBuilder->getRenderTarget(); GrStencilAttachment* sb = rt->renderTargetPriv().attachStencilAttachment(); this->getPathStencilSettingsForFilltype(fill, sb, &stencilSettings); GrDrawTarget::PipelineInfo pipelineInfo(pipelineBuilder, &scissorState, pathProc, &devBounds, this); if (pipelineInfo.mustSkipDraw()) { return; } this->onDrawPath(pathProc, path, stencilSettings, pipelineInfo); } void GrDrawTarget::drawPaths(GrPipelineBuilder* pipelineBuilder, const GrPathProcessor* pathProc, const GrPathRange* pathRange, const void* indices, PathIndexType indexType, const float transformValues[], PathTransformType transformType, int count, GrPathRendering::FillType fill) { SkASSERT(this->caps()->shaderCaps()->pathRenderingSupport()); SkASSERT(pathRange); SkASSERT(indices); SkASSERT(0 == reinterpret_cast<long>(indices) % GrPathRange::PathIndexSizeInBytes(indexType)); SkASSERT(transformValues); SkASSERT(pipelineBuilder); // Setup clip GrScissorState scissorState; GrPipelineBuilder::AutoRestoreFragmentProcessors arfp; GrPipelineBuilder::AutoRestoreStencil ars; if (!this->setupClip(pipelineBuilder, &arfp, &ars, &scissorState, NULL)) { return; } // set stencil settings for path GrStencilSettings stencilSettings; GrRenderTarget* rt = pipelineBuilder->getRenderTarget(); GrStencilAttachment* sb = rt->renderTargetPriv().attachStencilAttachment(); this->getPathStencilSettingsForFilltype(fill, sb, &stencilSettings); // Don't compute a bounding box for dst copy texture, we'll opt // instead for it to just copy the entire dst. Realistically this is a moot // point, because any context that supports NV_path_rendering will also // support NV_blend_equation_advanced. GrDrawTarget::PipelineInfo pipelineInfo(pipelineBuilder, &scissorState, pathProc, NULL, this); if (pipelineInfo.mustSkipDraw()) { return; } this->onDrawPaths(pathProc, pathRange, indices, indexType, transformValues, transformType, count, stencilSettings, pipelineInfo); } void GrDrawTarget::drawBWRect(GrPipelineBuilder* pipelineBuilder, GrColor color, const SkMatrix& viewMatrix, const SkRect& rect, const SkRect* localRect, const SkMatrix* localMatrix) { SkAutoTUnref<GrBatch> batch(GrRectBatch::Create(color, viewMatrix, rect, localRect, localMatrix)); this->drawBatch(pipelineBuilder, batch); } void GrDrawTarget::drawAARect(GrPipelineBuilder* pipelineBuilder, GrColor color, const SkMatrix& viewMatrix, const SkRect& rect, const SkRect& devRect) { GrAARectRenderer::FillAARect(this, pipelineBuilder, color, viewMatrix, rect, devRect); } void GrDrawTarget::clear(const SkIRect* rect, GrColor color, bool canIgnoreRect, GrRenderTarget* renderTarget) { if (fCaps->useDrawInsteadOfClear()) { // This works around a driver bug with clear by drawing a rect instead. // The driver will ignore a clear if it is the only thing rendered to a // target before the target is read. SkIRect rtRect = SkIRect::MakeWH(renderTarget->width(), renderTarget->height()); if (NULL == rect || canIgnoreRect || rect->contains(rtRect)) { rect = &rtRect; // We first issue a discard() since that may help tilers. this->discard(renderTarget); } GrPipelineBuilder pipelineBuilder; pipelineBuilder.setRenderTarget(renderTarget); this->drawSimpleRect(&pipelineBuilder, color, SkMatrix::I(), *rect); } else { this->onClear(rect, color, canIgnoreRect, renderTarget); } } typedef GrTraceMarkerSet::Iter TMIter; void GrDrawTarget::saveActiveTraceMarkers() { if (this->caps()->gpuTracingSupport()) { SkASSERT(0 == fStoredTraceMarkers.count()); fStoredTraceMarkers.addSet(fActiveTraceMarkers); for (TMIter iter = fStoredTraceMarkers.begin(); iter != fStoredTraceMarkers.end(); ++iter) { this->removeGpuTraceMarker(&(*iter)); } } } void GrDrawTarget::restoreActiveTraceMarkers() { if (this->caps()->gpuTracingSupport()) { SkASSERT(0 == fActiveTraceMarkers.count()); for (TMIter iter = fStoredTraceMarkers.begin(); iter != fStoredTraceMarkers.end(); ++iter) { this->addGpuTraceMarker(&(*iter)); } for (TMIter iter = fActiveTraceMarkers.begin(); iter != fActiveTraceMarkers.end(); ++iter) { this->fStoredTraceMarkers.remove(*iter); } } } void GrDrawTarget::addGpuTraceMarker(const GrGpuTraceMarker* marker) { if (this->caps()->gpuTracingSupport()) { SkASSERT(fGpuTraceMarkerCount >= 0); this->fActiveTraceMarkers.add(*marker); ++fGpuTraceMarkerCount; } } void GrDrawTarget::removeGpuTraceMarker(const GrGpuTraceMarker* marker) { if (this->caps()->gpuTracingSupport()) { SkASSERT(fGpuTraceMarkerCount >= 1); this->fActiveTraceMarkers.remove(*marker); --fGpuTraceMarkerCount; } } //////////////////////////////////////////////////////////////////////////////// namespace { // returns true if the read/written rect intersects the src/dst and false if not. bool clip_srcrect_and_dstpoint(const GrSurface* dst, const GrSurface* src, const SkIRect& srcRect, const SkIPoint& dstPoint, SkIRect* clippedSrcRect, SkIPoint* clippedDstPoint) { *clippedSrcRect = srcRect; *clippedDstPoint = dstPoint; // clip the left edge to src and dst bounds, adjusting dstPoint if necessary if (clippedSrcRect->fLeft < 0) { clippedDstPoint->fX -= clippedSrcRect->fLeft; clippedSrcRect->fLeft = 0; } if (clippedDstPoint->fX < 0) { clippedSrcRect->fLeft -= clippedDstPoint->fX; clippedDstPoint->fX = 0; } // clip the top edge to src and dst bounds, adjusting dstPoint if necessary if (clippedSrcRect->fTop < 0) { clippedDstPoint->fY -= clippedSrcRect->fTop; clippedSrcRect->fTop = 0; } if (clippedDstPoint->fY < 0) { clippedSrcRect->fTop -= clippedDstPoint->fY; clippedDstPoint->fY = 0; } // clip the right edge to the src and dst bounds. if (clippedSrcRect->fRight > src->width()) { clippedSrcRect->fRight = src->width(); } if (clippedDstPoint->fX + clippedSrcRect->width() > dst->width()) { clippedSrcRect->fRight = clippedSrcRect->fLeft + dst->width() - clippedDstPoint->fX; } // clip the bottom edge to the src and dst bounds. if (clippedSrcRect->fBottom > src->height()) { clippedSrcRect->fBottom = src->height(); } if (clippedDstPoint->fY + clippedSrcRect->height() > dst->height()) { clippedSrcRect->fBottom = clippedSrcRect->fTop + dst->height() - clippedDstPoint->fY; } // The above clipping steps may have inverted the rect if it didn't intersect either the src or // dst bounds. return !clippedSrcRect->isEmpty(); } } void GrDrawTarget::copySurface(GrSurface* dst, GrSurface* src, const SkIRect& srcRect, const SkIPoint& dstPoint) { SkASSERT(dst); SkASSERT(src); SkIRect clippedSrcRect; SkIPoint clippedDstPoint; // If the rect is outside the src or dst then we've already succeeded. if (!clip_srcrect_and_dstpoint(dst, src, srcRect, dstPoint, &clippedSrcRect, &clippedDstPoint)) { return; } this->onCopySurface(dst, src, clippedSrcRect, clippedDstPoint); } void GrDrawTarget::setupPipeline(const PipelineInfo& pipelineInfo, GrPipeline* pipeline) { SkNEW_PLACEMENT_ARGS(pipeline, GrPipeline, (*pipelineInfo.fPipelineBuilder, pipelineInfo.fColorPOI, pipelineInfo.fCoveragePOI, *this->caps(), *pipelineInfo.fScissor, &pipelineInfo.fDstTexture)); } /////////////////////////////////////////////////////////////////////////////// GrDrawTarget::PipelineInfo::PipelineInfo(GrPipelineBuilder* pipelineBuilder, GrScissorState* scissor, const GrPrimitiveProcessor* primProc, const SkRect* devBounds, GrDrawTarget* target) : fPipelineBuilder(pipelineBuilder) , fScissor(scissor) { fColorPOI = fPipelineBuilder->colorProcInfo(primProc); fCoveragePOI = fPipelineBuilder->coverageProcInfo(primProc); if (!target->setupDstReadIfNecessary(*fPipelineBuilder, fColorPOI, fCoveragePOI, &fDstTexture, devBounds)) { fPipelineBuilder = NULL; } } GrDrawTarget::PipelineInfo::PipelineInfo(GrPipelineBuilder* pipelineBuilder, GrScissorState* scissor, const GrBatch* batch, const SkRect* devBounds, GrDrawTarget* target) : fPipelineBuilder(pipelineBuilder) , fScissor(scissor) { fColorPOI = fPipelineBuilder->colorProcInfo(batch); fCoveragePOI = fPipelineBuilder->coverageProcInfo(batch); if (!target->setupDstReadIfNecessary(*fPipelineBuilder, fColorPOI, fCoveragePOI, &fDstTexture, devBounds)) { fPipelineBuilder = NULL; } } /////////////////////////////////////////////////////////////////////////////// GrClipTarget::GrClipTarget(GrContext* context) : INHERITED(context->getGpu(), context->resourceProvider()) , fContext(context) { fClipMaskManager.reset(SkNEW_ARGS(GrClipMaskManager, (this))); } bool GrClipTarget::setupClip(GrPipelineBuilder* pipelineBuilder, GrPipelineBuilder::AutoRestoreFragmentProcessors* arfp, GrPipelineBuilder::AutoRestoreStencil* ars, GrScissorState* scissorState, const SkRect* devBounds) { return fClipMaskManager->setupClipping(pipelineBuilder, arfp, ars, scissorState, devBounds); } void GrClipTarget::purgeResources() { // The clip mask manager can rebuild all its clip masks so just // get rid of them all. fClipMaskManager->purgeResources(); };
9,120
788
/* * 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.usergrid.chop.runner.drivers; import java.util.Collections; import java.util.HashMap; import java.util.Map; import org.apache.usergrid.chop.api.Signal; /** The driver States and its possible state transitions: hence its state machine. */ public enum State { // stopped ==> (reset signal) ==> ready COMPLETED( 3, new Signal[] {}, new Integer[] {} ), // stopped ==> (reset signal) ==> ready STOPPED( 2, new Signal[] {}, new Integer[] {} ), // running ==> (stop signal) ==> stopped // running ==> (completed signal) ==> ready RUNNING( 1, new Signal[] { Signal.STOP, Signal.COMPLETED }, new Integer[] { 2, 3 } ), // ready ==> (load signal) ==> ready // ready ==> (start signal) ==> running READY( 0, new Signal[] { Signal.START }, new Integer[] { 1 } ); private final int id; private final Map<Signal, Integer> trantab; private State( int id, Signal[] signals, Integer[] states ) { this.id = id; trantab = getTrantab( signals, states ); } public int getId() { return id; } public State get( Integer id ) { if ( id == null ) { return null; } switch ( id ) { case 0: return READY; case 1: return RUNNING; case 2: return STOPPED; case 3: return COMPLETED; } throw new RuntimeException( "Should never get here!" ); } public State next( Signal signal ) { return get( trantab.get( signal ) ); } private static Map<Signal, Integer> getTrantab( Signal[] signals, Integer[] states ) { Map<Signal, Integer> trantab = new HashMap<Signal, Integer>( signals.length ); for ( int ii = 0; ii < signals.length; ii++ ) { trantab.put( signals[ii], states[ii] ); } return Collections.unmodifiableMap( trantab ); } }
1,006
348
<gh_stars>100-1000 {"nom":"Pouébo","circ":"2ème circonscription","dpt":"Nouvelle-Calédonie","inscrits":2252,"abs":1705,"votants":547,"blancs":1,"nuls":3,"exp":543,"res":[{"nuance":"REG","nom":"<NAME>","voix":499},{"nuance":"UDI","nom":"<NAME>","voix":19},{"nuance":"FN","nom":"Mme <NAME>","voix":10},{"nuance":"DIV","nom":"M. <NAME>","voix":4},{"nuance":"DIV","nom":"M. <NAME>","voix":3},{"nuance":"REG","nom":"M. <NAME>","voix":3},{"nuance":"DVD","nom":"<NAME>","voix":2},{"nuance":"DVD","nom":"M. <NAME>","voix":2},{"nuance":"DVD","nom":"M. <NAME>","voix":1}]}
234
4,756
// Copyright 2020 The MACE Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef MICRO_INCLUDE_UTILS_BFLOAT16_H_ #define MICRO_INCLUDE_UTILS_BFLOAT16_H_ #include <stdint.h> #ifdef MACE_ENABLE_BFLOAT16 namespace micro { union Sphinx { uint32_t i; float f; Sphinx(uint32_t value) : i(value) {} Sphinx(float value) : f(value) {} }; class BFloat16 { public: BFloat16() {} explicit BFloat16(float value) { data_ = Sphinx(value).i >> 16; } explicit BFloat16(int value) { data_ = Sphinx(static_cast<float>(value)).i >> 16; } operator float() const { return Sphinx(static_cast<uint32_t>(data_ << 16)).f; } void operator=(const BFloat16 &value) { data_ = value.data_; } void operator=(float value) { data_ = Sphinx(value).i >> 16; } public: uint16_t data_; }; } // namespace micro #endif // MACE_ENABLE_BFLOAT16 #endif // MICRO_INCLUDE_UTILS_BFLOAT16_H_
517
5,169
<reponame>Gantios/Specs<filename>Specs/5/0/a/CHRTextFieldFormatter/1.0.1/CHRTextFieldFormatter.podspec.json { "name": "CHRTextFieldFormatter", "version": "1.0.1", "platforms": { "ios": "8.0" }, "source": { "git": "https://github.com/chebur/CHRTextFieldFormatter.git", "tag": "1.0.1" }, "source_files": "CHRTextFieldFormatter", "requires_arc": true, "summary": "Provides UITextField formatting masks. Such as phone number and credit card number formatters.", "authors": "chebur", "license": "MIT", "homepage": "https://github.com/chebur/CHRTextFieldFormatter" }
232
422
<gh_stars>100-1000 import django import sys, os rootpath = os.path.dirname(os.path.realpath(__file__)).replace("\\", "/") rootpath = rootpath.split("/apps")[0] # print(rootpath) syspath = sys.path sys.path = [] sys.path.append(rootpath) # 指定搜索路径绝对目录 sys.path.extend([rootpath + i for i in os.listdir(rootpath) if i[0] != "."]) # 将工程目录下的一级目录添加到python搜索路径中 sys.path.extend(syspath) from apps.common.func.WebFunc import * from apps.webportal.services.webPortalService import WebPortalService from all_models.models import * from apps.task.services.HTTP_taskService import HTTP_taskService import json, requests,copy if __name__ == "__main__": allBLDict = dbModelListToListDict(TbBusinessLine.objects.filter(state=1)) dataDict = {"envDetail": {}, "blDetail": {}} standardBlDict = {} allEnv = dbModelListToListDict(TbWebPortalStandardEnv.objects.filter(state=1, uiIsShow=1).order_by("lineSort")) for blIndex in allBLDict: blExecuteLen = len(TbUITestExecute.objects.filter(state=1, businessLineId=blIndex["id"])) if blExecuteLen > 0: standardBlDict[blIndex["bussinessLineName"]] = {} # 获取执行过的业务线下的模块 moduleList = dbModelListToListDict( TbBusinessLineModuleRelation.objects.filter(businessLineId=blIndex["id"])) # 获取执行过的业务线下执行过的模块 for moduleIndex in moduleList: module = TbModules.objects.get(id=moduleIndex["moduleId_id"]) mdExecuteLen = len(TbUITestExecute.objects.filter(state=1, moduleId=module.id)) if mdExecuteLen > 0: standardBlDict[blIndex["bussinessLineName"]][module.moduleName] = {} # blDetailDict = copy.deepcopy(standardBlDict) # # #生成确定值 # for blIndexKey,blIndexValue in blDetailDict.items(): # for mdIndexKey,mdIndexValue in blIndexValue.items(): # for envIndex in allEnv: # mdIndexValue[envIndex["httpConfKey"]] = {} # execDetail = TbUITestExecute.objects.filter(state=1,businessLineName=blIndexKey,moduleName=mdIndexKey,httpConfKey=envIndex["httpConfKey"]).last() # if execDetail: # mdIndexValue[envIndex["httpConfKey"]] = dbModelToDict(execDetail) # if mdIndexValue[envIndex["httpConfKey"]]["testResultMessage"] == "" or not isJson(mdIndexValue[envIndex["httpConfKey"]]["testResultMessage"]): # mdIndexValue[envIndex["httpConfKey"]]["testResultMessage"] = {"testResult": "NOTRUN", "testResultMessage": "", "casePassCount": 0, # "caseFailCount": 0, "caseWarningCount": 0,"caseNotrunCount": 0, "caseStepPassCount": 0, # "caseStepFailCount": 0, "caseStepWarningCount": 0, "caseStepNotrunCount": 0, # "totalTakeTime": 0} # else: # mdIndexValue[envIndex["httpConfKey"]]["testResultMessage"] = json.loads(mdIndexValue[envIndex["httpConfKey"]]["testResultMessage"]) blEnvDetail = {} for blIndexKey, blIndexValue in standardBlDict.items(): blEnvDetail[blIndexKey] = {"mdTestDetail":{},"testMessage":{},"testResultList" : []} for envIndex in allEnv: blEnvDetail[blIndexKey]["testMessage"][envIndex["httpConfKey"]] = { "caseStepPassCount": 0, "caseStepFailCount": 0, "caseStepWarningCount": 0, "caseStepNotrunCount": 0, "caseStepTotalCount": 0} for mdIndexKey, mdIndexValue in blIndexValue.items(): blEnvDetail[blIndexKey]["mdTestDetail"][mdIndexKey] = {"envTest":{}} for envIndex in allEnv: mdEnvTest = blEnvDetail[blIndexKey]["mdTestDetail"][mdIndexKey]["envTest"][envIndex["httpConfKey"]] = {} bsId = TbBusinessLine.objects.get(bussinessLineName=blIndexKey).id mdId = TbModules.objects.get(moduleName=mdIndexKey).id execDetail = TbUITestExecute.objects.filter(state=1, businessLineId=bsId, moduleId=mdId, httpConfKey=envIndex["httpConfKey"]).last() testResult = {"testResult": "NOTRUN", "testResultMessage": "", "caseStepPassCount": 0, "caseStepFailCount": 0, "caseStepWarningCount": 0, "caseStepNotrunCount": 0, "caseStepTotalCount": 0,"passRate" : "%.2f" % 0,"report":"javascript:void(0)"} if execDetail: execDetailDict = dbModelToDict(execDetail) if execDetailDict["testResultMessage"] != "" and isJson(execDetailDict["testResultMessage"]): testResult = json.loads(execDetailDict["testResultMessage"]) testResult["caseStepTotalCount"] = testResult["caseStepPassCount"] + testResult["caseStepFailCount"] + testResult["caseStepWarningCount"] + testResult["caseStepNotrunCount"] if testResult["caseStepTotalCount"] == 0: testResult["passRate"] = "%.2f" % 0 else: testResult["passRate"] = "%.2f" % (testResult["caseStepPassCount"] / testResult["caseStepTotalCount"] *100) if execDetailDict["reportDir"] != "": testResult["report"] = "/static/ui_test/reports/%s/report.html" % execDetailDict["reportDir"] if testResult["passRate"] > "90.00" or testResult["passRate"] == "100.00": testResult["color"] = "green" elif testResult["passRate"] < "90.00" and testResult["passRate"] > "80.00": testResult["color"] = "orange" else: testResult["color"] = "red" mdEnvTest["testMessage"] = testResult blEnvTestMessage = blEnvDetail[blIndexKey]["testMessage"][envIndex["httpConfKey"]] blEnvTestMessage["caseStepPassCount"] += testResult["caseStepPassCount"] blEnvTestMessage["caseStepFailCount"] += testResult["caseStepFailCount"] blEnvTestMessage["caseStepWarningCount"] += testResult["caseStepWarningCount"] blEnvTestMessage["caseStepNotrunCount"] += testResult["caseStepNotrunCount"] blEnvTestMessage["caseStepTotalCount"] += testResult["caseStepTotalCount"] blEnvDetail[blIndexKey]["testResultList"].append(testResult["testResult"]) for blIndexKey,blIndexValue in blEnvDetail.items(): if "EXCEPTION" in blIndexValue["testResultList"]: blIndexValue["testResult"] = "EXCEPITON" elif "ERROR" in blIndexValue["testResultList"]: blIndexValue["testResult"] = "ERROR" elif "FAIL" in blIndexValue["testResultList"]: blIndexValue["testResult"] = "FAIL" elif "PASS" in blIndexValue["testResultList"]: blIndexValue["testResult"] = "PASS" elif "NOTRUN" in blIndexValue["testResultList"]: blIndexValue["testResult"] = "NOTRUN" for envIndexKey,envIndexValue in blIndexValue["testMessage"].items(): if envIndexValue["caseStepTotalCount"] == 0: envIndexValue["passRate"] = "%.2f" % 0 else: envIndexValue["passRate"] = "%.2f" % (envIndexValue["caseStepPassCount"] / envIndexValue["caseStepTotalCount"] * 100) if envIndexValue["passRate"] > "90.00" or envIndexValue["passRate"] == "100.00": envIndexValue["color"] = "green" elif envIndexValue["passRate"] < "90.00" and envIndexValue["passRate"] > "80.00": envIndexValue["color"] = "orange" else: envIndexValue["color"] = "red" # print(json.dumps(blDetailDict)) # print(json.dumps(blEnvDetail)) resultDict = {"blEnvDetail":blEnvDetail} tbModel = TbWebPortalUITest() tbModel.testDetail = json.dumps(resultDict) tbModel.statisticalTime = datetime.datetime.now() tbModel.save() print("done!")
3,934
460
#ifndef WebCore_FWD_WREC_h #define WebCore_FWD_WREC_h #include <JavaScriptCore/WREC.h> #endif
48
384
# Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. def insert_wkt(override_values={}): # [START bigquery_insert_geography_wkt] from google.cloud import bigquery import shapely.geometry import shapely.wkt bigquery_client = bigquery.Client() # This example uses a table containing a column named "geo" with the # GEOGRAPHY data type. table_id = "my-project.my_dataset.my_table" # [END bigquery_insert_geography_wkt] # To facilitate testing, we replace values with alternatives # provided by the testing harness. table_id = override_values.get("table_id", table_id) # [START bigquery_insert_geography_wkt] # Use the Shapely library to generate WKT of a line from LAX to # JFK airports. Alternatively, you may define WKT data directly. my_geography = shapely.geometry.LineString( [(-118.4085, 33.9416), (-73.7781, 40.6413)] ) rows = [ # Convert data into a WKT string. {"geo": shapely.wkt.dumps(my_geography)}, ] # table already exists and has a column # named "geo" with data type GEOGRAPHY. errors = bigquery_client.insert_rows_json(table_id, rows) if errors: raise RuntimeError(f"row insert failed: {errors}") else: print(f"wrote 1 row to {table_id}") # [END bigquery_insert_geography_wkt] return errors
652
17,337
extern bool cppISteamApps_STEAMAPPS_INTERFACE_VERSION002_BIsSubscribed(void *); extern bool cppISteamApps_STEAMAPPS_INTERFACE_VERSION002_BIsLowViolence(void *); extern bool cppISteamApps_STEAMAPPS_INTERFACE_VERSION002_BIsCybercafe(void *); extern bool cppISteamApps_STEAMAPPS_INTERFACE_VERSION002_BIsVACBanned(void *); extern const char * cppISteamApps_STEAMAPPS_INTERFACE_VERSION002_GetCurrentGameLanguage(void *); extern const char * cppISteamApps_STEAMAPPS_INTERFACE_VERSION002_GetAvailableGameLanguages(void *); extern bool cppISteamApps_STEAMAPPS_INTERFACE_VERSION002_BIsSubscribedApp(void *, AppId_t);
219
2,603
[{"sale":{"_id":"54c7e8fa7261692b5acd0600","id":"los-angeles-modern-auctions-march-2015","name":"Los Angeles Modern Auctions - March 2015","is_auction":true,"auction_state":"open","published":true,"image_url":"https://d32dm0rphc51dk.cloudfront.net/BLv_dHIIVvShtDB8GCxFdg/:version.jpg","image_versions":["large_rectangle","source","square","wide"],"image_urls":{"large_rectangle":"https://d32dm0rphc51dk.cloudfront.net/BLv_dHIIVvShtDB8GCxFdg/large_rectangle.jpg","source":"https://d32dm0rphc51dk.cloudfront.net/BLv_dHIIVvShtDB8GCxFdg/source.jpg","square":"https://d32dm0rphc51dk.cloudfront.net/BLv_dHIIVvShtDB8GCxFdg/square.jpg","wide":"https://d32dm0rphc51dk.cloudfront.net/BLv_dHIIVvShtDB8GCxFdg/wide.jpg"},"original_width":null,"original_height":null,"created_at":"2015-01-27T19:37:30+00:00","currency":"USD"},"user":{"id":"56bcdc398b3b81698c000001","_id":"56bcdc398b3b81698c000001","name":"Testing Testing","default_profile_id":"user-56bcdc398b3b81698c000001"},"id":"56bcdc3a8b3b81698c00000f","created_by_admin":false,"created_at":"2016-02-11T19:08:42+00:00","pin":"7991"}]
453
2,753
<reponame>ShankarNara/shogun /* * Copyright (c) The Shogun Machine Learning Toolbox * Written (w) 2012 - 2013 <NAME> * Written (w) 2014 - 2017 <NAME> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * The views and conclusions contained in the software and documentation are those * of the authors and should not be interpreted as representing official policies, * either expressed or implied, of the Shogun Development Team. */ #include <shogun/io/SGIO.h> #include <shogun/lib/SGVector.h> #include <shogun/kernel/ShiftInvariantKernel.h> #include <shogun/distance/CustomDistance.h> #include <shogun/statistical_testing/TestEnums.h> #include <shogun/statistical_testing/QuadraticTimeMMD.h> #include <shogun/statistical_testing/MultiKernelQuadraticTimeMMD.h> #include <shogun/statistical_testing/internals/KernelManager.h> #include <shogun/statistical_testing/internals/mmd/ComputeMMD.h> #include <shogun/statistical_testing/internals/mmd/VarianceH1.h> #include <shogun/statistical_testing/internals/mmd/PermutationMMD.h> using namespace shogun; using namespace internal; using namespace mmd; using std::unique_ptr; struct MultiKernelQuadraticTimeMMD::Self { Self(QuadraticTimeMMD* owner); void update_pairwise_distance(const std::shared_ptr<Distance >&distance); QuadraticTimeMMD* m_owner; std::shared_ptr<CustomDistance> m_pairwise_distance; EDistanceType m_dtype; KernelManager m_kernel_mgr; ComputeMMD statistic_job; VarianceH1 variance_h1_job; PermutationMMD permutation_job; }; MultiKernelQuadraticTimeMMD::Self::Self(QuadraticTimeMMD* owner) : m_owner(owner), m_pairwise_distance(nullptr), m_dtype(D_UNKNOWN) { } void MultiKernelQuadraticTimeMMD::Self::update_pairwise_distance(const std::shared_ptr<Distance>& distance) { ASSERT(distance); if (m_dtype==distance->get_distance_type()) { ASSERT(m_pairwise_distance!=nullptr); io::info("Precomputed distance exists for {}!", distance->get_name()); } else { m_pairwise_distance=m_owner->compute_joint_distance(distance); m_dtype=distance->get_distance_type(); } } MultiKernelQuadraticTimeMMD::MultiKernelQuadraticTimeMMD() : RandomMixin<SGObject>() { self=unique_ptr<Self>(new Self(nullptr)); } MultiKernelQuadraticTimeMMD::MultiKernelQuadraticTimeMMD(QuadraticTimeMMD* owner) : RandomMixin<SGObject>() { self=unique_ptr<Self>(new Self(owner)); } MultiKernelQuadraticTimeMMD::~MultiKernelQuadraticTimeMMD() { cleanup(); } void MultiKernelQuadraticTimeMMD::add_kernel(const std::shared_ptr<shogun::Kernel>& kernel) { ASSERT(self->m_owner); require(kernel, "Kernel instance cannot be NULL!"); self->m_kernel_mgr.push_back(kernel->as<ShiftInvariantKernel>()); } void MultiKernelQuadraticTimeMMD::cleanup() { self->m_kernel_mgr.clear(); invalidate_precomputed_distance(); } void MultiKernelQuadraticTimeMMD::invalidate_precomputed_distance() { self->m_pairwise_distance=nullptr; self->m_dtype=D_UNKNOWN; } SGVector<float64_t> MultiKernelQuadraticTimeMMD::compute_statistic() { ASSERT(self->m_owner); return statistic(self->m_kernel_mgr); } SGVector<float64_t> MultiKernelQuadraticTimeMMD::compute_variance_h0() { ASSERT(self->m_owner); not_implemented(SOURCE_LOCATION);; return SGVector<float64_t>(); } SGVector<float64_t> MultiKernelQuadraticTimeMMD::compute_variance_h1() { ASSERT(self->m_owner); return variance_h1(self->m_kernel_mgr); } SGVector<float64_t> MultiKernelQuadraticTimeMMD::compute_test_power() { ASSERT(self->m_owner); return test_power(self->m_kernel_mgr); } SGMatrix<float32_t> MultiKernelQuadraticTimeMMD::sample_null() { ASSERT(self->m_owner); return sample_null(self->m_kernel_mgr); } SGVector<float64_t> MultiKernelQuadraticTimeMMD::compute_p_value() { ASSERT(self->m_owner); return p_values(self->m_kernel_mgr); } SGVector<bool> MultiKernelQuadraticTimeMMD::perform_test(float64_t alpha) { SGVector<float64_t> pvalues=compute_p_value(); SGVector<bool> rejections(pvalues.size()); for (auto i=0; i<pvalues.size(); ++i) { rejections[i]=pvalues[i]<alpha; } return rejections; } SGVector<float64_t> MultiKernelQuadraticTimeMMD::statistic(const KernelManager& kernel_mgr) { SG_TRACE("Entering"); require(kernel_mgr.num_kernels()>0, "Number of kernels ({}) have to be greater than 0!", kernel_mgr.num_kernels()); const auto nx=self->m_owner->get_num_samples_p(); const auto ny=self->m_owner->get_num_samples_q(); const auto stype = self->m_owner->get_statistic_type(); auto distance=kernel_mgr.get_distance_instance(); self->update_pairwise_distance(distance); kernel_mgr.set_precomputed_distance(self->m_pairwise_distance); self->statistic_job.m_n_x=nx; self->statistic_job.m_n_y=ny; self->statistic_job.m_stype=stype; SGVector<float64_t> result=self->statistic_job(kernel_mgr); kernel_mgr.unset_precomputed_distance(); for (auto i=0; i<result.vlen; ++i) result[i]=self->m_owner->normalize_statistic(result[i]); SG_TRACE("Leaving"); return result; } SGVector<float64_t> MultiKernelQuadraticTimeMMD::variance_h1(const KernelManager& kernel_mgr) { SG_TRACE("Entering"); require(kernel_mgr.num_kernels()>0, "Number of kernels ({}) have to be greater than 0!", kernel_mgr.num_kernels()); const auto nx=self->m_owner->get_num_samples_p(); const auto ny=self->m_owner->get_num_samples_q(); auto distance=kernel_mgr.get_distance_instance(); self->update_pairwise_distance(distance); kernel_mgr.set_precomputed_distance(self->m_pairwise_distance); self->variance_h1_job.m_n_x=nx; self->variance_h1_job.m_n_y=ny; SGVector<float64_t> result=self->variance_h1_job(kernel_mgr); kernel_mgr.unset_precomputed_distance(); SG_TRACE("Leaving"); return result; } SGVector<float64_t> MultiKernelQuadraticTimeMMD::test_power(const KernelManager& kernel_mgr) { SG_TRACE("Entering"); require(kernel_mgr.num_kernels()>0, "Number of kernels ({}) have to be greater than 0!", kernel_mgr.num_kernels()); require(self->m_owner->get_statistic_type()==ST_UNBIASED_FULL, "Only possible with UNBIASED_FULL!"); const auto nx=self->m_owner->get_num_samples_p(); const auto ny=self->m_owner->get_num_samples_q(); auto distance=kernel_mgr.get_distance_instance(); self->update_pairwise_distance(distance); kernel_mgr.set_precomputed_distance(self->m_pairwise_distance); self->variance_h1_job.m_n_x=nx; self->variance_h1_job.m_n_y=ny; SGVector<float64_t> result=self->variance_h1_job.test_power(kernel_mgr); kernel_mgr.unset_precomputed_distance(); SG_TRACE("Leaving"); return result; } SGMatrix<float32_t> MultiKernelQuadraticTimeMMD::sample_null(const KernelManager& kernel_mgr) { SG_TRACE("Entering"); require(self->m_owner->get_null_approximation_method()==NAM_PERMUTATION, "Multi-kernel tests requires the H0 approximation method to be PERMUTATION!"); require(kernel_mgr.num_kernels()>0, "Number of kernels ({}) have to be greater than 0!", kernel_mgr.num_kernels()); const auto nx=self->m_owner->get_num_samples_p(); const auto ny=self->m_owner->get_num_samples_q(); const auto stype = self->m_owner->get_statistic_type(); const auto num_null_samples = self->m_owner->get_num_null_samples(); auto distance=kernel_mgr.get_distance_instance(); self->update_pairwise_distance(distance); kernel_mgr.set_precomputed_distance(self->m_pairwise_distance); self->permutation_job.m_n_x=nx; self->permutation_job.m_n_y=ny; self->permutation_job.m_num_null_samples=num_null_samples; self->permutation_job.m_stype=stype; SGMatrix<float32_t> result=self->permutation_job(kernel_mgr, m_prng); kernel_mgr.unset_precomputed_distance(); for (index_t i=0; i<result.size(); ++i) result.matrix[i]=self->m_owner->normalize_statistic(result.matrix[i]); SG_TRACE("Leaving"); return result; } SGVector<float64_t> MultiKernelQuadraticTimeMMD::p_values(const KernelManager& kernel_mgr) { SG_TRACE("Entering"); require(self->m_owner->get_null_approximation_method()==NAM_PERMUTATION, "Multi-kernel tests requires the H0 approximation method to be PERMUTATION!"); require(kernel_mgr.num_kernels()>0, "Number of kernels ({}) have to be greater than 0!", kernel_mgr.num_kernels()); const auto nx=self->m_owner->get_num_samples_p(); const auto ny=self->m_owner->get_num_samples_q(); const auto stype = self->m_owner->get_statistic_type(); const auto num_null_samples = self->m_owner->get_num_null_samples(); auto distance=kernel_mgr.get_distance_instance(); self->update_pairwise_distance(distance); kernel_mgr.set_precomputed_distance(self->m_pairwise_distance); self->permutation_job.m_n_x=nx; self->permutation_job.m_n_y=ny; self->permutation_job.m_num_null_samples=num_null_samples; self->permutation_job.m_stype=stype; SGVector<float64_t> result=self->permutation_job.p_value(kernel_mgr, m_prng); kernel_mgr.unset_precomputed_distance(); SG_TRACE("Leaving"); return result; } const char* MultiKernelQuadraticTimeMMD::get_name() const { return "MultiKernelQuadraticTimeMMD"; }
3,811
1,405
package com.lenovo.safecenter.Laboratory; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import com.lenovo.safecenter.R; public class RootIntroduction extends Activity { /* access modifiers changed from: protected */ public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.rootintroduction_layout); ((TextView) findViewById(R.id.txt_title)).setText(R.string.root); ((ImageView) findViewById(R.id.title_back)).setOnClickListener(new View.OnClickListener() { /* class com.lenovo.safecenter.Laboratory.RootIntroduction.AnonymousClass1 */ public final void onClick(View v) { RootIntroduction.this.finish(); } }); } }
326
677
package io.qyi.e5.user.service; import io.qyi.e5.user.entity.User; import com.baomidou.mybatisplus.extension.service.IService; /** * <p> * 服务类 * </p> * * @author 落叶 * @since 2020-02-24 */ public interface IUserService extends IService<User> { }
116
7,892
<reponame>transat/audacity<gh_stars>1000+ /********************************************************************** Audacity: A Digital Audio Editor LoadEffects.cpp <NAME> **************************************************************************//** \class BuiltinEffectsModule \brief Internal module to auto register all built in effects. *****************************************************************************/ #include "LoadEffects.h" #include "Prefs.h" #include "Effect.h" #include "ModuleManager.h" static bool sInitialized = false; struct BuiltinEffectsModule::Entry { ComponentInterfaceSymbol name; BuiltinEffectsModule::Factory factory; bool excluded; using Entries = std::vector< Entry >; static Entries &Registry() { static Entries result; return result; } }; void BuiltinEffectsModule::DoRegistration( const ComponentInterfaceSymbol &name, const Factory &factory, bool excluded ) { wxASSERT( !sInitialized ); Entry::Registry().emplace_back( Entry{ name, factory, excluded } ); } // ============================================================================ // Module registration entry point // // This is the symbol that Audacity looks for when the module is built as a // dynamic library. // // When the module is builtin to Audacity, we use the same function, but it is // declared static so as not to clash with other builtin modules. // ============================================================================ DECLARE_MODULE_ENTRY(AudacityModule) { // Create and register the importer // Trust the module manager not to leak this return safenew BuiltinEffectsModule(); } // ============================================================================ // Register this as a builtin module // ============================================================================ DECLARE_BUILTIN_MODULE(BuiltinsEffectBuiltin); /////////////////////////////////////////////////////////////////////////////// // // BuiltinEffectsModule // /////////////////////////////////////////////////////////////////////////////// BuiltinEffectsModule::BuiltinEffectsModule() { } BuiltinEffectsModule::~BuiltinEffectsModule() { } // ============================================================================ // ComponentInterface implementation // ============================================================================ PluginPath BuiltinEffectsModule::GetPath() { return {}; } ComponentInterfaceSymbol BuiltinEffectsModule::GetSymbol() { return XO("Builtin Effects"); } VendorSymbol BuiltinEffectsModule::GetVendor() { return XO("The Audacity Team"); } wxString BuiltinEffectsModule::GetVersion() { // This "may" be different if this were to be maintained as a separate DLL return AUDACITY_VERSION_STRING; } TranslatableString BuiltinEffectsModule::GetDescription() { return XO("Provides builtin effects to Audacity"); } // ============================================================================ // ModuleInterface implementation // ============================================================================ bool BuiltinEffectsModule::Initialize() { for ( const auto &entry : Entry::Registry() ) { auto path = wxString(BUILTIN_EFFECT_PREFIX) + entry.name.Internal(); mEffects[ path ] = &entry; } sInitialized = true; return true; } void BuiltinEffectsModule::Terminate() { // Nothing to do here return; } EffectFamilySymbol BuiltinEffectsModule::GetOptionalFamilySymbol() { // Returns empty, because there should not be an option in Preferences to // disable the built-in effects. return {}; } const FileExtensions &BuiltinEffectsModule::GetFileExtensions() { static FileExtensions empty; return empty; } bool BuiltinEffectsModule::AutoRegisterPlugins(PluginManagerInterface & pm) { TranslatableString ignoredErrMsg; for (const auto &pair : mEffects) { const auto &path = pair.first; if (!pm.IsPluginRegistered(path, &pair.second->name.Msgid())) { if ( pair.second->excluded ) continue; // No checking of error ? DiscoverPluginsAtPath(path, ignoredErrMsg, PluginManagerInterface::DefaultRegistrationCallback); } } // We still want to be called during the normal registration process return false; } PluginPaths BuiltinEffectsModule::FindPluginPaths(PluginManagerInterface & WXUNUSED(pm)) { PluginPaths names; for ( const auto &pair : mEffects ) names.push_back( pair.first ); return names; } unsigned BuiltinEffectsModule::DiscoverPluginsAtPath( const PluginPath & path, TranslatableString &errMsg, const RegistrationCallback &callback) { errMsg = {}; auto effect = Instantiate(path); if (effect) { if (callback) callback(this, effect.get()); return 1; } errMsg = XO("Unknown built-in effect name"); return 0; } bool BuiltinEffectsModule::IsPluginValid(const PluginPath & path, bool bFast) { // bFast is unused as checking in the list is fast. static_cast<void>(bFast); return mEffects.find( path ) != mEffects.end(); } std::unique_ptr<ComponentInterface> BuiltinEffectsModule::CreateInstance(const PluginPath & path) { // Acquires a resource for the application. return Instantiate(path); } // ============================================================================ // BuiltinEffectsModule implementation // ============================================================================ std::unique_ptr<Effect> BuiltinEffectsModule::Instantiate(const PluginPath & path) { wxASSERT(path.StartsWith(BUILTIN_EFFECT_PREFIX)); auto iter = mEffects.find( path ); if ( iter != mEffects.end() ) return iter->second->factory(); wxASSERT( false ); return nullptr; }
1,611
903
<filename>smithy-openapi/src/main/java/software/amazon/smithy/openapi/model/CallbackObject.java<gh_stars>100-1000 /* * Copyright 2019 Amazon.com, Inc. or its affiliates. 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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 software.amazon.smithy.openapi.model; import java.util.Collections; import java.util.Map; import java.util.TreeMap; import software.amazon.smithy.model.node.Node; import software.amazon.smithy.model.node.ObjectNode; import software.amazon.smithy.utils.ToSmithyBuilder; public final class CallbackObject extends Component implements ToSmithyBuilder<CallbackObject> { private final Map<String, PathItem> paths; private CallbackObject(Builder builder) { super(builder); paths = Collections.unmodifiableMap(new TreeMap<>(builder.paths)); } public static Builder builder() { return new Builder(); } public Map<String, PathItem> getPaths() { return paths; } @Override protected ObjectNode.Builder createNodeBuilder() { ObjectNode.Builder builder = Node.objectNodeBuilder(); for (Map.Entry<String, PathItem> entry : paths.entrySet()) { builder.withMember(entry.getKey(), entry.getValue()); } return builder; } @Override public Builder toBuilder() { return builder().extensions(getExtensions()).paths(paths); } public static final class Builder extends Component.Builder<Builder, CallbackObject> { private Map<String, PathItem> paths = new TreeMap<>(); private Builder() {} @Override public CallbackObject build() { return new CallbackObject(this); } public Builder paths(Map<String, PathItem> paths) { this.paths.clear(); this.paths.putAll(paths); return this; } public Builder putPath(String expression, PathItem pathItem) { paths.put(expression, pathItem); return this; } } }
868
778
/* * Copyright (C) 2021 Intel Corporation * * SPDX-License-Identifier: MIT * */ #include "shared/source/os_interface/linux/local_memory_helper.h" #include "third_party/uapi/drm_tip/drm/i915_drm.h" #include <memory> namespace NEO { uint32_t createGemExtMemoryRegions(Drm *drm, void *data, uint32_t dataSize, size_t allocSize, uint32_t &handle) { drm_i915_gem_create_ext_memory_regions extRegions{}; extRegions.base.name = I915_GEM_CREATE_EXT_MEMORY_REGIONS; extRegions.num_regions = dataSize; extRegions.regions = reinterpret_cast<uintptr_t>(data); drm_i915_gem_create_ext createExt{}; createExt.size = allocSize; createExt.extensions = reinterpret_cast<uintptr_t>(&extRegions); auto ret = LocalMemoryHelper::ioctl(drm, DRM_IOCTL_I915_GEM_CREATE_EXT, &createExt); handle = createExt.handle; return ret; } bool isQueryDrmTip(uint8_t *dataQuery, int32_t length) { auto dataOnDrmTip = reinterpret_cast<drm_i915_query_memory_regions *>(dataQuery); auto lengthOnDrmTip = static_cast<int32_t>(sizeof(drm_i915_query_memory_regions) + dataOnDrmTip->num_regions * sizeof(drm_i915_memory_region_info)); return length == lengthOnDrmTip; } namespace PROD_DG1 { #undef DRM_IOCTL_I915_GEM_CREATE_EXT #undef __I915_EXEC_UNKNOWN_FLAGS #include "third_party/uapi/dg1/drm/i915_drm.h" } // namespace PROD_DG1 std::unique_ptr<uint8_t[]> translateToDrmTip(uint8_t *dataQuery, int32_t &length) { auto dataOnProdDrm = reinterpret_cast<PROD_DG1::drm_i915_query_memory_regions *>(dataQuery); auto lengthTranslated = static_cast<int32_t>(sizeof(drm_i915_query_memory_regions) + dataOnProdDrm->num_regions * sizeof(drm_i915_memory_region_info)); auto dataQueryTranslated = std::make_unique<uint8_t[]>(lengthTranslated); auto dataTranslated = reinterpret_cast<drm_i915_query_memory_regions *>(dataQueryTranslated.get()); dataTranslated->num_regions = dataOnProdDrm->num_regions; for (uint32_t i = 0; i < dataTranslated->num_regions; i++) { dataTranslated->regions[i].region.memory_class = dataOnProdDrm->regions[i].region.memory_class; dataTranslated->regions[i].region.memory_instance = dataOnProdDrm->regions[i].region.memory_instance; dataTranslated->regions[i].probed_size = dataOnProdDrm->regions[i].probed_size; dataTranslated->regions[i].unallocated_size = dataOnProdDrm->regions[i].unallocated_size; } length = lengthTranslated; return dataQueryTranslated; } } // namespace NEO
996
2,828
<reponame>tamaashu/curator /** * 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.curator.framework.recipes.atomic; /** * Uses an {@link DistributedAtomicNumber} and allocates values in chunks for better performance */ public class CachedAtomicLong { private final DistributedAtomicLong number; private final long cacheFactor; private AtomicValue<Long> currentValue = null; private int currentIndex = 0; /** * @param number the number to use * @param cacheFactor the number of values to allocate at a time */ public CachedAtomicLong(DistributedAtomicLong number, int cacheFactor) { this.number = number; this.cacheFactor = cacheFactor; } /** * Returns the next value (incrementing by 1). If a new chunk of numbers is needed, it is * requested from the number * * @return next increment * @throws Exception errors */ public AtomicValue<Long> next() throws Exception { MutableAtomicValue<Long> result = new MutableAtomicValue<Long>(0L, 0L); if ( currentValue == null ) { currentValue = number.add(cacheFactor); if ( !currentValue.succeeded() ) { currentValue = null; result.succeeded = false; return result; } currentIndex = 0; } result.succeeded = true; result.preValue = currentValue.preValue() + currentIndex; result.postValue = result.preValue + 1; if ( ++currentIndex >= cacheFactor ) { currentValue = null; } return result; } }
916
1,278
<filename>lobster/src/lobster/compiler.h // Copyright 2014 <NAME>. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef LOBSTER_COMPILER #define LOBSTER_COMPILER #include "lobster/natreg.h" namespace lobster { enum { RUNTIME_NO_ASSERT, RUNTIME_ASSERT, RUNTIME_ASSERT_PLUS }; extern void Compile(NativeRegistry &natreg, string_view fn, string_view stringsource, string &bytecode, string *parsedump, string *pakfile, bool dump_builtins, bool dump_names, bool return_value, int runtime_checks); extern bool LoadPakDir(const char *lpak); extern bool LoadByteCode(string &bytecode); extern void RegisterBuiltin(NativeRegistry &natreg, const char *name, void (* regfun)(NativeRegistry &)); extern void RegisterCoreLanguageBuiltins(NativeRegistry &natreg); extern VMArgs CompiledInit(int argc, char *argv[], const void *entry_point, const void *bytecodefb, size_t static_size, const lobster::block_t *vtables, FileLoader loader, NativeRegistry &nfr); extern "C" int ConsoleRunCompiledCodeMain(int argc, char *argv[], const void *entry_point, const void *bytecodefb, size_t static_size, const lobster::block_t *vtables); } // namespace lobster #endif // LOBSTER_COMPILER
728
1,405
package com.lenovo.safecenter.AppsManager; import android.app.Activity; import android.content.Intent; import android.graphics.Color; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.view.MotionEvent; import android.view.View; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ListAdapter; import android.widget.ListView; import android.widget.RelativeLayout; import android.widget.TextView; import com.lenovo.performancecenter.framework.DatabaseTables; import com.lenovo.safecenter.R; import com.lenovo.safecenter.adapter.NewLogsAdapter; import com.lenovo.safecenter.database.AppDatabase; import com.lenovo.safecenter.support.SafeLog; import com.lenovo.safecenter.utils.Const; import com.lenovo.safecenter.utils.TrackEvent; import com.lenovo.safecenter.utils.WflUtils; import java.util.List; public class PermissionControlNew extends Activity implements View.OnClickListener { private List<SafeLog> a; private TextView b; private TextView c; private TextView d; private TextView e; private TextView f; private ListView g; private ImageView h; private LinearLayout i; private RelativeLayout j; private RelativeLayout k; private RelativeLayout l; private RelativeLayout m; private int n = 0; private boolean o; private Handler p = new Handler() { /* class com.lenovo.safecenter.AppsManager.PermissionControlNew.AnonymousClass1 */ public final void handleMessage(Message msg) { switch (msg.what) { case 0: PermissionControlNew.this.f.setText(String.format(PermissionControlNew.this.getString(R.string.trust_app_num), Integer.valueOf(PermissionControlNew.this.n))); if (PermissionControlNew.this.a.size() == 0) { PermissionControlNew.this.c.setVisibility(0); PermissionControlNew.this.j.setVisibility(8); return; } PermissionControlNew.this.c.setVisibility(8); PermissionControlNew.this.j.setVisibility(0); PermissionControlNew.this.g.setAdapter((ListAdapter) new NewLogsAdapter(PermissionControlNew.this, PermissionControlNew.this.a)); return; case 1: PermissionControlNew.this.f.setText(String.format(PermissionControlNew.this.getString(R.string.trust_app_num), Integer.valueOf(PermissionControlNew.this.n))); return; default: return; } } }; /* access modifiers changed from: protected */ public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.permissioncontrol); this.o = WflUtils.isRoot(); this.d = (TextView) findViewById(R.id.txt_what); this.e = (TextView) findViewById(R.id.txt_answer); this.f = (TextView) findViewById(R.id.txt_trust); this.f.setOnTouchListener(new View.OnTouchListener() { /* class com.lenovo.safecenter.AppsManager.PermissionControlNew.AnonymousClass2 */ public final boolean onTouch(View v, MotionEvent event) { if (event.getAction() == 1) { PermissionControlNew.this.f.setTextColor(Color.parseColor("#29b1ef")); return false; } else if (event.getAction() == 0) { PermissionControlNew.this.f.setTextColor(Color.parseColor("#6600ff")); return false; } else if (event.getAction() != 3 && event.getAction() != 4) { return false; } else { PermissionControlNew.this.f.setTextColor(Color.parseColor("#29b1ef")); return false; } } }); this.b = (TextView) findViewById(R.id.txt_title); this.b.setText(R.string.permission_control); this.c = (TextView) findViewById(R.id.txt_empty); this.g = (ListView) findViewById(R.id.listView); this.g.setEnabled(false); this.h = (ImageView) findViewById(R.id.title_back); this.i = (LinearLayout) findViewById(R.id.more_logs); this.j = (RelativeLayout) findViewById(R.id.logs_layout); this.k = (RelativeLayout) findViewById(R.id.privacy_layout); this.l = (RelativeLayout) findViewById(R.id.location_layout); this.m = (RelativeLayout) findViewById(R.id.record_layout); this.l.setVisibility(0); this.l.setOnClickListener(this); this.h.setOnClickListener(this); this.f.setOnClickListener(this); this.i.setOnClickListener(this); this.k.setOnClickListener(this); this.m.setOnClickListener(this); } /* access modifiers changed from: protected */ public void onResume() { super.onResume(); TrackEvent.trackResume(this); if (Const.mDefaultPreference.getBoolean("privacy_first", true)) { this.d.setText(R.string.what_privacy); this.e.setVisibility(0); this.f.setVisibility(8); findViewById(R.id.trust_arrow).setVisibility(8); Const.mDefaultPreference.edit().putBoolean("privacy_first", false).commit(); } else { this.d.setText(R.string.privacy_protect); this.e.setVisibility(8); this.f.setVisibility(0); findViewById(R.id.trust_arrow).setVisibility(0); } new Thread() { /* class com.lenovo.safecenter.AppsManager.PermissionControlNew.AnonymousClass3 */ public final void run() { AppDatabase database = new AppDatabase(PermissionControlNew.this); if (Const.getScreenHeight() > 800) { PermissionControlNew.this.a = database.getTopThreeLogs(AppDatabase.DB_LOG_PRIVACY, 4); } else { PermissionControlNew.this.a = database.getTopThreeLogs(AppDatabase.DB_LOG_PRIVACY, 3); } if (PermissionControlNew.this.o) { PermissionControlNew.this.n = database.getTrustedApps(AppDatabase.PERM_TYPE_PRIVCY); } PermissionControlNew.this.p.sendMessage(PermissionControlNew.this.p.obtainMessage(0)); } }.start(); } /* access modifiers changed from: protected */ public void onPause() { TrackEvent.trackPause(this); super.onPause(); } public void onClick(View v) { switch (v.getId()) { case R.id.privacy_layout /*{ENCODED_INT: 2131296772}*/: Intent it1 = new Intent(this, ApplicationList.class); it1.putExtra("permType", AppDatabase.PERM_TYPE_PRIVCY); startActivityForResult(it1, 0); return; case R.id.location_layout /*{ENCODED_INT: 2131296778}*/: Intent it2 = new Intent(this, ApplicationList.class); it2.putExtra("permType", "location"); startActivityForResult(it2, 0); return; case R.id.more_logs /*{ENCODED_INT: 2131296887}*/: Intent it0 = new Intent(this, DisplayLog.class); it0.putExtra("from", DatabaseTables.SYSTEM_MARK); startActivityForResult(it0, 1); return; case R.id.record_layout /*{ENCODED_INT: 2131297147}*/: Intent it3 = new Intent(this, ApplicationList.class); it3.putExtra("permType", AppDatabase.PERM_TYPE_DEVICE); startActivityForResult(it3, 0); return; case R.id.txt_trust /*{ENCODED_INT: 2131297407}*/: Intent it = new Intent(this, AppsManager.class); it.putExtra("permType", AppDatabase.PERM_TYPE_PRIVCY); startActivityForResult(it, 0); return; case R.id.title_back /*{ENCODED_INT: 2131297709}*/: finish(); return; default: return; } } /* access modifiers changed from: protected */ public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); switch (resultCode) { case 0: default: return; case 1: this.a.clear(); this.p.sendMessage(this.p.obtainMessage(0)); return; } } }
4,067
1,847
/* * Copyright (C) 2021 The Android Open Source Project * * 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 <stdarg.h> #include <stdint.h> #include <stdio.h> #include <string> #include <android-base/stringprintf.h> #include <unwindstack/Log.h> namespace unwindstack { namespace Log { static void PrintToStdout(uint8_t indent, const char* format, va_list args) { std::string real_format; if (indent > 0) { real_format = android::base::StringPrintf("%*s%s", 2 * indent, " ", format); } else { real_format = format; } real_format += '\n'; vprintf(real_format.c_str(), args); } void Info(const char* format, ...) { va_list args; va_start(args, format); PrintToStdout(0, format, args); va_end(args); } void Info(uint8_t indent, const char* format, ...) { va_list args; va_start(args, format); PrintToStdout(indent, format, args); va_end(args); } void Error(const char* format, ...) { va_list args; va_start(args, format); PrintToStdout(0, format, args); va_end(args); } // Do nothing for async safe. void AsyncSafe(const char*, ...) {} } // namespace Log } // namespace unwindstack
562
380
<reponame>GluuFederation/oxAuth package org.gluu.oxauth.client; import javax.ws.rs.HttpMethod; import javax.ws.rs.client.Entity; import javax.ws.rs.client.Invocation.Builder; import org.apache.log4j.Logger; /** * @author <NAME> */ public class RevokeSessionClient extends BaseClient<RevokeSessionRequest, RevokeSessionResponse>{ private static final Logger LOG = Logger.getLogger(RevokeSessionClient.class); /** * Constructs a token client by providing a REST url where the token service * is located. * * @param url The REST Service location. */ public RevokeSessionClient(String url) { super(url); } @Override public String getHttpMethod() { return HttpMethod.POST; } public RevokeSessionResponse exec(RevokeSessionRequest request) { setRequest(request); return exec(); } public RevokeSessionResponse exec() { initClientRequest(); Builder clientRequest = webTarget.request(); new ClientAuthnEnabler(clientRequest, requestForm).exec(request); clientRequest.header("Content-Type", request.getContentType()); // clientRequest.setHttpMethod(getHttpMethod()); if (getRequest().getUserCriterionKey() != null) { requestForm.param("user_criterion_key", getRequest().getUserCriterionKey()); } if (getRequest().getUserCriterionValue() != null) { requestForm.param("user_criterion_value", getRequest().getUserCriterionValue()); } for (String key : getRequest().getCustomParameters().keySet()) { requestForm.param(key, getRequest().getCustomParameters().get(key)); } try { clientResponse = clientRequest.buildPost(Entity.form(requestForm)).invoke(); final RevokeSessionResponse response = new RevokeSessionResponse(clientResponse); setResponse(response); } catch (Exception e) { LOG.error(e.getMessage(), e); } finally { closeConnection(); } return getResponse(); } }
800
906
<gh_stars>100-1000 /* * This file is part of Mixin, licensed under the MIT License (MIT). * * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.asm.mixin.transformer; import java.util.List; import org.objectweb.asm.tree.ClassNode; import org.spongepowered.asm.mixin.MixinEnvironment; import org.spongepowered.asm.mixin.transformer.ext.IExtensionRegistry; import org.spongepowered.asm.service.ILegacyClassTransformer; /** * Transformation engine */ public interface IMixinTransformer { /** * Force-load all classes targetted by mixins but not yet applied * * @param environment current environment */ public abstract void audit(MixinEnvironment environment); /** * Update a mixin class with new bytecode. * * @param mixinClass Name of the mixin * @param classNode New bytecode * @return List of classes that need to be updated */ public abstract List<String> reload(String mixinClass, ClassNode classNode); /** * Called when the transformation reason is computing_frames. The only * operation we care about here is adding interfaces to target classes but * at the moment we don't have sufficient scaffolding to determine that * without triggering re-entrance. Currently just a no-op in order to not * cause a re-entrance crash under ModLauncher 7.0+. * * @param environment Current environment * @param name Class transformed name * @param classNode Class tree * @return true if the class was transformed */ public abstract boolean computeFramesForClass(MixinEnvironment environment, String name, ClassNode classNode); /** * Callback from the hotswap agent and LaunchWrapper Proxy, transform class * bytecode. This method delegates to class generation or class * transformation based on whether the supplied byte array is <tt>null</tt> * and is therefore suitable for hosts which follow the LaunchWrapper * contract. * * @param name Class name * @param transformedName Transformed class name * @param basicClass class bytecode * @return transformed class bytecode * * @see ILegacyClassTransformer#transformClassBytes(String, String, byte[]) */ public abstract byte[] transformClassBytes(String name, String transformedName, byte[] basicClass); /** * Apply mixins and postprocessors to the supplied class * * @param environment Current environment * @param name Class transformed name * @param classBytes Class bytecode * @return Transformed bytecode */ public abstract byte[] transformClass(MixinEnvironment environment, String name, byte[] classBytes); /** * Apply mixins and postprocessors to the supplied class * * @param environment Current environment * @param name Class transformed name * @param classNode Class tree * @return true if the class was transformed */ public abstract boolean transformClass(MixinEnvironment environment, String name, ClassNode classNode); /** * Generate the specified mixin-synthetic class * * @param environment Current environment * @param name Class name to generate * @return Generated bytecode or <tt>null</tt> if no class was generated */ public abstract byte[] generateClass(MixinEnvironment environment, String name); /** * @param environment Current environment * @param name Class transformed name * @param classNode Empty classnode to populate * @return True if the class was generated successfully */ public abstract boolean generateClass(MixinEnvironment environment, String name, ClassNode classNode); /** * Get the transformer extensions */ public abstract IExtensionRegistry getExtensions(); }
1,474
754
/*- * << * UAVStack * == * Copyright (C) 2016 - 2017 UAVStack * == * 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.creditease.monitor.datastore.jmx; import java.util.Collection; import java.util.Map; import com.creditease.agent.helpers.DataConvertHelper; import com.creditease.agent.helpers.JSONHelper; import com.creditease.monitor.UAVServer; import com.creditease.monitor.datastore.DataObserver; import com.creditease.monitor.datastore.spi.DataObserverListener; import com.creditease.monitor.log.Logger; import com.creditease.uav.profiling.spi.Profile; import com.creditease.uav.profiling.spi.ProfileConstants; import com.creditease.uav.profiling.spi.ProfileElement; import com.creditease.uav.profiling.spi.ProfileElementInstance; public class ProfileObserver implements ProfileObserverMBean { private final static Logger log = UAVServer.instance().getLog(); protected Profile profile; public ProfileObserver(Profile profile) { this.profile = profile; } @Override public String getData() { /** * for iplink, we should remove those iplink not active over 1 min, the health manager will help to maintain the * state change */ removeExpireIpLinkPEI(); String data = this.profile.getRepository().toJSONString(); // in case of \\ to / data = data.replace("\\", "/"); return data; } @SuppressWarnings("unchecked") private void removeExpireIpLinkPEI() { long curTime = System.currentTimeMillis(); long appTimeout = DataConvertHelper.toLong(System.getProperty("com.creditease.uav.iplink.app.timeout"), 3600000); long userTimeout = DataConvertHelper.toLong(System.getProperty("com.creditease.uav.iplink.user.timeout"), 60000); long proxyTimeout = DataConvertHelper.toLong(System.getProperty("com.creditease.uav.iplink.proxy.timeout"), 3600000); long proxyAppTimeout = DataConvertHelper .toLong(System.getProperty("com.creditease.uav.iplink.proxy.app.timeout"), 3600000); long proxyUserTimeout = DataConvertHelper .toLong(System.getProperty("com.creditease.uav.iplink.proxy.user.timeout"), 60000); ProfileElement pe = this.profile.getRepository().getElement(ProfileConstants.PROELEM_IPLINK); ProfileElementInstance[] peis = pe.getInstances(); for (ProfileElementInstance pei : peis) { // step 1: check pei expire String peiId = pei.getInstanceId(); long peiTimeout = 0; if (peiId.indexOf("browser") == 0) { peiTimeout = userTimeout; } else if (peiId.indexOf("proxy") == 0) { peiTimeout = proxyTimeout; } else { peiTimeout = appTimeout; } long ts = (Long) pei.getValues().get("ts"); if (curTime - ts > peiTimeout) { pe.removeInstance(pei.getInstanceId()); continue; } // step 2: check pei's clients expire if (!pei.getValues().containsKey(ProfileConstants.PEI_CLIENTS)) { continue; } Map<String, Long> clients = (Map<String, Long>) pei.getValues().get(ProfileConstants.PEI_CLIENTS); for (String key : clients.keySet()) { Long clientts = (long) clients.get(key); long clientTimeout = 0; if (key.indexOf("user") == 0) { clientTimeout = proxyUserTimeout; } else { clientTimeout = proxyAppTimeout; } if (curTime - clientts > clientTimeout) { clients.remove(key); } } } } @Override public boolean isUpdate() { return this.profile.getRepository().isUpdate(); } @Override public void setUpdate(boolean check) { this.profile.getRepository().setUpdate(check); } /** * Profile的事件监控接口 * * @param data * 接收数据格式:{event:"",data:""} event: 是每个listener自定义的一个事件字符串 data:是每个listener自动以的事件数据 * @return 必要时返回处理结果 * * 例如 {event:"uav.dp.service.register",data: * "{appid:\"com.creditease.uav.monitorframework.buildFat\",infos:[{id:\"test\",url:\"testurl\",name:\"testservice\",s:0,sval:\"testval\"}]}"} */ @SuppressWarnings({ "unchecked" }) @Override public String optData(String data) { Map<String, String> jo = JSONHelper.toObject(data, Map.class); if (null == jo) { return null; } String event = jo.get("event"); if (null == event) { return null; } String dat = jo.get("data"); if (null == dat) { return null; } Collection<DataObserverListener> listeners = DataObserver.instance().getListeners(); for (DataObserverListener l : listeners) { /** * only choose the first handlable listener */ if (l.isHandlable(event)) { try { return l.handle(dat); } catch (Exception e) { log.error("DataObserverListener[" + l.getClass().getName() + "] handle FAIL,event=" + event + ",data=" + data, e); continue; } } } return null; } @Override public int getState() { return this.profile.getRepository().getState(); } }
2,885
972
<filename>python/tests/spark_test_case.py<gh_stars>100-1000 # # Copyright 2017-2018 TWO SIGMA OPEN SOURCE, LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ''' The common code for all Flint unit tests ''' import os import sys import collections from tests.base_test_case import BaseTestCase class SparkTestCase(BaseTestCase): ''' Base class for all Flint tests ''' @classmethod def setUpClass(cls): ''' The automatic setup method for subclasses ''' cls.__setup() @classmethod def tearDownClass(cls): ''' The automatic tear down method for subclasses ''' cls.__teardown() @classmethod def __setup(cls, options=None): '''Starts spark and sets attributes `sc,sqlContext and flintContext''' from pyspark import SparkContext, SparkConf from pyspark.sql import SQLContext from ts.flint import FlintContext default_options = (SparkConf() .setAppName(cls.__name__) .setMaster("local") .set("spark.sql.session.timeZone", "UTC") .set("spark.flint.timetype", "timestamp")) setattr(cls, '_env', dict(os.environ)) setattr(cls, '_path', list(sys.path)) options = collections.ChainMap(options, default_options) spark_context = SparkContext(conf=SparkConf(options)) sql_context = SQLContext(spark_context) flint_context = FlintContext(sql_context) setattr(cls, 'sc', spark_context) setattr(cls, 'sqlContext', sql_context) setattr(cls, 'flintContext', flint_context) @classmethod def __teardown(cls): from pyspark import SparkContext '''Shuts down spark and removes attributes sc, and sqlContext''' cls.sc.stop() cls.sc._gateway.shutdown() cls.sc._gateway = None SparkContext._jvm = None SparkContext._gateway = None delattr(cls, 'sqlContext') delattr(cls, 'sc') os.environ = cls._env sys.path = cls._path delattr(cls, '_env') delattr(cls, '_path')
1,080
441
import ffn import matplotlib.pyplot as plt import matplotlib prices = ffn.get('aapl,msft', start='2020-04-01') stats = prices.calc_stats() print(stats.display())
60
566
<gh_stars>100-1000 /** * This file is part of dvo. * * Copyright 2013 <NAME> <<EMAIL>> (Technical University of Munich) * For more information see <http://vision.in.tum.de/data/software/dvo>. * * dvo 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 3 of the License, or * (at your option) any later version. * * dvo 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 dvo. If not, see <http://www.gnu.org/licenses/>. */ #ifndef POINT_SELECTION_PREDICATES_H_ #define POINT_SELECTION_PREDICATES_H_ namespace dvo { namespace core { /* struct PointSelectPredicate { bool operator() (const size_t& x, const size_t& y, const float& z, const float& idx, const float& idy, const float& zdx, const float& zdy) const { return false; } }; struct ValidPointPredicate { bool operator() (const size_t& x, const size_t& y, const float& z, const float& idx, const float& idy, const float& zdx, const float& zdy) const { return z == z && zdx == zdx && zdy == zdy; } }; struct ValidPointAndGradientThresholdPredicate { float intensity_threshold; float depth_threshold; ValidPointAndGradientThresholdPredicate() : intensity_threshold(0.0f), depth_threshold(0.0f) { } bool operator() (const size_t& x, const size_t& y, const float& z, const float& idx, const float& idy, const float& zdx, const float& zdy) const { //&& std::abs(zdx) < 0.5 && std::abs(zdy) < 0.5 return z == z && z < 3.0 && zdx == zdx && zdy == zdy && (std::abs(idx) > intensity_threshold || std::abs(idy) > intensity_threshold || std::abs(zdx) > depth_threshold || std::abs(zdy) > depth_threshold); } }; template<typename TPredicate> struct PredicateDebugDecorator { public: PredicateDebugDecorator() : max_x_(0), max_y_(0), current_rl_(0) { } bool operator() (const size_t& x, const size_t& y, const float& z, const float& idx, const float& idy, const float& zdx, const float& zdy) const { PredicateDebugDecorator<TPredicate> *me = const_cast<PredicateDebugDecorator<TPredicate>* >(this); if(x == 0 && y == 0) { me->selected_.clear(); me->max_x_ = 0;me->max_y_ = 0; me->current_rl_ = 0; } bool success = delegate(x, y, z, idx, idy, zdx, zdy); me->max_x_ = std::max(me->max_x_, x); me->max_y_ = std::max(me->max_y_, y); if(success) { me->selected_.push_back(me->current_rl_); me->current_rl_ = 1; } else { me->current_rl_ += 1; } return success; } template<typename TMask> void toMask(cv::Mat& mask) const { mask = cv::Mat::zeros(max_y_ + 1, max_x_ + 1, cv::DataType<TMask>::type); TMask *mask_ptr = mask.ptr<TMask>(); TMask one(1); for(std::vector<size_t>::const_iterator it = selected_.begin(); it != selected_.end(); ++it) { mask_ptr += (*it); *mask_ptr = one; } } template<typename TImage, typename TIter, typename TFunctor> void toImage(const TIter& begin, const TIter& end, cv::Mat& img, const TFunctor& transform) const { size_t n = std::min(selected_.size(), size_t(end - begin)); //std::cerr << max_y_ << " " << max_x_ << std::endl; img = cv::Mat::zeros(max_y_ + 1, max_x_ + 1, cv::DataType<TImage>::type); TImage *img_ptr = img.ptr<TImage>(); TIter value_it = begin; for(std::vector<size_t>::const_iterator it = selected_.begin(); it != selected_.begin() + n; ++it, ++value_it) { img_ptr += (*it); *img_ptr = transform(*value_it); } } TPredicate delegate; private: size_t max_x_, max_y_, current_rl_; std::vector<size_t> selected_; }; */ } /* namespace core */ } /* namespace dvo */ #endif /* POINT_SELECTION_PREDICATES_H_ */
1,612
922
from .degrade import *
7
643
<reponame>michaelsilverstein/scikit-bio # ---------------------------------------------------------------------------- # Copyright (c) 2013--, scikit-bio development team. # # Distributed under the terms of the Modified BSD License. # # The full license is in the file COPYING.txt, distributed with this software. # ---------------------------------------------------------------------------- import numpy as np import numpy.testing as npt import pandas as pd from unittest import TestCase, main from skbio import OrdinationResults from skbio.stats.ordination import cca from skbio.util import get_data_path, assert_ordination_results_equal class TestCCAErrors(TestCase): def setUp(self): """Data from table 11.3 in Legendre & Legendre 1998.""" self.Y = pd.DataFrame(np.loadtxt(get_data_path('example3_Y'))) self.X = pd.DataFrame(np.loadtxt(get_data_path('example3_X'))) def test_shape(self): X, Y = self.X, self.Y with npt.assert_raises(ValueError): cca(Y, X[:-1]) def test_Y_values(self): X, Y = self.X, self.Y Y[0, 0] = -1 with npt.assert_raises(ValueError): cca(Y, X) Y[0] = 0 with npt.assert_raises(ValueError): cca(Y, X) def test_scaling(self): X, Y = self.X, self.Y with npt.assert_raises(NotImplementedError): cca(Y, X, 3) def test_all_zero_row(self): X, Y = pd.DataFrame(np.zeros((3, 3))), pd.DataFrame(np.zeros((3, 3))) with npt.assert_raises(ValueError): cca(X, Y) class TestCCAResults1(TestCase): def setUp(self): """Data from table 11.3 in Legendre & Legendre 1998 (p. 590). Loaded results as computed with vegan 2.0-8 and compared with table 11.5 if also there.""" self.feature_ids = ['Feature0', 'Feature1', 'Feature2', 'Feature3', 'Feature4', 'Feature5', 'Feature6', 'Feature7', 'Feature8'] self.sample_ids = ['Sample0', 'Sample1', 'Sample2', 'Sample3', 'Sample4', 'Sample5', 'Sample6', 'Sample7', 'Sample8', 'Sample9'] self.env_ids = ['Constraint0', 'Constraint1', 'Constraint2'] self.pc_ids = ['CCA1', 'CCA2', 'CCA3', 'CCA4', 'CCA5', 'CCA6', 'CCA7', 'CCA8', 'CCA9'] self.Y = pd.DataFrame( np.loadtxt(get_data_path('example3_Y')), columns=self.feature_ids, index=self.sample_ids) self.X = pd.DataFrame( np.loadtxt(get_data_path('example3_X'))[:, :-1], columns=self.env_ids, index=self.sample_ids ) def test_scaling1(self): scores = cca(self.Y, self.X, scaling=1) # Load data as computed with vegan 2.0-8 vegan_features = pd.DataFrame( np.loadtxt(get_data_path( 'example3_species_scaling1_from_vegan')), index=self.feature_ids, columns=self.pc_ids) vegan_samples = pd.DataFrame( np.loadtxt(get_data_path( 'example3_site_scaling1_from_vegan')), index=self.sample_ids, columns=self.pc_ids) sample_constraints = pd.DataFrame( np.loadtxt(get_data_path( 'example3_sample_constraints_scaling1')), index=self.sample_ids, columns=self.pc_ids) mat = np.loadtxt(get_data_path( 'example3_biplot_scaling1')) cropped_pcs = self.pc_ids[:mat.shape[1]] biplot_scores = pd.DataFrame(mat, index=self.env_ids, columns=cropped_pcs) proportion_explained = pd.Series([0.466911, 0.238327, 0.100548, 0.104937, 0.044805, 0.029747, 0.012631, 0.001562, 0.000532], index=self.pc_ids) eigvals = pd.Series([0.366136, 0.186888, 0.078847, 0.082288, 0.035135, 0.023327, 0.009905, 0.001225, 0.000417], index=self.pc_ids) exp = OrdinationResults( 'CCA', 'Canonical Correspondence Analysis', samples=vegan_samples, features=vegan_features, sample_constraints=sample_constraints, biplot_scores=biplot_scores, proportion_explained=proportion_explained, eigvals=eigvals) assert_ordination_results_equal(scores, exp, decimal=6) def test_scaling2(self): scores = cca(self.Y, self.X, scaling=2) # Load data as computed with vegan 2.0-8 vegan_features = pd.DataFrame( np.loadtxt(get_data_path( 'example3_species_scaling2_from_vegan')), index=self.feature_ids, columns=self.pc_ids) vegan_samples = pd.DataFrame( np.loadtxt(get_data_path( 'example3_site_scaling2_from_vegan')), index=self.sample_ids, columns=self.pc_ids) sample_constraints = pd.DataFrame( np.loadtxt(get_data_path( 'example3_sample_constraints_scaling2')), index=self.sample_ids, columns=self.pc_ids) mat = np.loadtxt(get_data_path( 'example3_biplot_scaling2')) cropped_pc_ids = self.pc_ids[:mat.shape[1]] biplot_scores = pd.DataFrame(mat, index=self.env_ids, columns=cropped_pc_ids) proportion_explained = pd.Series([0.466911, 0.238327, 0.100548, 0.104937, 0.044805, 0.029747, 0.012631, 0.001562, 0.000532], index=self.pc_ids) eigvals = pd.Series([0.366136, 0.186888, 0.078847, 0.082288, 0.035135, 0.023327, 0.009905, 0.001225, 0.000417], index=self.pc_ids) exp = OrdinationResults( 'CCA', 'Canonical Correspondence Analysis', samples=vegan_samples, features=vegan_features, sample_constraints=sample_constraints, biplot_scores=biplot_scores, proportion_explained=proportion_explained, eigvals=eigvals) assert_ordination_results_equal(scores, exp, decimal=6) if __name__ == '__main__': main()
3,618
334
<gh_stars>100-1000 # -*- coding: utf-8 -*- # Copyright (c) 2015 Ericsson AB # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from collections import defaultdict from calvin.actor.actor import Actor, manage, condition, stateguard from calvin.runtime.north.calvin_token import EOSToken from calvin.utilities.calvinlogger import get_logger _log = get_logger(__name__) class WordCount(Actor): """ Count occurances of words in a stream of words. Inputs: in : a word Outputs: out : count for each word """ @manage([]) def init(self): self.word_counts = defaultdict(int) self.finished = False def exception_handler(self, action, args): self.finished = True @condition(['in'], []) def count_word(self, word): self.word_counts[word] = self.word_counts[word] + 1 @stateguard(lambda self: self.finished is True) @condition(action_output=['out']) def output_counts(self): self.finished = False return (self.word_counts,) action_priority = (count_word, output_counts) test_set = [ { 'inports': {'in': ['a', 'b', 'a', EOSToken()]}, 'outports': {'out': [{'a': 2, 'b': 1}]} } ]
648
1,655
<gh_stars>1000+ #include <windows.h> #pragma comment(lib, "USER32") BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved) { CHAR Command[] = "cmd"; CHAR ModulePath[MAX_PATH]; CHAR ModuleName[MAX_PATH]; STARTUPINFO si; PROCESS_INFORMATION pi; ZeroMemory(&si, sizeof(si)); ZeroMemory(&pi, sizeof(pi)); ZeroMemory(&ModulePath, sizeof(ModulePath)); ZeroMemory(&ModuleName, sizeof(ModuleName)); si.cb = sizeof si; // Learn what process we've loaded into, in case we need it. if (GetModuleFileNameA(NULL, ModulePath, sizeof ModulePath)) { _splitpath(ModulePath, NULL, NULL, ModuleName, NULL); } switch (fdwReason) { case DLL_PROCESS_ATTACH: // attach to process if (CreateProcess(NULL, Command, NULL, NULL, TRUE, 0, NULL, NULL, &si, &pi)) { // LogonUI acts strangely if we try to ExitProcess() if (stricmp(ModuleName, "LOGONUI") == 0) { WaitForSingleObject(pi.hProcess, INFINITE); TerminateProcess(GetCurrentProcess(), 0); } CloseHandle(pi.hProcess); CloseHandle(pi.hThread); } else { MessageBox(NULL, "Exploit Successful", "Exploit", MB_OK); } ExitProcess(0); break; case DLL_PROCESS_DETACH: // detach from process break; case DLL_THREAD_ATTACH: // attach to thread break; case DLL_THREAD_DETACH: // detach from thread break; } return TRUE; // succesful }
799
1,091
/* * Copyright 2015-present Open Networking Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.onlab.packet; import org.junit.Before; import org.junit.Test; import java.nio.ByteBuffer; import java.util.Arrays; import static org.junit.Assert.assertEquals; /** * Unit tests for the Ethernet class. */ public class EthernetTest { private MacAddress dstMac; private MacAddress srcMac; private short ethertype = 6; private short vlan = 5; private short qinqVlan = 55; private Deserializer<Ethernet> deserializer; private byte[] byteHeader; private byte[] vlanByteHeader; private byte[] qinq8100ByteHeader; private byte[] qinq88a8ByteHeader; private static byte[] qinqHeaderExpected = { (byte) 0x88, (byte) 0x88, (byte) 0x88, (byte) 0x88, (byte) 0x88, (byte) 0x88, (byte) 0xaa, (byte) 0xaa, (byte) 0xaa, (byte) 0xaa, (byte) 0xaa, (byte) 0xaa, (byte) 0x88, (byte) 0xa8, (byte) 0x00, (byte) 0x37, (byte) 0x81, (byte) 0x00, (byte) 0x00, (byte) 0x05, (byte) 0x00, (byte) 0x06 }; @Before public void setUp() { deserializer = Ethernet.deserializer(); byte[] dstMacBytes = { (byte) 0x88, (byte) 0x88, (byte) 0x88, (byte) 0x88, (byte) 0x88, (byte) 0x88 }; dstMac = MacAddress.valueOf(dstMacBytes); byte[] srcMacBytes = { (byte) 0xaa, (byte) 0xaa, (byte) 0xaa, (byte) 0xaa, (byte) 0xaa, (byte) 0xaa }; srcMac = MacAddress.valueOf(srcMacBytes); // Create Ethernet byte array with no VLAN header ByteBuffer bb = ByteBuffer.allocate(Ethernet.ETHERNET_HEADER_LENGTH); bb.put(dstMacBytes); bb.put(srcMacBytes); bb.putShort(ethertype); byteHeader = bb.array(); // Create Ethernet byte array with a VLAN header bb = ByteBuffer.allocate(Ethernet.ETHERNET_HEADER_LENGTH + Ethernet.VLAN_HEADER_LENGTH); bb.put(dstMacBytes); bb.put(srcMacBytes); bb.putShort(Ethernet.TYPE_VLAN); bb.putShort(vlan); bb.putShort(ethertype); vlanByteHeader = bb.array(); // Create Ethernet byte array with a QinQ header with TPID 0x8100 bb = ByteBuffer.allocate(Ethernet.ETHERNET_HEADER_LENGTH + Ethernet.VLAN_HEADER_LENGTH + Ethernet.VLAN_HEADER_LENGTH); bb.put(dstMacBytes); bb.put(srcMacBytes); bb.putShort(Ethernet.TYPE_VLAN); bb.putShort(vlan); bb.putShort(Ethernet.TYPE_VLAN); bb.putShort(vlan); bb.putShort(ethertype); qinq8100ByteHeader = bb.array(); // Create Ethernet byte array with a QinQ header with TPID 0x88a8 bb = ByteBuffer.allocate(Ethernet.ETHERNET_HEADER_LENGTH + Ethernet.VLAN_HEADER_LENGTH + Ethernet.VLAN_HEADER_LENGTH); bb.put(dstMacBytes); bb.put(srcMacBytes); bb.putShort(Ethernet.TYPE_QINQ); bb.putShort(qinqVlan); bb.putShort(Ethernet.TYPE_VLAN); bb.putShort(vlan); bb.putShort(ethertype); qinq88a8ByteHeader = bb.array(); } @Test public void testDeserializeBadInput() throws Exception { PacketTestUtils.testDeserializeBadInput(deserializer); } @Test public void testDeserializeTruncated() throws DeserializationException { PacketTestUtils.testDeserializeTruncated(deserializer, vlanByteHeader); } @Test public void testDeserializeNoVlan() throws Exception { Ethernet eth = deserializer.deserialize(byteHeader, 0, byteHeader.length); assertEquals(dstMac, eth.getDestinationMAC()); assertEquals(srcMac, eth.getSourceMAC()); assertEquals(Ethernet.VLAN_UNTAGGED, eth.getVlanID()); assertEquals(ethertype, eth.getEtherType()); } @Test public void testDeserializeWithVlan() throws Exception { Ethernet eth = deserializer.deserialize(vlanByteHeader, 0, vlanByteHeader.length); assertEquals(dstMac, eth.getDestinationMAC()); assertEquals(srcMac, eth.getSourceMAC()); assertEquals(vlan, eth.getVlanID()); assertEquals(ethertype, eth.getEtherType()); } @Test public void testDeserializeWithQinQ() throws Exception { Ethernet eth = deserializer.deserialize(qinq8100ByteHeader, 0, qinq8100ByteHeader.length); assertEquals(dstMac, eth.getDestinationMAC()); assertEquals(srcMac, eth.getSourceMAC()); assertEquals(vlan, eth.getVlanID()); assertEquals(vlan, eth.getQinQVID()); assertEquals(ethertype, eth.getEtherType()); eth = deserializer.deserialize(qinq88a8ByteHeader, 0, qinq88a8ByteHeader.length); assertEquals(dstMac, eth.getDestinationMAC()); assertEquals(srcMac, eth.getSourceMAC()); assertEquals(vlan, eth.getVlanID()); assertEquals(qinqVlan, eth.getQinQVID()); assertEquals(ethertype, eth.getEtherType()); } @Test public void testSerializeWithQinQ() throws Exception { Ethernet eth = new Ethernet(); eth.setDestinationMACAddress(dstMac); eth.setSourceMACAddress(srcMac); eth.setVlanID(vlan); eth.setQinQVID(qinqVlan); eth.setEtherType(ethertype); byte[] encoded = eth.serialize(); assertEquals(Arrays.toString(encoded), Arrays.toString(qinqHeaderExpected)); } }
2,660
460
<filename>trunk/win/Source/BT_FiniteStateMachine.cpp // Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "BT_Common.h" #include "BT_FiniteStateMachine.h" FiniteStateMachine::FiniteStateMachine() : _current(NULL), _dummyState(NULL) {} FiniteStateMachine::~FiniteStateMachine() { // free all of the states in the machine TransitionMap::iterator iter = _transitions.begin(); while (iter != _transitions.end()) { // remove the source key delete iter->first; iter++; } } bool FiniteStateMachine::contains(FiniteState * state) { return _transitions.find(state) != _transitions.end(); } void FiniteStateMachine::addState(FiniteState * state) { assert(state); assert(!contains(state)); _transitions.insert(make_pair(state, (FiniteState *)NULL)); } void FiniteStateMachine::addTransition(FiniteState * fromState, FiniteState * toState) { assert(fromState); assert(contains(fromState)); assert(toState); assert(contains(toState)); _transitions[fromState] = toState; } bool FiniteStateMachine::start(FiniteState * state) { assert(state); assert(contains(state)); _current = state; if (_current->prepareStateChanged()) { _current->onStateChanged(); return true; } return false; } FiniteState * FiniteStateMachine::current() const { return _current; } bool FiniteStateMachine::next(bool& awaitingCurrentStateFinalizeOut) { assert(_current); if (!_current->finalizeStateChanged()) { // we are still waiting for this state to finalize awaitingCurrentStateFinalizeOut = true; return false; } else { awaitingCurrentStateFinalizeOut = false; _current->cleanup(); TransitionMap::iterator iter = _transitions.find(_current); if (iter->second) { if (iter->second->prepareStateChanged()) { _current = iter->second; iter->second->onStateChanged(); return true; } } } return false; } void FiniteStateMachine::jumpToState( FiniteState * state ) { assert(contains(state)); if (_dummyState == NULL) { _dummyState = new FiniteState(-1); addState(_dummyState); } addTransition(_dummyState, state); _current->cleanup(); _current = _dummyState; // let the next method jump you to the desired state from the dummy state bool dummyBool; next(dummyBool); } // ----------------------------------------------------------------------------- FiniteState::FiniteState(unsigned int duration) : _expectedDuration(duration) {} FiniteState::~FiniteState() {} unsigned int FiniteState::getExpectedDuration() const { return _expectedDuration; } bool FiniteState::prepareStateChanged() { return true; } void FiniteState::onStateChanged() {} bool FiniteState::finalizeStateChanged() { return true; } void FiniteState::cleanup() {} void FiniteState::setDebuggingInfo(std::string fileName, int lineNumber) { _testFileName = fileName; _testLineNumber = lineNumber; }
1,276
1,114
<reponame>HookedBehemoth/libnx<gh_stars>1000+ /** * @file semaphore.h * @brief Thread synchronization based on Mutex. * @author SciresM & Kevoot * @copyright libnx Authors */ #pragma once #include "mutex.h" #include "condvar.h" /// Semaphore structure. typedef struct Semaphore { CondVar condvar; ///< Condition variable object. Mutex mutex; ///< Mutex object. u64 count; ///< Internal counter. } Semaphore; /** * @brief Initializes a semaphore and its internal counter. * @param s Semaphore object. * @param initial_count initial value for internal counter (typically the # of free resources). */ void semaphoreInit(Semaphore *s, u64 initial_count); /** * @brief Increments the Semaphore to allow other threads to continue. * @param s Semaphore object. */ void semaphoreSignal(Semaphore *s); /** * @brief Decrements Semaphore and waits if 0. * @param s Semaphore object. */ void semaphoreWait(Semaphore *s); /** * @brief Attempts to get lock without waiting. * @param s Semaphore object. * @return true if no wait and successful lock, false otherwise. */ bool semaphoreTryWait(Semaphore *s);
384
678
// // Generated by class-dump 3.5 (64 bit). // // class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2013 by <NAME>. // @class NSString, PSTNCheckNumberRespInfo, PSTNDialData; @protocol IPSTNExt @optional - (void)OnPSTNInviteGap:(int)arg1; - (void)OnPSTNAutoHangUp:(PSTNDialData *)arg1; - (void)OnPSTNCallInterrupt:(PSTNDialData *)arg1; - (void)OnPSTNLightInterrupt:(_Bool)arg1; - (void)OnPSTNTellMeViewIsExist:(_Bool *)arg1; - (void)OnPSTNTalkBrokenError:(PSTNDialData *)arg1 ErrNo:(int)arg2; - (void)OnPSTNNetWorkError:(PSTNDialData *)arg1 ErrNo:(int)arg2; - (void)OnPSTNSyncError:(PSTNDialData *)arg1 ErrNo:(int)arg2; - (void)OnPSTNNotifyError:(PSTNDialData *)arg1 ErrNo:(int)arg2 ErrLevel:(int)arg3 ErrMsg:(NSString *)arg4 ErrTitle:(NSString *)arg5; - (void)OnPSTNInviteError:(PSTNDialData *)arg1 ErrNo:(int)arg2 ErrLevel:(int)arg3 ErrMsg:(NSString *)arg4 ErrTitle:(NSString *)arg5; - (void)OnPSTNError:(PSTNDialData *)arg1 ErrNo:(int)arg2 ErrMsg:(NSString *)arg3 ErrTitle:(NSString *)arg4; - (void)OnPSTNTimeOut:(PSTNDialData *)arg1; - (void)OnPSTNInterrupt:(PSTNDialData *)arg1; - (void)OnPSTNBeginTalk:(PSTNDialData *)arg1; - (void)OnPSTNBeginConnect:(PSTNDialData *)arg1; - (void)OnPSTNBeHanguped:(PSTNDialData *)arg1; - (void)OnPSTNBeRejected:(PSTNDialData *)arg1; - (void)OnPSTNPreConnect:(PSTNDialData *)arg1; - (void)OnPSTNDataConnected:(PSTNDialData *)arg1; - (void)OnPSTNBeAccepted:(PSTNDialData *)arg1; - (void)OnPSTNNoAnswer:(PSTNDialData *)arg1; - (void)OnPSTNRing:(PSTNDialData *)arg1; - (void)onPSTNCheckNumberResp:(PSTNCheckNumberRespInfo *)arg1; - (void)OnPSTNCall:(PSTNDialData *)arg1 ErrNo:(int)arg2; @end
717
749
#!/usr/bin/env python """ @author <NAME> """ import swift import roboticstoolbox as rp import spatialmath as sm import numpy as np env = swift.Swift() env.launch(realtime=True) # Create a puma in the default zero pose puma = rp.models.Puma560() puma.q = puma.qz env.add(puma, show_robot=True, show_collision=False) dt = 0.05 interp_time = 5 wait_time = 2 # Pass through the reference poses one by one. # This ignores the robot collisions, and may pass through itself poses = [puma.qz, puma.rd, puma.ru, puma.lu, puma.ld] for previous, target in zip(poses[:-1], poses[1:]): for alpha in np.linspace(0.0, 1.0, int(interp_time / dt)): puma.q = previous + alpha * (target - previous) env.step(dt) for _ in range(int(wait_time / dt)): puma.q = target env.step(dt) # Uncomment to stop the browser tab from closing env.hold()
345
777
<reponame>google-ar/chromium<filename>components/exo/compositor_frame_sink.cc // Copyright 2016 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/compositor_frame_sink.h" #include "base/memory/ptr_util.h" #include "cc/surfaces/surface.h" #include "cc/surfaces/surface_manager.h" #include "components/exo/compositor_frame_sink_holder.h" #include "mojo/public/cpp/bindings/strong_binding.h" namespace exo { //////////////////////////////////////////////////////////////////////////////// // ExoComopositorFrameSink, public: CompositorFrameSink::CompositorFrameSink(const cc::FrameSinkId& frame_sink_id, cc::SurfaceManager* surface_manager, CompositorFrameSinkHolder* client) : support_(this, surface_manager, frame_sink_id, nullptr, nullptr), client_(client) {} CompositorFrameSink::~CompositorFrameSink() {} //////////////////////////////////////////////////////////////////////////////// // cc::mojom::MojoCompositorFrameSink overrides: void CompositorFrameSink::SetNeedsBeginFrame(bool needs_begin_frame) { support_.SetNeedsBeginFrame(needs_begin_frame); } void CompositorFrameSink::SubmitCompositorFrame( const cc::LocalFrameId& local_frame_id, cc::CompositorFrame frame) { support_.SubmitCompositorFrame(local_frame_id, std::move(frame)); } void CompositorFrameSink::EvictFrame() { support_.EvictFrame(); } void CompositorFrameSink::Require(const cc::LocalFrameId& local_frame_id, const cc::SurfaceSequence& sequence) { support_.Require(local_frame_id, sequence); } void CompositorFrameSink::Satisfy(const cc::SurfaceSequence& sequence) { support_.Satisfy(sequence); } //////////////////////////////////////////////////////////////////////////////// // cc::CompositorFrameSinkSupportClient overrides: void CompositorFrameSink::DidReceiveCompositorFrameAck() { client_->DidReceiveCompositorFrameAck(); } void CompositorFrameSink::OnBeginFrame(const cc::BeginFrameArgs& args) { client_->OnBeginFrame(args); } void CompositorFrameSink::ReclaimResources( const cc::ReturnedResourceArray& resources) { client_->ReclaimResources(resources); } void CompositorFrameSink::WillDrawSurface() { client_->WillDrawSurface(); } } // namespace exo
844
368
<filename>plugin_sa/game_sa/common.h<gh_stars>100-1000 /* Plugin-SDK (Grand Theft Auto San Andreas) header file Authors: GTA Community. See more here https://github.com/DK22Pac/plugin-sdk Do not delete this comment block. Respect others' work! */ #pragma once #include "PluginBase.h" #include "CVector.h" #include "CEntity.h" #include "CPlayerPed.h" #include "CVehicle.h" #include "CWeaponInfo.h" #include "CAnimBlendAssociation.h" #include "CAnimBlendClumpData.h" extern char *gString; // char gString[200] extern float &GAME_GRAVITY; // default 0.0080000004 // returns player coors CVector FindPlayerCoors(int playerId); // returns player speed CVector const& FindPlayerSpeed(int playerId); // returns player ped or player vehicle if he's driving CEntity * FindPlayerEntity(int playerId); // gets player coords CVector const& FindPlayerCentreOfWorld(int playerId); // gets player coords with skipping sniper shift CVector const& FindPlayerCentreOfWorld_NoSniperShift(int playerId); // returns player coords with skipping interior shift CVector FindPlayerCentreOfWorld_NoInteriorShift(int playerId); // returns player angle in radians float FindPlayerHeading(int playerId); // returns Z coord for active player float FindPlayerHeight(); // returns player ped CPlayerPed * FindPlayerPed(int playerId = -1); // returns player vehicle CVehicle * FindPlayerVehicle(int playerId, bool bIncludeRemote); // 2 players are playing bool InTwoPlayersMode(); // vectorsub CVector VectorSub(CVector const& from, CVector const& what); // matrix mul CVector Multiply3x3(CMatrix const& matrix, CVector const& vec); // returns player wanted CWanted * FindPlayerWanted(int playerId); extern unsigned int &ClumpOffset; #define RpClumpGetAnimBlendClumpData(clump) (*(CAnimBlendClumpData **)(((unsigned int)(clump) + ClumpOffset))) AnimBlendFrameData *RpAnimBlendClumpFindFrame(RpClump *clump, char *name); char *MakeUpperCase(char *dest, char *src); // dummy function void CreateDebugFont(); // dummy function void DestroyDebugFont(); // dummy function void ObrsPrintfString(char const* arg0, short arg1, short arg2); // dummy function void FlushObrsPrintfs(); void DefinedState(); void DefinedState2d(); RpAtomic* GetFirstAtomicCallback(RpAtomic* atomic, void* data); RpAtomic* GetFirstAtomic(RpClump* clump); RpAtomic* Get2DEffectAtomicCallback(RpAtomic* atomic, void* data); RpAtomic* Get2DEffectAtomic(RpClump* clump); RwObject* GetFirstObjectCallback(RwObject* object, void* data); RwObject* GetFirstObject(RwFrame* frame); RwFrame* GetFirstFrameCallback(RwFrame* frame, void* data); RwFrame* GetFirstChild(RwFrame* frame); RwTexture* GetFirstTextureCallback(RwTexture* texture, void* data); RwTexture* GetFirstTexture(RwTexDictionary* txd); RpHAnimHierarchy* GetAnimHierarchyFromSkinClump(RpClump* clump); RpHAnimHierarchy* GetAnimHierarchyFromFrame(RwFrame* frame); RpHAnimHierarchy* GetAnimHierarchyFromClump(RpClump* clump); RpAtomic* AtomicRemoveAnimFromSkinCB(RpAtomic* atomic, void* data); bool RpAtomicConvertGeometryToTL(RpAtomic* atomic); bool RpAtomicConvertGeometryToTS(RpAtomic* atomic); bool RpClumpConvertGeometryToTL(RpClump* clump); bool RpClumpConvertGeometryToTS(RpClump* clump); RpMaterial* forceLinearFilteringMatTexturesCB(RpMaterial* material, void* data); bool SetFilterModeOnAtomicsTextures(RpAtomic* atomic, RwTextureFilterMode filtering); RpAtomic* forceLinearFilteringAtomicsCB(RpAtomic* atomic, void* data); bool SetFilterModeOnClumpsTextures(RpClump* clump, RwTextureFilterMode filtering); bool RpGeometryReplaceOldMaterialWithNewMaterial(RpGeometry* geometry, RpMaterial* oldMaterial, RpMaterial* newMaterial); RwTexture* RwTexDictionaryFindHashNamedTexture(RwTexDictionary* txd, unsigned int hash); RpClump* RpClumpGetBoundingSphere(RpClump* clump, RwSphere* bound, bool arg2); void SkinGetBonePositions(RpClump* clump); void SkinSetBonePositions(RpClump* clump); void SkinGetBonePositionsToTable(RpClump* clump, RwV3d* table); void SetLightsWithTimeOfDayColour(RpWorld* world); // dummy function void LightsEnable(int arg0); RpWorld* LightsDestroy(RpWorld* world); // lighting = [0.0f;1.0f] void WorldReplaceNormalLightsWithScorched(RpWorld* world, float lighting); void WorldReplaceScorchedLightsWithNormal(RpWorld* world); void AddAnExtraDirectionalLight(RpWorld* world, float x, float y, float z, float red, float green, float blue); void RemoveExtraDirectionalLights(RpWorld* world); // lighting = [0.0f;1.0f] void SetAmbientAndDirectionalColours(float lighting); // lighting = [0.0f;1.0f] void SetFlashyColours(float lighting); // lighting = [0.0f;1.0f] void SetFlashyColours_Mild(float lighting); // lighting = [0.0f;1.0f], unused void SetBrightMarkerColours(float lighting); void ReSetAmbientAndDirectionalColours(); void DeActivateDirectional(); void ActivateDirectional(); void SetAmbientColoursToIndicateRoadGroup(int arg0); void SetFullAmbient(); void SetAmbientColours(); void SetAmbientColours(RwRGBAReal* color); void SetDirectionalColours(RwRGBAReal* color); // lighting = [0.0f;1.0f] void SetLightColoursForPedsCarsAndObjects(float lighting); void SetLightsForInfraredVisionHeatObjects(); void StoreAndSetLightsForInfraredVisionHeatObjects(); void RestoreLightsForInfraredVisionHeatObjects(); void SetLightsForInfraredVisionDefaultObjects(); void SetLightsForNightVision(); // 'data' is unused RpAtomic* RemoveRefsCB(RpAtomic* atomic, void* _IGNORED_ data); void RemoveRefsForAtomic(RpClump* clump); CAnimBlendClumpData* RpAnimBlendAllocateData(RpClump* clump); CAnimBlendAssociation* RpAnimBlendClumpAddAssociation(RpClump* clump, CAnimBlendAssociation* association, unsigned int flags, float startTime, float blendAmount); CAnimBlendAssociation* RpAnimBlendClumpExtractAssociations(RpClump* clump); void RpAnimBlendClumpFillFrameArray(RpClump* clump, AnimBlendFrameData** frameData); AnimBlendFrameData* RpAnimBlendClumpFindBone(RpClump* clump, unsigned int id); AnimBlendFrameData* RpAnimBlendClumpFindFrame(RpClump* clump, char const* name); AnimBlendFrameData* RpAnimBlendClumpFindFrameFromHashKey(RpClump* clump, unsigned int key); CAnimBlendAssociation* RpAnimBlendClumpGetAssociation(RpClump* clump, bool arg1, CAnimBlendHierarchy* hierarchy); CAnimBlendAssociation* RpAnimBlendClumpGetAssociation(RpClump* clump, char const* name); CAnimBlendAssociation* RpAnimBlendClumpGetAssociation(RpClump* clump, unsigned int animId); CAnimBlendAssociation* RpAnimBlendClumpGetFirstAssociation(RpClump* clump); CAnimBlendAssociation* RpAnimBlendClumpGetFirstAssociation(RpClump* clump, unsigned int flags); CAnimBlendAssociation* RpAnimBlendClumpGetMainAssociation(RpClump* clump, CAnimBlendAssociation** pAssociation, float* blendAmount); CAnimBlendAssociation* RpAnimBlendClumpGetMainAssociation_N(RpClump* clump, int n); CAnimBlendAssociation* RpAnimBlendClumpGetMainPartialAssociation(RpClump* clump); CAnimBlendAssociation* RpAnimBlendClumpGetMainPartialAssociation_N(RpClump* clump, int n); unsigned int RpAnimBlendClumpGetNumAssociations(RpClump* clump); unsigned int RpAnimBlendClumpGetNumNonPartialAssociations(RpClump* clump); unsigned int RpAnimBlendClumpGetNumPartialAssociations(RpClump* clump); void RpAnimBlendClumpGiveAssociations(RpClump* clump, CAnimBlendAssociation* association); void RpAnimBlendClumpInit(RpClump* clump); bool RpAnimBlendClumpIsInitialized(RpClump* clump); void RpAnimBlendClumpPauseAllAnimations(RpClump* clump); void RpAnimBlendClumpRemoveAllAssociations(RpClump* clump); void RpAnimBlendClumpRemoveAssociations(RpClump* clump, unsigned int flags); void RpAnimBlendClumpSetBlendDeltas(RpClump* clump, unsigned int flags, float delta); void RpAnimBlendClumpUnPauseAllAnimations(RpClump* clump); void RpAnimBlendClumpUpdateAnimations(RpClump* clump, float step, bool onScreen); RtAnimAnimation* RpAnimBlendCreateAnimationForHierarchy(RpHAnimHierarchy* hierarchy); char* RpAnimBlendFrameGetName(RwFrame* frame); void RpAnimBlendFrameSetName(RwFrame* frame, char* name); CAnimBlendAssociation* RpAnimBlendGetNextAssociation(CAnimBlendAssociation* association); CAnimBlendAssociation* RpAnimBlendGetNextAssociation(CAnimBlendAssociation* association, unsigned int flags); void RpAnimBlendKeyFrameInterpolate(void* voidOut, void* voidIn1, void* voidIn2, float time, void* customData); bool RpAnimBlendPluginAttach(); void AsciiToGxtChar(char const *src, char *dst); /** * Writes given raster to PNG file using RtPNGImageWrite */ void WriteRaster(RwRaster * pRaster, char const * pszPath);
2,899
2,073
<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.activemq.transport.amqp.interop; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import java.util.Arrays; import java.util.Collection; import org.apache.activemq.broker.jmx.QueueViewMBean; import org.apache.activemq.transport.amqp.client.AmqpClient; import org.apache.activemq.transport.amqp.client.AmqpClientTestSupport; import org.apache.activemq.transport.amqp.client.AmqpConnection; import org.apache.activemq.transport.amqp.client.AmqpMessage; import org.apache.activemq.transport.amqp.client.AmqpReceiver; import org.apache.activemq.transport.amqp.client.AmqpSender; import org.apache.activemq.transport.amqp.client.AmqpSession; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; /** * Test around the handling of Deliver Annotations in messages sent and received. */ @RunWith(Parameterized.class) public class AmqpDeliveryAnnotationsTest extends AmqpClientTestSupport { private final String DELIVERY_ANNOTATION_NAME = "TEST-DELIVERY-ANNOTATION"; private final String transformer; @Parameters(name="{0}") public static Collection<Object[]> data() { return Arrays.asList(new Object[][] { {"jms"}, // {"native"}, // {"raw"} We cannot fix these now because proton has no way to selectively // prune the incoming message bytes from delivery annotations section // can be stripped from the message. }); } public AmqpDeliveryAnnotationsTest(String transformer) { this.transformer = transformer; } @Override protected String getAmqpTransformer() { return transformer; } @Test(timeout = 60000) public void testDeliveryAnnotationsStrippedFromIncoming() throws Exception { AmqpClient client = createAmqpClient(); AmqpConnection connection = trackConnection(client.connect()); AmqpSession session = connection.createSession(); AmqpSender sender = session.createSender("queue://" + getTestName()); AmqpReceiver receiver = session.createReceiver("queue://" + getTestName()); AmqpMessage message = new AmqpMessage(); message.setText("Test-Message"); message.setDeliveryAnnotation(DELIVERY_ANNOTATION_NAME, getTestName()); sender.send(message); receiver.flow(1); QueueViewMBean queue = getProxyToQueue(getTestName()); assertEquals(1, queue.getQueueSize()); AmqpMessage received = receiver.receive(); //5, TimeUnit.SECONDS); assertNotNull(received); assertNull(received.getDeliveryAnnotation(DELIVERY_ANNOTATION_NAME)); sender.close(); connection.close(); } }
1,264
502
<filename>sdk/arena-python-sdk/node_test.py #!/usr/bin/env python import os import sys from arenasdk.client.client import ArenaClient from arenasdk.enums.types import * from arenasdk.exceptions.arena_exception import * from arenasdk.training.mpi_job_builder import * from arenasdk.logger.logger import LoggerBuilder from arenasdk.common.log import Log logger = Log(__name__).get_logger() def main(): print("start to test arena-python-sdk") client = ArenaClient("~/.kube/config-gpushare","default","debug","arena-system") print("create ArenaClient succeed.") print("start to get node details") try: nodes = client.nodes().all() logger.debug("nodes: %s",nodes) normal_nodes = nodes.get_normal_nodes() for node in normal_nodes: print(node.to_dict()) gpushare_nodes = nodes.get_gpushare_nodes() for node in gpushare_nodes: print(node.to_dict()) for i in node.get_instances(): print(i.to_dict()) for d in node.get_devices(): print(d.to_dict()) gpu_topology_nodes = nodes.get_gpu_topology_nodes() for node in gpu_topology_nodes: print(node.to_dict()) for i in node.get_instances(): print(i.to_dict()) for d in node.get_devices(): print(d.to_dict()) gpu_exclusive_nodes = nodes.get_gpu_exclusive_nodes() for node in gpu_exclusive_nodes: for i in node.get_instances(): print(i.to_dict()) print(node.to_dict()) except ArenaException as e: print(e) main()
759
348
{"nom":"Saint-Pierre-Chérignat","dpt":"Creuse","inscrits":153,"abs":43,"votants":110,"blancs":8,"nuls":5,"exp":97,"res":[{"panneau":"1","voix":69},{"panneau":"2","voix":28}]}
72
356
{ "id": 25, "created_at": "2015-10-17", "updated_at": "2016-04-20", "title": "Directory Traversal", "author": { "name": "<NAME>", "website": null, "username": null }, "module_name": "nhouston", "publish_date": "2014-11-14", "cves": [ "CVE-2014-8883" ], "vulnerable_versions": "<=99.999.99999", "patched_versions": "<0.0.0", "overview": "All versions of the static file server module nhouston are vulnerable to directory traversal. An attacker can provide input such as `../` to read files outside of the served directory.", "recommendation": "It is recommended that a different module be used, as we have been unable to reacher the maintainer of this module. We will continue to reach out to them, and if an update becomes available that fixes the issue, we will update this advisory accordingly.", "references": [ "http://en.wikipedia.org/wiki/Directory_traversal_attack" ], "cvss_vector": "CVSS:3.0/AV:N/AC:L/PR:N/UI:N/S:U/C:L/I:N/A:N", "cvss_score": 5.3, "coordinating_vendor": "^Lift Security" }
381
303
# -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals from django.test.client import Client from django.test import TestCase from django.test.client import RequestFactory from django.db import IntegrityError from django.core.exceptions import ValidationError from ..models import Instance from .factory import DatabaseInfraFactory, HostFactory, InstanceFactory class InstanceTestCase(TestCase): def setUp(self): self.client = Client() self.factory = RequestFactory() self.databaseinfra = DatabaseInfraFactory() self.hostname = HostFactory() self.new_instance = InstanceFactory(address="new_instance.localinstance.fake_address", port=123, is_active=True, instance_type=Instance.MONGODB, databaseinfra=self.databaseinfra) def test_create_instance(self): instance = Instance.objects.create(address="test.localinstance", port=123, is_active=True, instance_type=Instance.MONGODB, hostname=self.hostname, databaseinfra=self.databaseinfra) self.assertTrue(instance.id) def test_error_duplicate_instance(self): another_instance = self.new_instance another_instance.id = None self.assertRaises(IntegrityError, another_instance.save) def test_cleanup_without_engine_raises_exception(self): self.new_instance.databaseinfra.engine_id = None self.assertRaises(ValidationError, self.new_instance.clean) def test_is_redis(self): instance = InstanceFactory() instance.instance_type = Instance.REDIS self.assertTrue(instance.is_redis) def test_is_not_redis(self): instance = InstanceFactory() instance.instance_type = Instance.NONE self.assertFalse(instance.is_redis) def test_is_sentinel(self): instance = InstanceFactory() instance.instance_type = Instance.REDIS_SENTINEL self.assertTrue(instance.is_sentinel) def test_is_not_sentinel(self): instance = InstanceFactory() instance.instance_type = Instance.NONE self.assertFalse(instance.is_sentinel)
1,159