max_stars_count
int64
301
224k
text
stringlengths
6
1.05M
token_count
int64
3
727k
435
<filename>pycon-pl-2015/videos/pycon-pl-2015-maciej-szulik-microservices-on-openshift-v3.json { "description": "According to <NAME>, microservices \"is an approach to developing a single application as a suite of small services, each running in its own process and communicating with lightweight mechanisms, often an HTTP resource API. These services are built around business capabilities and independently deployable by fully automated deployment machinery. There is a bare minimum of centralized management of these services, which may be written in different programming languages and use different data storage technologies.\" (http://martinfowler.com/articles/microservices.html) That definition sounds very promising and makes you think about miscroservices architecture as something very easy. But is it really that simple to create such services? If you think about each of the pieces separately then maybe the answer is \"yes\", but what about that moment when your project grows into more than 5 tasks? What about deploying them into tens, hundreds or thousands of instances? What about rolling out a new release of a single component or even dozens of them? You can see that the problem becomes very complex, very quickly. But now can you imagine a world where doing such complex tasks will be as easy as pressing one button (or invoking one command for CLI nerds.", "duration": 2625, "recorded": "2015-10-15", "speakers": [ "<NAME>" ], "thumbnail_url": "https://i.ytimg.com/vi/iGzo3jURzaM/hqdefault.jpg", "title": "Microservices on OpenShift v3", "videos": [ { "type": "youtube", "url": "https://www.youtube.com/watch?v=iGzo3jURzaM" } ] }
435
1,402
<reponame>kvmanohar22/gtsam<gh_stars>1000+ // Example of using the GeographicLib::MGRS class #include <iostream> #include <exception> #include <string> #include <GeographicLib/UTMUPS.hpp> #include <GeographicLib/MGRS.hpp> using namespace std; using namespace GeographicLib; int main() { try { // See also example-GeoCoords.cpp { // Sample forward calculation double lat = 33.3, lon = 44.4; // Baghdad int zone; bool northp; double x, y; UTMUPS::Forward(lat, lon, zone, northp, x, y); string mgrs; MGRS::Forward(zone, northp, x, y, lat, 5, mgrs); cout << mgrs << "\n"; } { // Sample reverse calculation string mgrs = "38SMB4488"; int zone, prec; bool northp; double x, y; MGRS::Reverse(mgrs, zone, northp, x, y, prec); double lat, lon; UTMUPS::Reverse(zone, northp, x, y, lat, lon); cout << prec << " " << lat << " " << lon << "\n"; } } catch (const exception& e) { cerr << "Caught exception: " << e.what() << "\n"; return 1; } }
486
407
package com.alibaba.smart.framework.engine.configuration.impl; import java.util.Map; import com.alibaba.smart.framework.engine.common.util.MapUtil; import com.alibaba.smart.framework.engine.configuration.DelegationExecutor; import com.alibaba.smart.framework.engine.configuration.ExceptionProcessor; import com.alibaba.smart.framework.engine.configuration.InstanceAccessor; import com.alibaba.smart.framework.engine.configuration.ProcessEngineConfiguration; import com.alibaba.smart.framework.engine.context.ExecutionContext; import com.alibaba.smart.framework.engine.delegation.ContextBoundedJavaDelegation; import com.alibaba.smart.framework.engine.delegation.JavaDelegation; import com.alibaba.smart.framework.engine.delegation.TccDelegation; import com.alibaba.smart.framework.engine.exception.EngineException; import com.alibaba.smart.framework.engine.model.assembly.Activity; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Created by 高海军 帝奇 74394 on 2019-08-30 16:08. */ public class DefaultDelegationExecutor implements DelegationExecutor { private static final Logger LOGGER = LoggerFactory.getLogger(DefaultDelegationExecutor.class); @Override public void execute(ExecutionContext context, Activity activity) { Map<String, String> properties = activity.getProperties(); if(MapUtil.isNotEmpty(properties)){ String className = properties.get("class"); if(null != className){ execute(context, className,activity); }else { LOGGER.info("No behavior found:"+activity.getId()); } } } private static void execute(ExecutionContext context, String className, Activity activity) { ProcessEngineConfiguration processEngineConfiguration = context.getProcessEngineConfiguration(); ExceptionProcessor exceptionProcessor = processEngineConfiguration.getExceptionProcessor(); InstanceAccessor instanceAccessor = processEngineConfiguration .getInstanceAccessor(); Object delegation = instanceAccessor.access(className); try{ if (delegation instanceof ContextBoundedJavaDelegation) { ContextBoundedJavaDelegation contextBoundedJavaDelegation = (ContextBoundedJavaDelegation)delegation; contextBoundedJavaDelegation.setClassName(className); contextBoundedJavaDelegation.setActivity(activity); contextBoundedJavaDelegation.execute(context); } else if (delegation instanceof JavaDelegation) { JavaDelegation javaDelegation = (JavaDelegation)delegation; javaDelegation.execute(context); } else if (delegation instanceof TccDelegation) { TccDelegation tccDelegation = (TccDelegation)delegation; tccDelegation.tryExecute(context); } else { throw new EngineException("The delegation is not support : " + delegation.getClass()); } }catch (Exception e){ dealException(exceptionProcessor, e,context); } } private static void dealException(ExceptionProcessor exceptionProcessor, Exception exception,ExecutionContext context) { if (null != exceptionProcessor) { exceptionProcessor.process(exception,context); } else if (exception instanceof RuntimeException) { throw (RuntimeException)exception; } else { throw new EngineException(exception); } } }
1,312
1,663
/* Copyright (c) 2016 <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. */ #include <stddef.h> #include <stdint.h> #include <stdlib.h> #include <string.h> #include <errno.h> #include <unistd.h> #include <sys/mman.h> #include "stack.h" #include "utils.h" #include "ctx.h" /* The stacks are cached. The advantage of this is twofold. First, caching is faster than malloc(). Second, it results in fewer calls to mprotect(). */ /* Stack size in bytes. */ static size_t dill_stack_size = 256 * 1024; /* Maximum number of unused cached stacks. Must be at least 1. */ static int dill_max_cached_stacks = 64; /* Returns the smallest value that's greater than val and is a multiple of unit. */ static size_t dill_align(size_t val, size_t unit) { return val % unit ? val + unit - val % unit : val; } /* Get memory page size. The query is done once. The value is cached. */ static size_t dill_page_size(void) { static long pgsz = 0; if(dill_fast(pgsz)) return (size_t)pgsz; pgsz = sysconf(_SC_PAGE_SIZE); dill_assert(pgsz > 0); return (size_t)pgsz; } int dill_ctx_stack_init(struct dill_ctx_stack *ctx) { ctx->count = 0; dill_slist_init(&ctx->cache); return 0; } void dill_ctx_stack_term(struct dill_ctx_stack *ctx) { /* Deallocate leftover coroutines. */ struct dill_slist *it; while((it = dill_slist_pop(&ctx->cache)) != &ctx->cache) { #if (HAVE_POSIX_MEMALIGN && HAVE_MPROTECT) & !defined DILL_NOGUARD void *ptr = ((uint8_t*)(it + 1)) - dill_stack_size - dill_page_size(); int rc = mprotect(ptr, dill_page_size(), PROT_READ|PROT_WRITE); dill_assert(rc == 0); free(ptr); #else void *ptr = ((uint8_t*)(it + 1)) - dill_stack_size; free(ptr); #endif } } void *dill_allocstack(size_t *stack_size) { struct dill_ctx_stack *ctx = &dill_getctx->stack; if(stack_size) *stack_size = dill_stack_size; /* If there's a cached stack, use it. */ if(!dill_slist_empty(&ctx->cache)) { --ctx->count; return (void*)(dill_slist_pop(&ctx->cache) + 1); } /* Allocate a new stack. */ uint8_t *top; #if (HAVE_POSIX_MEMALIGN && HAVE_MPROTECT) & !defined DILL_NOGUARD /* Allocate the stack so that it's memory-page-aligned. Add one page as a stack overflow guard. */ size_t sz = dill_align(dill_stack_size, dill_page_size()) + dill_page_size(); uint8_t *ptr; int rc = posix_memalign((void**)&ptr, dill_page_size(), sz); if(dill_slow(rc != 0)) { errno = rc; return NULL; } /* The bottom page is used as a stack guard. This way a stack overflow will cause a segfault instead of randomly overwriting the heap. */ rc = mprotect(ptr, dill_page_size(), PROT_NONE); if(dill_slow(rc != 0)) { int err = errno; free(ptr); errno = err; return NULL; } top = ptr + dill_page_size() + dill_stack_size; #else /* Simple allocation without a guard page. */ uint8_t *ptr = malloc(dill_stack_size); if(dill_slow(!ptr)) { errno = ENOMEM; return NULL; } top = ptr + dill_stack_size; #endif return top; } void dill_freestack(void *stack) { struct dill_ctx_stack *ctx = &dill_getctx->stack; struct dill_slist *item = ((struct dill_slist*)stack) - 1; /* If the cache is full we will deallocate one stack from the cache. We can't deallocate the stack passed to this function directly because this very function can be still executing on that stack. */ if(ctx->count >= dill_max_cached_stacks) { struct dill_slist *old = dill_slist_pop(&ctx->cache); --ctx->count; #if (HAVE_POSIX_MEMALIGN && HAVE_MPROTECT) & !defined DILL_NOGUARD void *ptr = ((uint8_t*)(old + 1)) - dill_stack_size - dill_page_size(); int rc = mprotect(ptr, dill_page_size(), PROT_READ|PROT_WRITE); dill_assert(rc == 0); free(ptr); #else void *ptr = ((uint8_t*)(old + 1)) - dill_stack_size; free(ptr); #endif } /* Put the stack into the cache. */ dill_slist_push(&ctx->cache, item); ++ctx->count; }
2,051
1,091
<reponame>meodaiduoi/onos /* * Copyright 2016-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.onosproject.driver.extensions.codec; import com.fasterxml.jackson.databind.node.ObjectNode; import org.onosproject.codec.CodecContext; import org.onosproject.codec.JsonCodec; import org.onosproject.driver.extensions.DefaultMoveExtensionTreatment; import org.onosproject.driver.extensions.MoveExtensionTreatment; import org.onosproject.net.flow.instructions.ExtensionTreatmentType; import static com.google.common.base.Preconditions.checkNotNull; import static org.onlab.util.Tools.nullIsIllegal; /** * JSON Codec for MoveExtensionTreatment class. */ public final class MoveExtensionTreatmentCodec extends JsonCodec<MoveExtensionTreatment> { private static final String SRC_OFS = "srcOfs"; private static final String DST_OFS = "dstOfs"; private static final String N_BITS = "nBits"; private static final String SRC = "src"; private static final String DST = "dst"; private static final String TYPE = "type"; private static final String MISSING_MEMBER_MESSAGE = " member is required in MoveExtensionTreatment"; @Override public ObjectNode encode(MoveExtensionTreatment moveExtensionTreatment, CodecContext context) { checkNotNull(moveExtensionTreatment, "Move Extension Treatment cannot be null"); ObjectNode root = context.mapper().createObjectNode() .put(SRC_OFS, moveExtensionTreatment.srcOffset()) .put(DST_OFS, moveExtensionTreatment.dstOffset()) .put(N_BITS, moveExtensionTreatment.nBits()) .put(SRC, moveExtensionTreatment.src()) .put(DST, moveExtensionTreatment.dst()); return root; } @Override public MoveExtensionTreatment decode(ObjectNode json, CodecContext context) { if (json == null || !json.isObject()) { return null; } // parse extension treatment type ExtensionTreatmentType type = new ExtensionTreatmentType(nullIsIllegal(json.get(TYPE), TYPE + MISSING_MEMBER_MESSAGE).asInt()); // parse src off set int srcOfs = nullIsIllegal(json.get(SRC_OFS), SRC_OFS + MISSING_MEMBER_MESSAGE).asInt(); // parse dst off set int dstOfs = nullIsIllegal(json.get(DST_OFS), DST_OFS + MISSING_MEMBER_MESSAGE).asInt(); // parse n bits int nBits = nullIsIllegal(json.get(N_BITS), N_BITS + MISSING_MEMBER_MESSAGE).asInt(); // parse src int src = nullIsIllegal(json.get(SRC), SRC + MISSING_MEMBER_MESSAGE).asInt(); // parse dst int dst = nullIsIllegal(json.get(DST), DST + MISSING_MEMBER_MESSAGE).asInt(); return new DefaultMoveExtensionTreatment(srcOfs, dstOfs, nBits, src, dst, type); } }
1,236
7,482
<filename>bsp/imx6sx/iMX6_Platform_SDK/sdk/drivers/eim/test/eim_test.c /* * Copyright (c) 2012, Freescale Semiconductor, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * o Redistributions of source code must retain the above copyright notice, this list * of conditions and the following disclaimer. * * o 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. * * o Neither the name of Freescale Semiconductor, Inc. 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 HOLDER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <stdio.h> #include "sdk.h" #include "cfi_flash.h" #include "eim/eim_ifc.h" #define EIM_BUFFER_SZ 0x1000 extern flash_info_t flash_info[]; static uint32_t eim_test_buffer[EIM_BUFFER_SZ]; static void eim_hw_prepare(void) { /* Init EIM */ eim_init(EIM_CS0, DSZ_16_HIGH, FALSE, FALSE); /* Nor flash */ eim_cfg_set(EIM_CS0, GCR1_CREP, TRUE); /* Address hold time */ eim_cfg_set(EIM_CS0, GCR2_ADH, 1); /* Bypass grant(only for Muxed 16) */ eim_cfg_set(EIM_CS0, GCR2_MUX16_BYP_GRANT, FALSE); /* ADV navigation */ eim_cfg_set(EIM_CS0, RCR1_RADVN, 2); /* OE assertion */ eim_cfg_set(EIM_CS0, RCR1_OEA, 0); /* Read wait state control */ eim_cfg_set(EIM_CS0, RCR1_RWSC, 28); /* WE negation */ eim_cfg_set(EIM_CS0, WCR1_WEN, 1); /* WE assertion */ eim_cfg_set(EIM_CS0, WCR1_WEA, 1); /* BE negation */ eim_cfg_set(EIM_CS0, WCR1_WBEN, 2); /* BE assertion */ eim_cfg_set(EIM_CS0, WCR1_WBEA, 1); /* ADV Negation */ eim_cfg_set(EIM_CS0, WCR1_WADVN, 1); /* Write wait state control */ eim_cfg_set(EIM_CS0, WCR1_WWSC, 8); } static int eim_nor_test(void) { uint32_t idx, retv, size, start, end, *data; int32_t count, first[CFG_MAX_FLASH_BANKS], last[CFG_MAX_FLASH_BANKS]; flash_info_t *info = flash_info; /* Prepare buffer */ for (idx = 0; idx < EIM_BUFFER_SZ; idx++) { eim_test_buffer[idx] = idx + 0x5A5A0000; } #if defined(BOARD_SABRE_AI) // for EIM_D18 steering gpio_set_level(GPIO_PORT5, 4, GPIO_LOW_LEVEL); #endif /* HW init */ eim_hw_prepare(); /* Reset flash to read mode */ flash_reset(WEIM_CS_BASE_ADDR); /* Initialize flash */ size = flash_init(WEIM_CS_BASE_ADDR); if ((size == 0) || (info->flash_id == FLASH_UNKNOWN)) { printf("Error: Missing or Unknown FLASH type.\n"); return ERR; } else { printf("Flash size: 0x%8x\n", size); } start = WEIM_CS_BASE_ADDR; end = start + size - 1; /* Obtain sector info */ retv = flash_fill_sect_ranges(start, end, first, last, &count); if (retv == OK) { /* Unprotect */ retv = flash_sects_protect(0, first, last); if (retv == OK) { /* Erase sectors */ printf("Flash erase...\n"); retv = flash_sects_erase(first, first); if (retv == OK) { if (*(uint16_t *) start != 0xFFFF) { retv = ERR; printf("Error: erased data not 0xFFFF."); } else { /* Program data */ printf("\nFlash program...\n"); retv = flash_write((uint8_t *) eim_test_buffer, start, EIM_BUFFER_SZ * sizeof(uint32_t)); } } } /* Protect */ if (retv == OK) { retv = flash_sects_protect(1, first, last); } } /* Compare data */ if (retv == OK) { printf("Data compare...\n"); for (idx = 0, data = (uint32_t *) start; idx < EIM_BUFFER_SZ; idx++) { if (eim_test_buffer[idx] != data[idx]) { printf("[%d] Data mismatch: 0x%8x, 0x%8x\n", idx, eim_test_buffer[idx], data[idx]); retv = ERR; break; } } } return retv; } int eim_test(void) { uint8_t sel, retv; printf("EIM test start: \n"); do { printf(" s - to start EIM NOR flash test.\n"); printf(" x - to exit.\n"); do { sel = getchar(); } while (sel == NONE_CHAR); if (sel == 'x') { printf("Test exit.\n"); break; } if (sel == 's') { retv = eim_nor_test(); if (retv == OK) { printf("Test passed.\n"); } else { printf("Test failed.\n"); } } } while (1); return 0; }
2,632
13,006
package org.deeplearning4j.text.documentiterator; import java.util.List; /** * LabelAwareIterator wrapper which populates a LabelsSource while iterating. * * @author <NAME> */ public class LabelAwareIteratorWrapper implements LabelAwareIterator { private final LabelAwareIterator delegate; private final LabelsSource sink; public LabelAwareIteratorWrapper(LabelAwareIterator delegate, LabelsSource sink) { this.delegate = delegate; this.sink = sink; } @Override public boolean hasNext() { return delegate.hasNext(); } @Override public boolean hasNextDocument() { return delegate.hasNextDocument(); } @Override public LabelsSource getLabelsSource() { return sink; } @Override public LabelledDocument next() { return nextDocument(); } @Override public LabelledDocument nextDocument() { LabelledDocument doc = delegate.nextDocument(); List<String> labels = doc.getLabels(); if (labels != null) { for (String label : labels) { sink.storeLabel(label); } } return doc; } @Override public void reset() { delegate.reset(); sink.reset(); } @Override public void shutdown() {} }
391
2,151
/************************************************************************** * * Copyright 2009-2010 <NAME> <<EMAIL>> * All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sub license, 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 (including the * next paragraph) 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 EGLCURRENT_INCLUDED #define EGLCURRENT_INCLUDED #include "egltypedefs.h" #define _EGL_API_ALL_BITS \ (EGL_OPENGL_ES_BIT | \ EGL_OPENVG_BIT | \ EGL_OPENGL_ES2_BIT | \ EGL_OPENGL_BIT) #define _EGL_API_FIRST_API EGL_OPENGL_ES_API #define _EGL_API_LAST_API EGL_OPENGL_API #define _EGL_API_NUM_APIS (_EGL_API_LAST_API - _EGL_API_FIRST_API + 1) /** * Per-thread info */ struct _egl_thread_info { EGLint LastError; _EGLContext *CurrentContexts[_EGL_API_NUM_APIS]; /* use index for fast access to current context */ EGLint CurrentAPIIndex; }; /** * Return true if a client API enum is recognized. */ static INLINE EGLBoolean _eglIsApiValid(EGLenum api) { return (api >= _EGL_API_FIRST_API && api <= _EGL_API_LAST_API); } /** * Convert a client API enum to an index, for use by thread info. * The client API enum is assumed to be valid. */ static INLINE EGLint _eglConvertApiToIndex(EGLenum api) { return api - _EGL_API_FIRST_API; } /** * Convert an index, used by thread info, to a client API enum. * The index is assumed to be valid. */ static INLINE EGLenum _eglConvertApiFromIndex(EGLint idx) { return _EGL_API_FIRST_API + idx; } PUBLIC _EGLThreadInfo * _eglGetCurrentThread(void); extern void _eglDestroyCurrentThread(void); extern EGLBoolean _eglIsCurrentThreadDummy(void); PUBLIC _EGLContext * _eglGetAPIContext(EGLenum api); PUBLIC _EGLContext * _eglGetCurrentContext(void); PUBLIC EGLBoolean _eglError(EGLint errCode, const char *msg); #endif /* EGLCURRENT_INCLUDED */
966
1,745
<filename>Source/Scripting/bsfScript/Extensions/BsPhysicsMeshEx.h //********************************* bs::framework - Copyright 2018-2019 <NAME> ************************************// //*********** Licensed under the MIT license. See LICENSE.md for full terms. This notice is not to be removed. ***********// #pragma once #include "BsScriptEnginePrerequisites.h" #include "BsScriptObject.h" #include "Physics/BsPhysicsMesh.h" namespace bs { /** @addtogroup ScriptInteropEngine * @{ */ /** @cond SCRIPT_EXTENSIONS */ /** Extension class for PhysicsMesh, for adding additional functionality for the script version of the class. */ class BS_SCR_BE_EXPORT BS_SCRIPT_EXPORT(e:PhysicsMesh) PhysicsMeshEx { public: /** @copydoc PhysicsMesh::create() */ BS_SCRIPT_EXPORT(ec:PhysicsMesh) static HPhysicsMesh create(const SPtr<RendererMeshData>& meshData, PhysicsMeshType type = PhysicsMeshType::Convex); /** @copydoc PhysicsMesh::getMeshData() */ BS_SCRIPT_EXPORT(e:PhysicsMesh,n:MeshData,pr:getter) static SPtr<RendererMeshData> getMeshData(const HPhysicsMesh& thisPtr); }; /** @endcond */ /** @} */ }
370
903
/* * Copyright 2020 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.codegen.core.trace; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.UUID; import java.util.function.BiFunction; import software.amazon.smithy.codegen.core.Symbol; import software.amazon.smithy.codegen.core.SymbolProvider; import software.amazon.smithy.model.shapes.MemberShape; import software.amazon.smithy.model.shapes.Shape; import software.amazon.smithy.model.shapes.ShapeId; import software.amazon.smithy.utils.SmithyBuilder; /** * Decorates a {@link SymbolProvider} with a {@link TraceFile.Builder} and adds a {@link ShapeLink} object * to the builder on each call to toSymbol. */ public final class TracingSymbolProvider implements SymbolProvider { private final TraceFile.Builder traceFileBuilder = new TraceFile.Builder(); private final Set<ShapeId> visitedShapes = new HashSet<>(); private final SymbolProvider symbolProvider; private final BiFunction<Shape, Symbol, List<ShapeLink>> shapeLinkCreator; private TracingSymbolProvider(Builder builder) { symbolProvider = SmithyBuilder.requiredState("symbolProvider", builder.symbolProvider); shapeLinkCreator = SmithyBuilder.requiredState("shapeLinkCreator", builder.shapeLinkCreator); traceFileBuilder.metadata(SmithyBuilder.requiredState("metadata", builder.metadata)) .definitions(builder.artifactDefinitions); } /** * Builder to create a TracingSymbolProvider instance. * * @return Returns a new Builder. */ public static Builder builder() { return new Builder(); } /** * Builds and returns the {@link TracingSymbolProvider}'s {@link TraceFile.Builder}. * * @return The {@link TraceFile} built from this {@link TracingSymbolProvider}'s {@link TraceFile.Builder}. */ public TraceFile buildTraceFile() { return traceFileBuilder.build(); } /** * Converts a shape into a symbol by calling the toSymbol method of the * SymbolProvider used to construct this TracingSymbolProvider. Adds a * list of ShapeLinks to the TracingSymbolProvider's TraceFile.Builder. * * @param shape Shape to convert to Symbol. * @return Symbol created from Shape. */ @Override public Symbol toSymbol(Shape shape) { Symbol symbol = symbolProvider.toSymbol(shape); ShapeId shapeId = shape.getId(); if (visitedShapes.add(shapeId)) { List<ShapeLink> shapeLinks = shapeLinkCreator.apply(shape, symbol); if (shapeLinks.size() > 0) { traceFileBuilder.addShapeLinks(shapeId, shapeLinks); } } return symbol; } @Override public String toMemberName(MemberShape shape) { return symbolProvider.toMemberName(shape); } /** * Builder to create a TracingSymbolProvider instance. */ public static final class Builder implements SmithyBuilder<TracingSymbolProvider> { private SymbolProvider symbolProvider; private BiFunction<Shape, Symbol, List<ShapeLink>> shapeLinkCreator; private ArtifactDefinitions artifactDefinitions; private TraceMetadata metadata; /** * Sets this Builder's ArtifactDefinitions. * * @param artifactDefinitions ArtifactDefinitions for this TracingSymbolProvider's * TraceFile. * @return This Builder. */ public Builder artifactDefinitions(ArtifactDefinitions artifactDefinitions) { this.artifactDefinitions = artifactDefinitions; return this; } /** * Sets this Builder's TraceMetadata. * * @param metadata TraceMetadata for this TracingSymbolProvider's * TraceFile. * @return This Builder. */ public Builder metadata(TraceMetadata metadata) { this.metadata = metadata; return this; } /** * Sets the Builder's {@link TraceMetadata} based on the given type and * default values for other required fields. This method should ONLY be used * when the version, type, homepage, and typeVersion of the TraceMetadata * object is unknown at the time of code generation. This method will ONLY set * the required fields of the {@link TraceMetadata}. * * <p>The type is set to the artifactType that is passed in. The artifactType is * the code language of the generated artifact, e.g. Java. * * <p>The timestamp in TraceMetadata is set to the current time when the * method is called. * * <p>The id and version are set to a UUID that should be changed after the * TraceFile is constructed and the correct id and version are known. * * @param artifactType The type, i.e. language, of the TraceMetadata object. * @return This Builder. */ public Builder setTraceMetadataAsDefault(String artifactType) { String tempIdVersion = UUID.randomUUID().toString(); this.metadata = TraceMetadata.builder() .version(tempIdVersion) .id(tempIdVersion) .type(artifactType) .setTimestampAsNow() .build(); return this; } /** * Sets this Builder's shapeLinkCreator. The shapeLinkCreator * is a function that maps from a Symbol to a List of ShapeLinks. * Custom Functions should be designed for each code generator * that map apply the tags and types in the definitions files * to specific ShapeLinks. * * @param shapeLinkCreator A Function that defines a mapping * from a Symbol to a List of ShapeLinks. * @return This Builder. */ public Builder shapeLinkCreator(BiFunction<Shape, Symbol, List<ShapeLink>> shapeLinkCreator) { this.shapeLinkCreator = shapeLinkCreator; return this; } /** * Sets this Builder's SymbolProvider. * * @param symbolProvider The SymbolProvider that the * TracingSymbolProvider will decorate. * @return This Builder. */ public Builder symbolProvider(SymbolProvider symbolProvider) { this.symbolProvider = symbolProvider; return this; } /** * Builds a {@code TracingSymbolProvider} implementation. * * @return Built TracingSymbolProvider. */ public TracingSymbolProvider build() { return new TracingSymbolProvider(this); } } }
2,841
348
<reponame>chamberone/Leaflet.PixiOverlay {"nom":"Notre-Dame-de-Livaye","circ":"3ème circonscription","dpt":"Calvados","inscrits":102,"abs":54,"votants":48,"blancs":6,"nuls":1,"exp":41,"res":[{"nuance":"MDM","nom":"<NAME>","voix":22},{"nuance":"LR","nom":"<NAME>","voix":19}]}
117
317
<reponame>Bartixxx32/Bombsquad-Ballistica-Modded-Server # Released under the MIT License. See LICENSE for details. # """Functionality related to the draw screen.""" from __future__ import annotations from typing import TYPE_CHECKING import ba from bastd.activity.multiteamscore import MultiTeamScoreScreenActivity from bastd.actor.zoomtext import ZoomText if TYPE_CHECKING: pass class DrawScoreScreenActivity(MultiTeamScoreScreenActivity): """Score screen shown after a draw.""" default_music = None # Awkward silence... def on_begin(self) -> None: ba.set_analytics_screen('Draw Score Screen') super().on_begin() ZoomText(ba.Lstr(resource='drawText'), position=(0, 0), maxwidth=400, shiftposition=(-220, 0), shiftdelay=2.0, flash=False, trail=False, jitter=1.0).autoretain() ba.timer(0.35, ba.Call(ba.playsound, self._score_display_sound)) self.show_player_scores(results=self.settings_raw.get('results', None))
456
535
import logging import numpy as np from sklearn.base import BaseEstimator, ClassifierMixin from sklearn.ensemble import ExtraTreesClassifier from .compat import string_, str_cast, unicode_ from .util import get_and_union_features from .blocks import TagCountNoCSSReadabilityBlockifier class Extractor(BaseEstimator, ClassifierMixin): """ An sklearn-style classifier that extracts the main content (and/or comments) from an HTML document. Args: blockifier (``Blockifier``) features (str or List[str], ``Features`` or List[``Features``], or List[Tuple[str, ``Features``]]): One or more features to be used to transform blocks into a matrix of numeric values. If more than one, a :class:`FeatureUnion` is automatically constructed. See :func:`get_and_union_features`. model (:class:`ClassifierMixin`): A scikit-learn classifier that takes a numeric matrix of features and outputs a binary prediction of 1 for content or 0 for not-content. If None, a :class:`ExtraTreesClassifier` with default parameters is used. to_extract (str or Sequence[str]): Type of information to extract from an HTML document: 'content', 'comments', or both via ['content', 'comments']. prob_threshold (float): Minimum prediction probability of a block being classified as "content" for it actually be taken as such. max_block_weight (int): Maximum weight that a single block may be given when training the extractor model, where weights are set equal to the number of tokens in each block. Note: If ``prob_threshold`` is not None, then ``model`` must implement the ``predict_proba()`` method. """ def __init__(self, blockifier=TagCountNoCSSReadabilityBlockifier, features=('kohlschuetter', 'weninger', 'readability'), model=None, to_extract='content', prob_threshold=0.5, max_block_weight=200): self.blockifier = blockifier self.features = features # initialize model if model is None: self.model = ExtraTreesClassifier() elif isinstance(model, ClassifierMixin): self.model = model else: raise TypeError('invalid `model` type: "{}"'.format(type(model))) if isinstance(to_extract, string_): self.to_extract = (to_extract,) else: self.to_extract = tuple(to_extract) self.prob_threshold = prob_threshold self.max_block_weight = max_block_weight self._positive_idx = None @property def features(self): return self._features @features.setter def features(self, feats): self._features = get_and_union_features(feats) def fit(self, documents, labels, weights=None): """ Fit :class`Extractor` features and model to a training dataset. Args: blocks (List[Block]) labels (``np.ndarray``) weights (``np.ndarray``) Returns: :class`Extractor` """ block_groups = np.array([self.blockifier.blockify(doc) for doc in documents]) mask = [self._has_enough_blocks(blocks) for blocks in block_groups] block_groups = block_groups[mask] labels = np.concatenate(np.array(labels)[mask]) # TODO: This only 'fit's one doc at a time. No feature fitting actually # happens for now, but this might be important if the features change features_mat = np.concatenate([self.features.fit_transform(blocks) for blocks in block_groups]) if weights is None: self.model.fit(features_mat, labels) else: weights = np.concatenate(np.array(weights)[mask]) self.model.fit(features_mat, labels, sample_weight=weights) return self def get_html_labels_weights(self, data): """ Gather the html, labels, and weights of many files' data. Primarily useful for training/testing an :class`Extractor`. Args: data: Output of :func:`dragnet.data_processing.prepare_all_data`. Returns: Tuple[List[Block], np.array(int), np.array(int)]: All blocks, all labels, and all weights, respectively. """ all_html = [] all_labels = [] all_weights = [] for html, content, comments in data: all_html.append(html) labels, weights = self._get_labels_and_weights( content, comments) all_labels.append(labels) all_weights.append(weights) return np.array(all_html), np.array(all_labels), np.array(all_weights) def _has_enough_blocks(self, blocks): if len(blocks) < 3: logging.warning( 'extraction failed: too few blocks (%s)', len(blocks)) return False return True def _get_labels_and_weights(self, content, comments): """ Args: content (Tuple[np.array[int], np.array[int], List[str]]) comments (Tuple[np.array[int], np.array[int], List[str]]) Returns: Tuple[np.array[int], np.array[int], List[str]] """ # extract content and comments if 'content' in self.to_extract and 'comments' in self.to_extract: labels = np.logical_or(content[0], comments[0]).astype(int) weights = content[1], # extract content only elif 'content' in self.to_extract: labels = content[0] weights = content[1] # extract comments only else: labels = comments[0] weights = comments[1] if self.max_block_weight is None: weights = np.minimum(weights, self.max_block_weight) return labels, weights def extract(self, html, encoding=None, as_blocks=False): """ Extract the main content and/or comments from an HTML document and return it as a string or as a sequence of block objects. Args: html (str): HTML document as a string. encoding (str): Encoding of ``html``. If None (encoding unknown), the original encoding will be guessed from the HTML itself. as_blocks (bool): If False, return the main content as a combined string; if True, return the content-holding blocks as a list of block objects. Returns: str or List[Block] """ preds, blocks = self.predict(html, encoding=encoding, return_blocks=True) if as_blocks is False: return str_cast(b'\n'.join(blocks[ind].text for ind in np.flatnonzero(preds))) else: return [blocks[ind] for ind in np.flatnonzero(preds)] def predict(self, documents, **kwargs): """ Predict class (content=1 or not-content=0) of the blocks in one or many HTML document(s). Args: documents (str or List[str]): HTML document(s) Returns: ``np.ndarray`` or List[``np.ndarray``]: array of binary predictions for content (1) or not-content (0). """ if isinstance(documents, (str, bytes, unicode_, np.unicode_)): return self._predict_one(documents, **kwargs) else: return np.concatenate([self._predict_one(doc, **kwargs) for doc in documents]) def _predict_one(self, document, encoding=None, return_blocks=False): """ Predict class (content=1 or not-content=0) of each block in an HTML document. Args: documents (str): HTML document Returns: ``np.ndarray``: array of binary predictions for content (1) or not-content (0). """ # blockify blocks = self.blockifier.blockify(document, encoding=encoding) # get features try: features = self.features.transform(blocks) except ValueError: # Can't make features, predict no content preds = np.zeros((len(blocks))) # make predictions else: if self.prob_threshold is None: preds = self.model.predict(features) else: self._positive_idx = ( self._positive_idx or list(self.model.classes_).index(1)) preds = self.model.predict_proba(features) > self.prob_threshold preds = preds[:, self._positive_idx].astype(int) if return_blocks: return preds, blocks else: return preds
3,806
3,228
<filename>src/main/java/org/red5/server/stream/FileStreamSource.java /* * RED5 Open Source Media Server - https://github.com/Red5/ Copyright 2006-2016 by respective authors (see below). 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. */ package org.red5.server.stream; import org.red5.io.ITag; import org.red5.io.ITagReader; import org.red5.io.flv.IKeyFrameDataAnalyzer; import org.red5.io.flv.IKeyFrameDataAnalyzer.KeyFrameMeta; import org.red5.server.net.rtmp.event.AudioData; import org.red5.server.net.rtmp.event.IRTMPEvent; import org.red5.server.net.rtmp.event.Invoke; import org.red5.server.net.rtmp.event.Notify; import org.red5.server.net.rtmp.event.Unknown; import org.red5.server.net.rtmp.event.VideoData; import org.red5.server.net.rtmp.message.Constants; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Represents stream source that is file */ public class FileStreamSource implements ISeekableStreamSource, Constants { /** * Logger */ protected static Logger log = LoggerFactory.getLogger(FileStreamSource.class); /** * Tag reader */ private ITagReader reader; /** * Key frame metadata */ private KeyFrameMeta keyFrameMeta; /** * Creates file stream source with tag reader * * @param reader * Tag reader */ public FileStreamSource(ITagReader reader) { this.reader = reader; } /** * Closes tag reader */ public void close() { reader.close(); } /** * Get tag from queue and convert to message * * @return RTMP event */ public IRTMPEvent dequeue() { if (reader.hasMoreTags()) { ITag tag = reader.readTag(); IRTMPEvent msg; switch (tag.getDataType()) { case TYPE_AUDIO_DATA: msg = new AudioData(tag.getBody()); break; case TYPE_VIDEO_DATA: msg = new VideoData(tag.getBody()); break; case TYPE_INVOKE: msg = new Invoke(tag.getBody()); break; case TYPE_NOTIFY: msg = new Notify(tag.getBody()); break; default: log.warn("Unexpected type? {}", tag.getDataType()); msg = new Unknown(tag.getDataType(), tag.getBody()); break; } msg.setTimestamp(tag.getTimestamp()); //msg.setSealed(true); return msg; } return null; } /** {@inheritDoc} */ public boolean hasMore() { return reader.hasMoreTags(); } /** {@inheritDoc} */ public int seek(int ts) { log.trace("Seek ts: {}", ts); if (keyFrameMeta == null) { if (!(reader instanceof IKeyFrameDataAnalyzer)) { // Seeking not supported return ts; } keyFrameMeta = ((IKeyFrameDataAnalyzer) reader).analyzeKeyFrames(); } if (keyFrameMeta.positions.length == 0) { // no video keyframe metainfo, it's an audio-only FLV we skip the seek for now. // TODO add audio-seek capability return ts; } int frame = 0; for (int i = 0; i < keyFrameMeta.positions.length; i++) { if (keyFrameMeta.timestamps[i] > ts) { break; } frame = i; } reader.position(keyFrameMeta.positions[frame]); return keyFrameMeta.timestamps[frame]; } }
1,842
4,054
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.vespa.clustercontroller.core; import com.yahoo.vdslib.state.*; import com.yahoo.vespa.clustercontroller.core.hostinfo.HostInfo; import com.yahoo.vespa.clustercontroller.core.hostinfo.StorageNodeStatsBridge; import org.junit.Test; import java.util.Set; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.*; /** * @author hakonhall */ public class ClusterStateViewTest { private final NodeInfo nodeInfo = mock(NodeInfo.class); private final ClusterStatsAggregator statsAggregator = mock(ClusterStatsAggregator.class); private final ClusterState clusterState = mock(ClusterState.class); private final ClusterStateView clusterStateView = new ClusterStateView(clusterState, statsAggregator); private HostInfo createHostInfo(String version) { return HostInfo.createHostInfo("{ \"cluster-state-version\": " + version + " }"); } @Test public void testWrongNodeType() { when(nodeInfo.isDistributor()).thenReturn(false); clusterStateView.handleUpdatedHostInfo(nodeInfo, createHostInfo("101")); verify(statsAggregator, never()).updateForDistributor(anyInt(), any()); } @Test public void testStateVersionMismatch() { when(nodeInfo.isDistributor()).thenReturn(true); when(clusterState.getVersion()).thenReturn(101); clusterStateView.handleUpdatedHostInfo(nodeInfo, createHostInfo("22")); verify(statsAggregator, never()).updateForDistributor(anyInt(), any()); } @Test public void testFailToGetStats() { when(nodeInfo.isDistributor()).thenReturn(true); when(clusterState.getVersion()).thenReturn(101); clusterStateView.handleUpdatedHostInfo(nodeInfo, createHostInfo("22")); verify(statsAggregator, never()).updateForDistributor(anyInt(), any()); } @Test public void testSuccessCase() { when(nodeInfo.isDistributor()).thenReturn(true); HostInfo hostInfo = HostInfo.createHostInfo( "{" + " \"cluster-state-version\": 101," + " \"distributor\": {\n" + " \"storage-nodes\": [\n" + " {\n" + " \"node-index\": 3\n" + " }\n" + " ]}}"); when(nodeInfo.getNodeIndex()).thenReturn(3); when(clusterState.getVersion()).thenReturn(101); clusterStateView.handleUpdatedHostInfo(nodeInfo, hostInfo); verify(statsAggregator).updateForDistributor(3, StorageNodeStatsBridge.generate(hostInfo.getDistributor())); } @Test public void testIndicesOfUpNodes() { when(clusterState.getNodeCount(NodeType.DISTRIBUTOR)).thenReturn(7); NodeState nodeState = mock(NodeState.class); when(nodeState.getState()). thenReturn(State.MAINTENANCE). // 0 thenReturn(State.RETIRED). // 1 thenReturn(State.INITIALIZING). // 2 thenReturn(State.DOWN). thenReturn(State.STOPPING). thenReturn(State.UNKNOWN). thenReturn(State.UP); // 6 when(clusterState.getNodeState(any())).thenReturn(nodeState); Set<Integer> indices = ClusterStateView.getIndicesOfUpNodes(clusterState, NodeType.DISTRIBUTOR); assertEquals(4, indices.size()); assert(indices.contains(0)); assert(indices.contains(1)); assert(indices.contains(2)); assert(indices.contains(6)); } }
1,535
678
<filename>iOSOpenDev/frameworks/SoftwareUpdateServices.framework/Headers/SUAssetSupport.h<gh_stars>100-1000 /** * This header is generated by class-dump-z 0.2b. * * Source: /System/Library/PrivateFrameworks/SoftwareUpdateServices.framework/SoftwareUpdateServices */ #import <SoftwareUpdateServices/XXUnknownSuperclass.h> #import <SoftwareUpdateServices/SoftwareUpdateServices-Structs.h> @interface SUAssetSupport : XXUnknownSuperclass { } + (id)assetDownloadOptionsFromMetadata:(id)metadata priority:(int)priority; // 0x1181d + (id)defaultAssetDownloadOptionsWithPriority:(int)priority; // 0x11769 + (id)localURLForAsset:(MobileAsset *)asset; // 0x1171d + (id)createPossibleDocumentationAssetsFromDescriptor:(id)descriptor; // 0x11555 + (MobileAsset *)createUpdateAssetUsingProductType:(id)type productBuild:(id)build productVersion:(id)version releaseType:(id)type4; // 0x11545 + (MobileAsset *)createDefaultUpdateAsset; // 0x114b1 + (void)cleanupUpdateAndDocumentationForAsset:(MobileAsset *)asset; // 0x113d5 + (void)cleanupAssets:(id)assets; // 0x11335 + (void)cleanupAsset:(MobileAsset *)asset; // 0x112a5 + (id)tryCreateDocumentationFromAsset:(MobileAsset *)asset; // 0x110b9 + (id)createDescriptorFromAsset:(MobileAsset *)asset state:(id)state; // 0x10b09 + (id)tryCreateDescriptorFromAsset:(MobileAsset *)asset; // 0x10aa9 + (id)tryCreateDescriptorFromCachedAsset; // 0x10a61 @end
464
1,290
<reponame>enjoyproduct/iOS-SlideMenu // // SlideMenuTests.h // SlideMenuTests // // Created by <NAME> on 4/24/13. // Copyright (c) 2013 <NAME>. All rights reserved. // #import <XCTest/XCTest.h> @interface SlideMenuTests : XCTestCase @end
99
7,706
<gh_stars>1000+ /* * 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. */ package com.google.tsunami.common.version; import static com.google.common.truth.Truth.assertThat; import static org.junit.Assert.assertThrows; import com.google.common.collect.ImmutableList; import org.junit.Test; import org.junit.experimental.theories.DataPoints; import org.junit.experimental.theories.FromDataPoints; import org.junit.experimental.theories.Theories; import org.junit.experimental.theories.Theory; import org.junit.runner.RunWith; /** Tests for {@link Version}. */ @RunWith(Theories.class) public final class VersionTest { @Test public void create_whenNormalVersionAndValueIsNull_throwsException() { assertThrows(IllegalArgumentException.class, () -> Version.fromString(null)); } @Test public void create_whnNormalVersionAndValueIsEmpty_throwsExceptionIfStringIsNull() { assertThrows(IllegalArgumentException.class, () -> Version.fromString("")); } @Test public void create_whenNormalVersion_returnsTypeNormal() { Version version = Version.fromString("1.1"); assertThat(version.versionType()).isEqualTo(Version.Type.NORMAL); } @Test public void createMaximum_always_returnsTypeMaximum() { Version version = Version.maximum(); assertThat(version.versionType()).isEqualTo(Version.Type.MAXIMUM); } @Test public void createMaximum_always_returnsTypeMinimum() { Version version = Version.minimum(); assertThat(version.versionType()).isEqualTo(Version.Type.MINIMUM); } @DataPoints("InvalidVersion") public static ImmutableList<String> invalidVersionTestCases() { return ImmutableList.of("", "N/A", "...", "-"); } @Theory public void fromString_invalidVersionString_throwsIllegalArgumentException( @FromDataPoints("InvalidVersion") String version) { assertThrows(IllegalArgumentException.class, () -> Version.fromString(version)); } @Test public void fromString_validString_storesInputAsRawString() { assertThat(Version.fromString("1.0").versionString()).isEqualTo("1.0"); } @Test public void fromString_noEpoch_appendsZeroEpoch() { assertThat(Version.fromString("1.0").segments()) .containsExactly(Segment.fromString("0"), Segment.fromString("1.0")); } @Test public void fromString_withEpoch_epochIsParsed() { assertThat(Version.fromString("1:1.0").segments()) .containsExactly(Segment.fromString("1"), Segment.fromString("1.0")); } @Test public void fromString_withMultipleSegments_segmentsParsedCorrectly() { assertThat(Version.fromString("1:9.7.0.dfsg.P1-gg3.0").segments()) .containsExactly( Segment.fromString("1"), Segment.fromString("9.7.0.dfsg.P1"), Segment.fromString("3.0")); } @DataPoints("Equals") public static ImmutableList<EqualsTestCase<Version>> equalsTestCases() { return ImmutableList.of( EqualsTestCase.create(Version.fromString("1.0"), Version.fromString("1.0")), EqualsTestCase.create(Version.fromString("1.0"), Version.fromString("0:1.0")), EqualsTestCase.create(Version.fromString("1.0-"), Version.fromString("1.0-gg")), EqualsTestCase.create(Version.maximum(), Version.maximum()), EqualsTestCase.create(Version.minimum(), Version.minimum())); } @Theory public void compareTo_equalsTestCase_returnsZero( @FromDataPoints("Equals") EqualsTestCase<Version> testCase) { assertThat(testCase.first()).isEquivalentAccordingToCompareTo(testCase.second()); } @DataPoints("LessThan") public static ImmutableList<LessThanTestCase<Version>> lessThanTestCases() { return ImmutableList.of( LessThanTestCase.create(Version.minimum(), Version.fromString("1.0")), LessThanTestCase.create(Version.minimum(), Version.maximum()), LessThanTestCase.create(Version.fromString("1.0"), Version.maximum()), LessThanTestCase.create(Version.fromString("0.9"), Version.fromString("1.0")), LessThanTestCase.create(Version.fromString("1.0-0"), Version.fromString("1.0-110313082")), LessThanTestCase.create( Version.fromString("0.161-gg2.0"), Version.fromString("0.165-gg1.0")), LessThanTestCase.create(Version.fromString("0.87-gg1.2"), Version.fromString("0.87-gg1.3")), LessThanTestCase.create( Version.fromString("2017b-gg1.0"), Version.fromString("2018b-gg0.")), LessThanTestCase.create(Version.fromString("18-4"), Version.fromString("19-1")), LessThanTestCase.create( Version.fromString("1:9.7.0.dfsg.P1-gg3.0"), Version.fromString("1:9.8.0.dfsg.P0-gg1.0")), LessThanTestCase.create(Version.fromString("5.7-gg2.0"), Version.fromString("5.8-gg1.0")), LessThanTestCase.create( Version.fromString("2.4.6-12"), Version.fromString("2.4.6-12+patched1")), LessThanTestCase.create(Version.fromString("20170727-1"), Version.fromString("20170801-1")), LessThanTestCase.create( Version.fromString("3.12-443-ga51ea6dc8202-gg2.2"), Version.fromString("3.13-440-ga51eadfe472-gg1.0")), LessThanTestCase.create(Version.fromString("1.0a"), Version.fromString("1.0b")), LessThanTestCase.create(Version.fromString("1a"), Version.fromString("2")), LessThanTestCase.create( Version.fromString("4d01146f1679dd90bba45adb60d24ad11fe1155e"), Version.fromString("e40b437401966fe06b0c4d5430c35e4494675c90")), LessThanTestCase.create(Version.fromString("7.10"), Version.fromString("1_7.9")), LessThanTestCase.create(Version.fromString("9.10"), Version.fromString("1_9.11")), LessThanTestCase.create( Version.fromString("1.0.0-alpha"), Version.fromString("1.0.0-alpha.1")), LessThanTestCase.create( Version.fromString("1.0.0-alpha.1"), Version.fromString("1.0.0-alpha.beta")), LessThanTestCase.create( Version.fromString("1.0.0-alpha.beta"), Version.fromString("1.0.0-beta")), LessThanTestCase.create( Version.fromString("1.0.0-beta"), Version.fromString("1.0.0-beta.2")), LessThanTestCase.create( Version.fromString("1.0.0-beta.2"), Version.fromString("1.0.0-beta.11")), LessThanTestCase.create( Version.fromString("1.0.0-beta.11"), Version.fromString("1.0.0-rc.1")), LessThanTestCase.create(Version.fromString("1.0.0-rc.1"), Version.fromString("1.0.0")), LessThanTestCase.create(Version.fromString("1.0.0-alpha"), Version.fromString("1.0.0")), LessThanTestCase.create(Version.fromString("1.0.0-alpha.1"), Version.fromString("1.0.0")), LessThanTestCase.create( Version.fromString("1.0.0-alpha.beta"), Version.fromString("1.0.0")), LessThanTestCase.create(Version.fromString("1.0.0-beta"), Version.fromString("1.0.0")), LessThanTestCase.create(Version.fromString("1.0.0-beta.2"), Version.fromString("1.0.0")), LessThanTestCase.create(Version.fromString("1.0.0-beta.11"), Version.fromString("1.0.0")), LessThanTestCase.create(Version.fromString("7.6-0"), Version.fromString("7.6p2-4")), LessThanTestCase.create(Version.fromString("1.0-1"), Version.fromString("1.0.3-3")), LessThanTestCase.create(Version.fromString("1.2.2-2"), Version.fromString("1.3")), LessThanTestCase.create(Version.fromString("1.2.2"), Version.fromString("1.3")), LessThanTestCase.create(Version.fromString("0-pre"), Version.fromString("0-pree")), LessThanTestCase.create(Version.fromString("1.1.6r-1"), Version.fromString("1.1.6r2-2")), LessThanTestCase.create(Version.fromString("2.6b-2"), Version.fromString("2.6b2-1")), LessThanTestCase.create( Version.fromString("98.1-pre2-b6-2"), Version.fromString("98.1p5-1")), LessThanTestCase.create(Version.fromString("0.4-1"), Version.fromString("0.4a6-2")), LessThanTestCase.create(Version.fromString("1:3.0.5-2"), Version.fromString("1:3.0.5.1")), LessThanTestCase.create(Version.fromString("10.3"), Version.fromString("1:0.4")), LessThanTestCase.create(Version.fromString("1:1.25-4"), Version.fromString("1:1.25-8")), LessThanTestCase.create(Version.fromString("1.18.35"), Version.fromString("1.18.36")), LessThanTestCase.create(Version.fromString("1.18.35"), Version.fromString("0:1.18.36")), LessThanTestCase.create( Version.fromString("9:1.18.36:5.4-20"), Version.fromString("10:0.5.1-22")), LessThanTestCase.create( Version.fromString("9:1.18.36:5.4-20"), Version.fromString("9:1.18.36:5.5-1")), LessThanTestCase.create( Version.fromString("9:1.18.36:5.4-20"), Version.fromString("9:1.18.37:4.3-22")), LessThanTestCase.create( Version.fromString("1.18.36-0.17.35-18"), Version.fromString("1.18.36-19")), LessThanTestCase.create( Version.fromString("1:1.2.13-3"), Version.fromString("1:1.2.13-3.1")), LessThanTestCase.create(Version.fromString("2.0.7pre1-4"), Version.fromString("2.0.7r-1")), LessThanTestCase.create(Version.fromString("0.2"), Version.fromString("1.0-0")), LessThanTestCase.create(Version.fromString("1.0"), Version.fromString("1.0-0+b1")), LessThanTestCase.create(Version.fromString("1.2.3"), Version.fromString("1.2.3-1")), LessThanTestCase.create(Version.fromString("1.2.3"), Version.fromString("1.2.4")), LessThanTestCase.create(Version.fromString("1.2.3"), Version.fromString("1.2.4")), LessThanTestCase.create(Version.fromString("1.2.3"), Version.fromString("1.2.24")), LessThanTestCase.create(Version.fromString("0.8.7"), Version.fromString("0.10.0")), LessThanTestCase.create(Version.fromString("2.3"), Version.fromString("3.2")), LessThanTestCase.create(Version.fromString("1.3.2"), Version.fromString("1.3.2a")), LessThanTestCase.create(Version.fromString("0.5.0~git"), Version.fromString("0.5.0~git2")), LessThanTestCase.create(Version.fromString("2a"), Version.fromString("21")), LessThanTestCase.create(Version.fromString("1.3.2a"), Version.fromString("1.3.2b")), LessThanTestCase.create(Version.fromString("1.2.4"), Version.fromString("1:1.2.3")), LessThanTestCase.create(Version.fromString("1:1.2.3"), Version.fromString("1:1.2.4")), LessThanTestCase.create(Version.fromString("1.2a+~bCd3"), Version.fromString("1.2a++")), LessThanTestCase.create(Version.fromString("1.2a+~"), Version.fromString("1.2a+~bCd3")), LessThanTestCase.create(Version.fromString("304-2"), Version.fromString("5:2")), LessThanTestCase.create(Version.fromString("5:2"), Version.fromString("304:2")), LessThanTestCase.create(Version.fromString("3:2"), Version.fromString("25:2")), LessThanTestCase.create(Version.fromString("1:2:123"), Version.fromString("1:12:3")), LessThanTestCase.create(Version.fromString("1.2-3-5"), Version.fromString("1.2-5")), LessThanTestCase.create(Version.fromString("5.005"), Version.fromString("5.10.0")), LessThanTestCase.create(Version.fromString("3.10.2"), Version.fromString("3a9.8")), LessThanTestCase.create(Version.fromString("3~10"), Version.fromString("3a9.8")), LessThanTestCase.create( Version.fromString("1.4+OOo3.0.0~"), Version.fromString("1.4+OOo3.0.0-4")), LessThanTestCase.create(Version.fromString("3.0~rc1-1"), Version.fromString("3.0-1")), LessThanTestCase.create(Version.fromString("2.4.7-1"), Version.fromString("2.4.7-z")), LessThanTestCase.create(Version.fromString("1.00"), Version.fromString("1.002-1+b2")), LessThanTestCase.create(Version.fromString("5.36-r0"), Version.fromString("5.36")), LessThanTestCase.create(Version.fromString("5.36-r0"), Version.fromString("5.36-gg1.0")), LessThanTestCase.create( Version.fromString("5.36-r0"), Version.fromString("5.36-r0-gg1.0"))); } @Theory public void compareTo_lessThanTestCase_hasCorrectSymmetryResult( @FromDataPoints("LessThan") LessThanTestCase<Version> testCase) { assertThat(testCase.smaller()).isLessThan(testCase.larger()); assertThat(testCase.larger()).isGreaterThan(testCase.smaller()); } }
5,320
1,350
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. package com.microsoft.azure.servicebus.management; import com.microsoft.azure.servicebus.security.SecurityConstants; import java.security.SecureRandom; import java.util.Base64; import java.util.HashSet; import java.util.List; public class SharedAccessAuthorizationRule extends AuthorizationRule { static final int SUPPORTED_SAS_KEY_LENGTH = 44; static final String FIXED_CLAIM_TYPE = "SharedAccessKey"; private String keyName; private String primaryKey; private String secondaryKey; private List<AccessRights> rights; SharedAccessAuthorizationRule() { } public SharedAccessAuthorizationRule(String keyName, List<AccessRights> rights) { this(keyName, SharedAccessAuthorizationRule.generateRandomKey(), SharedAccessAuthorizationRule.generateRandomKey(), rights); } public SharedAccessAuthorizationRule(String keyName, String primaryKey, List<AccessRights> rights) { this(keyName, primaryKey, SharedAccessAuthorizationRule.generateRandomKey(), rights); } public SharedAccessAuthorizationRule(String keyName, String primaryKey, String secondaryKey, List<AccessRights> rights) { this.setKeyName(keyName); this.setPrimaryKey(primaryKey); this.setSecondaryKey(secondaryKey); this.setRights(rights); } @Override public String getClaimType() { return SharedAccessAuthorizationRule.FIXED_CLAIM_TYPE; } @Override String getClaimValue() { return "None"; } @Override public String getKeyName() { return keyName; } @Override public void setKeyName(String keyName) { if (keyName == null || keyName.isEmpty()) { throw new IllegalArgumentException("Argument cannot be null"); } if (keyName.length() > SecurityConstants.MAX_KEY_NAME_LENGTH) { throw new IllegalArgumentException("sasKeyName cannot be greater than " + SecurityConstants.MAX_KEY_NAME_LENGTH + " characters."); } this.keyName = keyName; } public String getPrimaryKey() { return primaryKey; } public void setPrimaryKey(String primaryKey) { if (primaryKey == null || primaryKey.isEmpty()) { throw new IllegalArgumentException("Argument cannot be null"); } if (primaryKey.length() > SharedAccessAuthorizationRule.SUPPORTED_SAS_KEY_LENGTH) { throw new IllegalArgumentException("sasKey cannot be greater than " + SharedAccessAuthorizationRule.SUPPORTED_SAS_KEY_LENGTH + " characters."); } this.primaryKey = primaryKey; } public String getSecondaryKey() { return secondaryKey; } public void setSecondaryKey(String secondaryKey) { if (secondaryKey == null || secondaryKey.isEmpty()) { throw new IllegalArgumentException("Argument cannot be null"); } if (secondaryKey.length() > SharedAccessAuthorizationRule.SUPPORTED_SAS_KEY_LENGTH) { throw new IllegalArgumentException("sasKey cannot be greater than " + SharedAccessAuthorizationRule.SUPPORTED_SAS_KEY_LENGTH + " characters."); } this.secondaryKey = secondaryKey; } @Override public List<AccessRights> getRights() { return rights; } @Override public void setRights(List<AccessRights> rights) { if (rights == null || rights.size() <= 0 || rights.size() > ManagementClientConstants.SUPPORTED_CLAIMS_COUNT) { throw new IllegalArgumentException("Rights cannot be null, empty or greater than " + ManagementClientConstants.SUPPORTED_CLAIMS_COUNT); } HashSet<AccessRights> dedupedAccessRights = new HashSet<>(rights); if (rights.size() != dedupedAccessRights.size()) { throw new IllegalArgumentException("Access rights on an authorization rule must be unique"); } if (dedupedAccessRights.contains(AccessRights.Manage) && dedupedAccessRights.size() != 3) { throw new IllegalArgumentException("Manage permission should also include Send and Listen."); } this.rights = rights; } @Override public boolean equals(Object o) { if (o == this) { return true; } if (!(o instanceof SharedAccessAuthorizationRule)) { return false; } SharedAccessAuthorizationRule other = (SharedAccessAuthorizationRule) o; if (this.keyName != null && !this.keyName.equalsIgnoreCase(other.keyName) || this.primaryKey != null && !this.primaryKey.equalsIgnoreCase(other.primaryKey) || this.secondaryKey != null && !this.secondaryKey.equalsIgnoreCase(other.secondaryKey)) { return false; } if ((this.rights != null && other.rights == null) || this.rights == null && other.rights != null) { return false; } if (this.rights != null) { if (this.rights.size() != other.rights.size()) { return false; } HashSet<AccessRights> thisRights = new HashSet<>(this.rights); if (!thisRights.containsAll(other.rights)) { return false; } } return true; } @Override public int hashCode() { int hash = 13; if (this.keyName != null) { hash = (hash * 7) + this.keyName.hashCode(); } if (this.primaryKey != null) { hash = (hash * 7) + this.primaryKey.hashCode(); } if (this.secondaryKey != null) { hash = (hash * 7) + this.secondaryKey.hashCode(); } if (this.rights != null) { hash = (hash * 7) + this.rights.hashCode(); } return hash; } private static String generateRandomKey() { SecureRandom random = new SecureRandom(); byte[] key256 = new byte[32]; random.nextBytes(key256); return Base64.getEncoder().encodeToString(key256); } }
2,403
875
//package com.jeecg.p3.weixin.dao.impl; // //import java.util.List; //import java.util.Map; // //import org.jeecgframework.p3.core.utils.common.PageQuery; //import org.jeecgframework.p3.core.utils.common.PageQueryWrapper; //import org.jeecgframework.p3.core.utils.persistence.mybatis.GenericDaoDefault; //import org.springframework.stereotype.Repository; // //import com.google.common.collect.Maps; //import com.jeecg.p3.weixin.dao.WeixinTagDao; //import com.jeecg.p3.weixin.entity.WeixinTag; // ///** // * 描述:</b>粉丝标签表<br> // * @author:weijian.zhang // * @since:2018年08月13日 14时53分22秒 星期一 // * @version:1.0 // */ //@Repository("weixinTagDao") //public class WeixinTagDaoImpl extends GenericDaoDefault<WeixinTag> implements WeixinTagDao{ // // @Override // public Integer count(PageQuery<WeixinTag> pageQuery) { // return (Integer) super.queryOne("count",pageQuery); // } // // @SuppressWarnings("unchecked") // @Override // public List<WeixinTag> queryPageList( // PageQuery<WeixinTag> pageQuery,Integer itemCount) { // PageQueryWrapper<WeixinTag> wrapper = new PageQueryWrapper<WeixinTag>(pageQuery.getPageNo(), pageQuery.getPageSize(),itemCount, pageQuery.getQuery()); // return (List<WeixinTag>)super.query("queryPageList",wrapper); // } // // /** // * @功能:根据jwid清空该公众号创建的标签 // * @param jwid // */ // @Override // public void deleteTagsByJwid(String jwid) { // super.delete("deleteTagsByJwid", jwid); // } // // /** // * @功能:根据jwid获取该公众号创建的标签 // */ // @SuppressWarnings("unchecked") // @Override // public List<WeixinTag> getAllTags(String jwid) { // return super.query("getAllTags", jwid); // } // // /** // * @功能:根据tagId和jwid获取标签信息 // */ // @Override // public WeixinTag queryByTagIdAndJwid(String tagId, String jwid) { // Map<String, Object> param=Maps.newConcurrentMap(); // param.put("tagId", tagId); // param.put("jwid", jwid); // return (WeixinTag) super.queryOne("queryByTagIdAndJwid", param); // } // // //} //
896
634
<filename>server/container/cli/src/main/java/org/apache/james/cli/type/CmdType.java<gh_stars>100-1000 /**************************************************************** * Licensed to the Apache Software Foundation (ASF) under one * * or more contributor license agreements. See the NOTICE file * * distributed with this work for additional information * * regarding copyright ownership. The ASF licenses this file * * to you under the Apache License, Version 2.0 (the * * "License"); you may not use this file except in compliance * * with the License. You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, * * software distributed under the License is distributed on an * * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * * KIND, either express or implied. See the License for the * * specific language governing permissions and limitations * * under the License. * ****************************************************************/ package org.apache.james.cli.type; import java.util.Arrays; /** * Enumeration of valid command types. */ public enum CmdType { ADDUSER("AddUser", "username","password"), REMOVEUSER("RemoveUser", "username"), LISTUSERS("ListUsers"), ADDDOMAIN("AddDomain", "domainName"), REMOVEDOMAIN("RemoveDomain", "domainName"), CONTAINSDOMAIN("ContainsDomain", "domainName"), LISTDOMAINS("ListDomains"), LISTMAPPINGS("ListMappings"), LISTUSERDOMAINMAPPINGS("ListUserDomainMappings", "user","domain"), ADDADDRESSMAPPING("AddAddressMapping", "fromUser","fromDomain", "toAddress"), REMOVEADDRESSMAPPING("RemoveAddressMapping", "fromUser","fromDomain", "toAddress"), ADDREGEXMAPPING("AddRegexMapping", "user","domain", "regex"), REMOVEREGEXMAPPING("RemoveRegexMapping", "user","domain", "regex"), SETPASSWORD("SetPassword", "username","password"), COPYMAILBOX("CopyMailbox", "srcBean","dstBean"), DELETEUSERMAILBOXES("DeleteUserMailboxes", "user"), CREATEMAILBOX("CreateMailbox", "namespace", "user", "name"), LISTUSERMAILBOXES("ListUserMailboxes", "user"), DELETEMAILBOX("DeleteMailbox", "namespace", "user", "name"), IMPORTEML("ImportEml", "namespace", "user", "name", "path"), GETSTORAGEQUOTA("GetStorageQuota", "quotaroot"), GETMESSAGECOUNTQUOTA("GetMessageCountQuota", "quotaroot"), GETQUOTAROOT("GetQuotaroot", "namespace", "user", "name"), GETMAXSTORAGEQUOTA("GetMaxStorageQuota", "quotaroot"), GETMAXMESSAGECOUNTQUOTA("GetMaxMessageCountQuota", "quotaroot"), SETMAXSTORAGEQUOTA("SetMaxStorageQuota", "quotaroot", "maxMessageCount"), SETMAXMESSAGECOUNTQUOTA("SetMaxMessageCountQuota", "quotaroot", "maxStorage"), SETGLOBALMAXSTORAGEQUOTA("SetGlobalMaxStorageQuota", "maxStorage"), SETGLOBALMAXMESSAGECOUNTQUOTA("SetGlobalMaxMessageCountQuota", "maxMessageCount"), GETGLOBALMAXSTORAGEQUOTA("GetGlobalMaxStorageQuota"), GETGLOBALMAXMESSAGECOUNTQUOTA("GetGlobalMaxMessageCountQuota"), REINDEXMAILBOX("ReindexMailbox", "namespace", "user", "name"), REINDEXALL("ReindexAll"), GETSIEVEQUOTA("GetSieveQuota"), SETSIEVEQUOTA("SetSieveQuota", "quota"), REMOVESIEVEQUOTA("RemoveSieveQuota"), GETSIEVEUSERQUOTA("GetSieveUserQuota", "username"), SETSIEVEUSERQUOTA("SetSieveUserQuota", "username", "quota"), REMOVESIEVEUSERQUOTA("RemoveSieveUserQuota", "username"), ADDACTIVESIEVESCRIPT("AddActiveSieveScript", "username", "scriptname", "path"); private final String command; private final String[] arguments; CmdType(String command, String... arguments) { this.command = command; this.arguments = arguments; } /** * Validate that the number of arguments match the passed value. * * @param arguments * The number of argument to compare. * @return true if values match, false otherwise. */ public boolean hasCorrectArguments(int arguments) { return this.arguments.length + 1 == arguments; } /** * Return a CmdType enumeration that matches the passed command. * * @param command * The command to use for lookup. * @return the CmdType enumeration that matches the passed command, or null * if not found. */ public static CmdType lookup(String command) { if (command != null) { return Arrays.stream(values()) .filter(cmd -> cmd.getCommand().equalsIgnoreCase(command)) .findFirst() .orElse(null); } return null; } /** * Return the value of command. * * @return the value of command. */ public String getCommand() { return this.command; } /** * Return the value of arguments. * * @return the value of arguments. */ public int getArgumentCount() { return this.arguments.length + 1; } public String getUsage() { StringBuilder stringBuilder = new StringBuilder(command); for (String argument : arguments) { stringBuilder.append(" <" + argument + ">"); } return stringBuilder.toString(); } }
2,258
8,747
<reponame>lovyan03/esp-idf /* * SPDX-FileCopyrightText: 2021 Espressif Systems (Shanghai) CO LTD * * SPDX-License-Identifier: Apache-2.0 */ #pragma once #ifndef __cpp_exceptions #error system C++ classes only usable when C++ exceptions enabled. Enable CONFIG_COMPILER_CXX_EXCEPTIONS in Kconfig #endif /** * This is a "Strong Value Type" base class for types in IDF C++ classes. * The idea is that subclasses completely check the contained value during construction. * After that, it's trapped and encapsulated inside and cannot be changed anymore. * Consequently, the API functions receiving a correctly implemented sub class as parameter * don't need to check it anymore. Only at API boundaries the valid value will be retrieved * with get_value(). */ template<typename ValueT> class StrongValue { protected: StrongValue(ValueT value_arg) : value(value_arg) { } ValueT get_value() const { return value; } private: ValueT value; }; /** * This class adds comparison properties to StrongValue, but no sorting properties. */ template<typename ValueT> class StrongValueComparable : public StrongValue<ValueT> { protected: StrongValueComparable(ValueT value_arg) : StrongValue<ValueT>(value_arg) { } using StrongValue<ValueT>::get_value; bool operator==(const StrongValueComparable<ValueT> &other_gpio) const { return get_value() == other_gpio.get_value(); } bool operator!=(const StrongValueComparable<ValueT> &other_gpio) const { return get_value() != other_gpio.get_value(); } };
499
1,350
<reponame>Shashi-rk/azure-sdk-for-java // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.resourcemanager.automation.implementation; import com.azure.core.annotation.ExpectedResponses; import com.azure.core.annotation.Get; import com.azure.core.annotation.HeaderParam; import com.azure.core.annotation.Headers; import com.azure.core.annotation.Host; import com.azure.core.annotation.HostParam; import com.azure.core.annotation.PathParam; import com.azure.core.annotation.QueryParam; import com.azure.core.annotation.ReturnType; import com.azure.core.annotation.ServiceInterface; import com.azure.core.annotation.ServiceMethod; import com.azure.core.annotation.UnexpectedResponseExceptionType; import com.azure.core.http.rest.PagedFlux; import com.azure.core.http.rest.PagedIterable; import com.azure.core.http.rest.PagedResponse; import com.azure.core.http.rest.PagedResponseBase; import com.azure.core.http.rest.Response; import com.azure.core.http.rest.RestProxy; import com.azure.core.management.exception.ManagementException; import com.azure.core.util.Context; import com.azure.core.util.FluxUtil; import com.azure.core.util.logging.ClientLogger; import com.azure.resourcemanager.automation.fluent.ActivitiesClient; import com.azure.resourcemanager.automation.fluent.models.ActivityInner; import com.azure.resourcemanager.automation.models.ActivityListResult; import reactor.core.publisher.Mono; /** An instance of this class provides access to all the operations defined in ActivitiesClient. */ public final class ActivitiesClientImpl implements ActivitiesClient { private final ClientLogger logger = new ClientLogger(ActivitiesClientImpl.class); /** The proxy service used to perform REST calls. */ private final ActivitiesService service; /** The service client containing this operation class. */ private final AutomationClientImpl client; /** * Initializes an instance of ActivitiesClientImpl. * * @param client the instance of the service client containing this operation class. */ ActivitiesClientImpl(AutomationClientImpl client) { this.service = RestProxy.create(ActivitiesService.class, client.getHttpPipeline(), client.getSerializerAdapter()); this.client = client; } /** * The interface defining all the services for AutomationClientActivities to be used by the proxy service to perform * REST calls. */ @Host("{$host}") @ServiceInterface(name = "AutomationClientActi") private interface ActivitiesService { @Headers({"Content-Type: application/json"}) @Get( "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Automation" + "/automationAccounts/{automationAccountName}/modules/{moduleName}/activities/{activityName}") @ExpectedResponses({200}) @UnexpectedResponseExceptionType(ManagementException.class) Mono<Response<ActivityInner>> get( @HostParam("$host") String endpoint, @PathParam("resourceGroupName") String resourceGroupName, @PathParam("automationAccountName") String automationAccountName, @PathParam("moduleName") String moduleName, @PathParam("activityName") String activityName, @PathParam("subscriptionId") String subscriptionId, @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, Context context); @Headers({"Content-Type: application/json"}) @Get( "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Automation" + "/automationAccounts/{automationAccountName}/modules/{moduleName}/activities") @ExpectedResponses({200}) @UnexpectedResponseExceptionType(ManagementException.class) Mono<Response<ActivityListResult>> listByModule( @HostParam("$host") String endpoint, @PathParam("resourceGroupName") String resourceGroupName, @PathParam("automationAccountName") String automationAccountName, @PathParam("moduleName") String moduleName, @PathParam("subscriptionId") String subscriptionId, @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, Context context); @Headers({"Content-Type: application/json"}) @Get("{nextLink}") @ExpectedResponses({200}) @UnexpectedResponseExceptionType(ManagementException.class) Mono<Response<ActivityListResult>> listByModuleNext( @PathParam(value = "nextLink", encoded = true) String nextLink, @HostParam("$host") String endpoint, @HeaderParam("Accept") String accept, Context context); } /** * Retrieve the activity in the module identified by module name and activity name. * * @param resourceGroupName Name of an Azure Resource group. * @param automationAccountName The name of the automation account. * @param moduleName The name of module. * @param activityName The name of activity. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return definition of the activity. */ @ServiceMethod(returns = ReturnType.SINGLE) private Mono<Response<ActivityInner>> getWithResponseAsync( String resourceGroupName, String automationAccountName, String moduleName, String activityName) { if (this.client.getEndpoint() == null) { return Mono .error( new IllegalArgumentException( "Parameter this.client.getEndpoint() is required and cannot be null.")); } if (resourceGroupName == null) { return Mono .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); } if (automationAccountName == null) { return Mono .error(new IllegalArgumentException("Parameter automationAccountName is required and cannot be null.")); } if (moduleName == null) { return Mono.error(new IllegalArgumentException("Parameter moduleName is required and cannot be null.")); } if (activityName == null) { return Mono.error(new IllegalArgumentException("Parameter activityName is required and cannot be null.")); } if (this.client.getSubscriptionId() == null) { return Mono .error( new IllegalArgumentException( "Parameter this.client.getSubscriptionId() is required and cannot be null.")); } final String apiVersion = "2019-06-01"; final String accept = "application/json"; return FluxUtil .withContext( context -> service .get( this.client.getEndpoint(), resourceGroupName, automationAccountName, moduleName, activityName, this.client.getSubscriptionId(), apiVersion, accept, context)) .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); } /** * Retrieve the activity in the module identified by module name and activity name. * * @param resourceGroupName Name of an Azure Resource group. * @param automationAccountName The name of the automation account. * @param moduleName The name of module. * @param activityName The name of activity. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return definition of the activity. */ @ServiceMethod(returns = ReturnType.SINGLE) private Mono<Response<ActivityInner>> getWithResponseAsync( String resourceGroupName, String automationAccountName, String moduleName, String activityName, Context context) { if (this.client.getEndpoint() == null) { return Mono .error( new IllegalArgumentException( "Parameter this.client.getEndpoint() is required and cannot be null.")); } if (resourceGroupName == null) { return Mono .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); } if (automationAccountName == null) { return Mono .error(new IllegalArgumentException("Parameter automationAccountName is required and cannot be null.")); } if (moduleName == null) { return Mono.error(new IllegalArgumentException("Parameter moduleName is required and cannot be null.")); } if (activityName == null) { return Mono.error(new IllegalArgumentException("Parameter activityName is required and cannot be null.")); } if (this.client.getSubscriptionId() == null) { return Mono .error( new IllegalArgumentException( "Parameter this.client.getSubscriptionId() is required and cannot be null.")); } final String apiVersion = "2019-06-01"; final String accept = "application/json"; context = this.client.mergeContext(context); return service .get( this.client.getEndpoint(), resourceGroupName, automationAccountName, moduleName, activityName, this.client.getSubscriptionId(), apiVersion, accept, context); } /** * Retrieve the activity in the module identified by module name and activity name. * * @param resourceGroupName Name of an Azure Resource group. * @param automationAccountName The name of the automation account. * @param moduleName The name of module. * @param activityName The name of activity. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return definition of the activity. */ @ServiceMethod(returns = ReturnType.SINGLE) private Mono<ActivityInner> getAsync( String resourceGroupName, String automationAccountName, String moduleName, String activityName) { return getWithResponseAsync(resourceGroupName, automationAccountName, moduleName, activityName) .flatMap( (Response<ActivityInner> res) -> { if (res.getValue() != null) { return Mono.just(res.getValue()); } else { return Mono.empty(); } }); } /** * Retrieve the activity in the module identified by module name and activity name. * * @param resourceGroupName Name of an Azure Resource group. * @param automationAccountName The name of the automation account. * @param moduleName The name of module. * @param activityName The name of activity. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return definition of the activity. */ @ServiceMethod(returns = ReturnType.SINGLE) public ActivityInner get( String resourceGroupName, String automationAccountName, String moduleName, String activityName) { return getAsync(resourceGroupName, automationAccountName, moduleName, activityName).block(); } /** * Retrieve the activity in the module identified by module name and activity name. * * @param resourceGroupName Name of an Azure Resource group. * @param automationAccountName The name of the automation account. * @param moduleName The name of module. * @param activityName The name of activity. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return definition of the activity. */ @ServiceMethod(returns = ReturnType.SINGLE) public Response<ActivityInner> getWithResponse( String resourceGroupName, String automationAccountName, String moduleName, String activityName, Context context) { return getWithResponseAsync(resourceGroupName, automationAccountName, moduleName, activityName, context) .block(); } /** * Retrieve a list of activities in the module identified by module name. * * @param resourceGroupName Name of an Azure Resource group. * @param automationAccountName The name of the automation account. * @param moduleName The name of module. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the response model for the list activity operation. */ @ServiceMethod(returns = ReturnType.SINGLE) private Mono<PagedResponse<ActivityInner>> listByModuleSinglePageAsync( String resourceGroupName, String automationAccountName, String moduleName) { if (this.client.getEndpoint() == null) { return Mono .error( new IllegalArgumentException( "Parameter this.client.getEndpoint() is required and cannot be null.")); } if (resourceGroupName == null) { return Mono .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); } if (automationAccountName == null) { return Mono .error(new IllegalArgumentException("Parameter automationAccountName is required and cannot be null.")); } if (moduleName == null) { return Mono.error(new IllegalArgumentException("Parameter moduleName is required and cannot be null.")); } if (this.client.getSubscriptionId() == null) { return Mono .error( new IllegalArgumentException( "Parameter this.client.getSubscriptionId() is required and cannot be null.")); } final String apiVersion = "2019-06-01"; final String accept = "application/json"; return FluxUtil .withContext( context -> service .listByModule( this.client.getEndpoint(), resourceGroupName, automationAccountName, moduleName, this.client.getSubscriptionId(), apiVersion, accept, context)) .<PagedResponse<ActivityInner>>map( res -> new PagedResponseBase<>( res.getRequest(), res.getStatusCode(), res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)) .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); } /** * Retrieve a list of activities in the module identified by module name. * * @param resourceGroupName Name of an Azure Resource group. * @param automationAccountName The name of the automation account. * @param moduleName The name of module. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the response model for the list activity operation. */ @ServiceMethod(returns = ReturnType.SINGLE) private Mono<PagedResponse<ActivityInner>> listByModuleSinglePageAsync( String resourceGroupName, String automationAccountName, String moduleName, Context context) { if (this.client.getEndpoint() == null) { return Mono .error( new IllegalArgumentException( "Parameter this.client.getEndpoint() is required and cannot be null.")); } if (resourceGroupName == null) { return Mono .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); } if (automationAccountName == null) { return Mono .error(new IllegalArgumentException("Parameter automationAccountName is required and cannot be null.")); } if (moduleName == null) { return Mono.error(new IllegalArgumentException("Parameter moduleName is required and cannot be null.")); } if (this.client.getSubscriptionId() == null) { return Mono .error( new IllegalArgumentException( "Parameter this.client.getSubscriptionId() is required and cannot be null.")); } final String apiVersion = "2019-06-01"; final String accept = "application/json"; context = this.client.mergeContext(context); return service .listByModule( this.client.getEndpoint(), resourceGroupName, automationAccountName, moduleName, this.client.getSubscriptionId(), apiVersion, accept, context) .map( res -> new PagedResponseBase<>( res.getRequest(), res.getStatusCode(), res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)); } /** * Retrieve a list of activities in the module identified by module name. * * @param resourceGroupName Name of an Azure Resource group. * @param automationAccountName The name of the automation account. * @param moduleName The name of module. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the response model for the list activity operation. */ @ServiceMethod(returns = ReturnType.COLLECTION) private PagedFlux<ActivityInner> listByModuleAsync( String resourceGroupName, String automationAccountName, String moduleName) { return new PagedFlux<>( () -> listByModuleSinglePageAsync(resourceGroupName, automationAccountName, moduleName), nextLink -> listByModuleNextSinglePageAsync(nextLink)); } /** * Retrieve a list of activities in the module identified by module name. * * @param resourceGroupName Name of an Azure Resource group. * @param automationAccountName The name of the automation account. * @param moduleName The name of module. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the response model for the list activity operation. */ @ServiceMethod(returns = ReturnType.COLLECTION) private PagedFlux<ActivityInner> listByModuleAsync( String resourceGroupName, String automationAccountName, String moduleName, Context context) { return new PagedFlux<>( () -> listByModuleSinglePageAsync(resourceGroupName, automationAccountName, moduleName, context), nextLink -> listByModuleNextSinglePageAsync(nextLink, context)); } /** * Retrieve a list of activities in the module identified by module name. * * @param resourceGroupName Name of an Azure Resource group. * @param automationAccountName The name of the automation account. * @param moduleName The name of module. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the response model for the list activity operation. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedIterable<ActivityInner> listByModule( String resourceGroupName, String automationAccountName, String moduleName) { return new PagedIterable<>(listByModuleAsync(resourceGroupName, automationAccountName, moduleName)); } /** * Retrieve a list of activities in the module identified by module name. * * @param resourceGroupName Name of an Azure Resource group. * @param automationAccountName The name of the automation account. * @param moduleName The name of module. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the response model for the list activity operation. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedIterable<ActivityInner> listByModule( String resourceGroupName, String automationAccountName, String moduleName, Context context) { return new PagedIterable<>(listByModuleAsync(resourceGroupName, automationAccountName, moduleName, context)); } /** * Get the next page of items. * * @param nextLink The nextLink parameter. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the response model for the list activity operation. */ @ServiceMethod(returns = ReturnType.SINGLE) private Mono<PagedResponse<ActivityInner>> listByModuleNextSinglePageAsync(String nextLink) { if (nextLink == null) { return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null.")); } if (this.client.getEndpoint() == null) { return Mono .error( new IllegalArgumentException( "Parameter this.client.getEndpoint() is required and cannot be null.")); } final String accept = "application/json"; return FluxUtil .withContext(context -> service.listByModuleNext(nextLink, this.client.getEndpoint(), accept, context)) .<PagedResponse<ActivityInner>>map( res -> new PagedResponseBase<>( res.getRequest(), res.getStatusCode(), res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)) .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); } /** * Get the next page of items. * * @param nextLink The nextLink parameter. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the response model for the list activity operation. */ @ServiceMethod(returns = ReturnType.SINGLE) private Mono<PagedResponse<ActivityInner>> listByModuleNextSinglePageAsync(String nextLink, Context context) { if (nextLink == null) { return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null.")); } if (this.client.getEndpoint() == null) { return Mono .error( new IllegalArgumentException( "Parameter this.client.getEndpoint() is required and cannot be null.")); } final String accept = "application/json"; context = this.client.mergeContext(context); return service .listByModuleNext(nextLink, this.client.getEndpoint(), accept, context) .map( res -> new PagedResponseBase<>( res.getRequest(), res.getStatusCode(), res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)); } }
10,450
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 "chrome/browser/extensions/api/identity/identity_api.h" #include <memory> #include "base/threading/thread_task_runner_handle.h" #include "chrome/browser/extensions/test_extension_prefs.h" #include "chrome/test/base/testing_profile.h" #include "components/signin/public/base/signin_buildflags.h" #include "components/signin/public/identity_manager/identity_test_environment.h" #include "content/public/test/browser_task_environment.h" #include "google_apis/gaia/core_account_id.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/abseil-cpp/absl/types/optional.h" namespace extensions { class IdentityAPITest : public testing::Test { public: IdentityAPITest() : prefs_(base::ThreadTaskRunnerHandle::Get()), event_router_(prefs_.profile(), prefs_.prefs()), api_(CreateIdentityAPI()) { // IdentityAPITest requires the extended account info callbacks to be fired // on account update/removal. identity_env_.EnableRemovalOfExtendedAccountInfo(); } ~IdentityAPITest() override { api_->Shutdown(); } std::unique_ptr<IdentityAPI> CreateIdentityAPI() { return base::WrapUnique(new IdentityAPI(prefs_.profile(), identity_env_.identity_manager(), prefs_.prefs(), &event_router_)); } void ResetIdentityAPI(std::unique_ptr<IdentityAPI> new_api) { api_ = std::move(new_api); } content::BrowserTaskEnvironment* task_env() { return &task_env_; } signin::IdentityTestEnvironment* identity_env() { return &identity_env_; } TestExtensionPrefs* prefs() { return &prefs_; } IdentityAPI* api() { return api_.get(); } private: content::BrowserTaskEnvironment task_env_; signin::IdentityTestEnvironment identity_env_; TestExtensionPrefs prefs_; EventRouter event_router_; std::unique_ptr<IdentityAPI> api_; }; // Tests that all accounts in extensions is enabled for regular profiles. TEST_F(IdentityAPITest, AllAccountsExtensionEnabled) { EXPECT_FALSE(api()->AreExtensionsRestrictedToPrimaryAccount()); } TEST_F(IdentityAPITest, GetGaiaIdForExtension) { std::string extension_id = prefs()->AddExtensionAndReturnId("extension"); std::string gaia_id = identity_env()->MakeAccountAvailable("<EMAIL>").gaia; api()->SetGaiaIdForExtension(extension_id, gaia_id); EXPECT_EQ(api()->GetGaiaIdForExtension(extension_id), gaia_id); std::string another_extension_id = prefs()->AddExtensionAndReturnId("another_extension"); EXPECT_EQ(api()->GetGaiaIdForExtension(another_extension_id), absl::nullopt); } TEST_F(IdentityAPITest, GetGaiaIdForExtension_SurvivesShutdown) { std::string extension_id = prefs()->AddExtensionAndReturnId("extension"); std::string gaia_id = identity_env()->MakeAccountAvailable("<EMAIL>").gaia; api()->SetGaiaIdForExtension(extension_id, gaia_id); EXPECT_EQ(api()->GetGaiaIdForExtension(extension_id), gaia_id); api()->Shutdown(); ResetIdentityAPI(CreateIdentityAPI()); EXPECT_EQ(api()->GetGaiaIdForExtension(extension_id), gaia_id); } TEST_F(IdentityAPITest, EraseGaiaIdForExtension) { std::string extension_id = prefs()->AddExtensionAndReturnId("extension"); CoreAccountInfo account = identity_env()->MakeAccountAvailable("<EMAIL>"); api()->SetGaiaIdForExtension(extension_id, account.gaia); EXPECT_EQ(api()->GetGaiaIdForExtension(extension_id), account.gaia); api()->EraseGaiaIdForExtension(extension_id); EXPECT_EQ(api()->GetGaiaIdForExtension(extension_id), absl::nullopt); } TEST_F(IdentityAPITest, GaiaIdErasedAfterSignOut) { std::string extension_id = prefs()->AddExtensionAndReturnId("extension"); CoreAccountInfo account = identity_env()->MakeAccountAvailable("<EMAIL>"); api()->SetGaiaIdForExtension(extension_id, account.gaia); EXPECT_EQ(api()->GetGaiaIdForExtension(extension_id), account.gaia); identity_env()->RemoveRefreshTokenForAccount(account.account_id); EXPECT_EQ(api()->GetGaiaIdForExtension(extension_id), absl::nullopt); } TEST_F(IdentityAPITest, GaiaIdErasedAfterSignOut_TwoAccounts) { std::string extension1_id = prefs()->AddExtensionAndReturnId("extension1"); CoreAccountInfo account1 = identity_env()->MakeAccountAvailable("<EMAIL>"); api()->SetGaiaIdForExtension(extension1_id, account1.gaia); EXPECT_EQ(api()->GetGaiaIdForExtension(extension1_id), account1.gaia); std::string extension2_id = prefs()->AddExtensionAndReturnId("extension2"); CoreAccountInfo account2 = identity_env()->MakeAccountAvailable("<EMAIL>"); api()->SetGaiaIdForExtension(extension2_id, account2.gaia); EXPECT_EQ(api()->GetGaiaIdForExtension(extension2_id), account2.gaia); identity_env()->RemoveRefreshTokenForAccount(account1.account_id); EXPECT_EQ(api()->GetGaiaIdForExtension(extension1_id), absl::nullopt); EXPECT_EQ(api()->GetGaiaIdForExtension(extension2_id), account2.gaia); } TEST_F(IdentityAPITest, GaiaIdErasedAfterSignOut_AfterShutdown) { std::string extension_id = prefs()->AddExtensionAndReturnId("extension"); CoreAccountInfo account = identity_env()->MakeAccountAvailable("<EMAIL>"); api()->SetGaiaIdForExtension(extension_id, account.gaia); EXPECT_EQ(api()->GetGaiaIdForExtension(extension_id), account.gaia); api()->Shutdown(); ResetIdentityAPI(nullptr); identity_env()->RemoveRefreshTokenForAccount(account.account_id); ResetIdentityAPI(CreateIdentityAPI()); EXPECT_EQ(api()->GetGaiaIdForExtension(extension_id), absl::nullopt); } } // namespace extensions
2,093
12,718
#include <string.h> #include <libgen.h> char *basename(char *s) { size_t i; if (!s || !*s) return "."; i = strlen(s)-1; for (; i&&s[i]=='/'; i--) s[i] = 0; for (; i&&s[i-1]!='/'; i--); return s+i; } weak_alias(basename, __xpg_basename);
131
2,208
from pybrain.rl.experiments.experiment import Experiment from pybrain.rl.experiments.episodic import EpisodicExperiment from pybrain.rl.experiments.continuous import ContinuousExperiment
48
1,076
//////////////////////////////////////////////////////////////////////////////// // / // 2012-2019 (c) Baical / // / // This library is free software; you can redistribute it and/or / // modify it under the terms of the GNU Lesser General Public / // License as published by the Free Software Foundation; either / // version 3.0 of the License, or (at your option) any later version. / // / // This library is distributed in the hope that it will be useful, / // but WITHOUT ANY WARRANTY; without even the implied warranty of / // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU / // Lesser General Public License for more details. / // / // You should have received a copy of the GNU Lesser General Public / // License along with this library. / // / //////////////////////////////////////////////////////////////////////////////// #ifndef PSYSTEM_H #define PSYSTEM_H class CSys { public: /////////////////////////////////////////////////////////////////////////////// //Get_Host_Name static tBOOL Get_Host_Name(tWCHAR *o_pName, size_t i_szName) { if ( (NULL == o_pName) || (32 >= i_szName) ) { return FALSE; } DWORD l_dwMax_Len = (DWORD)i_szName; return GetComputerNameW((wchar_t*)o_pName, &l_dwMax_Len); }//Get_Host_Name /////////////////////////////////////////////////////////////////////////////// //Get_Host_Name static tBOOL Get_Host_Name(tACHAR *o_pName, size_t i_szName) { const size_t l_szName = 256; DWORD l_dwSize = (DWORD)l_szName; wchar_t l_pName[l_szName]; if (GetComputerNameW((wchar_t*)l_pName, &l_dwSize)) { Convert_UTF16_To_UTF8(l_pName, o_pName, (tUINT32)i_szName); } else { strcpy_s(o_pName, i_szName, "Unknown:Error"); } return TRUE; }//Get_Host_Name /////////////////////////////////////////////////////////////////////////////// //Get_DateTime static tBOOL Get_DateTime(tUINT32 &o_rYear, tUINT32 &o_rMonth, tUINT32 &o_rDay, tUINT32 &o_rHour, tUINT32 &o_rMinute, tUINT32 &o_rSecond, tUINT32 &o_rmSec ) { SYSTEMTIME l_sTitem = {0}; GetLocalTime(&l_sTitem); o_rYear = (tUINT32)l_sTitem.wYear; o_rMonth = (tUINT32)l_sTitem.wMonth; o_rDay = (tUINT32)l_sTitem.wDay; o_rHour = (tUINT32)l_sTitem.wHour; o_rMinute = (tUINT32)l_sTitem.wMinute; o_rSecond = (tUINT32)l_sTitem.wSecond; o_rmSec = (tUINT32)l_sTitem.wMilliseconds; return TRUE; }//Get_Host_Name }; #endif //PSYSTEM_H
1,963
684
<reponame>MirageEarl/activiti /* 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.activiti.explorer.ui.content.email; import java.io.InputStream; import java.io.InputStreamReader; import org.activiti.engine.ProcessEngines; import org.activiti.engine.TaskService; import org.activiti.engine.impl.util.json.JSONObject; import org.activiti.engine.impl.util.json.JSONTokener; import org.activiti.engine.task.Attachment; import org.activiti.explorer.Constants; import org.activiti.explorer.ExplorerApp; import org.activiti.explorer.I18nManager; import org.activiti.explorer.Messages; import org.activiti.explorer.ui.mainlayout.ExplorerLayout; import com.vaadin.ui.AbstractLayout; import com.vaadin.ui.Alignment; import com.vaadin.ui.GridLayout; import com.vaadin.ui.Label; import com.vaadin.ui.Layout.SpacingHandler; import com.vaadin.ui.themes.Reindeer; import com.vaadin.ui.Panel; /** * @author <NAME> */ public class EmailDetailPanel extends Panel { private static final long serialVersionUID = 1L; protected I18nManager i18nManager; protected transient TaskService taskService; protected Label content; protected Attachment attachment; protected GridLayout gridLayout; public EmailDetailPanel(Attachment attachment) { setSizeFull(); ((AbstractLayout) getContent()).setMargin(true); ((SpacingHandler) getContent()).setSpacing(true); addStyleName(Reindeer.PANEL_LIGHT); this.attachment = attachment; this.i18nManager = ExplorerApp.get().getI18nManager(); this.taskService = ProcessEngines.getDefaultProcessEngine().getTaskService(); gridLayout = new GridLayout(2, 4); gridLayout.setSpacing(true); addComponent(gridLayout); InputStream contentStream = taskService.getAttachmentContent(attachment.getId()); // TODO: Error handling JSONObject emailJson = new JSONObject(new JSONTokener(new InputStreamReader(contentStream))); String html = emailJson.getString(Constants.EMAIL_HTML_CONTENT); String subject = emailJson.getString(Constants.EMAIL_SUBJECT); String recipients = emailJson.getString(Constants.EMAIL_RECIPIENT); String sentDate = emailJson.getString(Constants.EMAIL_SENT_DATE); String receivedDate = emailJson.getString(Constants.EMAIL_RECEIVED_DATE); // Add subject addSimpleRow(Messages.EMAIL_SUBJECT, subject); addSimpleRow(Messages.EMAIL_RECIPIENTS, recipients); addSimpleRow(Messages.EMAIL_SENT_DATE, sentDate); addSimpleRow(Messages.EMAIL_RECEIVED_DATE, receivedDate); // Add HTML content addHtmlContent(html); } protected void addHtmlContent(String html) { Panel panel = new Panel(); panel.setWidth(800, UNITS_PIXELS); panel.setHeight(300, UNITS_PIXELS); content = new Label(html, Label.CONTENT_XHTML); content.setHeight(100, UNITS_PERCENTAGE); panel.addComponent(content); addComponent(panel); } protected void addSimpleRow(String labelMessageKey, String content) { addLabel(labelMessageKey); Label subjectLabel = new Label(content); subjectLabel.setSizeUndefined(); subjectLabel.addStyleName(ExplorerLayout.STYLE_LABEL_BOLD); gridLayout.addComponent(subjectLabel); gridLayout.setComponentAlignment(subjectLabel, Alignment.MIDDLE_LEFT); } protected void addLabel(String messageKey) { Label theLabel = new Label(i18nManager.getMessage(messageKey)); theLabel.setSizeUndefined(); gridLayout.addComponent(theLabel); } }
1,350
2,921
{ "name": "PIN", "type": "ERC20", "symbol": "PIN", "decimals": 18, "website": "https://publicindex.network", "description": "PIN📌is a proof-of-work cryptocurrency designed to index web3 metadata. PIN also exists as a wrapped token on Ethereum, Binance Smart Chain, and Polygon.", "explorer": "https://etherscan.io/token/<KEY>", "status": "active", "id": "<KEY>" }
150
2,151
//===----------------------------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // UNSUPPORTED: c++98, c++03, c++11, c++14 // type_traits // template<class... B> struct disjunction; // C++17 // template<class... B> // constexpr bool disjunction_v = disjunction<B...>::value; // C++17 #include <type_traits> #include <cassert> struct True { static constexpr bool value = true; }; struct False { static constexpr bool value = false; }; int main() { static_assert (!std::disjunction<>::value, "" ); static_assert ( std::disjunction<std::true_type >::value, "" ); static_assert (!std::disjunction<std::false_type>::value, "" ); static_assert (!std::disjunction_v<>, "" ); static_assert ( std::disjunction_v<std::true_type >, "" ); static_assert (!std::disjunction_v<std::false_type>, "" ); static_assert ( std::disjunction<std::true_type, std::true_type >::value, "" ); static_assert ( std::disjunction<std::true_type, std::false_type>::value, "" ); static_assert ( std::disjunction<std::false_type, std::true_type >::value, "" ); static_assert (!std::disjunction<std::false_type, std::false_type>::value, "" ); static_assert ( std::disjunction_v<std::true_type, std::true_type >, "" ); static_assert ( std::disjunction_v<std::true_type, std::false_type>, "" ); static_assert ( std::disjunction_v<std::false_type, std::true_type >, "" ); static_assert (!std::disjunction_v<std::false_type, std::false_type>, "" ); static_assert ( std::disjunction<std::true_type, std::true_type, std::true_type >::value, "" ); static_assert ( std::disjunction<std::true_type, std::false_type, std::true_type >::value, "" ); static_assert ( std::disjunction<std::false_type, std::true_type, std::true_type >::value, "" ); static_assert ( std::disjunction<std::false_type, std::false_type, std::true_type >::value, "" ); static_assert ( std::disjunction<std::true_type, std::true_type, std::false_type>::value, "" ); static_assert ( std::disjunction<std::true_type, std::false_type, std::false_type>::value, "" ); static_assert ( std::disjunction<std::false_type, std::true_type, std::false_type>::value, "" ); static_assert (!std::disjunction<std::false_type, std::false_type, std::false_type>::value, "" ); static_assert ( std::disjunction_v<std::true_type, std::true_type, std::true_type >, "" ); static_assert ( std::disjunction_v<std::true_type, std::false_type, std::true_type >, "" ); static_assert ( std::disjunction_v<std::false_type, std::true_type, std::true_type >, "" ); static_assert ( std::disjunction_v<std::false_type, std::false_type, std::true_type >, "" ); static_assert ( std::disjunction_v<std::true_type, std::true_type, std::false_type>, "" ); static_assert ( std::disjunction_v<std::true_type, std::false_type, std::false_type>, "" ); static_assert ( std::disjunction_v<std::false_type, std::true_type, std::false_type>, "" ); static_assert (!std::disjunction_v<std::false_type, std::false_type, std::false_type>, "" ); static_assert ( std::disjunction<True >::value, "" ); static_assert (!std::disjunction<False>::value, "" ); static_assert ( std::disjunction_v<True >, "" ); static_assert (!std::disjunction_v<False>, "" ); }
1,324
1,759
<gh_stars>1000+ /** * @file BSocksClient.h * @author <NAME> <<EMAIL>> * * @section LICENSE * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the author 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 AUTHOR BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * @section DESCRIPTION * * SOCKS5 client. TCP only, no authentication. */ #ifndef BADVPN_SOCKS_BSOCKSCLIENT_H #define BADVPN_SOCKS_BSOCKSCLIENT_H #include <stddef.h> #include <stdint.h> #include <stdbool.h> #include <misc/debug.h> #include <misc/debugerror.h> #include <misc/socks_proto.h> #include <misc/packed.h> #include <base/DebugObject.h> #include <base/BPending.h> #include <system/BConnection.h> #include <flow/PacketStreamSender.h> #define BSOCKSCLIENT_EVENT_ERROR 1 #define BSOCKSCLIENT_EVENT_UP 2 #define BSOCKSCLIENT_EVENT_ERROR_CLOSED 3 #define BSOCKSCLIENT_EVENT_CONNECTED 4 /** * Handler for events generated by the SOCKS client. * * The event is one of the following: * - BSOCKSCLIENT_EVENT_ERROR: An error has occured. The object must be freed from the * job closure of the handler and no further I/O must be attempted. * - BSOCKSCLIENT_EVENT_ERROR_CLOSED: The server has closed the connection. This event * can only be reported after BSOCKSCLIENT_EVENT_UP. The object must be freed from * the job closure of the handler and no further I/O must be attempted. * - BSOCKSCLIENT_EVENT_UP: The CONNECT or UDP ASSOCIATE operation was successful. In * the case of CONNECT, application I/O may now begin. * - BSOCKSCLIENT_EVENT_CONNECTED: The TCP connection to the server has been established * and the SOCKS protocol is about to begin. The local address of the TCP connection is * now available via @ref BSocksClient_GetLocalAddr. The job closure of this callback * is the last chance to call @ref BSocksClient_SetDestAddr. * * @param user as in {@link BSocksClient_Init} * @param event See above. */ typedef void (*BSocksClient_handler) (void *user, int event); struct BSocksClient_auth_info { int auth_type; union { struct { const char *username; size_t username_len; const char *password; size_t password_len; } password; }; }; typedef struct { const struct BSocksClient_auth_info *auth_info; size_t num_auth_info; BAddr dest_addr; bool udp; BAddr bind_addr; BSocksClient_handler handler; void *user; BReactor *reactor; int state; char *buffer; BConnector connector; BConnection con; BPending continue_job; union { struct { PacketPassInterface *send_if; PacketStreamSender send_sender; StreamRecvInterface *recv_if; uint8_t *recv_dest; int recv_len; int recv_total; } control; }; DebugError d_err; DebugObject d_obj; } BSocksClient; struct BSocksClient_auth_info BSocksClient_auth_none (void); struct BSocksClient_auth_info BSocksClient_auth_password (const char *username, size_t username_len, const char *password, size_t password_len); /** * Initializes the object. * * This object connects to a SOCKS5 server and performs a CONNECT or UDP ASSOCIATE * operation. In any case, the object reports the BSOCKSCLIENT_EVENT_UP event via the * handler when the operation was completed successfully. In the case of CONNECT, the * user may then use the send and receive interfaces to exchange data through the * connection (@ref BSocksClient_GetSendInterface and @ref BSocksClient_GetRecvInterface). * * @param o the object * @param server_addr SOCKS5 server address * @param auth_info List of supported authentication methods and associated parameters. * Initialize these using functions such as BSocksClient_auth_none() and * BSocksClient_auth_password(). The pointer must remain valid while this object * exists, the data is not copied. * @param num_auth_info Number of the above. There should be at least one, otherwise it * certainly won't work. * @param dest_addr Address to send as DST.ADDR in the CONNECT or UDP ASSOCIATE request. * It is also possible to specify it later from the BSOCKSCLIENT_EVENT_CONNECTED * event callback using @ref BSocksClient_SetDestAddr; this is necessary for UDP * if the local TCP connection address must be known to bind the UDP socket. * @param udp false to perform a CONNECT, true to perform a UDP ASSOCIATE * @param handler handler for up and error events * @param user value passed to handler * @param reactor reactor we live in * @return 1 on success, 0 on failure */ int BSocksClient_Init (BSocksClient *o, BAddr server_addr, const struct BSocksClient_auth_info *auth_info, size_t num_auth_info, BAddr dest_addr, bool udp, BSocksClient_handler handler, void *user, BReactor *reactor) WARN_UNUSED; /** * Frees the object. * * @param o the object */ void BSocksClient_Free (BSocksClient *o); /** * Get the local address of the TCP socket for the SOCKS server connection. * * This may only be called after the BSOCKSCLIENT_EVENT_CONNECTED event was reported. * * @param o the object * @param local_addr On success the local address is returned here. * @return 1 on success, 0 on failure */ int BSocksClient_GetLocalAddr (BSocksClient *o, BAddr *local_addr); /** * Set the DST.ADDR to send, overriding that specified in @ref BSocksClient_Init. * * The last chance to call this function is in the job closure of the * BSOCKSCLIENT_EVENT_CONNECTED event, this must not be called after that. * * @param o the object * @param dest_addr DST.ADDR to set. */ void BSocksClient_SetDestAddr (BSocksClient *o, BAddr dest_addr); /** * Return the BND.ADDR that the SOCKS server reported. * * This may only be called after the BSOCKSCLIENT_EVENT_UP event was reported. * This address is needed for UDP ASSOCIATE because it is the address that the * client should send UDP packets to. * * @param o the object * @return The BND.ADDR, of type BADDR_TYPE_IPV4 or BADDR_TYPE_IPV6. */ BAddr BSocksClient_GetBindAddr (BSocksClient *o); /** * Returns the send interface. * The object must be in up state. Additionally this must not be called if the * object was initialized in UDP ASSOCIATE mode. * * @param o the object * @return send interface */ StreamPassInterface * BSocksClient_GetSendInterface (BSocksClient *o); /** * Returns the receive interface. * The object must be in up state. Additionally this must not be called if the * object was initialized in UDP ASSOCIATE mode. * * @param o the object * @return receive interface */ StreamRecvInterface * BSocksClient_GetRecvInterface (BSocksClient *o); #endif
2,626
631
/** * 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.metron.rest.controller; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiParam; import io.swagger.annotations.ApiResponse; import io.swagger.annotations.ApiResponses; import org.apache.hadoop.fs.Path; import org.apache.metron.rest.RestException; import org.apache.metron.rest.service.HdfsService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import java.util.List; import static java.nio.charset.StandardCharsets.UTF_8; @RestController @RequestMapping("/api/v1/hdfs") public class HdfsController { @Autowired private HdfsService hdfsService; @ApiOperation(value = "Lists an HDFS directory") @ApiResponse(message = "HDFS directory list", code = 200) @RequestMapping(value = "/list", method = RequestMethod.GET) ResponseEntity<List<String>> list(@ApiParam(name = "path", value = "Path to HDFS directory", required = true) @RequestParam String path) throws RestException { return new ResponseEntity<>(hdfsService.list(new Path(path)), HttpStatus.OK); } @ApiOperation(value = "Reads a file from HDFS and returns the contents") @ApiResponse(message = "Returns file contents", code = 200) @RequestMapping(method = RequestMethod.GET) ResponseEntity<String> read(@ApiParam(name = "path", value = "Path to HDFS file", required = true) @RequestParam String path) throws RestException { String contents = hdfsService.read(new Path(path)); if (contents != null) { return new ResponseEntity<>(hdfsService.read(new Path(path)), HttpStatus.OK); } else { return new ResponseEntity<>(HttpStatus.NOT_FOUND); } } @ApiOperation(value = "Writes contents to an HDFS file. Warning: this will overwrite the contents of a file if it already exists.") @ApiResponse(message = "Contents were written", code = 200) @RequestMapping(method = RequestMethod.POST) ResponseEntity<Void> write( @ApiParam(name = "path", value = "Path to HDFS file", required = true) @RequestParam String path, @ApiParam(name = "contents", value = "File contents", required = true) @RequestBody String contents, @ApiParam(name = "userMode", value = "requested user permissions") @RequestParam(required = false, defaultValue = "") String userMode, @ApiParam(name = "groupMode", value = "requested group permissions") @RequestParam(required = false, defaultValue = "") String groupMode, @ApiParam(name = "otherMode", value = "requested other permissions") @RequestParam(required = false, defaultValue = "") String otherMode ) throws RestException { hdfsService.write(new Path(path), contents.getBytes(UTF_8), userMode, groupMode, otherMode); return new ResponseEntity<>(HttpStatus.OK); } @ApiOperation(value = "Deletes a file from HDFS") @ApiResponses(value = { @ApiResponse(message = "File was deleted", code = 200), @ApiResponse(message = "File was not found in HDFS", code = 404) }) @RequestMapping(method = RequestMethod.DELETE) ResponseEntity<Boolean> delete(@ApiParam(name = "path", value = "Path to HDFS file", required = true) @RequestParam String path, @ApiParam(name = "recursive", value = "Delete files recursively") @RequestParam(required = false, defaultValue = "false") boolean recursive) throws RestException { if (hdfsService.delete(new Path(path), recursive)) { return new ResponseEntity<>(HttpStatus.OK); } else { return new ResponseEntity<>(HttpStatus.NOT_FOUND); } } }
1,458
335
<gh_stars>100-1000 { "word": "Splenomegaly", "definitions": [ "Abnormal enlargement of the spleen." ], "parts-of-speech": "Noun" }
73
17,702
<gh_stars>1000+ // // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE.md file in the project root for full license information. // #pragma once #include <string> #include <vector> #include "Config.h" #include "Descriptors.h" namespace CNTK { // A helper class for text specific parameters. // A simple wrapper around CNTK ConfigParameters. class TextConfigHelper { public: explicit TextConfigHelper(const Microsoft::MSR::CNTK::ConfigParameters& config); // Get all input streams that are specified in the configuration. const vector<StreamDescriptor>& GetStreams() const { return m_streams; } // Get full path to the input file. const wstring& GetFilePath() const { return m_filepath; } size_t GetRandomizationWindow() const { return m_randomizationWindow; } bool UseSampleBasedRandomizationWindow() const { return m_sampleBasedRandomizationWindow; } bool ShouldSkipSequenceIds() const { return m_skipSequenceIds; } bool ShouldCacheIndex() const { return m_cacheIndex; } unsigned int GetMaxAllowedErrors() const { return m_maxErrors; } unsigned int GetTraceLevel() const { return m_traceLevel; } size_t GetChunkSize() const { return m_chunkSizeBytes; } bool ShouldKeepDataInMemory() const { return m_keepDataInMemory; } bool IsInFrameMode() const { return m_frameMode; } DataType GetDataType() const { return m_elementType; } DISABLE_COPY_AND_MOVE(TextConfigHelper); private: std::wstring m_filepath; std::vector<StreamDescriptor> m_streams; size_t m_randomizationWindow; // Specifies how to interpret randomization window, if true randomization window == number of samples, else // randomization window = number of chunks (default). bool m_sampleBasedRandomizationWindow; DataType m_elementType; bool m_skipSequenceIds; unsigned int m_maxErrors; unsigned int m_traceLevel; size_t m_chunkSizeBytes; // chunks size in bytes bool m_keepDataInMemory; // if true the whole dataset is kept in memory bool m_frameMode; // if true, the maximum expected sequence length in the dataset is one sample. bool m_cacheIndex; // When true, the index will be loaded from a cache file it if exists. // If cache does not exist, the index, once created, will be written out to a file. }; }
753
2,583
<filename>blender/arm/props_exporter.py import os import shutil import stat import subprocess import webbrowser import bpy from bpy.types import Menu, Panel, UIList from bpy.props import * import arm.assets as assets import arm.utils if arm.is_reload(__name__): assets = arm.reload_module(assets) arm.utils = arm.reload_module(arm.utils) else: arm.enable_reload(__name__) def remove_readonly(func, path, excinfo): os.chmod(path, stat.S_IWRITE) func(path) def update_gapi_custom(self, context): bpy.data.worlds['Arm'].arm_recompile = True assets.invalidate_compiled_data(self, context) def update_gapi_win(self, context): if os.path.isdir(arm.utils.get_fp_build() + '/windows-build'): shutil.rmtree(arm.utils.get_fp_build() + '/windows-build', onerror=remove_readonly) bpy.data.worlds['Arm'].arm_recompile = True assets.invalidate_compiled_data(self, context) def update_gapi_linux(self, context): if os.path.isdir(arm.utils.get_fp_build() + '/linux-build'): shutil.rmtree(arm.utils.get_fp_build() + '/linux-build', onerror=remove_readonly) bpy.data.worlds['Arm'].arm_recompile = True assets.invalidate_compiled_data(self, context) def update_gapi_mac(self, context): if os.path.isdir(arm.utils.get_fp_build() + '/osx-build'): shutil.rmtree(arm.utils.get_fp_build() + '/osx-build', onerror=remove_readonly) bpy.data.worlds['Arm'].arm_recompile = True assets.invalidate_compiled_data(self, context) def update_gapi_android(self, context): if os.path.isdir(arm.utils.get_fp_build() + '/android-build'): shutil.rmtree(arm.utils.get_fp_build() + '/android-build', onerror=remove_readonly) bpy.data.worlds['Arm'].arm_recompile = True assets.invalidate_compiled_data(self, context) def update_gapi_ios(self, context): if os.path.isdir(arm.utils.get_fp_build() + '/ios-build'): shutil.rmtree(arm.utils.get_fp_build() + '/ios-build', onerror=remove_readonly) bpy.data.worlds['Arm'].arm_recompile = True assets.invalidate_compiled_data(self, context) def update_gapi_html5(self, context): bpy.data.worlds['Arm'].arm_recompile = True assets.invalidate_compiled_data(self, context) class ArmExporterListItem(bpy.types.PropertyGroup): name: StringProperty( name="Name", description="A name for this item", default="Preset") arm_project_rp: StringProperty( name="Render Path", description="A name for this item", default="") arm_project_scene: PointerProperty( name="Scene", description="Scene to load when launching", type=bpy.types.Scene) arm_project_target: EnumProperty( items = [('html5', 'HTML5 (JS)', 'html5'), ('windows-hl', 'Windows (C)', 'windows-hl'), ('krom-windows', 'Windows (Krom)', 'krom-windows'), ('macos-hl', 'macOS (C)', 'macos-hl'), ('krom-macos', 'macOS (Krom)', 'krom-macos'), ('linux-hl', 'Linux (C)', 'linux-hl'), ('krom-linux', 'Linux (Krom)', 'krom-linux'), ('ios-hl', 'iOS (C)', 'ios-hl'), ('android-hl', 'Android (C)', 'android-hl'), ('node', 'Node (JS)', 'node'), ('custom', 'Custom', 'custom'),], name="Target", default='html5', description='Build platform') arm_project_khamake: StringProperty(name="Khamake", description="Specify arguments for the 'node Kha/make' call") arm_gapi_custom: EnumProperty( items = [('opengl', 'OpenGL', 'opengl'), ('vulkan', 'Vulkan', 'vulkan'), ('direct3d11', 'Direct3D11', 'direct3d11'), ('direct3d12', 'Direct3D12', 'direct3d12'), ('metal', 'Metal', 'metal')], name="Graphics API", default='opengl', description='Based on currently selected target', update=update_gapi_custom) arm_gapi_win: EnumProperty( items = [('direct3d11', 'Auto', 'direct3d11'), ('opengl', 'OpenGL', 'opengl'), ('vulkan', 'Vulkan', 'vulkan'), ('direct3d11', 'Direct3D11', 'direct3d11'), ('direct3d12', 'Direct3D12', 'direct3d12')], name="Graphics API", default='direct3d11', description='Based on currently selected target', update=update_gapi_win) arm_gapi_linux: EnumProperty( items = [('opengl', 'Auto', 'opengl'), ('opengl', 'OpenGL', 'opengl'), ('vulkan', 'Vulkan', 'vulkan')], name="Graphics API", default='opengl', description='Based on currently selected target', update=update_gapi_linux) arm_gapi_android: EnumProperty( items = [('opengl', 'Auto', 'opengl'), ('opengl', 'OpenGL', 'opengl'), ('vulkan', 'Vulkan', 'vulkan')], name="Graphics API", default='opengl', description='Based on currently selected target', update=update_gapi_android) arm_gapi_mac: EnumProperty( items = [('opengl', 'Auto', 'opengl'), ('opengl', 'OpenGL', 'opengl'), ('metal', 'Metal', 'metal')], name="Graphics API", default='opengl', description='Based on currently selected target', update=update_gapi_mac) arm_gapi_ios: EnumProperty( items = [('opengl', 'Auto', 'opengl'), ('opengl', 'OpenGL', 'opengl'), ('metal', 'Metal', 'metal')], name="Graphics API", default='opengl', description='Based on currently selected target', update=update_gapi_ios) arm_gapi_html5: EnumProperty( items = [('webgl', 'Auto', 'webgl'), ('webgl', 'WebGL2', 'webgl')], name="Graphics API", default='webgl', description='Based on currently selected target', update=update_gapi_html5) class ArmExporterAndroidPermissionListItem(bpy.types.PropertyGroup): arm_android_permissions: EnumProperty( items = [('ACCESS_COARSE_LOCATION ', 'Access Coarse Location', 'Allows an app to access approximate location'), ('ACCESS_NETWORK_STATE', 'Access Network State', 'Allows applications to access information about networks'), ('ACCESS_FINE_LOCATION', 'Access Fine Location', 'Allows an app to access precise location'), ('ACCESS_WIFI_STATE', 'Access Wi-Fi State', 'Allows applications to access information about Wi-Fi networks'), ('BLUETOOTH', 'Bluetooth', 'Allows applications to connect to paired bluetooth devices'), ('BLUETOOTH_ADMIN', 'Bluetooth Admin', 'Allows applications to discover and pair bluetooth devices'), ('CAMERA', 'Camera', 'Required to be able to access the camera device'), ('EXPAND_STATUS_BAR', 'Expand Status Bar', 'Allows an application to expand or collapse the status bar'), ('FOREGROUND_SERVICE', 'Foreground Service', 'Allows a regular application to use Service.startForeground'), ('GET_ACCOUNTS', 'Get Accounts', 'Allows access to the list of accounts in the Accounts Service'), ('INTERNET', 'Internet', 'Allows applications to open network sockets'), ('READ_EXTERNAL_STORAGE', 'Read External Storage', 'Allows an application to read from external storage.'), ('VIBRATE', 'Vibrate', 'Allows access to the vibrator'), ('WRITE_EXTERNAL_STORAGE', 'Write External Storage', 'Allows an application to write to external storage')], name="Permission", default='VIBRATE', description='Android Permission') class ArmExporterAndroidAbiListItem(bpy.types.PropertyGroup): arm_android_abi: EnumProperty( items = [('arm64-v8a', 'arm64-v8a', 'This ABI is for ARMv8-A based CPUs, which support the 64-bit AArch64 architecture'), ('armeabi-v7a', 'armeabi-v7a', 'This ABI is for 32-bit ARM-based CPUs'), ('x86', 'x86', 'This ABI is for CPUs supporting the instruction set commonly known as x86, i386, or IA-32'), ('x86_64', 'x86_64', 'This ABI is for CPUs supporting the instruction set commonly referred to as x86-64')], name="Android ABI", default='arm64-v8a', description='Android ABI') class ARM_UL_ExporterList(bpy.types.UIList): def draw_item(self, context, layout, data, item, icon, active_data, active_propname, index): # We could write some code to decide which icon to use here... custom_icon = 'DOT' # Make sure your code supports all 3 layout types if self.layout_type in {'DEFAULT', 'COMPACT'}: row = layout.row() row.prop(item, "name", text="", emboss=False, icon=custom_icon) col = row.column() col.alignment = 'RIGHT' col.label(text=item.arm_project_target) elif self.layout_type in {'GRID'}: layout.alignment = 'CENTER' layout.label(text="", icon = custom_icon) class ARM_UL_Exporter_AndroidPermissionList(bpy.types.UIList): def draw_item(self, context, layout, data, item, icon, active_data, active_propname, index): # We could write some code to decide which icon to use here... custom_icon = 'DOT' # Make sure your code supports all 3 layout types if self.layout_type in {'DEFAULT', 'COMPACT'}: row = layout.row() row.prop(item, "name", text="", emboss=False, icon=custom_icon) col = row.column() col.alignment = 'RIGHT' col.label(text=item.arm_android_permissions) elif self.layout_type in {'GRID'}: layout.alignment = 'CENTER' layout.label(text="", icon = custom_icon) class ARM_UL_Exporter_AndroidAbiList(bpy.types.UIList): def draw_item(self, context, layout, data, item, icon, active_data, active_propname, index): # We could write some code to decide which icon to use here... custom_icon = 'DOT' # Make sure your code supports all 3 layout types if self.layout_type in {'DEFAULT', 'COMPACT'}: row = layout.row() row.prop(item, "name", text="", emboss=False, icon=custom_icon) col = row.column() col.alignment = 'RIGHT' col.label(text=item.arm_android_abi) elif self.layout_type in {'GRID'}: layout.alignment = 'CENTER' layout.label(text="", icon = custom_icon) class ArmExporterListNewItem(bpy.types.Operator): # Add a new item to the list bl_idname = "arm_exporterlist.new_item" bl_label = "Add a new item" def execute(self, context): mdata = bpy.data.worlds['Arm'] mdata.arm_exporterlist.add() mdata.arm_exporterlist_index = len(mdata.arm_exporterlist) - 1 if len(mdata.arm_rplist) > mdata.arm_exporterlist_index: mdata.arm_exporterlist[-1].arm_project_rp = mdata.arm_rplist[mdata.arm_rplist_index].name mdata.arm_exporterlist[-1].arm_project_scene = context.scene return{'FINISHED'} class ArmExporterListDeleteItem(bpy.types.Operator): # Delete the selected item from the list bl_idname = "arm_exporterlist.delete_item" bl_label = "Deletes an item" @classmethod def poll(self, context): """ Enable if there's something in the list """ mdata = bpy.data.worlds['Arm'] return len(mdata.arm_exporterlist) > 0 def execute(self, context): mdata = bpy.data.worlds['Arm'] list = mdata.arm_exporterlist index = mdata.arm_exporterlist_index list.remove(index) if index > 0: index = index - 1 mdata.arm_exporterlist_index = index return{'FINISHED'} class ArmExporterListMoveItem(bpy.types.Operator): # Move an item in the list bl_idname = "arm_exporterlist.move_item" bl_label = "Move an item in the list" direction: EnumProperty( items=( ('UP', 'Up', ""), ('DOWN', 'Down', ""),)) def move_index(self): # Move index of an item render queue while clamping it mdata = bpy.data.worlds['Arm'] index = mdata.arm_exporterlist_index list_length = len(mdata.arm_exporterlist) - 1 new_index = 0 if self.direction == 'UP': new_index = index - 1 elif self.direction == 'DOWN': new_index = index + 1 new_index = max(0, min(new_index, list_length)) mdata.arm_exporterlist.move(index, new_index) mdata.arm_exporterlist_index = new_index def execute(self, context): mdata = bpy.data.worlds['Arm'] list = mdata.arm_exporterlist index = mdata.arm_exporterlist_index if self.direction == 'DOWN': neighbor = index + 1 self.move_index() elif self.direction == 'UP': neighbor = index - 1 self.move_index() else: return{'CANCELLED'} return{'FINISHED'} class ArmExporter_AndroidPermissionListNewItem(bpy.types.Operator): # Add a new item to the list bl_idname = "arm_exporter_android_permission_list.new_item" bl_label = "Add a new item" def execute(self, context): mdata = bpy.data.worlds['Arm'] mdata.arm_exporter_android_permission_list.add() mdata.arm_exporter_android_permission_list_index = len(mdata.arm_exporter_android_permission_list) - 1 return{'FINISHED'} class ArmExporter_AndroidPermissionListDeleteItem(bpy.types.Operator): # Delete the selected item from the list bl_idname = "arm_exporter_android_permission_list.delete_item" bl_label = "Deletes an item" @classmethod def poll(self, context): """ Enable if there's something in the list """ mdata = bpy.data.worlds['Arm'] return len(mdata.arm_exporter_android_permission_list) > 0 def execute(self, context): mdata = bpy.data.worlds['Arm'] list = mdata.arm_exporter_android_permission_list index = mdata.arm_exporter_android_permission_list_index list.remove(index) if index > 0: index = index - 1 mdata.arm_exporter_android_permission_list_index = index return{'FINISHED'} class ArmExporter_AndroidAbiListNewItem(bpy.types.Operator): # Add a new item to the list bl_idname = "arm_exporter_android_abi_list.new_item" bl_label = "Add a new item" def execute(self, context): mdata = bpy.data.worlds['Arm'] mdata.arm_exporter_android_abi_list.add() mdata.arm_exporter_android_abi_list_index = len(mdata.arm_exporter_android_abi_list) - 1 return{'FINISHED'} class ArmExporter_AndroidAbiListDeleteItem(bpy.types.Operator): # Delete the selected item from the list bl_idname = "arm_exporter_android_abi_list.delete_item" bl_label = "Deletes an item" @classmethod def poll(self, context): """ Enable if there's something in the list """ mdata = bpy.data.worlds['Arm'] return len(mdata.arm_exporter_android_abi_list) > 0 def execute(self, context): mdata = bpy.data.worlds['Arm'] list = mdata.arm_exporter_android_abi_list index = mdata.arm_exporter_android_abi_list_index list.remove(index) if index > 0: index = index - 1 mdata.arm_exporter_android_abi_list_index = index return{'FINISHED'} class ArmExporterSpecialsMenu(bpy.types.Menu): bl_label = "More" bl_idname = "ARM_MT_ExporterListSpecials" def draw(self, context): layout = self.layout layout.operator("arm.exporter_open_folder") layout.operator("arm.exporter_gpuprofile") class ArmoryExporterOpenFolderButton(bpy.types.Operator): """Open published folder""" bl_idname = 'arm.exporter_open_folder' bl_label = 'Open Folder' def execute(self, context): wrd = bpy.data.worlds['Arm'] if len(wrd.arm_exporterlist) == 0: return {'CANCELLED'} item = wrd.arm_exporterlist[wrd.arm_exporterlist_index] p = os.path.join(arm.utils.get_fp_build(), item.arm_project_target) if os.path.exists(p): webbrowser.open('file://' + p) return{'FINISHED'} class ArmExporterGpuProfileButton(bpy.types.Operator): '''GPU profile''' bl_idname = 'arm.exporter_gpuprofile' bl_label = 'Open in RenderDoc' def execute(self, context): p = arm.utils.get_renderdoc_path() if p == '': self.report({'ERROR'}, 'Configure RenderDoc path in Armory add-on preferences') return {'CANCELLED'} pbin = '' base = arm.utils.get_fp_build() ext1 = '/krom-windows/' + arm.utils.safestr(bpy.data.worlds['Arm'].arm_project_name) + '.exe' ext2 = '/krom-linux/' + arm.utils.safestr(bpy.data.worlds['Arm'].arm_project_name) if os.path.exists(base + ext1): pbin = base + ext1 elif os.path.exists(base + ext2): pbin = base + ext2 if pbin == '': self.report({'ERROR'}, 'Publish project using Krom target first') return {'CANCELLED'} subprocess.Popen([p, pbin]) return{'FINISHED'} def register(): bpy.utils.register_class(ArmExporterListItem) bpy.utils.register_class(ArmExporterAndroidPermissionListItem) bpy.utils.register_class(ArmExporterAndroidAbiListItem) bpy.utils.register_class(ARM_UL_ExporterList) bpy.utils.register_class(ARM_UL_Exporter_AndroidPermissionList) bpy.utils.register_class(ARM_UL_Exporter_AndroidAbiList) bpy.utils.register_class(ArmExporterListNewItem) bpy.utils.register_class(ArmExporterListDeleteItem) bpy.utils.register_class(ArmExporterListMoveItem) bpy.utils.register_class(ArmExporter_AndroidPermissionListNewItem) bpy.utils.register_class(ArmExporter_AndroidPermissionListDeleteItem) bpy.utils.register_class(ArmExporter_AndroidAbiListNewItem) bpy.utils.register_class(ArmExporter_AndroidAbiListDeleteItem) bpy.utils.register_class(ArmExporterSpecialsMenu) bpy.utils.register_class(ArmExporterGpuProfileButton) bpy.utils.register_class(ArmoryExporterOpenFolderButton) bpy.types.World.arm_exporterlist = CollectionProperty(type=ArmExporterListItem) bpy.types.World.arm_exporterlist_index = IntProperty(name="Index for my_list", default=0) bpy.types.World.arm_exporter_android_permission_list = CollectionProperty(type=ArmExporterAndroidPermissionListItem) bpy.types.World.arm_exporter_android_permission_list_index = IntProperty(name="Index for my_list", default=0) bpy.types.World.arm_exporter_android_abi_list = CollectionProperty(type=ArmExporterAndroidAbiListItem) bpy.types.World.arm_exporter_android_abi_list_index = IntProperty(name="Index for my_list", default=0) def unregister(): bpy.utils.unregister_class(ArmExporterListItem) bpy.utils.unregister_class(ArmExporterAndroidPermissionListItem) bpy.utils.unregister_class(ArmExporterAndroidAbiListItem) bpy.utils.unregister_class(ARM_UL_ExporterList) bpy.utils.unregister_class(ARM_UL_Exporter_AndroidPermissionList) bpy.utils.unregister_class(ARM_UL_Exporter_AndroidAbiList) bpy.utils.unregister_class(ArmExporterListNewItem) bpy.utils.unregister_class(ArmExporterListDeleteItem) bpy.utils.unregister_class(ArmExporterListMoveItem) bpy.utils.unregister_class(ArmExporter_AndroidPermissionListNewItem) bpy.utils.unregister_class(ArmExporter_AndroidPermissionListDeleteItem) bpy.utils.unregister_class(ArmExporter_AndroidAbiListNewItem) bpy.utils.unregister_class(ArmExporter_AndroidAbiListDeleteItem) bpy.utils.unregister_class(ArmExporterSpecialsMenu) bpy.utils.unregister_class(ArmExporterGpuProfileButton) bpy.utils.unregister_class(ArmoryExporterOpenFolderButton)
8,473
12,252
/* * Copyright 2016 Red Hat, Inc. and/or its affiliates * and other contributors as indicated by the @author tags. * * 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.keycloak.adapters.saml.elytron; import java.net.URI; import java.util.LinkedList; import java.util.List; import java.util.Set; import org.jboss.logging.Logger; import org.keycloak.adapters.saml.SamlDeployment; import org.keycloak.adapters.saml.SamlSession; import org.keycloak.adapters.saml.SamlSessionStore; import org.keycloak.adapters.saml.SamlUtil; import org.keycloak.adapters.spi.SessionIdMapper; import org.keycloak.adapters.spi.SessionIdMapperUpdater; import org.keycloak.common.util.KeycloakUriBuilder; import org.keycloak.saml.processing.core.saml.v2.util.XMLTimeUtil; import org.wildfly.security.http.HttpScope; import org.wildfly.security.http.Scope; import javax.xml.datatype.DatatypeConstants; import javax.xml.datatype.XMLGregorianCalendar; /** * @author <a href="mailto:<EMAIL>"><NAME></a> * @version $Revision: 1 $ */ public class ElytronSamlSessionStore implements SamlSessionStore, ElytronTokeStore { protected static Logger log = Logger.getLogger(SamlSessionStore.class); public static final String SAML_REDIRECT_URI = "SAML_REDIRECT_URI"; private final SessionIdMapper idMapper; private final SessionIdMapperUpdater idMapperUpdater; protected final SamlDeployment deployment; private final ElytronHttpFacade exchange; public ElytronSamlSessionStore(ElytronHttpFacade exchange, SessionIdMapper idMapper, SessionIdMapperUpdater idMapperUpdater, SamlDeployment deployment) { this.exchange = exchange; this.idMapper = idMapper; this.idMapperUpdater = idMapperUpdater; this.deployment = deployment; } @Override public void setCurrentAction(CurrentAction action) { if (action == CurrentAction.NONE && !exchange.getScope(Scope.SESSION).exists()) return; exchange.getScope(Scope.SESSION).setAttachment(CURRENT_ACTION, action); } @Override public boolean isLoggingIn() { HttpScope session = exchange.getScope(Scope.SESSION); if (!session.exists()) return false; CurrentAction action = (CurrentAction) session.getAttachment(CURRENT_ACTION); return action == CurrentAction.LOGGING_IN; } @Override public boolean isLoggingOut() { HttpScope session = exchange.getScope(Scope.SESSION); if (!session.exists()) return false; CurrentAction action = (CurrentAction) session.getAttachment(CURRENT_ACTION); return action == CurrentAction.LOGGING_OUT; } @Override public void logoutAccount() { HttpScope session = getSession(false); if (session.exists()) { log.debug("Logging out - current account"); SamlSession samlSession = (SamlSession)session.getAttachment(SamlSession.class.getName()); if (samlSession != null) { if (samlSession.getSessionIndex() != null) { idMapperUpdater.removeSession(idMapper, session.getID()); } session.setAttachment(SamlSession.class.getName(), null); } session.setAttachment(SAML_REDIRECT_URI, null); } } @Override public void logoutByPrincipal(String principal) { Set<String> sessions = idMapper.getUserSessions(principal); if (sessions != null) { log.debugf("Logging out - by principal: %s", sessions); List<String> ids = new LinkedList<>(); ids.addAll(sessions); logoutSessionIds(ids); for (String id : ids) { idMapperUpdater.removeSession(idMapper, id); } } } @Override public void logoutBySsoId(List<String> ssoIds) { if (ssoIds == null) return; log.debugf("Logging out - by session IDs: %s", ssoIds); List<String> sessionIds = new LinkedList<>(); for (String id : ssoIds) { String sessionId = idMapper.getSessionFromSSO(id); if (sessionId != null) { sessionIds.add(sessionId); idMapperUpdater.removeSession(idMapper, sessionId); } } logoutSessionIds(sessionIds); } protected void logoutSessionIds(List<String> sessionIds) { sessionIds.forEach(id -> { HttpScope scope = exchange.getScope(Scope.SESSION, id); if (scope.exists()) { log.debugf("Invalidating session %s", id); scope.setAttachment(SamlSession.class.getName(), null); scope.invalidate(); } }); } @Override public boolean isLoggedIn() { HttpScope session = getSession(false); if (!session.exists()) { log.debug("session was null, returning null"); return false; } if (! idMapper.hasSession(session.getID()) && ! idMapperUpdater.refreshMapping(idMapper, session.getID())) { log.debugf("Session %s has expired on some other node", session.getID()); session.setAttachment(SamlSession.class.getName(), null); return false; } final SamlSession samlSession = SamlUtil.validateSamlSession(session.getAttachment(SamlSession.class.getName()), deployment); if (samlSession == null) { return false; } exchange.authenticationComplete(samlSession); restoreRequest(); return true; } @Override public void saveAccount(SamlSession account) { HttpScope session = getSession(true); session.setAttachment(SamlSession.class.getName(), account); String sessionId = changeSessionId(session); idMapperUpdater.map(idMapper, account.getSessionIndex(), account.getPrincipal().getSamlSubject(), sessionId); } protected String changeSessionId(HttpScope session) { if (!deployment.turnOffChangeSessionIdOnLogin()) return session.getID(); else return session.getID(); } @Override public SamlSession getAccount() { HttpScope session = getSession(true); return (SamlSession)session.getAttachment(SamlSession.class.getName()); } @Override public String getRedirectUri() { HttpScope session = exchange.getScope(Scope.SESSION); String redirect = (String) session.getAttachment(SAML_REDIRECT_URI); if (redirect == null) { URI uri = exchange.getURI(); String path = uri.getPath(); String relativePath = exchange.getRequest().getRelativePath(); String contextPath = path.substring(0, path.indexOf(relativePath)); if (!contextPath.isEmpty()) { contextPath = contextPath + "/"; } String baseUri = KeycloakUriBuilder.fromUri(path).replacePath(contextPath).build().toString(); return SamlUtil.getRedirectTo(exchange, contextPath, baseUri); } return redirect; } @Override public void saveRequest() { exchange.suspendRequest(); HttpScope scope = exchange.getScope(Scope.SESSION); if (!scope.exists()) { scope.create(); } scope.setAttachment(SAML_REDIRECT_URI, exchange.getRequest().getURI()); } @Override public boolean restoreRequest() { return exchange.restoreRequest(); } protected HttpScope getSession(boolean create) { HttpScope scope = exchange.getScope(Scope.SESSION); if (!scope.exists() && create) { scope.create(); } return scope; } @Override public void logout(boolean glo) { logoutAccount(); } }
3,373
5,823
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #import <Cocoa/Cocoa.h> #import "flutter/shell/platform/darwin/macos/framework/Headers/FlutterEngine.h" #import "flutter/shell/platform/darwin/macos/framework/Source/FlutterMacOSExternalTexture.h" /* * Delegate methods for FlutterTextureRegistrar. */ @protocol FlutterTextureRegistrarDelegate /* * Called by the FlutterTextureRegistrar when a texture is registered. */ - (nonnull id<FlutterMacOSExternalTexture>)onRegisterTexture:(nonnull id<FlutterTexture>)texture; @end /* * Holds the external textures and implements the FlutterTextureRegistry. */ @interface FlutterTextureRegistrar : NSObject <FlutterTextureRegistry> /* * Use `initWithDelegate:engine:` instead. */ - (nullable instancetype)init NS_UNAVAILABLE; /* * Use `initWithDelegate:engine:` instead. */ + (nullable instancetype)new NS_UNAVAILABLE; /* * Initialzes the texture registrar. */ - (nullable instancetype)initWithDelegate:(nonnull id<FlutterTextureRegistrarDelegate>)delegate engine:(nonnull FlutterEngine*)engine NS_DESIGNATED_INITIALIZER; /* * Returns the registered texture with the provided `textureID`. */ - (nullable id<FlutterMacOSExternalTexture>)getTextureWithID:(int64_t)textureID; @end
464
551
#ifndef BITMAP_TEXT_H #define BITMAP_TEXT_H #include "Actor.h" class RageTexture; class Font; struct FontPageTextures; /** @brief An actor that holds a Font and draws text to the screen. */ class BitmapText : public Actor { public: BitmapText(); BitmapText(const BitmapText& cpy); auto operator=(const BitmapText& cpy) -> BitmapText&; ~BitmapText() override; void LoadFromNode(const XNode* pNode) override; [[nodiscard]] auto Copy() const -> BitmapText* override; struct BMT_TweenState { // We'd be better off not adding strokes to things we can't control // themewise (ScreenDebugOverlay for example). -Midiman BMT_TweenState() : m_stroke_color(RageColor(0, 0, 0, 0)) { } static void MakeWeightedAverage(BMT_TweenState& out, BMT_TweenState const& from, BMT_TweenState const& to, float between); auto operator==(BMT_TweenState const& other) const -> bool; auto operator!=(BMT_TweenState const& other) const -> bool { return !operator==(other); } void SetStrokeColor(RageColor const& c) { m_stroke_color = c; } [[nodiscard]] auto GetStrokeColor() const -> RageColor const& { return m_stroke_color; } private: RageColor m_stroke_color; }; auto BMT_DestTweenState() -> BMT_TweenState& { if (BMT_Tweens.empty()) { return BMT_current; } return BMT_Tweens.back(); } [[nodiscard]] auto BMT_DestTweenState() const -> BMT_TweenState const& { return const_cast<BitmapText*>(this)->BMT_DestTweenState(); } void SetCurrentTweenStart() override; void EraseHeadTween() override; void UpdatePercentThroughTween(float between) override; void BeginTweening(float time, ITween* interp) override; // This function exists because the compiler tried to connect a call of // "BeginTweening(1.2f)" to the function above. -Kyz virtual void BeginTweening(float time, TweenType tt = TWEEN_LINEAR) override { Actor::BeginTweening(time, tt); } void StopTweening() override; void FinishTweening() override; auto LoadFromFont(const std::string& sFontName) -> bool; auto LoadFromTextureAndChars(const std::string& sTexturePath, const std::string& sChars) -> bool; virtual void SetText(const std::string& sText, const std::string& sAlternateText = "", int iWrapWidthPixels = -1); void SetVertSpacing(int iSpacing); void SetMaxWidth(float fMaxWidth); void SetMaxHeight(float fMaxHeight); void SetMaxDimUseZoom(bool use); void SetWrapWidthPixels(int iWrapWidthPixels); void CropLineToWidth(size_t l, int width); void CropToWidth(int width); [[nodiscard]] auto EarlyAbortDraw() const -> bool override; void DrawPrimitives() override; void SetUppercase(bool b); void SetRainbowScroll(bool b) { m_bRainbowScroll = b; } void SetJitter(bool b) { m_bJitter = b; } void SetDistortion(float f); void UnSetDistortion(); void set_mult_attrs_with_diffuse(bool m); [[nodiscard]] auto get_mult_attrs_with_diffuse() const -> bool; void SetHorizAlign(float f) override; void SetStrokeColor(const RageColor& c) { BMT_DestTweenState().SetStrokeColor(c); } auto GetStrokeColor() -> RageColor const& { return BMT_DestTweenState().GetStrokeColor(); } void SetCurrStrokeColor(const RageColor& c) { BMT_current.SetStrokeColor(c); } auto GetCurrStrokeColor() -> RageColor const& { return BMT_current.GetStrokeColor(); } void SetTextGlowMode(TextGlowMode tgm) { m_TextGlowMode = tgm; } void GetLines(std::vector<std::wstring>& wTextLines) const { wTextLines = m_wTextLines; } [[nodiscard]] auto GetLines() const -> const std::vector<std::wstring>& { return m_wTextLines; } [[nodiscard]] auto GetText() const -> std::string { return m_sText; } // Return true if the string 's' will use an alternate string, if available. [[nodiscard]] auto StringWillUseAlternate( const std::string& sText, const std::string& sAlternateText) const -> bool; struct Attribute { int length{ -1 }; RageColor diffuse[NUM_DIFFUSE_COLORS]; RageColor glow; void FromStack(lua_State* L, int iPos); }; [[nodiscard]] auto GetDefaultAttribute() const -> Attribute; void AddAttribute(size_t iPos, const Attribute& attr); void ClearAttributes(); // Commands void PushSelf(lua_State* L) override; std::vector<RageSpriteVertex> m_aVertices; protected: Font* m_pFont; bool m_bUppercase; std::string m_sText; std::vector<std::wstring> m_wTextLines; std::vector<int> m_iLineWidths; // in source pixels int m_iWrapWidthPixels; // -1 = no wrap float m_fMaxWidth; // 0 = no max float m_fMaxHeight; // 0 = no max bool m_MaxDimensionUsesZoom; bool m_bRainbowScroll; bool m_bJitter; bool m_bUsingDistortion; bool m_mult_attrs_with_diffuse; float m_fDistortion; int m_iVertSpacing; std::vector<FontPageTextures*> m_vpFontPageTextures; std::map<size_t, Attribute> m_mAttributes; bool m_bHasGlowAttribute; TextGlowMode m_TextGlowMode; // recalculate the items in SetText() void BuildChars(); void DrawChars(bool bUseStrokeTexture); void UpdateBaseZoom(); private: void SetTextInternal(); std::vector<BMT_TweenState> BMT_Tweens; BMT_TweenState BMT_current; BMT_TweenState BMT_start; }; // With the addition of Attributes to BitmapText, this class may very well be // redundant. (Leave it in for now, though.) -aj class ColorBitmapText : public BitmapText { public: [[nodiscard]] auto Copy() const -> ColorBitmapText* override; void SetText(const std::string& sText, const std::string& sAlternateText = "", int iWrapWidthPixels = -1) override; void ResetText(); void DrawPrimitives() override; int lines = 0; void SetMaxLines(int iNumLines, int iDirection, unsigned int& scroll); void SetMaxLines(int iLines, bool bCutBottom = true); // if bCutBottom = // false then, it will // crop the top void SimpleAddLine(const std::string& sAddition, int iWidthPixels); void SetMaxLines(int iNumLines, int iDirection); void PushSelf(lua_State* L) override; protected: struct ColorChange { RageColor c; // Color to change to int l{}; // Change Location }; std::vector<ColorChange> m_vColors; }; #endif
2,328
5,766
<reponame>YKYou/poco // // HeaderGenerator.h // // Copyright (c) 2020, Applied Informatics Software Engineering GmbH. // and Contributors. // // SPDX-License-Identifier: BSL-1.0 // #ifndef ActiveRecordCompiler_HeaderGenerator_INCLUDED #define ActiveRecordCompiler_HeaderGenerator_INCLUDED #include "CodeGenerator.h" #include "Types.h" namespace Poco { namespace ActiveRecord { namespace Compiler { class HeaderGenerator: public CodeGenerator { public: HeaderGenerator(const std::string& source, std::ostream& stream, const Class& clazz, const ClassMap& classes); void generate() const; void writeClass() const; void writeTypeHandler() const; void writeSimpleAccessors() const; void writeReferencingAccessors() const; void writeVariables() const; void writeGetter(const Property& property) const; void writeSetter(const Property& property) const; void writeReferenceGetter(const Property& property) const; void writeReferenceSetter(const Property& property) const; void writeInlineAccessorImpls() const; void writeInlineReferencingAccessorImpls() const; void writeInlineGetterImpl(const Property& property) const; void writeInlineSetterImpl(const Property& property) const; void writeInlineReferencingGetterImpl(const Property& property) const; void writeInlineReferencingSetterImpl(const Property& property) const; const Class& referencedClass(const Property& property) const; protected: std::string includeGuard(const std::string& nameSpace, const std::string& name) const; private: Class _class; const ClassMap& _classes; }; } } } // namespace Poco::ActiveRecord::Compiler #endif // ActiveRecordCompiler_HeaderGenerator_INCLUDED
500
4,256
<reponame>ilelann/s2n /* * Copyright 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. */ #pragma once #define S2N_GCC_VERSION (__GNUC__ * 10000 \ + __GNUC_MINOR__ * 100 \ + __GNUC_PATCHLEVEL__) #define S2N_GCC_VERSION_AT_LEAST(major, minor, patch_level) \ ((S2N_GCC_VERSION) >= ((major) * 10000 + (minor) * 100 + (patch_level)))
312
2,667
import random import string import timeit import unittest from collections import Hashable import six from six.moves import xrange import match_counter from testutil import repeat_until_passes # Here's an alternative implementation. Unlike the simple one, it never constructs a new data # structure, or modifies dictionary keys while iterating, but it is still slower. class MatchCounterOther(object): def __init__(self, _sample): self.sample_counts = {v: 0 for v in _sample} def count_unique(self, iterable): for v in iterable: try: n = self.sample_counts.get(v) if n is not None: self.sample_counts[v] = n + 1 except TypeError: pass matches = 0 for v, n in six.iteritems(self.sample_counts): if n > 0: matches += 1 self.sample_counts[v] = 0 return matches # If not for dealing with unhashable errors, `.intersection(iterable)` would be by far the # fastest. But with the extra iteration and especially checking for Hashable, it's super slow. class MatchCounterIntersection(object): def __init__(self, _sample): self.sample = set(_sample) def count_unique(self, iterable): return len(self.sample.intersection(v for v in iterable if isinstance(v, Hashable))) # This implementation doesn't measure the intersection, but it's interesting to compare its # timings: this is still slower! Presumably because set intersection is native code that's more # optimized than checking membership many times from Python. class MatchCounterSimple(object): def __init__(self, _sample): self.sample = set(_sample) def count_all(self, iterable): return sum(1 for r in iterable if present(r, self.sample)) # This is much faster than using `isinstance(v, Hashable) and v in value_set` def present(v, value_set): try: return v in value_set except TypeError: return False # Set up a predictable random number generator. r = random.Random(17) def random_string(): length = r.randint(10,20) return ''.join(r.choice(string.ascii_letters) for x in xrange(length)) def sample_with_repl(population, n): return [r.choice(population) for x in xrange(n)] # Here's some sample generated data. sample = [random_string() for x in xrange(200)] data1 = sample_with_repl([random_string() for x in xrange(20)] + r.sample(sample, 5), 1000) data2 = sample_with_repl([random_string() for x in xrange(100)] + r.sample(sample, 15), 500) # Include an example with an unhashable value, to ensure all implementation can handle it. data3 = sample_with_repl([random_string() for x in xrange(10)] + sample, 2000) + [[1,2,3]] class TestMatchCounter(unittest.TestCase): def test_match_counter(self): m = match_counter.MatchCounter(sample) self.assertEqual(m.count_unique(data1), 5) self.assertEqual(m.count_unique(data2), 15) self.assertEqual(m.count_unique(data3), 200) m = MatchCounterOther(sample) self.assertEqual(m.count_unique(data1), 5) self.assertEqual(m.count_unique(data2), 15) self.assertEqual(m.count_unique(data3), 200) # Do it again to ensure that we clear out state between counting. self.assertEqual(m.count_unique(data1), 5) self.assertEqual(m.count_unique(data2), 15) self.assertEqual(m.count_unique(data3), 200) m = MatchCounterIntersection(sample) self.assertEqual(m.count_unique(data1), 5) self.assertEqual(m.count_unique(data2), 15) self.assertEqual(m.count_unique(data3), 200) m = MatchCounterSimple(sample) self.assertGreaterEqual(m.count_all(data1), 5) self.assertGreaterEqual(m.count_all(data2), 15) self.assertGreaterEqual(m.count_all(data3), 200) @repeat_until_passes(3) def test_timing(self): setup=''' import match_counter import test_match_counter as t m1 = match_counter.MatchCounter(t.sample) m2 = t.MatchCounterOther(t.sample) m3 = t.MatchCounterSimple(t.sample) m4 = t.MatchCounterIntersection(t.sample) ''' N = 100 t1 = min(timeit.repeat(stmt='m1.count_unique(t.data1)', setup=setup, number=N, repeat=3)) / N t2 = min(timeit.repeat(stmt='m2.count_unique(t.data1)', setup=setup, number=N, repeat=3)) / N t3 = min(timeit.repeat(stmt='m3.count_all(t.data1)', setup=setup, number=N, repeat=3)) / N t4 = min(timeit.repeat(stmt='m4.count_unique(t.data1)', setup=setup, number=N, repeat=3)) / N #print "Timings/iter data1: %.3fus %.3fus %.3fus %.3fus" % (t1 * 1e6, t2 * 1e6, t3*1e6, t4*1e6) self.assertLess(t1, t2) self.assertLess(t1, t3) self.assertLess(t1, t4) t1 = min(timeit.repeat(stmt='m1.count_unique(t.data2)', setup=setup, number=N, repeat=3)) / N t2 = min(timeit.repeat(stmt='m2.count_unique(t.data2)', setup=setup, number=N, repeat=3)) / N t3 = min(timeit.repeat(stmt='m3.count_all(t.data2)', setup=setup, number=N, repeat=3)) / N t4 = min(timeit.repeat(stmt='m4.count_unique(t.data2)', setup=setup, number=N, repeat=3)) / N #print "Timings/iter data2: %.3fus %.3fus %.3fus %.3fus" % (t1 * 1e6, t2 * 1e6, t3*1e6, t4*1e6) self.assertLess(t1, t2) self.assertLess(t1, t3) self.assertLess(t1, t4) t1 = min(timeit.repeat(stmt='m1.count_unique(t.data3)', setup=setup, number=N, repeat=3)) / N t2 = min(timeit.repeat(stmt='m2.count_unique(t.data3)', setup=setup, number=N, repeat=3)) / N t3 = min(timeit.repeat(stmt='m3.count_all(t.data3)', setup=setup, number=N, repeat=3)) / N t4 = min(timeit.repeat(stmt='m4.count_unique(t.data3)', setup=setup, number=N, repeat=3)) / N #print "Timings/iter data3: %.3fus %.3fus %.3fus %.3fus" % (t1 * 1e6, t2 * 1e6, t3*1e6, t4*1e6) self.assertLess(t1, t2) #self.assertLess(t1, t3) # This fails on occasion, but it's a fairly pointless check. self.assertLess(t1, t4) if __name__ == "__main__": unittest.main()
2,281
892
<reponame>westonsteimel/advisory-database-github { "schema_version": "1.2.0", "id": "GHSA-rhxg-2cq5-ch36", "modified": "2022-03-17T00:04:19Z", "published": "2022-03-03T00:00:51Z", "aliases": [ "CVE-2022-22301" ], "details": "An improper neutralization of special elements used in an OS Command vulnerability [CWE-78] in FortiAP-C console 5.4.0 through 5.4.3, 5.2.0 through 5.2.1 may allow an authenticated attacker to execute unauthorized commands by running CLI commands with specifically crafted arguments.", "severity": [ { "type": "CVSS_V3", "score": "CVSS:3.1/AV:L/AC:L/PR:L/UI:N/S:U/C:H/I:H/A:H" } ], "affected": [ ], "references": [ { "type": "ADVISORY", "url": "https://nvd.nist.gov/vuln/detail/CVE-2022-22301" }, { "type": "WEB", "url": "https://fortiguard.com/psirt/FG-IR-21-227" } ], "database_specific": { "cwe_ids": [ "CWE-78" ], "severity": "HIGH", "github_reviewed": false } }
469
1,738
/* * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or * its licensors. * * For complete copyright and license terms please see the LICENSE at the root of this * distribution (the "License"). All use of this software is governed by the License, * or, if provided, by the license below or the license accompanying this file. Do not * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * */ // Original file Copyright Crytek GMBH or its affiliates, used under license. #pragma once #include "AnimNode.h" class CTODNodeDescription; ////////////////////////////////////////////////////////////////////////// class CAnimTODNode : public CAnimNode { public: AZ_CLASS_ALLOCATOR(CAnimTODNode, AZ::SystemAllocator, 0); AZ_RTTI(CAnimTODNode, "{589BD27C-0C44-4802-B040-6D063E60D3FB}", CAnimNode); //----------------------------------------------------------------------------- //! static void Initialize(); static CTODNodeDescription* GetTODNodeDescription(AnimNodeType nodeType); static CAnimNode* CreateNode(const int id, AnimNodeType nodeType); //----------------------------------------------------------------------------- //! CAnimTODNode(); CAnimTODNode(const int id, AnimNodeType nodeType, CTODNodeDescription* desc); //----------------------------------------------------------------------------- //! virtual void SerializeAnims(XmlNodeRef& xmlNode, bool loading, bool loadEmptyTracks); //----------------------------------------------------------------------------- //! virtual unsigned int GetParamCount() const; virtual CAnimParamType GetParamType(unsigned int index) const; //----------------------------------------------------------------------------- //! virtual void CreateDefaultTracks(); virtual void Activate(bool activate); virtual void OnReset(); //----------------------------------------------------------------------------- //! virtual void Animate(SAnimContext& ac); void InitPostLoad(IAnimSequence* sequence) override; static void Reflect(AZ::SerializeContext* serializeContext); protected: virtual bool GetParamInfoFromType(const CAnimParamType& paramId, SParamInfo& info) const; typedef std::map< AnimNodeType, _smart_ptr<CTODNodeDescription> > TODNodeDescriptionMap; static StaticInstance<TODNodeDescriptionMap> s_TODNodeDescriptions; static bool s_initialized; CTODNodeDescription* m_description; XmlNodeRef m_xmlData; };
711
2,835
import base64 import boto3 def get_aws_secret(secret_name, region): session = boto3.session.Session() client = session.client( service_name="secretsmanager", region_name=region, ) get_secret_value_response = client.get_secret_value(SecretId=secret_name) if "SecretString" in get_secret_value_response: return get_secret_value_response["SecretString"] else: return base64.b64decode(get_secret_value_response["SecretBinary"])
185
1,350
<gh_stars>1000+ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.resourcemanager.devtestlabs.models; import com.azure.core.annotation.Fluent; import com.azure.core.util.logging.ClientLogger; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import java.util.List; /** Configuration for public IP address sharing. */ @Fluent public final class SubnetSharedPublicIpAddressConfiguration { @JsonIgnore private final ClientLogger logger = new ClientLogger(SubnetSharedPublicIpAddressConfiguration.class); /* * Backend ports that virtual machines on this subnet are allowed to expose */ @JsonProperty(value = "allowedPorts") private List<Port> allowedPorts; /** * Get the allowedPorts property: Backend ports that virtual machines on this subnet are allowed to expose. * * @return the allowedPorts value. */ public List<Port> allowedPorts() { return this.allowedPorts; } /** * Set the allowedPorts property: Backend ports that virtual machines on this subnet are allowed to expose. * * @param allowedPorts the allowedPorts value to set. * @return the SubnetSharedPublicIpAddressConfiguration object itself. */ public SubnetSharedPublicIpAddressConfiguration withAllowedPorts(List<Port> allowedPorts) { this.allowedPorts = allowedPorts; return this; } /** * Validates the instance. * * @throws IllegalArgumentException thrown if the instance is not valid. */ public void validate() { if (allowedPorts() != null) { allowedPorts().forEach(e -> e.validate()); } } }
621
323
/* * @Copyright (c) 2018 缪聪(<EMAIL>) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.mcg.controller; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; import com.mcg.common.Constants; import com.mcg.controller.base.BaseController; import com.mcg.entity.auth.McgUser; import com.mcg.entity.auth.PermissionCollection; import com.mcg.entity.auth.UserCacheBean; /** * * @ClassName: LoginController * @Description: TODO(负责登录和登出) * @author: 缪聪(<EMAIL>) * @date: 2018年3月9日 下午5:24:29 * */ @Controller public class LoginController extends BaseController { @RequestMapping(value = "/login", method = RequestMethod.POST) public ModelAndView index(HttpServletRequest reuqest, HttpServletResponse response) { ModelAndView mv = this.getModelAndView(); if(reuqest.getHeader("x-requested-with")!=null && reuqest.getHeader("x-requested-with").equalsIgnoreCase("XMLHttpRequest")){ //不记录上次登录的url mv.setViewName("timeout"); } else { UserCacheBean ucb = PermissionCollection.getInstance().getUserCache(reuqest.getSession().getId()); if(ucb == null ) { if(reuqest.getParameter("userKey") != null && !"".equals(reuqest.getParameter("userKey"))) { ucb = new UserCacheBean(); ucb.setSessionID(reuqest.getSession().getId()); McgUser mu = new McgUser(); mu.setUserKey(reuqest.getParameter("userKey")); ucb.setUser(mu); PermissionCollection.getInstance().addSessionUserCache(reuqest.getSession().getId(), ucb); reuqest.getSession().setMaxInactiveInterval(Constants.HTTP_SESSION_TIME_OUT); mv.setViewName("redirect:/index"); } else { mv.setViewName("redirect:/login.jsp"); } } else { mv.setViewName("redirect:/index"); } } return mv; } }
1,175
3,459
/* FCE Ultra - NES/Famicom Emulator * * Copyright notice for this file: * Copyright (C) 2002 Xodnizel * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /****************************************************************/ /* FCE Ultra */ /* */ /* This file contains code for parsing command-line */ /* options. */ /* */ /****************************************************************/ #include <stdio.h> #include <stdlib.h> #include <string.h> #include "../../types.h" #include "args.h" int ParseEA(int x, int argc, char *argv[], ARGPSTRUCT *argsps) { int y=0; int ret=1; do { if(!argsps[y].name) { ParseEA(x,argc,argv,(ARGPSTRUCT*)argsps[y].var); y++; continue; } if(!strcmp(argv[x],argsps[y].name)) // A match. { //ret++; if(argsps[y].subs) { if((x+1)>=argc) break; ret++; if(argsps[y].substype&0x2000) { ((void (*)(char *))argsps[y].subs)(argv[x+1]); } else if(argsps[y].substype&0x8000) { *(int *)argsps[y].subs&=~(argsps[y].substype&(~0x8000)); *(int *)argsps[y].subs|=atoi(argv[x+1])?(argsps[y].substype&(~0x8000)):0; } else switch(argsps[y].substype&(~0x4000)) { case 0: // Integer *(int *)argsps[y].subs=atoi(argv[x+1]); break; case 2: // Double float *(double *)argsps[y].subs=atof(argv[x+1]); break; case 1: // String if(argsps[y].substype&0x4000) { if(*(char **)argsps[y].subs) free(*(char **)argsps[y].subs); if(!( *(char **)argsps[y].subs=(char*)malloc(strlen(argv[x+1])+1) )) break; } strcpy(*(char **)argsps[y].subs,argv[x+1]); break; } } if(argsps[y].var) *argsps[y].var=1; } y++; } while(argsps[y].var || argsps[y].subs); return ret; } int ParseArguments(int argc, char *argv[], ARGPSTRUCT *argsps) { int x; for(x=0;x<argc;) { int temp = ParseEA(x,argc,argv,argsps); if(temp == 1 && x==argc-1) return argc-1; x += temp; } return argc; }
1,332
1,056
<filename>platform/core.multiview/test/unit/src/org/netbeans/core/multiview/MultiViewProcessorTest.java /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.netbeans.core.multiview; import java.awt.Dialog; import java.awt.EventQueue; import java.awt.GraphicsEnvironment; import java.awt.Image; import java.awt.event.ActionEvent; import java.awt.image.BufferedImage; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.Serializable; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.Map; import java.util.logging.Level; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.JComponent; import javax.swing.JPanel; import javax.swing.JSplitPane; import junit.framework.Test; import junit.framework.TestSuite; import org.netbeans.api.editor.mimelookup.MimeLookup; import org.netbeans.api.editor.mimelookup.MimeRegistration; import org.netbeans.core.api.multiview.MultiViewHandler; import org.netbeans.core.api.multiview.MultiViewPerspective; import org.netbeans.core.api.multiview.MultiViews; import org.netbeans.core.spi.multiview.CloseOperationHandler; import org.netbeans.core.spi.multiview.CloseOperationState; import org.netbeans.core.spi.multiview.MultiViewDescription; import org.netbeans.core.spi.multiview.MultiViewElement; import org.netbeans.core.spi.multiview.MultiViewElementCallback; import org.netbeans.core.spi.multiview.MultiViewFactory; import org.netbeans.core.spi.multiview.text.MultiViewEditorElement; import org.netbeans.core.spi.multiview.text.MultiViewEditorElementTest; import org.netbeans.junit.Log; import org.netbeans.junit.MockServices; import org.netbeans.junit.NbTestCase; import org.openide.DialogDescriptor; import org.openide.DialogDisplayer; import org.openide.NotifyDescriptor; import org.openide.awt.UndoRedo; import org.openide.text.CloneableEditorSupport; import org.openide.util.Lookup; import org.openide.util.LookupEvent; import org.openide.util.LookupListener; import org.openide.util.io.NbMarshalledObject; import org.openide.util.lookup.AbstractLookup; import org.openide.util.lookup.InstanceContent; import org.openide.util.test.AnnotationProcessorTestUtils; import org.openide.windows.CloneableTopComponent; import org.openide.windows.TopComponent; /** * * @author <NAME> <<EMAIL>> */ public class MultiViewProcessorTest extends NbTestCase { public static Test suite() { return GraphicsEnvironment.isHeadless() ? new TestSuite() : new TestSuite(MultiViewProcessorTest.class); } public MultiViewProcessorTest(String n) { super(n); } @Override protected void setUp() throws Exception { MVE.closeState = null; CloseH.globalElements = null; CloseH.retValue = null; DD.d = null; DD.ret = -1; MockServices.setServices(DD.class); } public void testMultiViewsCreate() { TopComponent mvc = MultiViews.createMultiView("text/figaro", new LP(Lookup.EMPTY)); assertNotNull("MultiViewComponent created", mvc); mvc.open(); mvc.requestActive(); MultiViewHandler handler = MultiViews.findMultiViewHandler(mvc); assertNotNull("Handler found", handler); MultiViewPerspective[] arr = handler.getPerspectives(); assertEquals("Two perspetives found", 2, arr.length); assertEquals("Figaro", arr[0].getDisplayName()); assertEquals("Figaro", arr[1].getDisplayName()); MultiViewDescription description = Accessor.DEFAULT.extractDescription(arr[0]); assertTrue(description instanceof ContextAwareDescription); assertFalse("First one is not for split", ((ContextAwareDescription)description).isSplitDescription()); description = Accessor.DEFAULT.extractDescription(arr[1]); assertTrue(description instanceof ContextAwareDescription); assertTrue("Second one is for split", ((ContextAwareDescription)description).isSplitDescription()); CloseH.retValue = true; MVE.closeState = MultiViewFactory.createUnsafeCloseState("warn", new AbstractAction() { @Override public void actionPerformed( ActionEvent e ) { MVE.closeState = null; } }, null); assertTrue("Closed OK", mvc.close()); assertNotNull(CloseH.globalElements); assertEquals("One handle", 1, CloseH.globalElements.length); assertEquals("states are the same", MVE.closeState, CloseH.globalElements[0]); } public void testCloneableMultiViewsCreate() { InstanceContent ic = new InstanceContent(); Lookup lookup = new AbstractLookup(ic); CloneableTopComponent cmv = MultiViews.createCloneableMultiView("text/context", new LP(lookup)); assertNotNull("MultiViewComponent created", cmv); cmv.open(); TopComponent mvc = cmv.cloneTopComponent(); doCheck(mvc, ic); assertTrue("First component can be closed without any questions", cmv.close()); CntAction accept = new CntAction() { @Override public void actionPerformed( ActionEvent e ) { super.actionPerformed( e ); MVE.closeState = null; } }; CntAction discard = new CntAction(); CloseH.retValue = false; MVE.closeState = MultiViewFactory.createUnsafeCloseState("warn", accept, discard); DD.ret = 2; mvc.open(); assertFalse("Closed cancelled", mvc.close()); assertEquals("No accept", 0, accept.cnt); assertEquals("No discard", 0, discard.cnt); MVE.closeState = MultiViewFactory.createUnsafeCloseState("warn", accept, discard); DD.ret = 1; DD.d = null; mvc.open(); assertTrue("Changes discarded, close accepted", mvc.close()); assertEquals("Still no accept", 0, accept.cnt); assertEquals("One discard", 1, discard.cnt); MVE.closeState = MultiViewFactory.createUnsafeCloseState("warn", accept, discard); DD.ret = 0; DD.d = null; mvc.open(); assertTrue("Closed accepted OK", mvc.close()); assertEquals("Three buttons", 3, DD.d.getOptions().length); assertNull("Not called, we use default handler", CloseH.globalElements); MVE.closeState = null; } public void testCloneableMultiViewsSerialize() throws Exception { InstanceContent ic = new InstanceContent(); Lookup lookup = new AbstractLookup(ic); CloneableTopComponent cmv = MultiViews.createCloneableMultiView("text/context", new LP(lookup)); assertPersistence("Always", TopComponent.PERSISTENCE_ALWAYS, cmv); assertNotNull("MultiViewComponent created", cmv); NbMarshalledObject mar = new NbMarshalledObject(cmv); TopComponent mvc = (TopComponent) mar.get(); doCheck(mvc, ic); } private void assertPersistence(String msg, int pt, TopComponent cmv) { CharSequence log = Log.enable("org.netbeans.core.multiview", Level.WARNING); int res = cmv.getPersistenceType(); if (log.length() > 0) { fail("There should be no warnings to compute getPersistenceType():\n" + log); } assertEquals(msg, pt, res); } private void doCheck(TopComponent mvc, InstanceContent ic) { assertNotNull("MultiViewComponent cloned", mvc); MultiViewHandler handler = MultiViews.findMultiViewHandler(mvc); assertNotNull("Handler found", handler); MultiViewPerspective[] arr = handler.getPerspectives(); assertEquals("Two perspetives found", 2, arr.length); assertEquals("Contextual", arr[0].getDisplayName()); assertEquals("Contextual", arr[1].getDisplayName()); MultiViewDescription description = Accessor.DEFAULT.extractDescription(arr[0]); assertTrue(description instanceof ContextAwareDescription); assertFalse("First one is not for split", ((ContextAwareDescription)description).isSplitDescription()); description = Accessor.DEFAULT.extractDescription(arr[1]); assertTrue(description instanceof ContextAwareDescription); assertTrue("Second one is for split", ((ContextAwareDescription)description).isSplitDescription()); assertPersistence("Always", TopComponent.PERSISTENCE_ALWAYS, mvc); mvc.open(); mvc.requestActive(); mvc.requestVisible(); handler.requestActive(arr[0]); assertNull("No integer now", mvc.getLookup().lookup(Integer.class)); ic.add(1); assertEquals("1 now", Integer.valueOf(1), mvc.getLookup().lookup(Integer.class)); ((MultiViewCloneableTopComponent)mvc).splitComponent(JSplitPane.HORIZONTAL_SPLIT, -1); handler.requestActive(arr[0]); ic.remove(1); assertNull("No integer now", mvc.getLookup().lookup(Integer.class)); ic.add(2); assertEquals("2 now", Integer.valueOf(2), mvc.getLookup().lookup(Integer.class)); } public void testLookupInitializedForCloneable() { InstanceContent ic = new InstanceContent(); Lookup lookup = new AbstractLookup(ic); ic.add(10); CloneableTopComponent cmv = MultiViews.createCloneableMultiView("text/context", new LP(lookup)); assertEquals("10 now", Integer.valueOf(10), cmv.getLookup().lookup(Integer.class)); assertNotNull("MultiViewComponent created", cmv); TopComponent mvc = cmv.cloneTopComponent(); assertNotNull("MultiViewComponent cloned", mvc); MultiViewHandler handler = MultiViews.findMultiViewHandler(mvc); assertNotNull("Handler found", handler); assertEquals("10 now", Integer.valueOf(10), mvc.getLookup().lookup(Integer.class)); ic.remove(10); ic.add(1); assertEquals("1 now", Integer.valueOf(1), mvc.getLookup().lookup(Integer.class)); } public void testLookupInitialized() { InstanceContent ic = new InstanceContent(); Lookup lookup = new AbstractLookup(ic); ic.add(10); TopComponent mvc = MultiViews.createMultiView("text/context", new LP(lookup)); assertEquals("10 now", Integer.valueOf(10), mvc.getLookup().lookup(Integer.class)); ic.remove(10); ic.add(1); assertEquals("1 now", Integer.valueOf(1), mvc.getLookup().lookup(Integer.class)); } public void testNotSourceView() { int cnt = 0; for (MultiViewDescription d : MimeLookup.getLookup("text/context").lookupAll(MultiViewDescription.class)) { cnt++; assertFalse( "No view in text/context has source element", MultiViewCloneableTopComponent.isSourceView(d) ); } if (cnt == 0) { fail("There shall be at least one description"); } } public void testCompileInApt() throws Exception { clearWorkDir(); String src = "\n" + "import org.netbeans.core.spi.multiview.MultiViewElement;\n" + "public class Test extends org.netbeans.core.multiview.MultiViewProcessorTest.MVE {\n" + "@MultiViewElement.Registration(displayName = \"Testing\"," + "mimeType = \"text/ble\"," + "persistenceType = 0," + "preferredID = \"bleple\")" + " public static MultiViewElement create() {\n" + " return new Test();\n" + " }\n" + "}\n"; AnnotationProcessorTestUtils.makeSource(getWorkDir(), "pkg.Test", src); ByteArrayOutputStream os = new ByteArrayOutputStream(); boolean res = AnnotationProcessorTestUtils.runJavac(getWorkDir(), null, getWorkDir(), null, os); assertTrue("Compilation should succeed:\n" + os.toString(), res); } public void testCompileInAptFullPath() throws Exception { clearWorkDir(); String src = "\n" + "import org.netbeans.core.spi.multiview.MultiViewElement;\n" + "public class Test extends org.netbeans.core.multiview.MultiViewProcessorTest.MVE {\n" + "@MultiViewElement.Registration(displayName = \"Testing\"," + "iconBase = \"pkg/one.png\"," + "mimeType = \"text/ble\"," + "persistenceType = 0," + "preferredID = \"bleple\")" + " public static MultiViewElement create() {\n" + " return new Test();\n" + " }\n" + "}\n"; generateIcon("one.png"); AnnotationProcessorTestUtils.makeSource(getWorkDir(), "pkg.Test", src); ByteArrayOutputStream os = new ByteArrayOutputStream(); boolean res = AnnotationProcessorTestUtils.runJavac(getWorkDir(), null, getWorkDir(), null, os); assertTrue("Compilation should succeed:\n" + os.toString(), res); } private void generateIcon(String icon) throws IOException { File pkg = new File(getWorkDir(), "pkg"); pkg.mkdirs(); File f = new File(pkg, icon); f.createNewFile(); } public void testFailsWithoutAnIcon() throws Exception { clearWorkDir(); String src = "\n" + "import org.netbeans.core.spi.multiview.MultiViewElement;\n" + "public class Test extends org.netbeans.core.multiview.MultiViewProcessorTest.MVE {\n" + "@MultiViewElement.Registration(displayName = \"Testing\"," + "iconBase = \"pkg/none-existing.png\"," + "mimeType = \"text/ble\"," + "persistenceType = 0," + "preferredID = \"bleple\")" + " public static MultiViewElement create() {\n" + " return new Test();\n" + " }\n" + "}\n"; AnnotationProcessorTestUtils.makeSource(getWorkDir(), "pkg.Test", src); ByteArrayOutputStream os = new ByteArrayOutputStream(); boolean res = AnnotationProcessorTestUtils.runJavac(getWorkDir(), null, getWorkDir(), null, os); if (AnnotationProcessorTestUtils.searchClasspathBroken()) { assertTrue("Alas, compilation succeded", res); return; } assertFalse("Compilation should fail:\n" + os.toString(), res); assertTrue("because of missing icon:\n" + os.toString(), os.toString().contains("iconBase")); assertTrue("because of missing icon:\n" + os.toString(), os.toString().contains("Cannot find resource pkg/none-existing.png")); } public void testIsSourceView() { int cnt = 0; for (MultiViewDescription d : MimeLookup.getLookup("text/plaintest").lookupAll(MultiViewDescription.class)) { cnt++; assertTrue( "All views in text/plaintest have source element: " + d, MultiViewCloneableTopComponent.isSourceView(d) ); } if (cnt == 0) { fail("There shall be at least one description"); } } public void testIconIsAlwaysTakenFromSourceView() throws Exception { InstanceContent ic = new InstanceContent(); Lookup lkp = new AbstractLookup(ic); ic.add(MultiViewEditorElementTest.createSupport(lkp)); final CloneableTopComponent tc = MultiViews.createCloneableMultiView("text/plaintest", new LP(lkp)); final CloneableEditorSupport.Pane p = (CloneableEditorSupport.Pane) tc; EventQueue.invokeAndWait(new Runnable() { @Override public void run() { p.updateName(); } }); assertNull("No icon yet", tc.getIcon()); MultiViewHandler handler = MultiViews.findMultiViewHandler(tc); final MultiViewPerspective[] two = handler.getPerspectives(); assertEquals("Two elements only" + Arrays.asList(two), 2, handler.getPerspectives().length); assertEquals("First one is source", "source", two[0].preferredID()); MultiViewDescription description = Accessor.DEFAULT.extractDescription(two[0]); assertTrue(description instanceof ContextAwareDescription); assertFalse("First one is not for split", ((ContextAwareDescription)description).isSplitDescription()); assertEquals("Second one is source", "source", two[1].preferredID()); description = Accessor.DEFAULT.extractDescription(two[1]); assertTrue(description instanceof ContextAwareDescription); assertTrue("Second one is for split", ((ContextAwareDescription)description).isSplitDescription()); handler.requestVisible(two[0]); class P implements PropertyChangeListener { int cnt; @Override public void propertyChange(PropertyChangeEvent evt) { cnt++; } } P listener = new P(); tc.addPropertyChangeListener("icon", listener); BufferedImage img = new BufferedImage(16, 16, BufferedImage.TYPE_BYTE_GRAY); ic.add(img); assertEquals("One change in listener", 1, listener.cnt); assertEquals("Image changed", img, tc.getIcon()); ic.remove(img); assertEquals("Second change in listener", 2, listener.cnt); assertNull("No icon again", tc.getIcon()); ((MultiViewCloneableTopComponent)tc).splitComponent(JSplitPane.HORIZONTAL_SPLIT, -1); handler.requestVisible(two[1]); ic.add(img); assertEquals("Third change in listener", 3, listener.cnt); assertEquals("Image changed", img, tc.getIcon()); ic.remove(img); assertEquals("Forth change in listener", 4, listener.cnt); assertNull("No icon again", tc.getIcon()); } public void testMultiViewsContextCreate() { InstanceContent ic = new InstanceContent(); Lookup lookup = new AbstractLookup(ic); TopComponent mvc = MultiViews.createMultiView("text/context", new LP(lookup)); assertNotNull("MultiViewComponent created", mvc); MultiViewHandler handler = MultiViews.findMultiViewHandler(mvc); assertNotNull("Handler found", handler); MultiViewPerspective[] arr = handler.getPerspectives(); assertEquals("Two perspetives found", 2, arr.length); assertEquals("Contextual", arr[0].getDisplayName()); assertEquals("Contextual", arr[1].getDisplayName()); MultiViewDescription description = Accessor.DEFAULT.extractDescription(arr[0]); assertTrue(description instanceof ContextAwareDescription); assertFalse("First one is not for split", ((ContextAwareDescription)description).isSplitDescription()); description = Accessor.DEFAULT.extractDescription(arr[1]); assertTrue(description instanceof ContextAwareDescription); assertTrue("Second one is for split", ((ContextAwareDescription)description).isSplitDescription()); mvc.open(); mvc.requestActive(); mvc.requestVisible(); handler.requestActive(arr[0]); assertNull("No integer now", mvc.getLookup().lookup(Integer.class)); ic.add(1); assertEquals("1 now", Integer.valueOf(1), mvc.getLookup().lookup(Integer.class)); ((MultiViewTopComponent)mvc).splitComponent(JSplitPane.HORIZONTAL_SPLIT, -1); ic.remove(1); handler.requestActive(arr[1]); assertNull("No integer now", mvc.getLookup().lookup(Integer.class)); ic.add(2); assertEquals("2 now", Integer.valueOf(2), mvc.getLookup().lookup(Integer.class)); } @MimeRegistration(mimeType="text/figaro", service=CloseOperationHandler.class) public static class CloseH implements CloseOperationHandler { static CloseOperationState[] globalElements; static Boolean retValue; @Override public boolean resolveCloseOperation(CloseOperationState[] elements) { assertNull("globalElement not specified yet", globalElements); assertNotNull("We know what to return", retValue); boolean r = retValue; retValue = null; globalElements = elements; return r; } } @MultiViewElement.Registration( displayName="org.netbeans.core.multiview.TestBundle#FIGARO", mimeType="text/figaro", persistenceType=TopComponent.PERSISTENCE_NEVER, preferredID="figaro" ) public static class MVE extends JPanel implements MultiViewElement { static CloseOperationState closeState; private JPanel toolbar = new JPanel(); public MVE() { } @Override public JComponent getVisualRepresentation() { return this; } @Override public JComponent getToolbarRepresentation() { return toolbar; } @Override public Action[] getActions() { return new Action[0]; } @Override public Lookup getLookup() { return Lookup.EMPTY; } @Override public void componentOpened() { } @Override public void componentClosed() { } @Override public void componentShowing() { } @Override public void componentHidden() { } @Override public void componentActivated() { } @Override public void componentDeactivated() { } @Override public UndoRedo getUndoRedo() { return UndoRedo.NONE; } @Override public void setMultiViewCallback(MultiViewElementCallback callback) { } @Override public CloseOperationState canCloseElement() { if (closeState != null) { return closeState; } return CloseOperationState.STATE_OK; } } // end of MVE @MultiViewElement.Registration( displayName="Contextual", mimeType="text/context", persistenceType=TopComponent.PERSISTENCE_ALWAYS, preferredID="context" ) public static CntxMVE create(Lookup lkp) { return new CntxMVE(lkp); } static class CntxMVE extends MVE { private Lookup context; public CntxMVE(Lookup context) { this.context = context; } public CntxMVE() { } @Override public Lookup getLookup() { return context; } } // end of CntxMVE @MultiViewElement.Registration( displayName="Source", mimeType="text/plaintest", persistenceType=TopComponent.PERSISTENCE_NEVER, preferredID="source" ) public static class SourceMVC extends MultiViewEditorElement implements LookupListener { private final Lookup.Result<Image> res; public SourceMVC(Lookup lookup) { super(lookup); res = lookup.lookupResult(Image.class); res.addLookupListener(this); resultChanged(null); } @Override public final void resultChanged(LookupEvent ev) { Collection<? extends Image> all = res.allInstances(); if (all.isEmpty()) { getComponent().setIcon(null); } else { getComponent().setIcon(all.iterator().next()); } } } public static class LP implements Lookup.Provider, Serializable { private static final Map<Integer,Lookup> map = new HashMap<Integer, Lookup>(); private final int cnt; public LP(Lookup lkp) { synchronized (map) { cnt = map.size() + 1; map.put(cnt, lkp); } } @Override public Lookup getLookup() { return map.get(cnt); } } public static final class DD extends DialogDisplayer { static int ret; static NotifyDescriptor d; @Override public Object notify(NotifyDescriptor descriptor) { assertNull("No descriptor yet", d); if (ret == -1) { fail("We should know what to return"); } d = descriptor; if (d.getOptions().length <= ret) { fail("not enough options. Need index " + ret + " but is just " + Arrays.toString(d.getOptions())); } Object obj = d.getOptions()[ret]; ret = -1; return obj; } @Override public Dialog createDialog(DialogDescriptor descriptor) { throw new UnsupportedOperationException("Not supported yet."); } } private static class CntAction extends AbstractAction { int cnt; @Override public void actionPerformed(ActionEvent e) { cnt++; } } }
10,520
359
from learntools.core import * import numpy as np import os class MyConfig(object): def __init__(self): self.columns = 7 self.rows = 6 self.inarow = 4 config = MyConfig() class MyBoard(object): def __init__(self, board, mark): self.board = board self.mark = mark def flip_mark(board): return list(np.where(np.array(board)==2, 1, np.array(board)*2)) def check_column(agent, my_board, true_column): sel_column = agent(my_board, config) reshaped_board = np.array(my_board.board).reshape([config.rows,config.columns]).__str__().replace('[', '').replace(']', '').replace('\n ','\n') assert sel_column == true_column, \ """For the game board below, the agent has mark {}, and the opponent has mark {}. \nThe agent should have selected column {}, but it selected column {}. \n(_Recall that column indexing starts at 0: so, column 0 is the leftmost column, and column 6 is the rightmost column._) \n`{}` """.format(my_board.mark, my_board.mark%2+1, true_column, sel_column, reshaped_board) pos_diag_board = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 2, 0, 0, 0, 0, 1, 2, 2, 0, 0, 0, 0, 2, 1, 2, 0, 0] pos_diag_col = 1 obs_pos_diag_win_1 = MyBoard(pos_diag_board, 1) obs_pos_diag_win_2 = MyBoard(flip_mark(pos_diag_board), 2) obs_pos_diag_block_1 = MyBoard(flip_mark(pos_diag_board), 1) obs_pos_diag_block_2 = MyBoard(pos_diag_board, 2) neg_diag_board = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 2, 1, 0, 0, 0, 0, 0, 2, 2, 1, 0, 0, 0, 0, 1, 1, 2, 0, 0] neg_diag_col = 5 obs_neg_diag_win_1 = MyBoard(neg_diag_board, 1) obs_neg_diag_win_2 = MyBoard(flip_mark(neg_diag_board), 2) obs_neg_diag_block_1 = MyBoard(flip_mark(neg_diag_board), 1) obs_neg_diag_block_2 = MyBoard(neg_diag_board, 2) horizontal_board = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 0, 0, 0, 0, 2, 1, 1, 1, 0, 0] horizontal_col = 5 obs_horizontal_win_1 = MyBoard(horizontal_board, 1) obs_horizontal_win_2 = MyBoard(flip_mark(horizontal_board), 2) obs_horizontal_block_1 = MyBoard(flip_mark(horizontal_board), 1) obs_horizontal_block_2 = MyBoard(horizontal_board, 2) vertical_board = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 2, 0, 0, 0, 0, 0, 1, 2, 2, 0, 0] vertical_col = 2 obs_vertical_win_1 = MyBoard(vertical_board, 1) obs_vertical_win_2 = MyBoard(flip_mark(vertical_board), 2) obs_vertical_block_1 = MyBoard(flip_mark(vertical_board), 1) obs_vertical_block_2 = MyBoard(vertical_board, 2) ################################################################################# class SelectWinning(CodingProblem): _var = "agent_q1" _hint = ("Use the `check_winning_move()` function, and set `piece=obs.mark`. You can check if " "the agent can win the game by dropping its piece in a specific column by supplying the column " "as the `col` argument to the function.") _solution = CS( """def agent_q1(obs, config): valid_moves = [col for col in range(config.columns) if obs.board[col] == 0] for col in valid_moves: if check_winning_move(obs, config, col, obs.mark): return col return random.choice(valid_moves) """) _var = 'agent_q1' def check(self, agent_q1): check_column(agent_q1, obs_pos_diag_win_1, pos_diag_col) check_column(agent_q1, obs_pos_diag_win_2, pos_diag_col) check_column(agent_q1, obs_neg_diag_win_1, neg_diag_col) check_column(agent_q1, obs_neg_diag_win_2, neg_diag_col) check_column(agent_q1, obs_horizontal_win_1, horizontal_col) check_column(agent_q1, obs_horizontal_win_2, horizontal_col) check_column(agent_q1, obs_vertical_win_1, vertical_col) check_column(agent_q1, obs_vertical_win_2, vertical_col) class BlockOpponent(CodingProblem): _hint = ("Start with the code from the agent you created above. To check if the opponent can " "win in its next move, use the same `check_winning_move()` function, and set `piece=obs.mark%2+1`.") _solution = CS( """def agent_q2(obs, config): valid_moves = [col for col in range(config.columns) if obs.board[col] == 0] for col in valid_moves: if check_winning_move(obs, config, col, obs.mark): return col for col in valid_moves: if check_winning_move(obs, config, col, obs.mark%2+1): return col return random.choice(valid_moves) """) _var = 'agent_q2' def check(self, agent_q2): # win check_column(agent_q2, obs_pos_diag_win_1, pos_diag_col) check_column(agent_q2, obs_pos_diag_win_2, pos_diag_col) check_column(agent_q2, obs_neg_diag_win_1, neg_diag_col) check_column(agent_q2, obs_neg_diag_win_2, neg_diag_col) check_column(agent_q2, obs_horizontal_win_1, horizontal_col) check_column(agent_q2, obs_horizontal_win_2, horizontal_col) check_column(agent_q2, obs_vertical_win_1, vertical_col) check_column(agent_q2, obs_vertical_win_2, vertical_col) # block check_column(agent_q2, obs_pos_diag_block_1, pos_diag_col) check_column(agent_q2, obs_pos_diag_block_2, pos_diag_col) check_column(agent_q2, obs_neg_diag_block_1, neg_diag_col) check_column(agent_q2, obs_neg_diag_block_2, neg_diag_col) check_column(agent_q2, obs_horizontal_block_1, horizontal_col) check_column(agent_q2, obs_horizontal_block_2, horizontal_col) check_column(agent_q2, obs_vertical_block_1, vertical_col) check_column(agent_q2, obs_vertical_block_2, vertical_col) class WhyNotOptimal(ThoughtExperiment): board1 = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 0, 0, 0, 0, 1, 1, 1, 0, 0] board1_shaped = np.array(board1).reshape([config.rows,config.columns]).__str__().replace('[', '').replace(']', '').replace('\n ','\n') board2 = [2, 1, 2, 2, 2, 0, 2, 1, 2, 1, 1, 1, 0, 1, 2, 1, 2, 2, 2, 0, 2, 1, 2, 1, 1, 1, 0, 1, 2, 1, 2, 2, 2, 0, 2, 1, 2, 1, 1, 2, 0, 1] board2_shaped = np.array(board2).reshape([config.rows,config.columns]).__str__().replace('[', '').replace(']', '').replace('\n ','\n') _hint = \ """\ Consider this board: \n `{}`\n or this board: \n `{}` """.format(board1_shaped, board2_shaped) _solution = ( """The agent can still lose the game, if - the opponent has set up the board so that it can win in the next move by dropping a disc in any of 2 or more columns, or - the only move that is available to the agent is one where, once played, the opponent can win in the next move. """) class CreateAgentEx1(CodingProblem): _hint = "Follow the instructions to create an agent." _solution = "Follow the instructions to create an agent." _congrats = "Thank you for creating an agent!" _correct_message = "" def check(self): pass class SubmissionEx1(CodingProblem): _hint = "Follow the instructions to create a submission file." _solution = "Follow the instructions to create a submission file." _congrats = "Thank you for creating a submission file!" _correct_message = "" def check(self): assert os.path.exists("./submission.py"), "You do not yet have a submission file." qvars = bind_exercises(globals(), [ SelectWinning, BlockOpponent, WhyNotOptimal, CreateAgentEx1, SubmissionEx1 ], var_format='q_{n}', ) __all__ = list(qvars)
3,642
1,561
<reponame>anshuman35/java-docs-samples /* * Copyright 2016 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.example.compute.sendgrid; import com.sendgrid.Method; import com.sendgrid.Request; import com.sendgrid.Response; import com.sendgrid.SendGrid; import com.sendgrid.helpers.mail.Mail; import com.sendgrid.helpers.mail.objects.Content; import com.sendgrid.helpers.mail.objects.Email; import java.io.IOException; // [START example] public class SendEmailServlet { static final String SENDGRID_API_KEY = "YOUR-SENDGRID-API-KEY"; static final String SENDGRID_SENDER = "YOUR-SENDGRID-FROM-EMAIL"; static final String TO_EMAIL = "DESTINATION-EMAIL"; public static void main(String[] args) throws IOException { // Set content for request. Email to = new Email(TO_EMAIL); Email from = new Email(SENDGRID_SENDER); String subject = "This is a test email"; Content content = new Content("text/plain", "Example text body."); Mail mail = new Mail(from, subject, to, content); // Instantiates SendGrid client. SendGrid sendgrid = new SendGrid(SENDGRID_API_KEY); // Instantiate SendGrid request. Request request = new Request(); // Set request configuration. request.setMethod(Method.POST); request.setEndpoint("mail/send"); request.setBody(mail.build()); // Use the client to send the API request. Response response = sendgrid.api(request); if (response.getStatusCode() != 202) { System.out.print(String.format("An error occurred: %s", response.getStatusCode())); return; } System.out.print("Email sent."); } } // [END example]
691
338
<gh_stars>100-1000 """ bio submodule. """ from .bio_data import * from .bio_rsp import * from .bio_ecg_preprocessing import * from .bio_ecg import * from .bio_eda import * from .bio_emg import * from .bio_meta import *
90
1,253
#include<bits/stdc++.h> #include<graphics.h> #define ll long long int #define ld long double using namespace std; int main() { int gd = DETECT, gm, tmp = 0; ld dx, dy, d1, d2, x = 0, y, rx, ry, xc, yc; cin >> rx >> ry >> xc >> yc; y = ry; //declare all variables before it initgraph(&gd,&gm, NULL); //draw here d1 = (ry * ry) - (rx * rx * ry) + (0.25 * rx * rx); dx = 2 * ry * ry * x; dy = 2 * rx * rx * y; while (dx < dy) { putpixel(100 + x + xc, 100 + y + yc, 15); putpixel(100 - x + xc, 100 + y + yc, 15); putpixel(100 + x + xc, 100 - y + yc, 15); putpixel(100 - x + xc, 100 - y + yc, 15); if (d1 < 0) { x++; dx = dx + (2 * ry * ry); d1 = d1 + dx + (ry * ry); } else { x++; y--; dx = dx + (2 * ry * ry); dy = dy - (2 * rx * rx); d1 = d1 + dx - dy + (ry * ry); } delay(300); } d2 = ((ry * ry) * ((x + 0.5) * (x + 0.5))) + ((rx * rx) * ((y - 1) * (y - 1))) - (rx * rx * ry * ry); while (y >= 0) { putpixel(100 + x + xc, 100 + y + yc, 15); putpixel(100 - x + xc, 100 + y + yc, 15); putpixel(100 + x + xc, 100 - y + yc, 15); putpixel(100 - x + xc, 100 - y + yc, 15); if (d2 > 0) { y--; dy = dy - (2 * rx * rx); d2 = d2 + (rx * rx) - dy; } else { y--; x++; dx = dx + (2 * ry * ry); dy = dy - (2 * rx * rx); d2 = d2 + dx - dy + (rx * rx); } delay(300); } //draw ends getche(); closegraph(); return 0; }
974
428
<reponame>Akash1S/meethub from django.test import TestCase from django.contrib.auth.models import User from userprofile.models import Profile class ProfileModelTest(TestCase): @classmethod def setUpTestData(cls): user = User.objects.create(username='iyanu', password=<PASSWORD>, email='<EMAIL>') Profile.objects.create(user=user, date_of_birth='2018-05-18', photo='') def test_user_label(self): profile = Profile.objects.get(date_of_birth='2018-05-18') field_label = profile._meta.get_field('user').verbose_name self.assertEquals(field_label, 'user') def test_date_of_birth_label(self): profile = Profile.objects.get(date_of_birth='2018-05-18') field_label = profile._meta.get_field('date_of_birth').verbose_name self.assertEquals(field_label, 'date of birth') def test_photo_label(self): profile = Profile.objects.get(date_of_birth='2018-05-18') field_label = profile._meta.get_field('photo').verbose_name self.assertEquals(field_label, 'image') def test_profile_object_name(self): profile = Profile.objects.get(date_of_birth='2018-05-18') expected_object_name = '{0}\'s profile'.format(profile.user.username) self.assertEquals(expected_object_name, str(profile)) def test_get_absolute_url(self): profile = Profile.objects.get(date_of_birth='2018-05-18') self.assertEquals(profile.get_absolute_url(), '/userprofile/detail/8/') def test_get_absolute_url_not_none(self): profile = Profile.objects.get(date_of_birth='2018-05-18') self.assertIsNotNone(profile.get_absolute_url()) def test_verbose_name_plural(self): self.assertEquals(str(Profile._meta.verbose_name_plural), 'profiles') def test_get_date_of_birth(self): profile = Profile.objects.get(date_of_birth='2018-05-18') self.assertEquals(profile.get_date_of_birth(), '2018, 5, 18')
788
868
<gh_stars>100-1000 /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.activemq; import javax.jms.TextMessage; /** * */ public class JmsTopicSendSameMessageTest extends JmsTopicSendReceiveWithTwoConnectionsTest { private static final org.apache.commons.logging.Log LOG = org.apache.commons.logging.LogFactory.getLog(JmsTopicSendSameMessageTest.class); @Override public void testSendReceive() throws Exception { messages.clear(); TextMessage message = session.createTextMessage(); for (int i = 0; i < data.length; i++) { message.setText(data[i]); message.setStringProperty("stringProperty", data[i]); message.setIntProperty("intProperty", i); if (verbose) { LOG.info("About to send a message: " + message + " with text: " + data[i]); } producer.send(producerDestination, message); } assertMessagesAreReceived(); } }
528
852
#ifndef HeterogeneousCore_CUDAUtilities_interface_HistoContainer_h #define HeterogeneousCore_CUDAUtilities_interface_HistoContainer_h #include "HeterogeneousCore/CUDAUtilities/interface/OneToManyAssoc.h" namespace cms { namespace cuda { template <typename Histo, typename T> __global__ void countFromVector(Histo *__restrict__ h, uint32_t nh, T const *__restrict__ v, uint32_t const *__restrict__ offsets) { int first = blockDim.x * blockIdx.x + threadIdx.x; for (int i = first, nt = offsets[nh]; i < nt; i += gridDim.x * blockDim.x) { auto off = cuda_std::upper_bound(offsets, offsets + nh + 1, i); assert((*off) > 0); int32_t ih = off - offsets - 1; assert(ih >= 0); assert(ih < int(nh)); (*h).count(v[i], ih); } } template <typename Histo, typename T> __global__ void fillFromVector(Histo *__restrict__ h, uint32_t nh, T const *__restrict__ v, uint32_t const *__restrict__ offsets) { int first = blockDim.x * blockIdx.x + threadIdx.x; for (int i = first, nt = offsets[nh]; i < nt; i += gridDim.x * blockDim.x) { auto off = cuda_std::upper_bound(offsets, offsets + nh + 1, i); assert((*off) > 0); int32_t ih = off - offsets - 1; assert(ih >= 0); assert(ih < int(nh)); (*h).fill(v[i], i, ih); } } template <typename Histo, typename T> inline __attribute__((always_inline)) void fillManyFromVector(Histo *__restrict__ h, uint32_t nh, T const *__restrict__ v, uint32_t const *__restrict__ offsets, int32_t totSize, int nthreads, typename Histo::index_type *mem, cudaStream_t stream #ifndef __CUDACC__ = cudaStreamDefault #endif ) { typename Histo::View view = {h, nullptr, mem, -1, totSize}; launchZero(view, stream); #ifdef __CUDACC__ auto nblocks = (totSize + nthreads - 1) / nthreads; assert(nblocks > 0); countFromVector<<<nblocks, nthreads, 0, stream>>>(h, nh, v, offsets); cudaCheck(cudaGetLastError()); launchFinalize(view, stream); fillFromVector<<<nblocks, nthreads, 0, stream>>>(h, nh, v, offsets); cudaCheck(cudaGetLastError()); #else countFromVector(h, nh, v, offsets); h->finalize(); fillFromVector(h, nh, v, offsets); #endif } // iteratate over N bins left and right of the one containing "v" template <typename Hist, typename V, typename Func> __host__ __device__ __forceinline__ void forEachInBins(Hist const &hist, V value, int n, Func func) { int bs = Hist::bin(value); int be = std::min(int(Hist::nbins() - 1), bs + n); bs = std::max(0, bs - n); assert(be >= bs); for (auto pj = hist.begin(bs); pj < hist.end(be); ++pj) { func(*pj); } } // iteratate over bins containing all values in window wmin, wmax template <typename Hist, typename V, typename Func> __host__ __device__ __forceinline__ void forEachInWindow(Hist const &hist, V wmin, V wmax, Func const &func) { auto bs = Hist::bin(wmin); auto be = Hist::bin(wmax); assert(be >= bs); for (auto pj = hist.begin(bs); pj < hist.end(be); ++pj) { func(*pj); } } template <typename T, // the type of the discretized input values uint32_t NBINS, // number of bins int32_t SIZE, // max number of element. If -1 is initialized at runtime using external storage uint32_t S = sizeof(T) * 8, // number of significant bits in T typename I = uint32_t, // type stored in the container (usually an index in a vector of the input values) uint32_t NHISTS = 1 // number of histos stored > class HistoContainer : public OneToManyAssoc<I, NHISTS * NBINS + 1, SIZE> { public: using Base = OneToManyAssoc<I, NHISTS * NBINS + 1, SIZE>; using View = typename Base::View; using Counter = typename Base::Counter; using index_type = typename Base::index_type; using UT = typename std::make_unsigned<T>::type; static constexpr uint32_t ilog2(uint32_t v) { constexpr uint32_t b[] = {0x2, 0xC, 0xF0, 0xFF00, 0xFFFF0000}; constexpr uint32_t s[] = {1, 2, 4, 8, 16}; uint32_t r = 0; // result of log2(v) will go here for (auto i = 4; i >= 0; i--) if (v & b[i]) { v >>= s[i]; r |= s[i]; } return r; } static constexpr uint32_t sizeT() { return S; } static constexpr uint32_t nbins() { return NBINS; } static constexpr uint32_t nhists() { return NHISTS; } static constexpr uint32_t totbins() { return NHISTS * NBINS + 1; } static constexpr uint32_t nbits() { return ilog2(NBINS - 1) + 1; } // static_assert(int32_t(totbins())==Base::ctNOnes()); static constexpr auto histOff(uint32_t nh) { return NBINS * nh; } static constexpr UT bin(T t) { constexpr uint32_t shift = sizeT() - nbits(); constexpr uint32_t mask = (1 << nbits()) - 1; return (t >> shift) & mask; } __host__ __device__ __forceinline__ void count(T t) { uint32_t b = bin(t); assert(b < nbins()); Base::atomicIncrement(this->off[b]); } __host__ __device__ __forceinline__ void fill(T t, index_type j) { uint32_t b = bin(t); assert(b < nbins()); auto w = Base::atomicDecrement(this->off[b]); assert(w > 0); this->content[w - 1] = j; } __host__ __device__ __forceinline__ void count(T t, uint32_t nh) { uint32_t b = bin(t); assert(b < nbins()); b += histOff(nh); assert(b < totbins()); Base::atomicIncrement(this->off[b]); } __host__ __device__ __forceinline__ void fill(T t, index_type j, uint32_t nh) { uint32_t b = bin(t); assert(b < nbins()); b += histOff(nh); assert(b < totbins()); auto w = Base::atomicDecrement(this->off[b]); assert(w > 0); this->content[w - 1] = j; } }; } // namespace cuda } // namespace cms #endif // HeterogeneousCore_CUDAUtilities_interface_HistoContainer_h
3,525
728
package org.sirix.gui.view.splines; import java.util.List; import org.sirix.gui.view.sunburst.AbstractSunburstGUI; import processing.core.PGraphics; import processing.core.PVector; public interface Spline { float b(int i, float t); PVector p(int i, float t, final List<PVector> paramPath); void draw(final AbstractSunburstGUI pGUI, final PGraphics paramGraphic, final List<PVector> paramPath); }
157
348
<reponame>chamberone/Leaflet.PixiOverlay {"nom":"Empuré","circ":"3ème circonscription","dpt":"Charente","inscrits":88,"abs":37,"votants":51,"blancs":3,"nuls":2,"exp":46,"res":[{"nuance":"SOC","nom":"M. <NAME>","voix":30},{"nuance":"REM","nom":"Mme <NAME>","voix":16}]}
114
372
<gh_stars>100-1000 /* -*- mode: c; c-basic-offset: 4; indent-tabs-mode: nil -*- */ /* * lib/krb5/os/sn2princ.c * * Copyright 1991,2002 by the Massachusetts Institute of Technology. * All Rights Reserved. * * Export of this software from the United States of America may * require a specific license from the United States Government. * It is the responsibility of any person or organization contemplating * export to obtain such a license before exporting. * * WITHIN THAT CONSTRAINT, permission to use, copy, modify, and * distribute this software and its documentation for any purpose and * without fee is hereby granted, provided that the above copyright * notice appear in all copies and that both that copyright notice and * this permission notice appear in supporting documentation, and that * the name of M.I.T. not be used in advertising or publicity pertaining * to distribution of the software without specific, written prior * permission. Furthermore if you modify this software you must label * your software as modified software and not distribute it in such a * fashion that it might be confused with the original M.I.T. software. * M.I.T. makes no representations about the suitability of * this software for any purpose. It is provided "as is" without express * or implied warranty. * * * Convert a hostname and service name to a principal in the "standard" * form. */ #include "k5-int.h" #include "os-proto.h" #include "fake-addrinfo.h" #include <ctype.h> #ifdef HAVE_SYS_PARAM_H #include <sys/param.h> #endif #if !defined(DEFAULT_RDNS_LOOKUP) #define DEFAULT_RDNS_LOOKUP 1 #endif static int maybe_use_reverse_dns (krb5_context context, int defalt) { krb5_error_code code; char * value = NULL; int use_rdns = 0; code = profile_get_string(context->profile, KRB5_CONF_LIBDEFAULTS, KRB5_CONF_RDNS, 0, 0, &value); if (code) return defalt; if (value == 0) return defalt; use_rdns = _krb5_conf_boolean(value); profile_release_string(value); return use_rdns; } krb5_error_code KRB5_CALLCONV krb5_sname_to_principal(krb5_context context, const char *hostname, const char *sname, krb5_int32 type, krb5_principal *ret_princ) { char **hrealms, *realm, *remote_host; krb5_error_code retval; register char *cp; char localname[MAXHOSTNAMELEN]; #ifdef DEBUG_REFERRALS printf("krb5_sname_to_principal(host=%s, sname=%s, type=%d)\n",hostname,sname,type); printf(" name types: 0=unknown, 3=srv_host\n"); #endif if ((type == KRB5_NT_UNKNOWN) || (type == KRB5_NT_SRV_HST)) { /* if hostname is NULL, use local hostname */ if (! hostname) { if (gethostname(localname, MAXHOSTNAMELEN)) return SOCKET_ERRNO; hostname = localname; } /* if sname is NULL, use "host" */ if (! sname) sname = "host"; /* copy the hostname into non-volatile storage */ if (type == KRB5_NT_SRV_HST) { struct addrinfo *ai, hints; int err; char hnamebuf[NI_MAXHOST]; /* Note that the old code would accept numeric addresses, and if the gethostbyaddr step could convert them to real hostnames, you could actually get reasonable results. If the mapping failed, you'd get dotted triples as realm names. *sigh* The latter has been fixed in hst_realm.c, but we should keep supporting numeric addresses if they do have hostnames associated. */ memset(&hints, 0, sizeof(hints)); hints.ai_family = AF_INET; hints.ai_flags = AI_CANONNAME; try_getaddrinfo_again: err = getaddrinfo(hostname, 0, &hints, &ai); if (err) { #ifdef DEBUG_REFERRALS printf("sname_to_princ: probably punting due to bad hostname of %s\n",hostname); #endif if (hints.ai_family == AF_INET) { /* Just in case it's an IPv6-only name. */ hints.ai_family = 0; goto try_getaddrinfo_again; } return KRB5_ERR_BAD_HOSTNAME; } remote_host = strdup(ai->ai_canonname ? ai->ai_canonname : hostname); if (!remote_host) { freeaddrinfo(ai); return ENOMEM; } if (maybe_use_reverse_dns(context, DEFAULT_RDNS_LOOKUP)) { /* * Do a reverse resolution to get the full name, just in * case there's some funny business going on. If there * isn't an in-addr record, give up. */ /* XXX: This is *so* bogus. There are several cases where this won't get us the canonical name of the host, but this is what we've trained people to expect. We'll probably fix it at some point, but let's try to preserve the current behavior and only shake things up once when it comes time to fix this lossage. */ err = getnameinfo(ai->ai_addr, ai->ai_addrlen, hnamebuf, sizeof(hnamebuf), 0, 0, NI_NAMEREQD); freeaddrinfo(ai); if (err == 0) { free(remote_host); remote_host = strdup(hnamebuf); if (!remote_host) return ENOMEM; } } else freeaddrinfo(ai); } else /* type == KRB5_NT_UNKNOWN */ { remote_host = strdup(hostname); } if (!remote_host) return ENOMEM; #ifdef DEBUG_REFERRALS printf("sname_to_princ: hostname <%s> after rdns processing\n",remote_host); #endif if (type == KRB5_NT_SRV_HST) for (cp = remote_host; *cp; cp++) if (isupper((unsigned char) (*cp))) *cp = tolower((unsigned char) (*cp)); /* * Windows NT5's broken resolver gratuitously tacks on a * trailing period to the hostname (at least it does in * Beta2). Find and remove it. */ if (remote_host[0]) { cp = remote_host + strlen(remote_host)-1; if (*cp == '.') *cp = 0; } if ((retval = krb5_get_host_realm(context, remote_host, &hrealms))) { free(remote_host); return retval; } #ifdef DEBUG_REFERRALS printf("sname_to_princ: realm <%s> after krb5_get_host_realm\n",hrealms[0]); #endif if (!hrealms[0]) { free(remote_host); free(hrealms); return KRB5_ERR_HOST_REALM_UNKNOWN; } realm = hrealms[0]; retval = krb5_build_principal(context, ret_princ, strlen(realm), realm, sname, remote_host, (char *)0); if (retval == 0) krb5_princ_type(context, *ret_princ) = type; #ifdef DEBUG_REFERRALS printf("krb5_sname_to_principal returning\n"); printf("realm: <%s>, sname: <%s>, remote_host: <%s>\n", realm,sname,remote_host); krb5int_dbgref_dump_principal("krb5_sname_to_principal",*ret_princ); #endif free(remote_host); krb5_free_host_realm(context, hrealms); return retval; } else { return KRB5_SNAME_UNSUPP_NAMETYPE; } }
3,615
36,052
<gh_stars>1000+ [Subtables] ligatures: [ "'dlig' Discretionary Ligatures lookup 21 subtable", "Ligature Substitution lookup 23 subtable" ]
53
809
<reponame>nikitavlaev/embox<filename>src/tests/mem/page_allocator.c /** * @file * * @brief * * @date 12.07.2018 * @author <NAME> */ #include <embox/test.h> #include <mem/page.h> EMBOX_TEST_SUITE("page_allocator_init test"); TEST_CASE("Init page_allocator with one page") { struct page_allocator *allocator; char buff[0x10]; allocator = page_allocator_init(buff, 0x10, 0x10); test_assert_null(allocator); } TEST_CASE("Init page_allocator with len < page_size") { struct page_allocator *allocator; char buff[0x100]; allocator = page_allocator_init(buff, 0x10, 0x100); test_assert_null(allocator); }
254
648
{"resourceType":"DataElement","id":"Medication.package.batch.expirationDate","meta":{"lastUpdated":"2017-04-19T07:44:43.294+10:00"},"url":"http://hl7.org/fhir/DataElement/Medication.package.batch.expirationDate","status":"draft","experimental":true,"stringency":"fully-specified","element":[{"id":"Medication.package.batch.expirationDate","path":"Medication.package.batch.expirationDate","short":"When batch will expire","definition":"When this specific batch of product will expire.","min":0,"max":"1","type":[{"code":"dateTime"}],"mapping":[{"identity":"script10.6","map":"no mapping"},{"identity":"v2","map":"RXA-16 Substance Expiration Date / RXG-20 Substance Expiration Date"},{"identity":"rim","map":"participation[typeCode=CSM].role[classCode=INST].scopedRole.scoper[classCode=MMAT].expirationTime"}]}]}
232
2,151
/* 7zAlloc.h -- Allocation functions 2013-03-25 : <NAME> : Public domain */ #ifndef __7Z_ALLOC_H #define __7Z_ALLOC_H #include <stdlib.h> #ifdef __cplusplus extern "C" { #endif void *SzAlloc(void *p, size_t size); void SzFree(void *p, void *address); void *SzAllocTemp(void *p, size_t size); void SzFreeTemp(void *p, void *address); #ifdef __cplusplus } #endif #endif
162
25,360
<reponame>spod-ai/jeecg-boot package org.jeecg.modules.system.util; import org.springframework.web.util.HtmlUtils; import java.util.regex.Pattern; /** * @Description: 工具类XSSUtils,现在的做法是替换成空字符,CSDN的是进行转义,比如文字开头的"<"转成&lt; * @author: lsq * @date: 2021年07月26日 19:13 */ public class XSSUtils { public static String striptXSS(String value) { if (value != null) { value = value.replaceAll(" ", ""); Pattern scriptPattern = Pattern.compile("<script>(.*?)</script>", Pattern.CASE_INSENSITIVE); value = scriptPattern.matcher(value).replaceAll(""); scriptPattern = Pattern.compile("src[\r\n]*=[\r\n]*\\\'(.*?)\\\'", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL); value = scriptPattern.matcher(value).replaceAll(""); scriptPattern = Pattern.compile("src[\r\n]*=[\r\n]*\\\"(.*?)\\\"", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL); value = scriptPattern.matcher(value).replaceAll(""); scriptPattern = Pattern.compile("</script>", Pattern.CASE_INSENSITIVE); value = scriptPattern.matcher(value).replaceAll(""); scriptPattern = Pattern.compile("<script(.*?)>", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL); value = scriptPattern.matcher(value).replaceAll(""); scriptPattern = Pattern.compile("eval\\((.*?)\\)", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL); value = scriptPattern.matcher(value).replaceAll(""); scriptPattern = Pattern.compile("e­xpression\\((.*?)\\)", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL); value = scriptPattern.matcher(value).replaceAll(""); scriptPattern = Pattern.compile("javascript:", Pattern.CASE_INSENSITIVE); value = scriptPattern.matcher(value).replaceAll(""); scriptPattern = Pattern.compile("vbscript:", Pattern.CASE_INSENSITIVE); value = scriptPattern.matcher(value).replaceAll(""); scriptPattern = Pattern.compile("onload(.*?)=", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL); value = scriptPattern.matcher(value).replaceAll(""); } return HtmlUtils.htmlEscape(value); } public static void main(String[] args) { String s = striptXSS("<img src=x onload=alert(111).*?><script></script>javascript:eval()\\\\."); System.err.println("s======>" + s); } }
1,096
412
// This is C99, but currently only works with clang. // gcc and Visual Studio appear to hard-wire FLT_ROUNDS to 1. #ifdef __clang__ #include <assert.h> #include <fenv.h> #include <float.h> int main() { fesetround(FE_DOWNWARD); assert(FLT_ROUNDS == 3); fesetround(FE_TONEAREST); assert(FLT_ROUNDS == 1); fesetround(FE_TOWARDZERO); assert(FLT_ROUNDS == 0); fesetround(FE_UPWARD); assert(FLT_ROUNDS == 2); } #else int main() { } #endif
200
28,056
package com.alibaba.json.bvt; import org.junit.Assert; import com.alibaba.fastjson.JSON; import junit.framework.TestCase; public class StringFieldTest_special_reader extends TestCase { public void test_special() throws Exception { Model model = new Model(); model.name = "a\\bc"; String text = JSON.toJSONString(model); Assert.assertEquals("{\"name\":\"a\\\\bc\"}", text); Model model2 = JSON.parseObject(text, Model.class); Assert.assertEquals(model.name, model2.name); } public void test_special_2() throws Exception { Model model = new Model(); model.name = "a\\bc\""; String text = JSON.toJSONString(model); Assert.assertEquals("{\"name\":\"a\\\\bc\\\"\"}", text); Model model2 = JSON.parseObject(text, Model.class); Assert.assertEquals(model.name, model2.name); } public static class Model { public String name; } }
386
1,144
<gh_stars>1000+ /* SPDX-License-Identifier: GPL-2.0+ */ /* * (C) Copyright 2001 * <NAME>, DENX Software Engineering, <EMAIL>. */ #ifndef __rtc_def_h #define __rtc_def_h /* * The struct used to pass data from the generic interface code to * the hardware dependend low-level code ande vice versa. Identical * to struct rtc_time used by the Linux kernel. * * Note that there are small but significant differences to the * common "struct time": * * struct time: struct rtc_time: * tm_mon 0 ... 11 1 ... 12 * tm_year years since 1900 years since 0 */ struct rtc_time { int tm_sec; int tm_min; int tm_hour; int tm_mday; int tm_mon; int tm_year; int tm_wday; int tm_yday; int tm_isdst; }; #endif
280
466
<reponame>tkerr97/nullpomino package net.omegaboshi.nullpomino.game.subsystem.randomizer; import mu.nu.nullpo.game.component.Piece; public abstract class LimitedHistoryRandomizer extends Randomizer { int[] history; int id; int numrolls; boolean firstPiece; public LimitedHistoryRandomizer() { super(); } public LimitedHistoryRandomizer(boolean[] pieceEnable, long seed) { super(pieceEnable, seed); } public void init() { firstPiece = true; } public int next() { if (firstPiece && !isPieceSZOOnly()) { do { id = r.nextInt(pieces.length); } while (pieces[id] == Piece.PIECE_O || pieces[id] == Piece.PIECE_Z || pieces[id] == Piece.PIECE_S); firstPiece = false; } else { for (int i = 0; i < numrolls; i++) { id = r.nextInt(pieces.length); if (!(pieces[id] == history[0] || pieces[id] == history[1] || pieces[id] == history[2] || pieces[id] == history[3])) { break; } } } for (int i = 3; i > 0; i--) { history[i] = history[i-1]; } history[0] = pieces[id]; return pieces[id]; } }
493
1,330
<reponame>denissnykio/struts<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 com.opensymphony.xwork2.ognl.accessor; import com.opensymphony.xwork2.conversion.impl.XWorkConverter; import com.opensymphony.xwork2.util.reflection.ReflectionContextState; import ognl.ObjectPropertyAccessor; import ognl.OgnlException; import java.util.Map; /** * @author Gabe */ public class XWorkObjectPropertyAccessor extends ObjectPropertyAccessor { @Override public Object getProperty(Map context, Object target, Object oname) throws OgnlException { //set the last set objects in the context //so if the next objects accessed are //Maps or Collections they can use the information //to determine conversion types context.put(XWorkConverter.LAST_BEAN_CLASS_ACCESSED, target.getClass()); context.put(XWorkConverter.LAST_BEAN_PROPERTY_ACCESSED, oname.toString()); ReflectionContextState.updateCurrentPropertyPath(context, oname); return super.getProperty(context, target, oname); } }
566
1,658
/* Copyright 2015 shizhefei(LuckyJayce) 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.shizhefei.mvc.data; public class Data4<VALUE1, VALUE2, VALUE3, VALUE4> { private VALUE1 value1; private VALUE2 value2; private VALUE3 value3; private VALUE4 value4; public Data4() { super(); } public Data4(VALUE1 value1, VALUE2 value2, VALUE3 value3, VALUE4 value4) { super(); this.value1 = value1; this.value2 = value2; this.value3 = value3; this.value4 = value4; } public VALUE4 getValue4() { return value4; } public void setValue4(VALUE4 value4) { this.value4 = value4; } public VALUE1 getValue1() { return value1; } public void setValue1(VALUE1 value1) { this.value1 = value1; } public VALUE2 getValue2() { return value2; } public void setValue2(VALUE2 value2) { this.value2 = value2; } public VALUE3 getValue3() { return value3; } public void setValue3(VALUE3 value3) { this.value3 = value3; } }
515
1,068
#include "drv8301.hpp" #include "utils.hpp" #include "cmsis_os.h" #include "board.h" const SPI_InitTypeDef Drv8301::spi_config_ = { .Mode = SPI_MODE_MASTER, .Direction = SPI_DIRECTION_2LINES, .DataSize = SPI_DATASIZE_16BIT, .CLKPolarity = SPI_POLARITY_LOW, .CLKPhase = SPI_PHASE_2EDGE, .NSS = SPI_NSS_SOFT, .BaudRatePrescaler = SPI_BAUDRATEPRESCALER_16, .FirstBit = SPI_FIRSTBIT_MSB, .TIMode = SPI_TIMODE_DISABLE, .CRCCalculation = SPI_CRCCALCULATION_DISABLE, .CRCPolynomial = 10, }; bool Drv8301::config(float requested_gain, float* actual_gain) { // Calculate gain setting: Snap down to have equal or larger range as // requested or largest possible range otherwise // for reference: // 20V/V on 500uOhm gives a range of +/- 150A // 40V/V on 500uOhm gives a range of +/- 75A // 20V/V on 666uOhm gives a range of +/- 110A // 40V/V on 666uOhm gives a range of +/- 55A uint16_t gain_setting = 3; float gain_choices[] = {10.0f, 20.0f, 40.0f, 80.0f}; while (gain_setting && (gain_choices[gain_setting] > requested_gain)) { gain_setting--; } if (actual_gain) { *actual_gain = gain_choices[gain_setting]; } RegisterFile new_config; new_config.control_register_1 = (21 << 6) // Overcurrent set to approximately 150A at 100degC. This may need tweaking. | (0b01 << 4) // OCP_MODE: latch shut down | (0b0 << 3) // 6x PWM mode | (0b0 << 2) // don't reset latched faults | (0b00 << 0); // gate-drive peak current: 1.7A new_config.control_register_2 = (0b0 << 6) // OC_TOFF: cycle by cycle | (0b00 << 4) // calibration off (normal operation) | (gain_setting << 2) // select gain | (0b00 << 0); // report both over temperature and over current on nOCTW pin bool regs_equal = (regs_.control_register_1 == new_config.control_register_1) && (regs_.control_register_2 == new_config.control_register_2); if (!regs_equal) { regs_ = new_config; state_ = kStateUninitialized; enable_gpio_.write(false); } return true; } bool Drv8301::init() { uint16_t val; if (state_ == kStateReady) { return true; } // Reset DRV chip. The enable pin also controls the SPI interface, not only // the driver stages. enable_gpio_.write(false); delay_us(40); // mimumum pull-down time for full reset: 20us state_ = kStateUninitialized; // make is_ready() ignore transient errors before registers are set up enable_gpio_.write(true); osDelay(20); // t_spi_ready, max = 10ms // Write current configuration bool wrote_regs = write_reg(kRegNameControl1, regs_.control_register_1) && write_reg(kRegNameControl1, regs_.control_register_1) && write_reg(kRegNameControl1, regs_.control_register_1) && write_reg(kRegNameControl1, regs_.control_register_1) && write_reg(kRegNameControl1, regs_.control_register_1) // the write operation tends to be ignored if only done once (not sure why) && write_reg(kRegNameControl2, regs_.control_register_2); if (!wrote_regs) { return false; } // Wait for configuration to be applied delay_us(100); state_ = kStateStartupChecks; bool is_read_regs = read_reg(kRegNameControl1, &val) && (val == regs_.control_register_1) && read_reg(kRegNameControl2, &val) && (val == regs_.control_register_2); if (!is_read_regs) { return false; } if (get_error() != FaultType_NoFault) { return false; } // There could have been an nFAULT edge meanwhile. In this case we shouldn't // consider the driver ready. CRITICAL_SECTION() { if (state_ == kStateStartupChecks) { state_ = kStateReady; } } return state_ == kStateReady; } void Drv8301::do_checks() { if (state_ != kStateUninitialized && !nfault_gpio_.read()) { state_ = kStateUninitialized; } } bool Drv8301::is_ready() { return state_ == kStateReady; } Drv8301::FaultType_e Drv8301::get_error() { uint16_t fault1, fault2; if (!read_reg(kRegNameStatus1, &fault1) || !read_reg(kRegNameStatus2, &fault2)) { return (FaultType_e)0xffffffff; } return (FaultType_e)((uint32_t)fault1 | ((uint32_t)(fault2 & 0x0080) << 16)); } bool Drv8301::read_reg(const RegName_e regName, uint16_t* data) { tx_buf_ = build_ctrl_word(DRV8301_CtrlMode_Read, regName, 0); if (!spi_arbiter_->transfer(spi_config_, ncs_gpio_, (uint8_t *)(&tx_buf_), nullptr, 1, 1000)) { return false; } delay_us(1); tx_buf_ = build_ctrl_word(DRV8301_CtrlMode_Read, regName, 0); rx_buf_ = 0xffff; if (!spi_arbiter_->transfer(spi_config_, ncs_gpio_, (uint8_t *)(&tx_buf_), (uint8_t *)(&rx_buf_), 1, 1000)) { return false; } delay_us(1); if (rx_buf_ == 0xbeef) { return false; } if (data) { *data = rx_buf_ & 0x07FF; } return true; } bool Drv8301::write_reg(const RegName_e regName, const uint16_t data) { // Do blocking write tx_buf_ = build_ctrl_word(DRV8301_CtrlMode_Write, regName, data); if (!spi_arbiter_->transfer(spi_config_, ncs_gpio_, (uint8_t *)(&tx_buf_), nullptr, 1, 1000)) { return false; } delay_us(1); return true; }
2,461
5,053
#!/usr/bin/env python3 # Copyright 2021 University of Stuttgart (<NAME>) # Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0) import glob import os import sys idir = sys.argv[1] def read_transcription(txt): utts = [] text = "" prev_sec = 0.0 started = False with open(txt) as f: for line in f: if line[0] == "[": sec = float(line[1:-2]) if started: text = text.lower() text = text.replace("- ", " ") text = text.replace("*", " ") text = text.replace("(())", " ") text = text.replace("~", " ") text = text.replace("_", " ") text = text.replace("á", "a") text = text.replace("é", "e") words = [ w if w[0] == "<" else w.replace("-", " ") for w in text.split() ] words = " ".join(words).split() if len(words) > 0 and words[0] != "<no-speech>": utts.append( {"start": prev_sec, "text": " ".join(words), "end": sec} ) started = False else: prev_sec = sec text = "" started = True else: text += " " + line return utts mysubsets = {"training": "train", "dev": "valid"} for subset in mysubsets.keys(): odir = "data/{}_babel".format(mysubsets[subset]) os.makedirs(odir, exist_ok=True) with open(odir + "/text", "w", encoding="utf-8") as text, open( odir + "/wav.scp", "w" ) as wavscp, open(odir + "/utt2spk", "w") as utt2spk, open( odir + "/segments", "w" ) as segments: for part in ["scripted", "conversational"]: for audio in glob.glob(os.path.join(idir, part, subset, "audio", "*.sph")): recoid = os.path.split(audio)[1][:-4] wavscp.write( f"{recoid} ffmpeg -i {audio}" + " -acodec pcm_s16le -ar 16000 -ac 1 -f wav - |\n" ) transcription = os.path.join( idir, part, subset, "transcription", recoid + ".txt" ) utts = read_transcription(transcription) for utt in utts: uttid = "{}_{:06d}_{:06d}".format( recoid, int(utt["start"] * 100), int(utt["end"] * 100) ) text.write("{} {}\n".format(uttid, utt["text"])) utt2spk.write("{} {}\n".format(uttid, uttid)) segments.write( "{} {} {} {}\n".format(uttid, recoid, utt["start"], utt["end"]) )
1,681
2,542
// ------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License (MIT). See License.txt in the repo root for license information. // ------------------------------------------------------------ #include "stdafx.h" using namespace Common; using namespace Reliability; using namespace std; NodeUpgradeProgress::NodeUpgradeProgress() { } NodeUpgradeProgress::NodeUpgradeProgress( Federation::NodeId nodeId, wstring const& nodeName, NodeUpgradePhase::Enum upgradePhase) : nodeId_(nodeId), nodeName_(nodeName), upgradePhase_(upgradePhase), pendingSafetyChecks_() { } NodeUpgradeProgress::NodeUpgradeProgress( Federation::NodeId nodeId, wstring const& nodeName, NodeUpgradePhase::Enum upgradePhase, UpgradeSafetyCheckKind::Enum kind) : nodeId_(nodeId), nodeName_(nodeName), upgradePhase_(upgradePhase), pendingSafetyChecks_() { UpgradeSafetyCheckSPtr safetyCheck = make_shared<SeedNodeUpgradeSafetyCheck>(kind); pendingSafetyChecks_.push_back(move(UpgradeSafetyCheckWrapper(move(safetyCheck)))); } NodeUpgradeProgress::NodeUpgradeProgress( Federation::NodeId nodeId, wstring const& nodeName, NodeUpgradePhase::Enum upgradePhase, UpgradeSafetyCheckKind::Enum kind, Guid partitionId) : nodeId_(nodeId), nodeName_(nodeName), upgradePhase_(upgradePhase), pendingSafetyChecks_() { UpgradeSafetyCheckSPtr safetyCheck = make_shared<PartitionUpgradeSafetyCheck>(kind, partitionId); pendingSafetyChecks_.push_back(move(UpgradeSafetyCheckWrapper(move(safetyCheck)))); } NodeUpgradeProgress::NodeUpgradeProgress(NodeUpgradeProgress && other) : nodeId_(other.nodeId_), nodeName_(move(other.nodeName_)), upgradePhase_(other.upgradePhase_), pendingSafetyChecks_(other.pendingSafetyChecks_) { } NodeUpgradeProgress & NodeUpgradeProgress::operator=(NodeUpgradeProgress && other) { if (this != &other) { nodeId_ = other.nodeId_; nodeName_ = other.nodeName_; upgradePhase_ = other.upgradePhase_; pendingSafetyChecks_ = other.pendingSafetyChecks_; } return *this; } bool NodeUpgradeProgress::operator==(NodeUpgradeProgress const & other) const { return this->Equals(other, false); } bool NodeUpgradeProgress::operator!=(NodeUpgradeProgress const & other) const { return !(*this == other); } bool NodeUpgradeProgress::Equals(NodeUpgradeProgress const & other, bool ignoreDynamicContent) const { if (nodeId_ != other.nodeId_) { return false; } if (nodeName_ != other.nodeName_) { return false; } if (upgradePhase_ != other.upgradePhase_) { return false; } if (pendingSafetyChecks_.size() != other.pendingSafetyChecks_.size()) { return false; } for (auto ix=0; ix< pendingSafetyChecks_.size(); ++ix) { if (pendingSafetyChecks_[ix].Equals(other.pendingSafetyChecks_[ix], ignoreDynamicContent)) { return false; } } return true; } void NodeUpgradeProgress::WriteTo(TextWriter & w, FormatOptions const&) const { w.WriteLine("NodeId={0}, NodeName={1}, Phase={2}", nodeId_, nodeName_, upgradePhase_); for (auto const& safetyCheck : pendingSafetyChecks_) { w.WriteLine(*safetyCheck.SafetyCheck); } } void NodeUpgradeProgress::ToPublicApi( __in ScopedHeap & heap, __out FABRIC_NODE_UPGRADE_PROGRESS & nodeUpgradeProgress) const { nodeUpgradeProgress.NodeName = heap.AddString(nodeName_); switch (upgradePhase_) { case NodeUpgradePhase::PreUpgradeSafetyCheck: nodeUpgradeProgress.UpgradePhase = FABRIC_NODE_UPGRADE_PHASE_PRE_UPGRADE_SAFETY_CHECK; break; case NodeUpgradePhase::Upgrading: nodeUpgradeProgress.UpgradePhase = FABRIC_NODE_UPGRADE_PHASE_UPGRADING; break; case NodeUpgradePhase::PostUpgradeSafetyCheck: nodeUpgradeProgress.UpgradePhase = FABRIC_NODE_UPGRADE_PHASE_POST_UPGRADE_SAFETY_CHECK; break; default: nodeUpgradeProgress.UpgradePhase = FABRIC_NODE_UPGRADE_PHASE_INVALID; break; } auto pendingSafetyCheckArray = heap.AddArray<FABRIC_UPGRADE_SAFETY_CHECK>(pendingSafetyChecks_.size()); for (auto ix = 0; ix < pendingSafetyChecks_.size(); ++ix) { pendingSafetyChecks_[ix].ToPublicApi(heap, pendingSafetyCheckArray[ix]); } auto upgradeSafetyCheckList = heap.AddItem<FABRIC_UPGRADE_SAFETY_CHECK_LIST>(); upgradeSafetyCheckList->Count = static_cast<ULONG>(pendingSafetyCheckArray.GetCount()); upgradeSafetyCheckList->Items = pendingSafetyCheckArray.GetRawArray(); nodeUpgradeProgress.PendingSafetyChecks = upgradeSafetyCheckList.GetRawPointer(); nodeUpgradeProgress.Reserved = NULL; } ErrorCode NodeUpgradeProgress::FromPublicApi( FABRIC_NODE_UPGRADE_PROGRESS const & nodeUpgradeProgress) { nodeId_ = Federation::NodeId::MinNodeId; pendingSafetyChecks_.clear(); auto hr = StringUtility::LpcwstrToWstring( nodeUpgradeProgress.NodeName, false, nodeName_); if (!SUCCEEDED(hr)) { return ErrorCode::FromHResult(hr); } switch (nodeUpgradeProgress.UpgradePhase) { case FABRIC_NODE_UPGRADE_PHASE_PRE_UPGRADE_SAFETY_CHECK: upgradePhase_ = NodeUpgradePhase::PreUpgradeSafetyCheck; break; case FABRIC_NODE_UPGRADE_PHASE_UPGRADING: upgradePhase_ = NodeUpgradePhase::Upgrading; break; case FABRIC_NODE_UPGRADE_PHASE_POST_UPGRADE_SAFETY_CHECK: upgradePhase_ = NodeUpgradePhase::PostUpgradeSafetyCheck; break; default: return ErrorCode( ErrorCodeValue::InvalidArgument, wformatString("{0} {1}", GET_FM_RC( Invalid_Node_Upgrade_Phase ), static_cast<int>(nodeUpgradeProgress.UpgradePhase))); } if (nodeUpgradeProgress.PendingSafetyChecks == NULL) { return ErrorCodeValue::Success; } FABRIC_UPGRADE_SAFETY_CHECK_LIST const * list = nodeUpgradeProgress.PendingSafetyChecks; if (list->Count == 0) { return ErrorCodeValue::Success; } if (list->Items == NULL) { return ErrorCode( ErrorCodeValue::ArgumentNull, wformatString("{0} {1} ({2})", GET_COM_RC( Null_Items ), list->Count, "PendingSafetyChecks")); } for (ULONG ix=0; ix<list->Count; ++ix) { UpgradeSafetyCheckWrapper safetyCheck; auto error = safetyCheck.FromPublicApi(list->Items[ix]); if (!error.IsSuccess()) { return error; } pendingSafetyChecks_.push_back(safetyCheck); } return ErrorCodeValue::Success; } UpgradeDomainProgress::UpgradeDomainProgress() { } UpgradeDomainProgress::UpgradeDomainProgress( wstring const& upgradeDomainName, vector<NodeUpgradeProgress> const& nodeUpgradeProgressList) : upgradeDomainName_(upgradeDomainName), nodeUpgradeProgressList_(nodeUpgradeProgressList) { } UpgradeDomainProgress::UpgradeDomainProgress(UpgradeDomainProgress && other) : upgradeDomainName_(move(other.upgradeDomainName_)), nodeUpgradeProgressList_(move(other.nodeUpgradeProgressList_)) { } UpgradeDomainProgress & UpgradeDomainProgress::operator=(UpgradeDomainProgress && other) { if (this != &other) { upgradeDomainName_ = move(other.upgradeDomainName_); nodeUpgradeProgressList_ = move(other.nodeUpgradeProgressList_); } return *this; } bool UpgradeDomainProgress::operator==(UpgradeDomainProgress const & other) const { return this->Equals(other, false); } bool UpgradeDomainProgress::operator!=(UpgradeDomainProgress const & other) const { return !(*this == other); } bool UpgradeDomainProgress::Equals(UpgradeDomainProgress const & other, bool ignoreDynamicContent) const { if (upgradeDomainName_ != other.upgradeDomainName_) { return false; } if (nodeUpgradeProgressList_.size() != other.nodeUpgradeProgressList_.size()) { return false; } for (auto ix=0; ix<nodeUpgradeProgressList_.size(); ++ix) { if (nodeUpgradeProgressList_[ix].Equals(other.nodeUpgradeProgressList_[ix], ignoreDynamicContent)) { return false; } } return true; } void UpgradeDomainProgress::WriteTo(TextWriter & w, FormatOptions const&) const { w.WriteLine("CurrentUpgradeDomain={0}", upgradeDomainName_); for (size_t i = 0; i < nodeUpgradeProgressList_.size(); i++) { w.WriteLine(nodeUpgradeProgressList_[i]); } } ErrorCode UpgradeDomainProgress::FromString( std::wstring const & json, __out UpgradeDomainProgress & result) { return JsonHelper::Deserialize(result, json); } void UpgradeDomainProgress::ToPublicApi( __in ScopedHeap & heap, __out FABRIC_UPGRADE_DOMAIN_PROGRESS & upgradeDomainProgress) const { upgradeDomainProgress.UpgradeDomainName = heap.AddString(upgradeDomainName_); auto nodeUpgradeProgressArray = heap.AddArray<FABRIC_NODE_UPGRADE_PROGRESS>(nodeUpgradeProgressList_.size()); for (auto ix = 0; ix < nodeUpgradeProgressList_.size(); ++ix) { auto & nodeUpgradeProgress = nodeUpgradeProgressArray.GetRawArray()[ix]; nodeUpgradeProgressList_[ix].ToPublicApi(heap, nodeUpgradeProgress); } auto nodeUpgradeProgressList = heap.AddItem<FABRIC_NODE_UPGRADE_PROGRESS_LIST>(); nodeUpgradeProgressList->Count = static_cast<ULONG>(nodeUpgradeProgressArray.GetCount()); nodeUpgradeProgressList->Items = nodeUpgradeProgressArray.GetRawArray(); upgradeDomainProgress.NodeProgressList = nodeUpgradeProgressList.GetRawPointer(); upgradeDomainProgress.Reserved = NULL; } ErrorCode UpgradeDomainProgress::FromPublicApi( FABRIC_UPGRADE_DOMAIN_PROGRESS const & upgradeDomainProgress) { nodeUpgradeProgressList_.clear(); auto hr = StringUtility::LpcwstrToWstring( upgradeDomainProgress.UpgradeDomainName, false, upgradeDomainName_); if (!SUCCEEDED(hr)) { return ErrorCode::FromHResult(hr); } if (upgradeDomainProgress.NodeProgressList == NULL) { return ErrorCodeValue::Success; } FABRIC_NODE_UPGRADE_PROGRESS_LIST * list = upgradeDomainProgress.NodeProgressList; if (list->Count == 0) { return ErrorCodeValue::Success; } if (list->Items == NULL) { return ErrorCode( ErrorCodeValue::ArgumentNull, wformatString("{0} {1}", GET_COM_RC( Null_Items ), list->Count)); } for (ULONG ix=0; ix<list->Count; ++ix) { NodeUpgradeProgress nodeProgress; auto error = nodeProgress.FromPublicApi(list->Items[ix]); if (!error.IsSuccess()) { return error; } nodeUpgradeProgressList_.push_back(nodeProgress); } return ErrorCodeValue::Success; }
4,035
508
''' This file is the main python file of the project importing all problem, model, hparam registrations ''' from t2t_csaky.problems import character_chatbot from t2t_csaky.problems import cornell_chatbots from t2t_csaky.problems import daily_dialog_chatbot from t2t_csaky.problems import persona_chat_chatbot from t2t_csaky.problems import opensubtitles_chatbot from t2t_csaky.models import gradient_checkpointed_seq2seq from t2t_csaky.hparams import transformer_hparams from t2t_csaky.hparams import seq2seq_hparams
178
321
#ifndef ANDROID_JAVA_WEAK_REF_H #define ANDROID_JAVA_WEAK_REF_H #include <jni.h> #ifdef __cplusplus extern "C" { #endif class java_weak_ref { public: java_weak_ref(jobject obj); virtual ~java_weak_ref(); jobject obj() { return weak_ref_;} protected: jweak weak_ref_; }; #ifdef __cplusplus } #endif #endif //ANDROID_JAVA_WEAK_REF_H
190
356
<gh_stars>100-1000 package org.jinstagram.auth.model; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import org.junit.Test; /** * The class <code>VerifierTest</code> contains tests for the class * <code>{@link Verifier}</code>. * */ public class VerifierTest { /** * Run the Verifier(String) constructor test. * * @throws Exception * if any error occurs */ @Test public void testVerifier() throws Exception { String value = "verifierCode"; Verifier result = new Verifier(value); assertNotNull(result); assertEquals("verifierCode", result.getValue()); } /** * Run the String getValue() method test. * * @throws Exception * if any error occurs */ @Test public void testGetValue() throws Exception { Verifier fixture = new Verifier("verifierCode"); String result = fixture.getValue(); // add additional test code here assertEquals("verifierCode", result); } }
339
9,095
<gh_stars>1000+ import numpy as np from scipy import stats import matplotlib.pyplot as plt def measure(n): """Measurement model, return two coupled measurements.""" m1 = np.random.normal(size=n) m2 = np.random.normal(scale=0.5, size=n) return m1+m2, m1-m2 m1, m2 = measure(2000) xmin = m1.min() xmax = m1.max() ymin = m2.min() ymax = m2.max() X, Y = np.mgrid[xmin:xmax:100j, ymin:ymax:100j] positions = np.vstack([X.ravel(), Y.ravel()]) values = np.vstack([m1, m2]) kernel = stats.gaussian_kde(values) Z = np.reshape(kernel.evaluate(positions).T, X.shape) fig = plt.figure(figsize=(8, 6)) ax = fig.add_subplot(111) ax.imshow(np.rot90(Z), cmap=plt.cm.gist_earth_r, extent=[xmin, xmax, ymin, ymax]) ax.plot(m1, m2, 'k.', markersize=2) ax.set_xlim([xmin, xmax]) ax.set_ylim([ymin, ymax]) plt.show()
389
4,054
<reponame>Anlon-Burke/vespa<filename>container-core/src/main/java/com/yahoo/processing/response/AbstractData.java // Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.processing.response; import com.yahoo.component.provider.ListenableFreezableClass; import com.yahoo.processing.Request; /** * Convenience superclass for implementations of data. This contains no payload. * * @author bratseth */ public abstract class AbstractData extends ListenableFreezableClass implements Data { private Request request; /** * Creates some data marked with the request that created it */ public AbstractData(Request request) { this.request = request; } /** * Returns the request that created this data */ public Request request() { return request; } }
269
2,671
a = [100,101,102,103,104,105,106,107] del a[0] print a
29
4,036
from bottle import Bottle, route, request, redirect, response app = Bottle() @app.route('/hello/<name>') def hello(name = "World!"): return "Hello " + name @route('/bye/<name>') def bye(name = "World!"): return "Bye " + name @route('/other') def other(): name = request.cookies.username return "User name is " + name @route('/wrong/url') def safe(): redirect("/right/url") @route('/wrong/<where>') def unsafe(where="/right/url"): redirect(where) @route('/args') def unsafe2(): redirect(request.query.where, code) @route('/xss') def maybe_xss(): response.body = "name is " + request.query.name
241
348
<gh_stars>100-1000 {"nom":"Epieds-en-Beauce","circ":"2ème circonscription","dpt":"Loiret","inscrits":967,"abs":504,"votants":463,"blancs":2,"nuls":31,"exp":430,"res":[{"nuance":"LR","nom":"<NAME>","voix":261},{"nuance":"REM","nom":"<NAME>","voix":169}]}
105
575
<reponame>iridium-browser/iridium-browser<filename>chrome/browser/ash/arc/notification/arc_boot_error_notification.h // 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. #ifndef CHROME_BROWSER_ASH_ARC_NOTIFICATION_ARC_BOOT_ERROR_NOTIFICATION_H_ #define CHROME_BROWSER_ASH_ARC_NOTIFICATION_ARC_BOOT_ERROR_NOTIFICATION_H_ #include "base/macros.h" #include "chrome/browser/ash/arc/session/arc_session_manager_observer.h" #include "components/keyed_service/core/keyed_service.h" namespace content { class BrowserContext; } // namespace content namespace arc { class ArcBridgeService; // Watches for ARC boot errors and show notifications. class ArcBootErrorNotification : public KeyedService, public ArcSessionManagerObserver { public: // Returns singleton instance for the given BrowserContext, // or nullptr if the browser |context| is not allowed to use ARC. static ArcBootErrorNotification* GetForBrowserContext( content::BrowserContext* context); ArcBootErrorNotification(content::BrowserContext* context, ArcBridgeService* bridge_service); ~ArcBootErrorNotification() override; // ArcSessionManagerObserver: void OnArcSessionStopped(ArcStopReason reason) override; private: content::BrowserContext* const context_; DISALLOW_COPY_AND_ASSIGN(ArcBootErrorNotification); }; } // namespace arc #endif // CHROME_BROWSER_ASH_ARC_NOTIFICATION_ARC_BOOT_ERROR_NOTIFICATION_H_
525
320
<filename>lib/hachoir/wx/field_view/core_type_menu_fwd.py<gh_stars>100-1000 import wx class core_type_menu_fwd_t: def __init__(self, imp): self.imp = imp def on_field_menu_ready(self, dispatcher, view): assert view is not None view.Bind(wx.EVT_MENU, self.on_type_selected) def on_type_selected(self, event): try: self.imp.on_type_selected(event.GetId()) except KeyError: event.Skip()
218
703
<reponame>Tekh-ops/ezEngine #pragma once // This file is included both in shader code and in C++ code CONSTANT_BUFFER(ezTextureSampleConstants, 2) { MAT4(ModelMatrix); MAT4(ViewProjectionMatrix); };
76
840
<gh_stars>100-1000 public static void executeStatement(Connection con) { try(PreparedStatement pstmt = con.prepareStatement("SELECT LastName, FirstName FROM Person.Contact WHERE LastName = ?");) { pstmt.setString(1, "Smith"); ResultSet rs = pstmt.executeQuery(); while (rs.next()) { System.out.println(rs.getString("LastName") + ", " + rs.getString("FirstName")); } } // Handle any errors that may have occurred. catch (SQLException e) { e.printStackTrace(); } }
229
457
<filename>AgoraLive-Android/app/src/main/java/io/agora/vlive/protocol/model/response/SeatStateResponse.java package io.agora.vlive.protocol.model.response; import java.util.List; public class SeatStateResponse extends Response { public List<SeatInfo> data; public class SeatInfo { public int no; public String userId; public String userName; public int uid; public int state; } }
167
1,346
<reponame>wwjiang007/dal package com.ctrip.platform.dal.daogen.entity; import com.ctrip.platform.dal.dao.DalPojo; import com.ctrip.platform.dal.dao.annotation.Database; import com.ctrip.platform.dal.dao.annotation.Type; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; import java.sql.Types; @Entity @Database(name = "dao") @Table(name = "config_template") public class ConfigTemplate implements DalPojo { @Id @Column(name = "id") @GeneratedValue(strategy = GenerationType.AUTO) @Type(value = Types.INTEGER) private Integer id; @Column(name = "config_type") @Type(value = Types.INTEGER) private Integer config_type; @Column(name = "lang_type") @Type(value = Types.INTEGER) private Integer lang_type; @Column(name = "template") @Type(value = Types.VARCHAR) private String template; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public Integer getConfig_type() { return config_type; } public void setConfig_type(Integer config_type) { this.config_type = config_type; } public Integer getLang_type() { return lang_type; } public void setLang_type(Integer lang_type) { this.lang_type = lang_type; } public String getTemplate() { return template; } public void setTemplate(String template) { this.template = template; } }
710
348
{"nom":"Gaujac","circ":"3ème circonscription","dpt":"Gard","inscrits":791,"abs":437,"votants":354,"blancs":17,"nuls":3,"exp":334,"res":[{"nuance":"REM","nom":"<NAME>","voix":176},{"nuance":"FN","nom":"Mme <NAME>","voix":158}]}
91
432
<gh_stars>100-1000 #include <sys/types.h> #include <sys/socket.h> #include <arpa/inet.h> #include <net/if.h> #include <netinet/in.h> #include <err.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> static void usage(const char *cmd) { fprintf(stderr, "%s -m addr -p port (-i addr | -I iface) [-a]\n", cmd); exit(1); } static int create_sock(const struct sockaddr_in *in0, const struct in_addr *iface, int iface_idx, int bind_any) { struct sockaddr_in in; int s, on; s = socket(AF_INET, SOCK_DGRAM, 0); if (s < 0) err(2, "socket failed"); on = 1; if (setsockopt(s, SOL_SOCKET, SO_REUSEPORT, &on, sizeof(on)) < 0) err(2, "setsockopt SO_REUSEPORT failed"); in = *in0; if (bind_any) in.sin_addr.s_addr = htonl(INADDR_ANY); if (bind(s, (const struct sockaddr *)&in, sizeof(in)) < 0) err(2, "bind failed"); if (iface_idx < 0) { struct ip_mreq mreq; fprintf(stderr, "ip_mreq add_member\n"); memset(&mreq, 0, sizeof(mreq)); mreq.imr_multiaddr = in0->sin_addr; mreq.imr_interface = *iface; if (setsockopt(s, IPPROTO_IP, IP_ADD_MEMBERSHIP, &mreq, sizeof(mreq)) < 0) err(2, "setsockopt IP_ADD_MEMBERSHIP ip_mreq failed"); } else { struct ip_mreqn mreqn; fprintf(stderr, "ip_mreqn add_member, ifindex %d\n", iface_idx); memset(&mreqn, 0, sizeof(mreqn)); mreqn.imr_multiaddr = in0->sin_addr; mreqn.imr_address = *iface; mreqn.imr_ifindex = iface_idx; if (setsockopt(s, IPPROTO_IP, IP_ADD_MEMBERSHIP, &mreqn, sizeof(mreqn)) < 0) err(2, "setsockopt IP_ADD_MEMBERSHIP ip_mreqn failed"); } return s; } int main(int argc, char *argv[]) { struct sockaddr_in in; struct in_addr iface; int s1, s2, opt, n, bind_any, iface_idx; uint8_t buf[18]; memset(&in, 0, sizeof(in)); in.sin_family = AF_INET; memset(&iface, 0, sizeof(iface)); bind_any = 0; iface_idx = -1; while ((opt = getopt(argc, argv, "I:ai:m:p:")) != -1) { switch (opt) { case 'I': iface_idx = if_nametoindex(optarg); break; case 'a': bind_any = 1; break; case 'i': if (inet_pton(AF_INET, optarg, &iface) <= 0) usage(argv[0]); break; case 'm': if (inet_pton(AF_INET, optarg, &in.sin_addr) <= 0) usage(argv[0]); break; case 'p': in.sin_port = strtol(optarg, NULL, 10); in.sin_port = htons(in.sin_port); break; default: usage(argv[0]); } } if (in.sin_addr.s_addr == INADDR_ANY || in.sin_port == 0 || (iface.s_addr == INADDR_ANY && iface_idx < 0)) usage(argv[0]); s1 = create_sock(&in, &iface, iface_idx, bind_any); s2 = create_sock(&in, &iface, iface_idx, bind_any); n = read(s1, buf, sizeof(buf)); if (n < 0) err(2, "read 1 failed"); fprintf(stderr, "read 1 got %d\n", n); n = read(s2, buf, sizeof(buf)); if (n < 0) err(2, "read 2 failed"); fprintf(stderr, "read 2 got %d\n", n); exit(0); }
1,422
839
/** * 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.cxf.wsn.util; import java.io.IOException; import java.net.URL; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.xml.namespace.QName; import javax.xml.transform.Source; import javax.xml.transform.stream.StreamSource; import javax.xml.ws.Endpoint; import javax.xml.ws.soap.SOAPBinding; import org.apache.cxf.jaxws.JaxWsProxyFactoryBean; import org.apache.cxf.wsn.wsdl.WSNWSDLLocator; /** * */ public class CXFWSNHelper extends WSNHelper { public boolean supportsExtraClasses() { return true; } @Override public <T> T getPort(String address, Class<T> serviceInterface, Class<?>... extraClasses) { ClassLoader cl = Thread.currentThread().getContextClassLoader(); try { if (setClassLoader) { Thread.currentThread().setContextClassLoader(WSNHelper.class.getClassLoader()); } JaxWsProxyFactoryBean jwfb = new JaxWsProxyFactoryBean(); jwfb.getClientFactoryBean().setWsdlURL(WSNWSDLLocator.getWSDLUrl().toExternalForm()); jwfb.setServiceName(new QName("http://cxf.apache.org/wsn/jaxws", serviceInterface.getSimpleName() + "Service")); jwfb.setEndpointName(new QName("http://cxf.apache.org/wsn/jaxws", serviceInterface.getSimpleName() + "Port")); jwfb.setAddress(address); if (extraClasses != null && extraClasses.length > 0) { Map<String, Object> props = new HashMap<>(); props.put("jaxb.additionalContextClasses", extraClasses); jwfb.getClientFactoryBean().getServiceFactory().setProperties(props); } return jwfb.create(serviceInterface); } finally { Thread.currentThread().setContextClassLoader(cl); } } public Endpoint publish(String address, Object o, Class<?> ... extraClasses) { Endpoint endpoint = Endpoint.create(SOAPBinding.SOAP12HTTP_BINDING, o); if (extraClasses != null && extraClasses.length > 0) { Map<String, Object> props = new HashMap<>(); props.put("jaxb.additionalContextClasses", extraClasses); endpoint.setProperties(props); } URL wsdlLocation = WSNWSDLLocator.getWSDLUrl(); if (wsdlLocation != null) { try { if (endpoint.getProperties() == null) { endpoint.setProperties(new HashMap<String, Object>()); } endpoint.getProperties().put("javax.xml.ws.wsdl.description", wsdlLocation.toExternalForm()); List<Source> mt = new ArrayList<>(); StreamSource src = new StreamSource(wsdlLocation.openStream(), wsdlLocation.toExternalForm()); mt.add(src); endpoint.setMetadata(mt); } catch (IOException e) { //ignore, no wsdl really needed } } endpoint.publish(address); return endpoint; } }
1,681
678
/** * This header is generated by class-dump-z 0.2b. * * Source: /System/Library/PrivateFrameworks/iTunesStoreUI.framework/iTunesStoreUI */ #import <iTunesStoreUI/SUScriptObject.h> @class NSString, NSMutableArray, SUMediaObject; @interface SUScriptMediaObject : SUScriptObject { NSMutableArray *_scriptFunctions; // 36 = 0x24 unsigned _thumbnailOffset; // 40 = 0x28 } @property(readonly, assign) NSString *mediaType; // G=0xbfee9; @property(readonly, assign) SUMediaObject *nativeMediaObject; // G=0xbf665; + (void)initialize; // 0xc0171 + (id)webScriptNameForSelector:(SEL)selector; // 0xc00b5 + (id)webScriptNameForKey:(const char *)key; // 0xc0011 - (id)scriptAttributeKeys; // 0xc0111 - (id)attributeKeys; // 0xc0101 - (void)_removeScriptFunction:(id)function; // 0xbffa9 - (void)_addScriptFunction:(id)function; // 0xbff09 // declared property getter: - (id)mediaType; // 0xbfee9 - (id)_className; // 0xbfedd - (id)valueForProperty:(id)property; // 0xbfe31 - (id)thumbnailWithMaximumSize:(int)maximumSize; // 0xbfd59 - (void)saveToLibraryWithCompletionHandler:(id)completionHandler; // 0xbfb4d - (void)loadLibraryThumbnailWithCompletionHandler:(id)completionHandler; // 0xbf81d - (void)generateThumbnailWithMaximumSize:(int)maximumSize completionHandler:(id)handler; // 0xbf68d // declared property getter: - (id)nativeMediaObject; // 0xbf665 - (void)dealloc; // 0xbf5f5 - (id)initWithNativeMediaObject:(id)nativeMediaObject; // 0xbf4ed - (id)init; // 0xbf4d9 @end
556
1,652
"""Filters that are used in jobfunnel's filter() method or as intermediate filters to reduce un-necessesary scraping <NAME> 2020 """ import logging from collections import namedtuple from copy import deepcopy from datetime import datetime from typing import Dict, List, Optional, Tuple import nltk import numpy as np from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.metrics.pairwise import cosine_similarity from jobfunnel.backend import Job from jobfunnel.backend.tools import Logger from jobfunnel.resources import (DEFAULT_MAX_TFIDF_SIMILARITY, MIN_JOBS_TO_PERFORM_SIMILARITY_SEARCH, DuplicateType, Remoteness) DuplicatedJob = namedtuple( 'DuplicatedJob', ['original', 'duplicate', 'type'], ) class JobFilter(Logger): """Class Used by JobFunnel and BaseScraper to filter collections of jobs TODO: make more configurable, maybe with a FilterBank class. """ def __init__(self, user_block_jobs_dict: Optional[Dict[str, str]] = None, duplicate_jobs_dict: Optional[Dict[str, str]] = None, blocked_company_names_list: Optional[List[str]] = None, max_job_date: Optional[datetime] = None, max_similarity: float = DEFAULT_MAX_TFIDF_SIMILARITY, desired_remoteness: Remoteness = Remoteness.ANY, min_tfidf_corpus_size: int = MIN_JOBS_TO_PERFORM_SIMILARITY_SEARCH, log_level: int = logging.INFO, log_file: str = None) -> None: """Init TODO: need a config for this Args: user_block_jobs_dict (Optional[Dict[str, str]], optional): dict containing user's blocked jobs. Defaults to None. duplicate_jobs_dict (Optional[Dict[str, str]], optional): dict containing duplicate jobs, detected by content. Defaults to None blocked_company_names_list (Optional[List[str]], optional): list of company names disallowed from results. Defaults to None. max_job_date (Optional[datetime], optional): maximium date that a job can be scraped. Defaults to None. desired_remoteness (Remoteness, optional): The desired level of work-remoteness. ANY will impart no restriction. log_level (Optional[int], optional): log level. Defaults to INFO. log_file (Optional[str], optional): log file, Defaults to None. """ super().__init__( level=log_level, file_path=log_file, ) self.user_block_jobs_dict = user_block_jobs_dict or {} self.duplicate_jobs_dict = duplicate_jobs_dict or {} self.blocked_company_names_list = blocked_company_names_list or [] self.max_job_date = max_job_date self.max_similarity = max_similarity self.desired_remoteness = desired_remoteness self.min_tfidf_corpus_size = min_tfidf_corpus_size # Retrieve stopwords if not already downloaded try: stopwords = nltk.corpus.stopwords.words('english') except LookupError: nltk.download('stopwords', quiet=True) stopwords = nltk.corpus.stopwords.words('english') # Init vectorizer self.vectorizer = TfidfVectorizer( strip_accents='unicode', lowercase=True, analyzer='word', stop_words=stopwords, ) def filter(self, jobs_dict: Dict[str, Job], remove_existing_duplicate_keys: bool = True) -> Dict[str, Job]: """Filter jobs that fail numerous tests, possibly including duplication Arguments: remove_existing_duplicate_keys: pass True to remove jobs if their ID was previously detected to be a duplicate via TFIDF cosine similarity NOTE: if you remove duplicates before processesing them into updates you will retain potentially stale job information. Returns: jobs_dict with all filtered items removed. """ return { key_id: job for key_id, job in jobs_dict.items() if not self.filterable( job, check_existing_duplicates=remove_existing_duplicate_keys ) } def filterable(self, job: Job, check_existing_duplicates: bool = True) -> bool: """Filter jobs out using all our available filters NOTE: this allows job to be partially initialized NOTE: if a job has UNKNOWN remoteness, we will include it anyways TODO: we should probably add some logging to this? Arguments: check_existing_duplicates: pass True to check if ID was previously detected to be a duplicate via TFIDF cosine similarity Returns: True if the job should be removed from incoming data, else False """ return bool( job.status and job.is_remove_status or (job.company in self.blocked_company_names_list) or (job.post_date and self.max_job_date and job.is_old(self.max_job_date)) or (job.key_id and self.user_block_jobs_dict and job.key_id in self.user_block_jobs_dict) or (check_existing_duplicates and self.is_duplicate(job)) or (job.remoteness != Remoteness.UNKNOWN and self.desired_remoteness != Remoteness.ANY and job.remoteness != self.desired_remoteness) ) def is_duplicate(self, job: Job) -> bool: """Return true if passed Job has key_id and it is in our duplicates list """ return bool(job.key_id and self.duplicate_jobs_dict and job.key_id in self.duplicate_jobs_dict) def find_duplicates(self, existing_jobs_dict: Dict[str, Job], incoming_jobs_dict: Dict[str, Job], ) -> List[DuplicatedJob]: """Remove all known duplicates from jobs_dict and update original data TODO: find duplicates by content within existing jobs Args: existing_jobs_dict (Dict[str, Job]): dict of jobs keyed by key_id. incoming_jobs_dict (Dict[str, Job]): dict of new jobs by key_id. Returns: Dict[str, Job]: jobs dict with all jobs keyed by known-duplicate key_ids removed, and their originals updated. """ duplicate_jobs_list = [] # type: List[DuplicatedJob] filt_existing_jobs_dict = deepcopy(existing_jobs_dict) filt_incoming_jobs_dict = {} # type: Dict[str, Job] # Look for matches by key id only for key_id, incoming_job in incoming_jobs_dict.items(): # The key-ids are a direct match between existing and new if key_id in existing_jobs_dict: self.logger.debug( f"Identified duplicate {key_id} between incoming data " "and existing data." ) duplicate_jobs_list.append( DuplicatedJob( original=existing_jobs_dict[key_id], duplicate=incoming_job, type=DuplicateType.KEY_ID, ) ) # The key id is a known-duplicate we detected via content match # NOTE: original and duplicate have the same key id. elif key_id in self.duplicate_jobs_dict: self.logger.debug( f"Identified existing content-matched duplicate {key_id} " "in incoming data." ) duplicate_jobs_list.append( DuplicatedJob( original=None, # TODO: load ref from duplicates dict duplicate=incoming_job, type=DuplicateType.EXISTING_TFIDF, ) ) else: # This key_id is not duplicate, we can use it for TFIDF filt_incoming_jobs_dict[key_id] = deepcopy(incoming_job) # Run the tfidf vectorizer if we have enough jobs left after removing # key duplicates if (len(filt_incoming_jobs_dict.keys()) + len(filt_existing_jobs_dict.keys()) < self.min_tfidf_corpus_size): self.logger.warning( "Skipping content-similarity filter because there are fewer than " f"{self.min_tfidf_corpus_size} jobs." ) elif filt_incoming_jobs_dict: duplicate_jobs_list.extend( self.tfidf_filter( incoming_jobs_dict=filt_incoming_jobs_dict, existing_jobs_dict=filt_existing_jobs_dict, ) ) else: self.logger.warning( "Skipping content-similarity filter because there are no " "incoming jobs" ) # Update duplicates list with more JSON-friendly entries # TODO: we should retain a reference to the original job's contents self.duplicate_jobs_dict.update({ j.duplicate.key_id: j.duplicate.as_json_entry for j in duplicate_jobs_list }) return duplicate_jobs_list def tfidf_filter(self, incoming_jobs_dict: Dict[str, dict], existing_jobs_dict: Dict[str, dict], ) -> List[DuplicatedJob]: """Fit a tfidf vectorizer to a corpus of Job.DESCRIPTIONs and identify duplicate jobs by cosine-similarity. NOTE/WARNING: if you are running this method, you should have already removed any duplicates by key_id NOTE: this only uses job descriptions to do the content matching. NOTE: it is recommended that you have at least around 25 ish Jobs. TODO: need to handle existing_jobs_dict = None TODO: have this raise an exception if there are too few words. TODO: we should consider caching the transformed corpus. Args: incoming_jobs_dict (Dict[str, dict]): dict of jobs containing potential duplicates (i.e jobs we just scraped) existing_jobs_dict (Dict[str, dict]): the existing jobs dict (i.e. Master CSV) Raises: ValueError: incoming_jobs_dict contains no job descriptions Returns: List[DuplicatedJob]: list of new duplicate Jobs and their existing Jobs found via content matching (for use in JobFunnel). """ def __dict_to_ids_and_words(jobs_dict: Dict[str, Job], is_incoming: bool = False, ) -> Tuple[List[str], List[str]]: """Get query words and ids as lists + prefilter NOTE: this is just a convenience method since we do this 2x TODO: consider moving this once/if we change iteration """ ids = [] # type: List[str] words = [] # type: List[str] filt_job_dict = {} # type: Dict[str, Job] for job in jobs_dict.values(): if is_incoming and job.key_id in self.duplicate_jobs_dict: # NOTE: we should never see this for incoming jobs. # we will see it for existing jobs since duplicates can # share a key_id. raise ValueError( "Attempting to run TFIDF with existing duplicate " f"{job.key_id}" ) elif not len(job.description): self.logger.debug( f"Removing {job.key_id} from scrape result, empty " "description." ) else: ids.append(job.key_id) words.append(job.description) # NOTE: We want to leave changing incoming_jobs_dict in # place till the end or we will break usage of # Job.update_if_newer() filt_job_dict[job.key_id] = job # TODO: assert on length of contents of the lists as well if not words: raise ValueError( "No data to fit, are your job descriptions all empty?" ) return ids, words, filt_job_dict query_ids, query_words, filt_incoming_jobs_dict = \ __dict_to_ids_and_words(incoming_jobs_dict, is_incoming=True) # Calculate corpus and format query data for TFIDF calculation corpus = [] # type: List[str] if existing_jobs_dict: self.logger.debug("Running TFIDF on incoming vs existing data.") reference_ids, reference_words, filt_existing_jobs_dict = \ __dict_to_ids_and_words(existing_jobs_dict, is_incoming=False) corpus = query_words + reference_words else: self.logger.debug("Running TFIDF on incoming data only.") reference_ids = query_ids, reference_words = query_words filt_existing_jobs_dict = filt_incoming_jobs_dict corpus = query_words # Provide a warning if we have few words. # TODO: warning should reflect actual corpus size if len(corpus) < self.min_tfidf_corpus_size: self.logger.warning( "It is not recommended to use this filter with less than " f"{self.min_tfidf_corpus_size} jobs" ) # Fit vectorizer to entire corpus self.vectorizer.fit(corpus) # Calculate cosine similarity between reference and current blurbs # This is a list of the similarity between that query job and all the # TODO: impl. in a more efficient way since fit() does the transform too similarities_per_query = cosine_similarity( self.vectorizer.transform(query_words), self.vectorizer.transform(reference_words) if existing_jobs_dict else None, ) # Find Duplicate jobs by similarity score # NOTE: multiple jobs can be determined to be a duplicate of same job! # TODO: traverse this so we look at max similarity for original vs query # currently it's the other way around so we can look at multi-matching # original jobs but not multiple matching queries for our original job. new_duplicate_jobs_list = [] # type: List[DuplicatedJob] for query_similarities, query_id in zip(similarities_per_query, query_ids): # Identify the jobs in existing_jobs_dict that our query is a # duplicate of # TODO: handle if everything is highly similar! similar_indeces = np.where( query_similarities >= self.max_similarity )[0] if similar_indeces.size > 0: # TODO: capture if more jobs are similar by content match top_similar_job = np.argmax(query_similarities[similar_indeces]) self.logger.debug( f"Identified incoming job {query_id} as new duplicate by " "contents of existing job " f"{reference_ids[top_similar_job]}" ) new_duplicate_jobs_list.append( DuplicatedJob( original=filt_existing_jobs_dict[ reference_ids[top_similar_job]], duplicate=filt_incoming_jobs_dict[query_id], type=DuplicateType.NEW_TFIDF, ) ) if not new_duplicate_jobs_list: self.logger.debug("Found no duplicates by content-matching.") # returns a list of newly-detected duplicate Jobs return new_duplicate_jobs_list
7,575
12,278
/** * This code is released under a BSD License. */ #ifndef SIMDBITCOMPAT_H_ #define SIMDBITCOMPAT_H_ #include <iso646.h> /* mostly for Microsoft compilers */ #include <string.h> #if SIMDCOMP_DEBUG # define SIMDCOMP_ALWAYS_INLINE inline # define SIMDCOMP_NEVER_INLINE # define SIMDCOMP_PURE #else # if defined(__GNUC__) # if __GNUC__ >= 3 # define SIMDCOMP_ALWAYS_INLINE inline __attribute__((always_inline)) # define SIMDCOMP_NEVER_INLINE __attribute__((noinline)) # define SIMDCOMP_PURE __attribute__((pure)) # else # define SIMDCOMP_ALWAYS_INLINE inline # define SIMDCOMP_NEVER_INLINE # define SIMDCOMP_PURE # endif # define SIMDCOMP_API __attribute__ ((visibility ("default"))) # elif defined(_MSC_VER) # define SIMDCOMP_ALWAYS_INLINE __forceinline # define SIMDCOMP_API __declspec(dllexport) # define SIMDCOMP_NEVER_INLINE # define SIMDCOMP_PURE # else # if __has_attribute(always_inline) # define SIMDCOMP_ALWAYS_INLINE inline __attribute__((always_inline)) # else # define SIMDCOMP_ALWAYS_INLINE inline # endif # if __has_attribute(noinline) # define SIMDCOMP_NEVER_INLINE __attribute__((noinline)) # else # define SIMDCOMP_NEVER_INLINE # endif # if __has_attribute(pure) # define SIMDCOMP_PURE __attribute__((pure)) # else # define SIMDCOMP_PURE # endif # endif #endif #if defined(_MSC_VER) && _MSC_VER < 1600 typedef unsigned int uint32_t; typedef unsigned char uint8_t; typedef signed char int8_t; #else #include <stdint.h> /* part of Visual Studio 2010 and better, others likely anyway */ #endif #if defined(_MSC_VER) #define SIMDCOMP_ALIGNED(x) __declspec(align(x)) #else #if defined(__GNUC__) #define SIMDCOMP_ALIGNED(x) __attribute__ ((aligned(x))) #endif #endif #if defined(_MSC_VER) # include <intrin.h> /* 64-bit needs extending */ # define SIMDCOMP_CTZ(result, mask) do { \ unsigned long index; \ if (!_BitScanForward(&(index), (mask))) { \ (result) = 32U; \ } else { \ (result) = (uint32_t)(index); \ } \ } while (0) #else # include <x86intrin.h> # define SIMDCOMP_CTZ(result, mask) \ result = __builtin_ctz(mask) #endif #endif /* SIMDBITCOMPAT_H_ */
855
2,338
# DExTer : Debugging Experience Tester # ~~~~~~ ~ ~~ ~ ~~ # # 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 from ctypes import * # Error codes are negative when received by python, but are typically # represented by unsigned hex elsewhere. Subtract 2^32 from the unsigned # hex to produce negative error codes. E_NOINTERFACE = 0x80004002 - 0x100000000 E_FAIL = 0x80004005 - 0x100000000 E_EINVAL = 0x80070057 - 0x100000000 E_INTERNALEXCEPTION = 0x80040205 - 0x100000000 S_FALSE = 1 # This doesn't fit into any convenient category DEBUG_ANY_ID = 0xFFFFFFFF class WinError(Exception): def __init__(self, msg, hstatus): self.hstatus = hstatus super(WinError, self).__init__(msg) def aborter(res, msg, ignore=[]): if res != 0 and res not in ignore: # Convert a negative error code to a positive unsigned one, which is # now NTSTATUSes appear in documentation. if res < 0: res += 0x100000000 msg = '{:08X} : {}'.format(res, msg) raise WinError(msg, res) IID_Data4_Type = c_ubyte * 8 class IID(Structure): _fields_ = [ ("Data1", c_uint), ("Data2", c_ushort), ("Data3", c_ushort), ("Data4", IID_Data4_Type) ] c_ulong_p = POINTER(c_ulong) c_ulong64_p = POINTER(c_ulonglong)
549
407
<reponame>iuskye/SREWorks<filename>saas/health/api/health/health-start/src/main/java/com/alibaba/sreworks/Application.java package com.alibaba.sreworks; import lombok.extern.slf4j.Slf4j; import org.mybatis.spring.annotation.MapperScan; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import javax.annotation.PostConstruct; /** * Pandora Boot应用的入口类 * <p> * 详情见http://gitlab.alibaba-inc.com/middleware-container/pandora-boot/wikis/spring-boot-diamond * * @author chengxu */ @Slf4j @SpringBootApplication( scanBasePackages = {"com.alibaba.sreworks"} ) @MapperScan(basePackages = {"com.alibaba.sreworks.health.domain"}) public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } @PostConstruct public void init() { log.info("######## Application Init Success ########"); } }
358
2,195
<reponame>tesYolan/conceptnet5 import xml.etree.ElementTree as ET from conceptnet5.edges import make_edge from conceptnet5.formats.msgpack_stream import MsgpackStreamWriter from conceptnet5.nodes import standardized_concept_uri from conceptnet5.uri import Licenses REL = '/r/SymbolOf' DATASET = '/d/emoji' LICENSE = Licenses.cc_attribution SOURCE = [{'contributor': '/s/resource/unicode/cldr/32.0.1'}] def strip_words(text): """ When multiple words (separated by '|') are used to describe emojis, we need to remove the '|' in order to create edges for each word. This function takes out the '|' and puts all the words into a list. """ return text.split(' | ') def handle_file(input_file, output_file): tree = ET.parse(input_file) out = MsgpackStreamWriter(output_file) root = tree.getroot() lang = root[0][1].attrib[ 'type' ] # language is at position [1] within the child node [0] if len(root) >= 2: for annotation in root[1]: for word in strip_words(annotation.text): start = standardized_concept_uri('mul', annotation.attrib['cp']) end = standardized_concept_uri(lang, word) edge = make_edge(REL, start, end, DATASET, LICENSE, SOURCE) out.write(edge) else: print("No emoji data in {!r}".format(input_file)) out.close()
565
2,921
{ "name": "<NAME>", "type": "ERC20", "symbol": "KISHU", "decimals": 9, "website": "https://kishu.finance/", "description": "Kishu Inu ($KISHU) is a community-focused, decentralized cryptocurrency with instant rewards for holders. Join the moon mission.", "explorer": "https://etherscan.io/token/0xa2b4c0af19cc16a6cfacce81f192b024d625817d", "status": "active", "id": "0xA2b4C0Af19cC16a6CfAcCe81F192B024d625817D" }
198
7,320
package com.google.classyshark.gui.theme.dark; import java.awt.Color; class DarkColorScheme { private DarkColorScheme() {} static final Color BACKGROUND = new Color(32,32,32); static final Color BACKGROUND_LIGHT = new Color(46, 48,50); static final Color IDENTIFIERS = new Color(0xFF, 0xFF, 0x80); static final Color DEFAULT = new Color(0xd8, 0xd8, 0xd8); static final Color KEYWORDS = new Color(133, 153, 0); static final Color ANNOTATIONS = new Color(108, 113, 196); static final Color SELECTION_BG = new Color(7, 56, 66); static final Color NAMES = new Color(88, 110, 117); }
222
1,451
/* * Copyright (c) 2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ #import <Foundation/Foundation.h> #import <UIKit/UIKit.h> #import <Bolts/BFAppLinkNavigation.h> @class BFAppLinkReturnToRefererView; @class BFURL; typedef NS_ENUM(NSUInteger, BFIncludeStatusBarInSize) { BFIncludeStatusBarInSizeNever, BFIncludeStatusBarInSizeIOS7AndLater, BFIncludeStatusBarInSizeAlways, }; /*! Protocol that a class can implement in order to be notified when the user has navigated back to the referer of an App Link. */ @protocol BFAppLinkReturnToRefererViewDelegate <NSObject> /*! Called when the user has tapped inside the close button. */ - (void)returnToRefererViewDidTapInsideCloseButton:(BFAppLinkReturnToRefererView *)view; /*! Called when the user has tapped inside the App Link portion of the view. */ - (void)returnToRefererViewDidTapInsideLink:(BFAppLinkReturnToRefererView *)view link:(BFAppLink *)link; @end /*! Provides a UIView that displays a button allowing users to navigate back to the application that launched the App Link currently being handled, if the App Link contained referer data. The user can also close the view by clicking a close button rather than navigating away. If the view is provided an App Link that does not contain referer data, it will have zero size and no UI will be displayed. */ @interface BFAppLinkReturnToRefererView : UIView /*! The delegate that will be notified when the user navigates back to the referer. */ @property (nonatomic, weak) id<BFAppLinkReturnToRefererViewDelegate> delegate; /*! The color of the text label and close button. */ @property (nonatomic, strong) UIColor *textColor; @property (nonatomic, strong) BFAppLink *refererAppLink; /*! Indicates whether to extend the size of the view to include the current status bar size, for use in scenarios where the view might extend under the status bar on iOS 7 and above; this property has no effect on earlier versions of iOS. */ @property (nonatomic, assign) BFIncludeStatusBarInSize includeStatusBarInSize; /*! Indicates whether the user has closed the view by clicking the close button. */ @property (nonatomic, assign) BOOL closed; @end
732
1,144
// SPDX-License-Identifier: GPL-2.0+ /* * (C) Copyright 2014 * <NAME>, DENX Software Engineering, <EMAIL>. * * Basic support for the pwm module on imx6. */ #include <common.h> #include <div64.h> #include <pwm.h> #include <asm/arch/imx-regs.h> #include <asm/io.h> #include "pwm-imx-util.h" int pwm_init(int pwm_id, int div, int invert) { struct pwm_regs *pwm = (struct pwm_regs *)pwm_id_to_reg(pwm_id); if (!pwm) return -1; writel(0, &pwm->ir); return 0; } int pwm_config(int pwm_id, int duty_ns, int period_ns) { struct pwm_regs *pwm = (struct pwm_regs *)pwm_id_to_reg(pwm_id); unsigned long period_cycles, duty_cycles, prescale; u32 cr; if (!pwm) return -1; pwm_imx_get_parms(period_ns, duty_ns, &period_cycles, &duty_cycles, &prescale); cr = PWMCR_PRESCALER(prescale) | PWMCR_DOZEEN | PWMCR_WAITEN | PWMCR_DBGEN | PWMCR_CLKSRC_IPG_HIGH; writel(cr, &pwm->cr); /* set duty cycles */ writel(duty_cycles, &pwm->sar); /* set period cycles */ writel(period_cycles, &pwm->pr); return 0; } int pwm_enable(int pwm_id) { struct pwm_regs *pwm = (struct pwm_regs *)pwm_id_to_reg(pwm_id); if (!pwm) return -1; setbits_le32(&pwm->cr, PWMCR_EN); return 0; } void pwm_disable(int pwm_id) { struct pwm_regs *pwm = (struct pwm_regs *)pwm_id_to_reg(pwm_id); if (!pwm) return; clrbits_le32(&pwm->cr, PWMCR_EN); }
649
2,739
# Copyright (c) 2019 PaddlePaddle 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. import sys import yaml import six import os import copy import paddle.distributed.fleet as fleet import logging import numpy as np logging.basicConfig( format='%(asctime)s - %(levelname)s - %(message)s', level=logging.INFO) logger = logging.getLogger(__name__) class Reader(fleet.MultiSlotDataGenerator): def init(self, config): self.config = config padding = 0 sparse_slots = "click 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26" self.sparse_slots = sparse_slots.strip().split(" ") self.dense_slots = ["dense_feature"] self.dense_slots_shape = [13] self.slots = self.sparse_slots + self.dense_slots self.slot2index = {} self.visit = {} for i in range(len(self.slots)): self.slot2index[self.slots[i]] = i self.visit[self.slots[i]] = False self.padding = padding logger.info("pipe init success") def line_process(self, line): line = line.strip().split(" ") output = [(i, []) for i in self.slots] for i in line: slot_feasign = i.split(":") slot = slot_feasign[0] if slot not in self.slots: continue if slot in self.sparse_slots: feasign = int(slot_feasign[1]) else: feasign = float(slot_feasign[1]) output[self.slot2index[slot]][1].append(feasign) self.visit[slot] = True for i in self.visit: slot = i if not self.visit[slot]: if i in self.dense_slots: output[self.slot2index[i]][1].extend( [self.padding] * self.dense_slots_shape[self.slot2index[i]]) else: output[self.slot2index[i]][1].extend([self.padding]) else: self.visit[slot] = False return output #return [label] + sparse_feature + [dense_feature] def generate_sample(self, line): "Dataset Generator" def reader(): output_dict = self.line_process(line) # {key, value} dict format: {'labels': [1], 'sparse_slot1': [2, 3], 'sparse_slot2': [4, 5, 6, 8], 'dense_slot': [1,2,3,4]} # dict must match static_model.create_feed() yield output_dict return reader if __name__ == "__main__": yaml_path = sys.argv[1] utils_path = sys.argv[2] sys.path.append(utils_path) import common yaml_helper = common.YamlHelper() config = yaml_helper.load_yaml(yaml_path) r = Reader() r.init(config) r.run_from_stdin()
1,505