repo_name
stringlengths
6
101
path
stringlengths
4
300
text
stringlengths
7
1.31M
PandaProgrammingHub/ls
app/services/schoolMasters/divisionFactory.js
<reponame>PandaProgrammingHub/ls angular.module('MyApp') .factory('divisionFactory', function($http) { return { getDivisionDetail: function() { return $http.get('/api/divisions'); } }; });
7aske/grain
src/test/java/com/_7aske/grain/http/json/JsonDeserializerTest.java
package com._7aske.grain.http.json; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; class JsonDeserializerTest { static class User { String username; @JsonIgnore String password; User manager; } @Test void test_deserialize() { User manager = new User(); manager.username = "manager"; manager.password = "<PASSWORD>"; User user = new User(); user.password = "<PASSWORD>"; user.username = "username"; user.manager = manager; JsonSerializer<User> deserializer = new JsonSerializer<>(User.class); JsonObject jsonObject = (JsonObject) deserializer.serialize(user); assertEquals("username", jsonObject.getString("username")); assertNull(jsonObject.get("password")); assertEquals(manager.username, jsonObject.getObject("manager").getString("username")); assertNull(jsonObject.getObject("manager").get("password")); assertNull(jsonObject.getObject("manager").get("manager")); } }
danieljurek/Sia-EventUI
cfg/distConstants.js
<filename>cfg/distConstants.js let baseConstants = require('./defaultConstants') const argv = require('minimist')(process.argv.slice(2)) let distConstants = Object.assign({}, baseConstants, { appEnv: 'dist', aadInstance: argv.aadInstance, aadTenant: argv.aadTenant, clientId: argv.clientId, baseUrl: argv.baseUrl, authRedirectUri: argv.authRedirectUri, authVersion: argv.authVersion }) module.exports = distConstants
waruqi/hikyuu
hikyuu_cpp/hikyuu/indicator/imp/Vigor.cpp
/* * Vigor.cpp * * Created on: 2013-4-12 * Author: fasiondog */ #include "Vigor.h" #include "../crt/EMA.h" #include "../crt/PRICELIST.h" #include "../crt/KDATA.h" #include "../crt/REF.h" namespace hku { Vigor::Vigor(): IndicatorImp("VIGOR", 1) { setParam<int>("n", 2); } Vigor::Vigor(const KData& kdata, int n): IndicatorImp() { size_t total = kdata.size(); _readyBuffer(total, 1); setParam<int>("n", n); if (n < 1) { HKU_ERROR("Invalide param[n] must >= 1 ! [Vigor::Vigor]"); return; } m_discard = 1; if (0 == total) { return; } PriceList tmp(total, Null<price_t>()); for (size_t i = 1; i < total; ++i) { tmp[i] = (kdata[i].closePrice - kdata[i-1].closePrice) * kdata[i].transCount; } Indicator ema = EMA(PRICELIST(tmp, 1), n); for (size_t i = 0; i < total; ++i) { _set(ema[i], i); } } Vigor::~Vigor() { } bool Vigor::check() { int n = getParam<int>("n"); if (n < 1) { HKU_ERROR("Invalide param[n] must >= 1 ! [Vigor::Vigor]"); return false; } return true; } void Vigor::_calculate(const Indicator& ind) { if (ind.getResultNumber() < 6) { HKU_ERROR("ind's result_num must > 6! [Vigor::_calculate]"); return; } size_t total = ind.size(); if (0 == total) { return; } int n = getParam<int>("n"); m_discard = 1 + ind.discard(); if (0 == total) { return; } PriceList tmp(total, Null<price_t>()); for (size_t i = m_discard; i < total; ++i) { //tmp[i] = (kdata[i].closePrice - kdata[i-1].closePrice) * kdata[i].transCount; tmp[i] = (ind.get(i,3) - ind.get(i-1,3)) * ind.get(i,5); } Indicator ema = EMA(PRICELIST(tmp, m_discard), n); for (size_t i = 0; i < total; ++i) { _set(ema[i], i); } } Indicator HKU_API VIGOR(const KData& data, int n) { return Indicator(IndicatorImpPtr(new Vigor(data, n))); } Indicator HKU_API VIGOR(int n) { IndicatorImpPtr p = make_shared<Vigor>(); p->setParam<int>("n", n); return Indicator(p); } Indicator HKU_API VIGOR(const Indicator& indicator, int n){ IndicatorImpPtr p = make_shared<Vigor>(); p->setParam<int>("n", n); p->calculate(indicator); return Indicator(p); } } /* namespace hku */
timami/PlaneSense
GoPositionalAudio/jsimplementation/node_modules/web-audio-engine/lib/api/index.js
"use strict"; module.exports = { AnalyserNode: require("./AnalyserNode"), AudioBuffer: require("./AudioBuffer"), AudioBufferSourceNode: require("./AudioBufferSourceNode"), AudioContext: require("./AudioContext"), AudioDestinationNode: require("./AudioDestinationNode"), AudioListener: require("./AudioListener"), AudioNode: require("./AudioNode"), AudioParam: require("./AudioParam"), BiquadFilterNode: require("./BiquadFilterNode"), ChannelMergerNode: require("./ChannelMergerNode"), ChannelSplitterNode: require("./ChannelSplitterNode"), ConvolverNode: require("./ConvolverNode"), DelayNode: require("./DelayNode"), DynamicsCompressorNode: require("./DynamicsCompressorNode"), EventTarget: require("./EventTarget"), GainNode: require("./GainNode"), IIRFilterNode: require("./IIRFilterNode"), OscillatorNode: require("./OscillatorNode"), PannerNode: require("./PannerNode"), PeriodicWave: require("./PeriodicWave"), ScriptProcessorNode: require("./ScriptProcessorNode"), SpatialListener: require("./SpatialListener"), SpatialPannerNode: require("./SpatialPannerNode"), StereoPannerNode: require("./StereoPannerNode"), WaveShaperNode: require("./WaveShaperNode") };
km-works/kmw-astgen
src/main/java/edu/rice/cs/plt/recur/ValueContinuation.java
<reponame>km-works/kmw-astgen /*BEGIN_COPYRIGHT_BLOCK* PLT Utilities BSD License Copyright (c) 2007-2010 JavaPLT group at Rice University All rights reserved. Developed by: Java Programming Languages Team Rice University http://www.cs.rice.edu/~javaplt/ Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of the JavaPLT group, Rice University, nor the names of the library's contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND 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. *END_COPYRIGHT_BLOCK*/ package edu.rice.cs.plt.recur; import edu.rice.cs.plt.lambda.Lambda; /** A continuation that is resolved at creation time. */ public class ValueContinuation<T> implements Continuation<T> { private final T _val; /** Wrap the given value as a continuation. */ public ValueContinuation(T val) { _val = val; } /** Return the wrapped value. */ public T value() { return _val; } /** Always {@code true}. */ public boolean isResolved() { return true; } /** Throw an {@code IllegalStateException}, because this continuation is already resolved. */ public Continuation<T> step() { throw new IllegalStateException(); } /** Create a {@link ComposedContinuation} in terms of this object and {@code c}. */ public <R> Continuation<R> compose(Lambda<? super T, ? extends Continuation<? extends R>> c) { return new ComposedContinuation<T, R>(this, c); } /** Call the constructor (allows {@code T} to be inferred). */ public static <T> ValueContinuation<T> make(T val) { return new ValueContinuation<T>(val); } }
Tinkoff/neptune
selenium/src/main/java/ru/tinkoff/qa/neptune/selenium/HttpProxy.java
<filename>selenium/src/main/java/ru/tinkoff/qa/neptune/selenium/HttpProxy.java package ru.tinkoff.qa.neptune.selenium; import org.openqa.selenium.WebDriverException; import org.openqa.selenium.devtools.DevTools; import org.openqa.selenium.devtools.v102.network.Network; import org.openqa.selenium.devtools.v102.network.model.RequestWillBeSent; import org.openqa.selenium.devtools.v102.network.model.ResponseReceived; import ru.tinkoff.qa.neptune.selenium.functions.browser.proxy.HttpTraffic; import java.util.List; import java.util.Optional; import java.util.concurrent.CopyOnWriteArrayList; import static java.util.Optional.ofNullable; public class HttpProxy { private final DevTools devTools; private final List<RequestWillBeSent> requestList = new CopyOnWriteArrayList<>(); private final List<ResponseReceived> responseList = new CopyOnWriteArrayList<>(); private final List<HttpTraffic> httpTrafficList = new CopyOnWriteArrayList<>(); public HttpProxy(DevTools dt) { this.devTools = dt; devTools.send(Network.enable(Optional.empty(), Optional.empty(), Optional.empty())); } public void listen() { devTools.addListener(Network.requestWillBeSent(), requestList::add); devTools.addListener(Network.responseReceived(), responseList::add); } public void clearDump() { requestList.clear(); responseList.clear(); httpTrafficList.clear(); } public void disabledNetwork() { ofNullable(devTools.getCdpSession()) .ifPresent(cdp -> devTools.send(Network.disable())); } public List<HttpTraffic> getTraffic() { try { requestList.forEach(request -> { var httpTraffic = new HttpTraffic(); var response = responseList .stream() .filter(r -> r.getRequestId().toString().equals(request.getRequestId().toString())) .findFirst() .orElse(null); httpTraffic.setRequest(request) .setResponse(response); try { ofNullable(devTools) .map(DevTools::getCdpSession) .ifPresent(session -> httpTraffic.setBody(devTools.send(Network.getResponseBody(request.getRequestId())))); } catch (WebDriverException e) { e.printStackTrace(); } httpTrafficList.add(httpTraffic); }); } finally { requestList.clear(); responseList.clear(); } return httpTrafficList; } }
l-cdc/scala
src/compiler/scala/tools/nsc/typechecker/PatternTypers.scala
/* * Scala (https://www.scala-lang.org) * * Copyright EPFL and Lightbend, Inc. * * Licensed under Apache License 2.0 * (http://www.apache.org/licenses/LICENSE-2.0). * * See the NOTICE file distributed with this work for * additional information regarding copyright ownership. */ package scala package tools package nsc package typechecker import scala.collection.mutable import symtab.Flags import Mode._ /** * A pattern match such as: * * {{{ * x match { case Foo(a, b) => ...} * }}} * * Might match an instance of any of the following definitions of Foo. * Note the analogous treatment between case classes and unapplies. * * {{{ * case class Foo(xs: Int*) * case class Foo(a: Int, xs: Int*) * case class Foo(a: Int, b: Int) * case class Foo(a: Int, b: Int, xs: Int*) * * object Foo { def unapplySeq(x: Any): Option[Seq[Int]] } * object Foo { def unapplySeq(x: Any): Option[(Int, Seq[Int])] } * object Foo { def unapply(x: Any): Option[(Int, Int)] } * object Foo { def unapplySeq(x: Any): Option[(Int, Int, Seq[Int])] } * }}} */ trait PatternTypers { self: Analyzer => import global._ import definitions._ trait PatternTyper { self: Typer => import TyperErrorGen._ import infer._ // If the tree's symbol's type does not define an extractor, maybe the tree's type does. // this is the case when we encounter an arbitrary tree as the target of an unapply call // (rather than something that looks like a constructor call.) (for now, this only happens // due to wrapClassTagUnapply, but when we support parameterized extractors, it will become // more common place) private def hasUnapplyMember(tpe: Type): Boolean = reallyExists(unapplyMember(tpe)) private def hasUnapplyMember(sym: Symbol): Boolean = hasUnapplyMember(sym.tpe_*) // ad-hoc overloading resolution to deal with unapplies and case class constructors // If some but not all alternatives survive filtering the tree's symbol with `p`, // then update the tree's symbol and type to exclude the filtered out alternatives. private def inPlaceAdHocOverloadingResolution(fun: Tree)(p: Symbol => Boolean): Tree = fun.symbol filter p match { case sym if sym.exists && (sym ne fun.symbol) => fun setSymbol sym modifyType (tp => filterOverloadedAlts(tp)(p)) case _ => fun } private def filterOverloadedAlts(tpe: Type)(p: Symbol => Boolean): Type = tpe match { case OverloadedType(pre, alts) => overloadedType(pre, alts filter p) case tp => tp } def typedConstructorPattern(fun0: Tree, pt: Type): Tree = { // Do some ad-hoc overloading resolution and update the tree's symbol and type // do not update the symbol if the tree's symbol's type does not define an unapply member // (e.g. since it's some method that returns an object with an unapply member) val fun = inPlaceAdHocOverloadingResolution(fun0)(hasUnapplyMember) val canElide = treeInfo.isQualifierSafeToElide(fun) val caseClass = companionSymbolOf(fun.tpe.typeSymbol.sourceModule, context) val member = unapplyMember(fun.tpe) def resultType = (fun.tpe memberType member).finalResultType def isEmptyType = resultOfIsEmpty(resultType) def isOkay = ( resultType.isErroneous || (resultType <:< BooleanTpe) || (isEmptyType <:< BooleanTpe) || member.isMacro || member.isOverloaded // the whole overloading situation is over the rails ) // if we're already failing, no need to emit another error here if (fun.tpe.isErroneous) fun // Dueling test cases: pos/overloaded-unapply.scala, run/case-class-23.scala, pos/t5022.scala // A case class with 23+ params has no unapply method. // A case class constructor may be overloaded with unapply methods in the companion. // A case class maybe have its own custom unapply (so non-synthetic) scala/bug#11252 // Unapply methods aren't `isCaseApplyOrUnapply` in Scala 3 tasty/run/src-2/tastytest/TestColour.scala else if (canElide && caseClass.isCase && !member.isOverloaded && (member == NoSymbol || member.isSynthetic)) logResult(s"convertToCaseConstructor($fun, $caseClass, pt=$pt)")(convertToCaseConstructor(fun, caseClass, pt)) else if (!reallyExists(member)) CaseClassConstructorError(fun, s"${fun.symbol} is not a case class, nor does it have a valid unapply/unapplySeq member") else if (isOkay) fun else if (isEmptyType == NoType) CaseClassConstructorError(fun, s"an unapply result must have a member `def isEmpty: Boolean`") else CaseClassConstructorError(fun, s"an unapply result must have a member `def isEmpty: Boolean` (found: `def isEmpty: $isEmptyType`)") } def typedArgsForFormals(args: List[Tree], formals: List[Type], mode: Mode): List[Tree] = { def typedArgWithFormal(arg: Tree, pt: Type) = { if (isByNameParamType(pt)) typedArg(arg, mode, mode.onlySticky, dropByName(pt)) else typedArg(arg, mode, mode.onlySticky | BYVALmode, pt) } if (formals.isEmpty) Nil else { val lastFormal = formals.last val isRepeated = isRepeatedParamType(lastFormal) if (isRepeated) { val fixed = formals.init val elem = dropRepeated(lastFormal) val front = map2(args, fixed)(typedArgWithFormal) val rest = context withinStarPatterns (args drop front.length map (typedArgWithFormal(_, elem))) front ::: rest } else { map2(args, formals)(typedArgWithFormal) } } } private def boundedArrayType(bound: Type): Type = { val tparam = context.owner.freshExistential("", 0) setInfo (TypeBounds upper bound) newExistentialType(tparam :: Nil, arrayType(tparam.tpe_*)) } protected def typedStarInPattern(tree: Tree, mode: Mode, pt: Type) = { val Typed(expr, tpt) = tree: @unchecked val exprTyped = typed(expr, mode) val baseClass = exprTyped.tpe.typeSymbol match { case ArrayClass => ArrayClass case NothingClass => NothingClass case _ => SeqClass } val starType = baseClass match { case ArrayClass if isPrimitiveValueType(pt) || !isFullyDefined(pt) => arrayType(pt) case ArrayClass => boundedArrayType(pt) case _ => seqType(pt) } val exprAdapted = adapt(exprTyped, mode, starType) exprAdapted.tpe baseType baseClass match { case TypeRef(_, _, elemtp :: Nil) => treeCopy.Typed(tree, exprAdapted, tpt setType elemtp) setType elemtp case _ if baseClass eq NothingClass => exprAdapted case _ => setError(tree) } } protected def typedInPattern(tree: Typed, mode: Mode, pt: Type) = { val Typed(expr, tpt) = tree val tptTyped = typedType(tpt, mode) val tpe = tptTyped.tpe val exprTyped = typed(expr, mode, tpe.deconst) val extractor = extractorForUncheckedType(tpt.pos, tpe) val canRemedy = tpe match { case RefinedType(_, decls) if !decls.isEmpty => false case RefinedType(parents, _) if parents exists isUncheckable => false case _ => extractor.nonEmpty } val ownType = inferTypedPattern(tptTyped, tpe, pt, canRemedy) val treeTyped = treeCopy.Typed(tree, exprTyped, tptTyped) setType ownType extractor match { case EmptyTree => treeTyped case _ => wrapClassTagUnapply(treeTyped, extractor, tpe) } } private class VariantToSkolemMap extends VariancedTypeMap { private val skolemBuffer = mutable.ListBuffer[TypeSymbol]() // !!! FIXME - skipping this when variance.isInvariant allows unsoundness, see scala/bug#5189 // Test case which presently requires the exclusion is run/gadts.scala. def eligible(tparam: Symbol) = ( tparam.isTypeParameterOrSkolem && tparam.owner.isTerm && !variance.isInvariant ) def skolems = try skolemBuffer.toList finally skolemBuffer.clear() def apply(tp: Type): Type = mapOver(tp) match { case tp @ TypeRef(NoPrefix, tpSym, Nil) if eligible(tpSym) => val bounds = ( if (variance.isInvariant) tpSym.tpeHK.bounds else if (variance.isPositive) TypeBounds.upper(tpSym.tpeHK) else TypeBounds.lower(tpSym.tpeHK) ) // origin must be the type param so we can deskolemize val skolem = context.owner.newGADTSkolem(freshTypeName("?" + tpSym.name), tpSym, bounds) skolemBuffer += skolem logResult(s"Created gadt skolem $skolem: ${skolem.tpe_*} to stand in for $tpSym")(skolem.tpe_*) case tp1 => tp1 } } /* * To deal with the type slack between actual (run-time) types and statically known types, for each abstract type T, * reflect its variance as a skolem that is upper-bounded by T (covariant position), or lower-bounded by T (contravariant). * * Consider the following example: * * class AbsWrapperCov[+A] * case class Wrapper[B](x: Wrapped[B]) extends AbsWrapperCov[B] * * def unwrap[T](x: AbsWrapperCov[T]): Wrapped[T] = x match { * case Wrapper(wrapped) => // Wrapper's type parameter must not be assumed to be equal to T, it's *upper-bounded* by it * wrapped // : Wrapped[_ <: T] * } * * this method should type check if and only if Wrapped is covariant in its type parameter * * when inferring Wrapper's type parameter B from x's type AbsWrapperCov[T], * we must take into account that x's actual type is AbsWrapperCov[Tactual] forSome {type Tactual <: T} * as AbsWrapperCov is covariant in A -- in other words, we must not assume we know T exactly, all we know is its upper bound * * since method application is the only way to generate this slack between run-time and compile-time types (TODO: right!?), * we can simply replace skolems that represent method type parameters as seen from the method's body * by other skolems that are (upper/lower)-bounded by that type-parameter skolem * (depending on the variance position of the skolem in the statically assumed type of the scrutinee, pt) * * see test/files/../t5189*.scala */ private def convertToCaseConstructor(tree: Tree, caseClass: Symbol, ptIn: Type): Tree = { val variantToSkolem = new VariantToSkolemMap // `caseClassType` is the prefix from which we're seeing the constructor info, so it must be kind *. // Need the `initialize` call to make sure we see any type params. val caseClassType = caseClass.initialize.tpe_*.asSeenFrom(tree.tpe.prefix, caseClass.owner) assert(!caseClassType.isHigherKinded, s"Unexpected type constructor $caseClassType") // If the case class is polymorphic, need to capture those type params in the type that we relativize using asSeenFrom, // as they may also be sensitive to the prefix (see test/files/pos/t11103.scala). // Note that undetParams may thus be different from caseClass.typeParams. // (For a monomorphic case class, GenPolyType will not create/destruct a PolyType.) val (undetparams, caseConstructorType) = GenPolyType.unapply { val ctorUnderClassTypeParams = GenPolyType(caseClass.typeParams, caseClass.primaryConstructor.info) ctorUnderClassTypeParams.asSeenFrom(caseClassType, caseClass) }.get // println(s"convertToCaseConstructor(${tree.tpe}, $caseClass, $ptIn) // $caseClassType // ${caseConstructorType.typeParams.map(_.info)}") val tree1 = TypeTree(caseConstructorType) setOriginal tree // have to open up the existential and put the skolems in scope // can't simply package up pt in an ExistentialType, because that takes us back to square one (List[_ <: T] == List[T] due to covariance) val ptSafe = logResult(s"case constructor from (${tree.summaryString}, $caseClassType, $ptIn)")(variantToSkolem(ptIn)) val freeVars = variantToSkolem.skolems // use "tree" for the context, not context.tree: don't make another CaseDef context, // as instantiateTypeVar's bounds would end up there val ctorContext = context.makeNewScope(tree, context.owner) freeVars foreach ctorContext.scope.enter newTyper(ctorContext).infer.inferConstructorInstance(tree1, undetparams, ptSafe) // simplify types without losing safety, // so that we get rid of unnecessary type slack, and so that error messages don't unnecessarily refer to skolems val extrapolator = new ExistentialExtrapolation(freeVars) def extrapolate(tp: Type) = extrapolator extrapolate tp // once the containing CaseDef has been type checked (see typedCase), // tree1's remaining type-slack skolems will be deskolemized (to the method type parameter skolems) tree1 modifyType { case MethodType(ctorArgs, restpe) => // ctorArgs are actually in a covariant position, since this is the type of the subpatterns of the pattern represented by this Apply node ctorArgs foreach (_ modifyInfo extrapolate) copyMethodType(tree1.tpe, ctorArgs, extrapolate(restpe)) // no need to clone ctorArgs, this is OUR method type case tp => tp } } def doTypedUnapply(tree: Tree, funOrig: Tree, funOverloadResolved: Tree, args: List[Tree], mode: Mode, pt: Type): Tree = { def errorTree: Tree = treeCopy.Apply(tree, funOrig, args) setType ErrorType if (args.lengthCompare(MaxTupleArity) > 0) { TooManyArgsPatternError(funOverloadResolved); errorTree } else { val extractorPos = funOverloadResolved.pos val extractorTp = funOverloadResolved.tpe val unapplyMethod = unapplyMember(extractorTp) val unapplyType = extractorTp memberType unapplyMethod lazy val remedyUncheckedWithClassTag = extractorForUncheckedType(extractorPos, firstParamType(unapplyType)) def canRemedy = remedyUncheckedWithClassTag != EmptyTree val selectorDummySym = context.owner.newValue(nme.SELECTOR_DUMMY, extractorPos, Flags.SYNTHETIC) setInfo { if (isApplicableSafe(Nil, unapplyType, pt :: Nil, WildcardType)) pt else { def freshArgType(tp: Type): Type = tp match { case MethodType(param :: _, _) => param.tpe case PolyType(tparams, restpe) => createFromClonedSymbols(tparams, freshArgType(restpe))(genPolyType) case OverloadedType(_, _) => OverloadedUnapplyError(funOverloadResolved); ErrorType case _ => UnapplyWithSingleArgError(funOverloadResolved); ErrorType } val GenPolyType(freeVars, unappFormal) = freshArgType(unapplyType.skolemizeExistential(context.owner, tree)) val unapplyContext = context.makeNewScope(tree, context.owner) freeVars foreach unapplyContext.scope.enter val pattp = newTyper(unapplyContext).infer.inferTypedPattern(tree, unappFormal, pt, canRemedy) // turn any unresolved type variables in freevars into existential skolems val skolems = freeVars map (fv => unapplyContext.owner.newExistentialSkolem(fv, fv)) pattp.substSym(freeVars, skolems) } } // Clearing the type is necessary so that ref will be stabilized; see scala/bug#881. val selectUnapply = Select(funOverloadResolved.clearType(), unapplyMethod) // NOTE: The symbol of unapplyArgTree (`<unapply-selector>`) may be referenced in `fun1.tpe` // the pattern matcher deals with this in ExtractorCallRegular -- SI-6130 val unapplyArg = Ident(selectorDummySym) updateAttachment SubpatternsAttachment(args) // attachment is for quasiquotes val typedApplied = typedPos(extractorPos)(Apply(selectUnapply, unapplyArg :: Nil)) if (typedApplied.tpe.isErroneous || unapplyMethod.isMacro && !typedApplied.isInstanceOf[Apply]) { if (unapplyMethod.isMacro) { if (isBlackbox(unapplyMethod)) BlackboxExtractorExpansion(tree) else WrongShapeExtractorExpansion(tree) } errorTree } else { val unapplyArgTypeInferred = selectorDummySym.tpe_* // the union of the expected type and the inferred type of the argument to unapply val extractedTp = glb(ensureFullyDefined(pt) :: unapplyArgTypeInferred :: Nil) val formals = patmat.unapplyFormals(typedApplied, args)(context) val typedUnapply = UnApply(typedApplied, typedArgsForFormals(args, formals, mode)) setPos tree.pos setType extractedTp if (canRemedy && !(typedApplied.symbol.owner isNonBottomSubClass ClassTagClass)) wrapClassTagUnapply(typedUnapply, remedyUncheckedWithClassTag, extractedTp) else typedUnapply } } } def wrapClassTagUnapply(uncheckedPattern: Tree, classTagExtractor: Tree, pt: Type): Tree = { // TODO: disable when in unchecked match // we don't create a new Context for a Match, so find the CaseDef, // then go out one level and navigate back to the match that has this case val args = List(uncheckedPattern) val app = atPos(uncheckedPattern.pos)(Apply(classTagExtractor, args)) // must call doTypedUnapply directly, as otherwise we get undesirable rewrites // and re-typechecks of the target of the unapply call in PATTERNmode, // this breaks down when the classTagExtractor (which defines the unapply member) is not a simple reference to an object, // but an arbitrary tree as is the case here val res = doTypedUnapply(app, classTagExtractor, classTagExtractor, args, PATTERNmode, pt) log(sm""" |wrapClassTagUnapply { | pattern: $uncheckedPattern | extract: $classTagExtractor | pt: $pt | res: $res |}""".trim) res } // if there's a ClassTag that allows us to turn the unchecked type test for `pt` into a checked type test // return the corresponding extractor (an instance of ClassTag[`pt`]) def extractorForUncheckedType(pos: Position, pt: Type): Tree = { if (isPastTyper || (pt eq NoType)) EmptyTree else { pt match { case RefinedType(parents, decls) if !decls.isEmpty || (parents exists isUncheckable) => return EmptyTree case _ => } // only look at top-level type, can't (reliably) do anything about unchecked type args (in general) // but at least make a proper type before passing it elsewhere val pt1 = pt.dealiasWiden match { case tr @ TypeRef(pre, sym, args) if args.nonEmpty => copyTypeRef(tr, pre, sym, sym.typeParams map (_.tpeHK)) // replace actual type args with dummies case pt1 => pt1 } if (isCheckable(pt1)) EmptyTree else resolveClassTag(pos, pt1) match { case tree if unapplyMember(tree.tpe).exists => tree case _ => devWarning(s"Cannot create runtime type test for $pt1") ; EmptyTree } } } } }
janduracz/acumen-dev
src/main/scala/acumen/interpreters/enclosure/event/tree/EventTree.scala
<reponame>janduracz/acumen-dev package acumen.interpreters.enclosure.event.tree import acumen.interpreters.enclosure._ import acumen.interpreters.enclosure.HybridSystem import acumen.interpreters.enclosure.Types._ import acumen.interpreters.enclosure.Types.Event import acumen.interpreters.enclosure.Util._ import acumen.interpreters.enclosure.affine.UnivariateAffineEnclosure import acumen.interpreters.enclosure.affine.UnivariateAffineScalarEnclosure import acumen.interpreters.enclosure.ivp.IVPSolver import acumen.interpreters.enclosure.ivp.PicardSolver /** TODO add description */ // TODO add tests abstract class EventSequence { val enclosure: UnivariateAffineEnclosure val mayBeLast: Boolean def sigma: Mode def tau: Set[Mode] def prefixes: Seq[EventSequence] def subSequences: Set[EventSequence] val size: Int val domain: Interval def setMayBeLastTo(value: Boolean): EventSequence } /** TODO add description */ // TODO add tests case class EmptySequence( val initialMode: Mode, val enclosure: UnivariateAffineEnclosure, val mayBeLast: Boolean) extends EventSequence { def sigma = initialMode def tau = Set(initialMode) def prefixes = Seq() def subSequences = Set(this) val size = 0 val domain = enclosure.domain def setMayBeLastTo(value: Boolean) = if (mayBeLast == value) this else EmptySequence(initialMode, enclosure, value) } /** TODO add description */ // TODO add tests case class NonemptySequence( val lastEvent: Event, val enclosure: UnivariateAffineEnclosure, val mayBeLast: Boolean, val prefix: EventSequence) extends EventSequence { def sigma = prefix.sigma def tau = Set(lastEvent.tau) def prefixes = prefix +: prefix.prefixes def subSequences = prefix.subSequences + this val size = prefix.size + 1 val domain = prefix.domain def setMayBeLastTo(value: Boolean) = if (mayBeLast == value) this else NonemptySequence(lastEvent, enclosure, value, prefix) } /** TODO add description */ // TODO add tests case class EventTree( maximalSequences: Set[EventSequence], T: Interval, H: HybridSystem, S: UncertainState, delta: Double, m: Int, n: Int, degree: Int) { def sequences = maximalSequences.flatMap(_.subSequences) /** TODO add description */ // TODO add tests def size = maximalSequences.map(_.size).max /** * helper function for onlyUpdateAffectedVariables * determines if variable i is affected by event e, as defined by: * (i) the fields of e.sigma and e.tau affect i in the same way * (ii) the reset map of e is the identity on i and any variable that * depends on i within the field of e.tau (note that one needs * to chase this dependence through multiple applications of * the field) */ private def eventDoesNotAffectVariable(e: Event, name: VarName) = { val fieldsHaveSameEffect = H.fields(e.sigma).components(name) == H.fields(e.tau).components(name) val resetIsIdentityOnThisAndAllDependentVariables = (Set(name) ++ H.dependentVariables(H.fields(e.tau))(name)).forall(n => H.resets(e).components(n) == Variable(n)) fieldsHaveSameEffect && resetIsIdentityOnThisAndAllDependentVariables } /** * Uses components from previous enclosure in place * of current ones for variables not affected by the * event e. * * Implements the event-variable independence analysis * algorithm in 6.3. * * property: result should be equal at T.hi to previous * components for unaffected variables and to * current for affected ones, as given by * eventDoesNotAffectVariable. */ // TODO add tests private def onlyUpdateAffectedComponents( e: Event, previous: UnivariateAffineEnclosure, current: Box) = current.map { case (name, x) => { name -> { if (eventDoesNotAffectVariable(e, name)) previous(name)(T.high) else x } } } /** * Adds another event to the event sequences in the tree. */ def addLayer(ivpSolver: IVPSolver): EventTree = { def newSequences(v: EventSequence, o: Outcome) = { o.events.map { e => { if (H.resets(e)(H.guards(e).support(v.enclosure.range)) == Set(false)) println("\naddLayer: illegal reset!") require(H.guards(e)(v.enclosure.range) != Set(false), "Rand(Y(v)) \\/ C_e must be nonempty") if (o.isInstanceOf[MaybeOneOf] && H.domains(e.tau)(H.resets(e)(H.guards(e).support(v.enclosure.range))) == Set(false)) { /** * We have detected that the event sequence v cannot be followed * by e as the reset maps the previous state outside the support * of the domain invariant of the target mode of e. */ v.setMayBeLastTo(true) } else { require( H.domains(e.tau)(H.resets(e)(H.guards(e).support(v.enclosure.range))) != Set(false), "Reset " + H.resets(e) + "\nmust map contracted enclosure " + H.guards(e).support(v.enclosure.range) + "\ninto target domain " + H.domains(e.tau)) val A = H.domains(e.tau).support(H.resets(e)(H.guards(e).support(v.enclosure.range))) val N = ivpSolver.solveIVP(H.fields(e.tau), T, A, delta, m, n, degree)._1.range val lastEvent = e val affines = N val enclosure = UnivariateAffineEnclosure(v.domain, affines) val mayBeLast = false val prefix = v NonemptySequence(lastEvent, enclosure, mayBeLast, prefix).asInstanceOf[EventSequence] } } } } /** TODO add description */ val newMaximalSequences = { /** * This is the main event detection algorithm. */ def detectNextEvent( H: HybridSystem, T: Interval, q: Mode, Y: UnivariateAffineEnclosure): Outcome = { /** * This is likely where we get the issues with enclosures exploding from. The * events that are deemed possible are determined by evaluating the guard over * the range of the enclosure, rather than directly on the enclosure which is * a major source of imprecision! */ val events = H.events.filter(e => e.sigma == q && H.guards(e)(Y.range) != Set(false)) if (events.isEmpty) MaybeOneOf(events) else if (H.domains(q)(Y(Y.domain.high)) == Set(false)) CertainlyOneOf(events) else MaybeOneOf(events) } maximalSequences.flatMap { v => if (v.prefixes.exists { w => w.tau == v.tau && w.enclosure.contains(v.enclosure) }) { Set(v) } else { val mode = v.tau.head val enclosure = v.enclosure val decision = detectNextEvent(H, T, mode, enclosure) if (decision.events isEmpty) Set(v.setMayBeLastTo(true)) else decision match { case CertainlyOneOf(es) => newSequences(v, decision) case MaybeOneOf(es) => newSequences(v.setMayBeLastTo(true), decision) } } } } EventTree(newMaximalSequences, T, H, S, delta, m, n, degree) } /** TODO add description */ // TODO add tests def endTimeStates: Set[UncertainState] = { val mayBeLastSequences = maximalSequences.flatMap(v => (v +: v.prefixes).toSet).filter(v => v.mayBeLast) val mayBeLastStates = mayBeLastSequences.flatMap { v => { val modes = v.tau // FIXME evaluating at the enclosure's domain.high instead of T.high // the latter caused an assertion failure as enclosures were evaluated // outside their domain. E.g. and enclosure over [0,1.5] would be evaluated // at the point [3,3]. val initialCondition = v.enclosure.components.mapValues(e => e(e.domain.high)) modes.map(q => UncertainState(q, initialCondition)) } } val modewiseMayBeLastStates = (mayBeLastStates groupBy (_.mode)).mapValues(_.map(_.initialCondition)) modewiseMayBeLastStates.mapValues(xs => xs.tail.foldLeft(xs.head) { (res, x) => zipDefault(res, x, Interval.zero).mapValues { case (l, r) => l /\ r } }).map { case (q, b) => UncertainState(q, H.domains(q).support(b)) }.toSet } /** TODO add description */ // TODO add tests def enclosureUnion: UnivariateAffineEnclosure = { val sequences = maximalSequences.flatMap(v => (v +: v.prefixes).toSet) require(sequences.nonEmpty) val affs = sequences.tail.foldLeft(sequences.head.enclosure.components) { (res, v) => zipDefault(res, v.enclosure.components, UnivariateAffineScalarEnclosure( // FIXME for now.. not sure of correct choice of domain! sequences.head.enclosure.domain, 0)).mapValues { case (l, r) => l union r } } UnivariateAffineEnclosure(maximalSequences.head.domain, affs) } /** TODO add description */ // TODO add tests def unprunedEnclosures: Seq[UnivariateAffineEnclosure] = { val sequences = maximalSequences.flatMap(v => (v +: v.prefixes).toSet) sequences.map(_.enclosure).toSeq } /** * Takes the box-hull of enclosures for non-empty event sequences * and intersects with the target mode domain invariant. * * This has the effect of "shaving off" of the parts of enclosures that e.g. * in the bouncing ball example "dip below" the ground. */ def prunedEnclosures: Seq[UnivariateAffineEnclosure] = maximalSequences.head match { case EmptySequence(_, enclosure, _) => Seq(enclosure) case _ => val sequences = maximalSequences.flatMap(v => (v +: v.prefixes).toSet) sequences.map(s => s.tau.foldLeft(s.enclosure.range) { case (res, mode) => H.domains(mode).support(res) }).map(ran => UnivariateAffineEnclosure(T, ran)).toSeq } // StateEnclosure extraction methods /** TODO add description */ def stateEnclosure: StateEnclosure = StateEnclosure.union(sequences.map(s => new StateEnclosure(Map( s.tau.head -> Some(H.domains(s.tau.head).support(s.enclosure.range)))))) /** TODO add description */ def endTimeStateEnclosure = StateEnclosure.union(endTimeStates.map(s => new StateEnclosure(Map(s.mode -> Some(s.initialCondition))))) } object EventTree { /** TODO add description */ // TODO add tests def initialTree( T: Interval, H: HybridSystem, S: UncertainState, delta: Double, m: Int, n: Int, degree: Int, ivpSolver: IVPSolver) = { val mode = S.mode val (enclosure, _) = ivpSolver.solveIVP(H.fields(mode), T, S.initialCondition, delta, m, n, degree) val mayBeLast = false val sequences = Set(EmptySequence(mode, enclosure, mayBeLast).asInstanceOf[EventSequence]) EventTree(sequences, T, H, S, delta, m, n, degree) } }
javaduke/data-weave-intellij-plugin
data-weave-plugin/src/main/java/org/mule/tooling/lang/dw/spellchecker/WeaveSpellCheckerStrategy.java
<filename>data-weave-plugin/src/main/java/org/mule/tooling/lang/dw/spellchecker/WeaveSpellCheckerStrategy.java package org.mule.tooling.lang.dw.spellchecker; import com.intellij.psi.PsiElement; import com.intellij.spellchecker.tokenizer.SpellcheckingStrategy; import org.jetbrains.annotations.NotNull; import org.mule.tooling.lang.dw.WeaveLanguage; public class WeaveSpellCheckerStrategy extends SpellcheckingStrategy { @Override public boolean isMyContext(@NotNull PsiElement element) { return element.getLanguage() == WeaveLanguage.getInstance(); } }
binhdv37/nong-nghiep-v2
application/src/main/java/org/thingsboard/server/dft/services/baocaoTongHop/BcTongHopService.java
<filename>application/src/main/java/org/thingsboard/server/dft/services/baocaoTongHop/BcTongHopService.java<gh_stars>0 package org.thingsboard.server.dft.services.baocaoTongHop; import java.util.List; import java.util.UUID; public interface BcTongHopService { // tong so canh bao trong 1 khoang thoi gian cua 1 dam tom long countDamtomCanhbao(UUID damtomId, long startTs, long endTs); long countTenantActiveDamtomCanhBao(UUID tenantId, List<UUID> activeDamtomIdList, long startTs, long endTs); String getMailContentData(UUID tenantId, UUID damtomId, long startTs, long endTs); }
ga4gh-beacon/beacon-elixir
elixir_beacon/src/main/java/org/ega_archive/elixirbeacon/dto/BeaconRequest.java
package org.ega_archive.elixirbeacon.dto; import java.util.List; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; @Data @Builder @AllArgsConstructor @NoArgsConstructor public class BeaconRequest { private String variantType; private String alternateBases; private String referenceBases; private String referenceName; private Integer start; private Integer startMin; private Integer startMax; private Integer end; private Integer endMin; private Integer endMax; private String mateName; private String assemblyId; private List<String> datasetIds; private String includeDatasetResponses; }
kas1e/Eldritch
Code/Libraries/UI/src/Actions/wbactionuishowhidewidget.h
<gh_stars>0 #ifndef WBACTIONUISHOWHIDEWIDGET_H #define WBACTIONUISHOWHIDEWIDGET_H #include "wbaction.h" class WBActionUIShowHideWidget : public WBAction { public: WBActionUIShowHideWidget(); virtual ~WBActionUIShowHideWidget(); DEFINE_WBACTION_FACTORY(UIShowHideWidget); virtual void InitializeFromDefinition(const SimpleString& DefinitionName); virtual void Execute(); private: HashedString m_ScreenName; // Config HashedString m_WidgetName; // Config bool m_Hidden; // Config bool m_SetDisabled; // Config: also set disabled if hiding, or set enabled if // showing }; #endif // WBACTIONUISHOWHIDEWIDGET_H
rillig/r4intellij
test/com/r4intellij/debugger/RForcedFunctionDebuggerHandlerTest.java
<reponame>rillig/r4intellij<gh_stars>100-1000 package com.r4intellij.debugger; import com.r4intellij.debugger.data.RLocation; import com.r4intellij.debugger.exception.RDebuggerException; import com.r4intellij.debugger.executor.RExecutionResult; import com.r4intellij.debugger.mock.MockRExecutor; import com.r4intellij.debugger.mock.MockRFunctionDebugger; import com.r4intellij.debugger.mock.MockRFunctionDebuggerFactory; import com.r4intellij.debugger.mock.MockROutputReceiver; import org.jetbrains.annotations.NotNull; import org.junit.Test; import java.util.Collections; import static org.junit.Assert.assertEquals; public class RForcedFunctionDebuggerHandlerTest { @Test public void stack1() throws RDebuggerException { /* def() { instruction1 } */ final String result = "[1] 1 2 3"; final Stack1RFunctionDebugger debugger = new Stack1RFunctionDebugger(); final MockRFunctionDebuggerFactory factory = new MockRFunctionDebuggerFactory(debugger); final MockROutputReceiver receiver = new MockROutputReceiver(); final RForcedFunctionDebuggerHandler handler = new RForcedFunctionDebuggerHandler( new IllegalRExecutor(), factory, receiver ); //noinspection StatementWithEmptyBody while (handler.advance()) { } assertEquals(1, debugger.getCounter()); assertEquals(1, factory.getCounter()); assertEquals(Collections.emptyList(), receiver.getOutputs()); assertEquals(Collections.emptyList(), receiver.getErrors()); assertEquals(result, handler.getResult()); } @Test public void stack21() throws RDebuggerException { /* def() { instruction1 abc() { instruction1 instruction2 } instruction2 } */ final String result = "[1] 1 2 3"; final MockRFunctionDebugger secondFunctionDebugger = new MockRFunctionDebugger("abc", 2, null); final MockRFunctionDebugger firstFunctionDebugger = new Stack211RFunctionDebugger(secondFunctionDebugger); final MockRFunctionDebuggerFactory factory = new MockRFunctionDebuggerFactory(firstFunctionDebugger); final MockROutputReceiver receiver = new MockROutputReceiver(); final RForcedFunctionDebuggerHandler handler = new RForcedFunctionDebuggerHandler( new IllegalRExecutor(), factory, receiver ); //noinspection StatementWithEmptyBody while (handler.advance()) { } assertEquals(2, secondFunctionDebugger.getCounter()); assertEquals(3, firstFunctionDebugger.getCounter()); assertEquals(1, factory.getCounter()); assertEquals(Collections.emptyList(), receiver.getOutputs()); assertEquals(Collections.emptyList(), receiver.getErrors()); assertEquals(result, handler.getResult()); } @Test public void stack22() throws RDebuggerException { /* def() { instruction1 abc() { instruction1 instruction2 } } */ final String result = "[1] 1 2 3"; final MockRFunctionDebugger secondFunctionDebugger = new Stack222RFunctionDebugger(); final MockRFunctionDebugger firstFunctionDebugger = new Stack221RFunctionDebugger(secondFunctionDebugger); final MockRFunctionDebuggerFactory factory = new MockRFunctionDebuggerFactory(firstFunctionDebugger); final MockROutputReceiver receiver = new MockROutputReceiver(); final RForcedFunctionDebuggerHandler handler = new RForcedFunctionDebuggerHandler( new IllegalRExecutor(), factory, receiver ); //noinspection StatementWithEmptyBody while (handler.advance()) { } assertEquals(2, secondFunctionDebugger.getCounter()); assertEquals(2, firstFunctionDebugger.getCounter()); assertEquals(1, factory.getCounter()); assertEquals(Collections.emptyList(), receiver.getOutputs()); assertEquals(Collections.emptyList(), receiver.getErrors()); assertEquals(result, handler.getResult()); } @Test public void stack3() throws RDebuggerException { /* def() { instruction1 abc() { instruction1 ghi() { instruction1 instruction2 } } instruction2 } */ final String result = "[1] 1 2 3"; final MockRFunctionDebugger thirdFunctionDebugger = new Stack33RFunctionDebugger(); final MockRFunctionDebugger secondFunctionDebugger = new Stack32RFunctionDebugger(thirdFunctionDebugger); final MockRFunctionDebugger firstFunctionDebugger = new Stack31RFunctionDebugger(secondFunctionDebugger); final MockRFunctionDebuggerFactory factory = new MockRFunctionDebuggerFactory(firstFunctionDebugger); final MockROutputReceiver receiver = new MockROutputReceiver(); final RForcedFunctionDebuggerHandler handler = new RForcedFunctionDebuggerHandler( new IllegalRExecutor(), factory, receiver ); //noinspection StatementWithEmptyBody while (handler.advance()) { } assertEquals(2, thirdFunctionDebugger.getCounter()); assertEquals(2, secondFunctionDebugger.getCounter()); assertEquals(3, firstFunctionDebugger.getCounter()); assertEquals(1, factory.getCounter()); assertEquals(Collections.emptyList(), receiver.getOutputs()); assertEquals(Collections.emptyList(), receiver.getErrors()); assertEquals(result, handler.getResult()); } private static class IllegalRExecutor extends MockRExecutor { @NotNull @Override protected RExecutionResult doExecute(@NotNull final String command) throws RDebuggerException { throw new IllegalStateException("DoExecute shouldn't be called"); } } private static class Stack1RFunctionDebugger extends MockRFunctionDebugger { public Stack1RFunctionDebugger() { super("", 1, null); } @NotNull @Override public RLocation getLocation() { throw new IllegalStateException("GetLocation shouldn't be called"); } @NotNull @Override public String getResult() { return "[1] 1 2 3"; } } private static class Stack211RFunctionDebugger extends MockRFunctionDebugger { @NotNull private final MockRFunctionDebugger myNextFunctionDebugger; public Stack211RFunctionDebugger(@NotNull final MockRFunctionDebugger debugger) { super("def", 3, null); myNextFunctionDebugger = debugger; } @NotNull @Override public RLocation getLocation() { throw new IllegalStateException("GetLocation shouldn't be called"); } @Override public void advance() throws RDebuggerException { super.advance(); if (getCounter() == 2) { assert getHandler() != null; getHandler().appendDebugger(myNextFunctionDebugger); } } @NotNull @Override public String getResult() { return "[1] 1 2 3"; } } private static class Stack221RFunctionDebugger extends MockRFunctionDebugger { @NotNull private final MockRFunctionDebugger myNextFunctionDebugger; public Stack221RFunctionDebugger(@NotNull final MockRFunctionDebugger debugger) { super("def", 2, null); myNextFunctionDebugger = debugger; } @NotNull @Override public RLocation getLocation() { throw new IllegalStateException("GetLocation shouldn't be called"); } @Override public void advance() throws RDebuggerException { super.advance(); if (getCounter() == 2) { assert getHandler() != null; myNextFunctionDebugger.setHandler(getHandler()); getHandler().appendDebugger(myNextFunctionDebugger); } } } private static class Stack222RFunctionDebugger extends MockRFunctionDebugger { public Stack222RFunctionDebugger() { super("abc", 2, null); } @NotNull @Override public RLocation getLocation() { throw new IllegalStateException("GetLocation shouldn't be called"); } @Override public void advance() throws RDebuggerException { super.advance(); if (getCounter() == 2) { assert getHandler() != null; getHandler().setDropFrames(2); } } @NotNull @Override public String getResult() { return "[1] 1 2 3"; } } private static class Stack31RFunctionDebugger extends MockRFunctionDebugger { @NotNull private final MockRFunctionDebugger myNextFunctionDebugger; public Stack31RFunctionDebugger(@NotNull final MockRFunctionDebugger nextFunctionDebugger) { super("def", 3, null); myNextFunctionDebugger = nextFunctionDebugger; } @Override public void advance() throws RDebuggerException { super.advance(); if (getCounter() == 2) { assert getHandler() != null; myNextFunctionDebugger.setHandler(getHandler()); getHandler().appendDebugger(myNextFunctionDebugger); } } @NotNull @Override public String getResult() { return "[1] 1 2 3"; } } private static class Stack32RFunctionDebugger extends MockRFunctionDebugger { @NotNull private final MockRFunctionDebugger myNextFunctionDebugger; public Stack32RFunctionDebugger(@NotNull final MockRFunctionDebugger nextFunctionDebugger) { super("abc", 2, null); myNextFunctionDebugger = nextFunctionDebugger; } @Override public void advance() throws RDebuggerException { super.advance(); if (getCounter() == 2) { assert getHandler() != null; myNextFunctionDebugger.setHandler(getHandler()); getHandler().appendDebugger(myNextFunctionDebugger); } } } private static class Stack33RFunctionDebugger extends MockRFunctionDebugger { public Stack33RFunctionDebugger() { super("ghi", 2, null); } @Override public void advance() throws RDebuggerException { super.advance(); if (getCounter() == 2) { assert getHandler() != null; getHandler().setDropFrames(2); } } } }
SimonCasteran/JobBoard
back/app.js
<filename>back/app.js const express = require ("express"); require("dotenv").config(); const app = express(); const connectTodatabase = require("./config/connectToDatabase") const bodyParser = require("body-parser"); const cors = require("cors") const port = process.env.PORT; const users = require("./controllers/users") const ads = require("./controllers/ads") const comp = require("./controllers/companies") const appl = require("./controllers/applications") const cookieParser = require('cookie-parser') app.use(cookieParser()) const auth = require('./middlewares/auth'); const admin = require('./middlewares/adminAuth') // connectTodatabase() app.use(bodyParser.json()); app.use(function(req, res, next) { res.header('Access-Control-Allow-Origin', "http://localhost:3000"); res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); res.header("Access-Control-Allow-Credentials", "true") next(); }); app.listen(port, () => console.log ("Server started on port "+port)); // Users routes app.post("/createUser", users.createUser); app.post("/login", users.verifyUser); app.get("/logout", users.logout) app.get("/getUser", auth, admin, users.getUser) app.get("/getSelfUser", auth, users.getSelfUser) app.get("/getAllUsers", auth, admin, users.getAllUsers) app.post("/updateUser", auth, admin, users.updateUser) app.post("/updateSelfUser", auth, users.updateSelfUser) app.post("/deleteUser", auth, admin, users.deleteUser) app.post("/deleteSelfUser", auth, users.deleteSelfUser) // Job ads routes app.post("/createAd", ads.createAd) app.post("/getAd", ads.getAd) app.post("/getAdsByCompanyId", ads.getAdsByCompanyId) app.post("/getAllAds", ads.getAllAds) app.post("/updateAd", auth, ads.updateAd) app.post("/deleteAd", auth, ads.deleteAd) // Companies CRUD app.post("/createCompany", comp.createCompany) app.post("/getCompany", comp.getCompany) app.get("/getAllCompanies", comp.getAllCompanies) app.post("/updateCompany", auth, comp.updateCompany) app.post("/deleteCompany", auth, comp.deleteCompany) // Applications CRUD app.post("/createApplication", appl.createApplication) app.get("/getApplication", auth, appl.getApplication) app.get("/getAllApplications", auth, appl.getAllApplications) app.get("/getUserApplications", auth, appl.getUserApplications) app.get("/getRecruiterApplications", auth, appl.getRecruiterApplications) app.post("/updateApplication", auth, appl.updateApplication) app.post("/deleteApplication", auth, appl.deleteApplication)
anubhavnandan/leetCode
14_Longest_Common_Prefix.cpp
<filename>14_Longest_Common_Prefix.cpp //C++ 11 #include<iostream> #include<bits/stdc++.h> using namespace std; class Solution { public: string longestCommonPrefix(vector<string>& strs) { string prefixHanger; int commonPrefixIndex=0; sort(strs.begin(),strs.end(),[] (const std::string& first, const std::string& second){ return first.size() < second.size(); }); for(int j=0; j<strs.size();j++){ if(strs[j]!=""){ for(int i=0; i<strs[j].length(); i++){ //cout<<strs[j][i]<<" "; if(j==0){ prefixHanger.push_back(strs[j][i]); commonPrefixIndex=i; }else if(prefixHanger[i]!=strs[j][i]){ (i-1)<commonPrefixIndex?commonPrefixIndex=(i-1):commonPrefixIndex; break; }else if((i<prefixHanger.length() && i==strs[j].length()-1)){ i<commonPrefixIndex?commonPrefixIndex=i:commonPrefixIndex; break; } } // cout<<endl; } else{ commonPrefixIndex=-1; break; } //cout<<commonPrefixIndex<<endl; } string out; for(int i=0; i<=commonPrefixIndex; i++){ out.insert(out.begin()+i,prefixHanger[i]); } return out; } }; int main(){ vector<string> v = { "flower","flawer","flvwer","flower"}; // vector<string> v = {"flower","flow","flight"}; //vector<string> v = {"dog","racecar","car"}; //vector<string> v = {"ab","a",""}; //vector<string> v = {"aaa","aa","aaa"}; // vector<string> v = { // "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", // "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", // "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", // "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", // "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", // "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", // "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", // "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", // "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", // "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", // "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", // "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", // "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", // "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", // "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", // "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", // "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", // "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", // "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", // "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", // "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", // "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", // "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", // "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", // "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", // "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", // "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", // "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", // "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", // "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", // "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", // "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", // "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", // "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", // "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", // "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", // "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", // "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", // "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", // "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", // "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", // "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", // "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", // "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", // "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", // "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", // "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", // "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", // "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", // "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", // "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", // "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", // "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", // "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", // "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", // "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", // "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", // "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", // "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", // "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", // "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", // "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", // "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", // "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", // "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", // "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", // "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", // "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", // "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", // "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", // "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", // "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", // "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", // "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", // "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", // "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", // "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", // "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", // "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", // "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", // "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", // "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", // "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", // "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", // "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", // "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", // "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", // "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", // "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", // "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", // "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", // "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", // "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", // "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", // "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", // "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", // "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", // "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", // "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", // "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", // "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" // }; Solution Obj; cout<<Obj.longestCommonPrefix(v); return 0; }
fluffynukeit/mdsplus
xmdsshr/XmdsWidgetCallbacks.c
<filename>xmdsshr/XmdsWidgetCallbacks.c<gh_stars>10-100 /* Copyright (c) 2017, Massachusetts Institute of Technology All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* VAX/DEC CMS REPLACEMENT HISTORY, Element XMDSWIDGETCALLBACKS.C */ /* *12 3-OCT-1994 16:05:36 TWF "Unix" */ /* *11 3-OCT-1994 15:59:31 TWF "Unix" */ /* *10 22-FEB-1994 10:48:21 TWF "Take out NO_X_GLBS" */ /* *9 3-MAR-1993 16:13:05 JAS "use xmdsshr.h" */ /* *8 26-FEB-1993 11:37:15 JAS "port to decc" */ /* *7 8-JAN-1993 08:38:37 TWF "Remove call to acceptfocus" */ /* *6 17-SEP-1992 10:44:22 TWF "Remove setinputfocus call" */ /* *5 6-FEB-1992 11:40:34 TWF "Remove XmdsNapplyProc" */ /* *4 6-FEB-1992 11:20:49 TWF "Add XmdsNapplyProc to ApplyButton" */ /* *3 14-JAN-1992 16:41:38 TWF "Add Apply,Ok,Reset,Cancel callbacks" */ /* *2 14-JAN-1992 16:29:45 TWF "Add Apply,Ok,Reset,Cancel callbacks" */ /* *1 8-OCT-1991 13:33:44 TWF "Callback convenience routines" */ /* VAX/DEC CMS REPLACEMENT HISTORY, Element XMDSWIDGETCALLBACKS.C */ /*------------------------------------------------------------------------------ Name: XmdsWIDGETCALLBACKS Type: C function Author: <NAME> Date: 9-MAR-1990 Purpose: Generic callbacks which take a widget as the tag Use XmdsRegisterWidgetCallback to enable widgets to be tag argument. ------------------------------------------------------------------------------ Call sequence: void XmdsManageChildCallback(Widget w1,Widget *w2); void XmdsUnmanageChildCallback(Widget w1,Widget *w2); void XmdsDestroyWidgetCallback(Widget w1,Widget *w2); void XmdsRegisterWidgetCallback(Widget w1,Widget *w2); void XmdsRaiseWindow(Widget w); void XmdsManageWindow(Widget w); ------------------------------------------------------------------------------ Copyright (c) 1990 Property of Massachusetts Institute of Technology, Cambridge MA 02139. This program cannot be copied or distributed in any form for non-MIT use without specific written approval of MIT Plasma Fusion Center Management. --------------------------------------------------------------------------- Description: ------------------------------------------------------------------------------*/ #include <Xm/Xm.h> #include <xmdsshr.h> static Widget FindShellChild(Widget w) { Widget sc; for (sc = w; sc && !XtIsShell(XtParent(sc)); sc = XtParent(sc)) ; return sc; } void XmdsRaiseWindow(Widget w) { Widget shell; for (shell = w; shell && !XtIsShell(shell); shell = XtParent(shell)) ; if (shell) XtPopup(shell, XtGrabNone); } void XmdsManageWindow(Widget w) { if (!XtIsManaged(w)) XtManageChild(w); else XmdsRaiseWindow(w); } void XmdsManageChildCallback(Widget w1, Widget *w2) { XmdsManageWindow(*w2); } void XmdsUnmanageChildCallback(Widget w1, Widget *w2) { XtUnmanageChild(*w2); } void XmdsDestroyWidgetCallback(Widget w1, Widget *w2) { XtDestroyWidget(*w2); } void XmdsRegisterWidgetCallback(Widget w1, Widget *w2) { *w2 = w1; } #ifndef _NO_XDS extern void XmdsResetAllXds(Widget w); extern Boolean XmdsXdsAreValid(Widget w); extern Boolean XmdsApplyAllXds(Widget w); void XmdsResetCallback(Widget w) { XmdsResetAllXds(FindShellChild(w)); return; } void XmdsOkCallback(Widget w) { int XmdsApplyCallback(Widget w); if (XmdsApplyCallback(w)) XtDestroyWidget(FindShellChild(w)); } int XmdsApplyCallback(Widget w) { int status; Widget db = FindShellChild(w); if ((status = XmdsXdsAreValid(db))) status = XmdsApplyAllXds(db); return status; } #endif /* _NO_XDS */ void XmdsCancelCallback(Widget w) { XtDestroyWidget(FindShellChild(w)); }
abelidze/planer-server
app/src/main/java/com/skillmasters/server/http/response/ObjectResponse.java
<filename>app/src/main/java/com/skillmasters/server/http/response/ObjectResponse.java package com.skillmasters.server.http.response; import java.util.List; public class ObjectResponse extends Response<Object, ObjectResponse> { public ObjectResponse() { super(ObjectResponse.class); } }
dram/metasfresh
backend/de.metas.adempiere.adempiere/base/src/test/java/de/metas/process/ADProcessServiceTest.java
<reponame>dram/metasfresh /* * #%L * de.metas.adempiere.adempiere.base * %% * Copyright (C) 2021 metas GmbH * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 2 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program. If not, see * <http://www.gnu.org/licenses/gpl-2.0.html>. * #L% */ package de.metas.process; import com.google.common.collect.ImmutableList; import de.metas.document.references.zoom_into.CustomizedWindowInfo; import de.metas.document.references.zoom_into.CustomizedWindowInfoMap; import de.metas.i18n.ImmutableTranslatableString; import lombok.Builder; import lombok.NonNull; import org.adempiere.ad.element.api.AdTabId; import org.adempiere.ad.element.api.AdWindowId; import org.adempiere.ad.table.api.AdTableId; import org.adempiere.model.InterfaceWrapperHelper; import org.adempiere.test.AdempiereTestHelper; import org.adempiere.test.AdempiereTestWatcher; import org.assertj.core.api.Assertions; import org.compiere.model.I_AD_Table; import org.compiere.model.I_AD_Table_Process; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import javax.annotation.Nullable; @ExtendWith(AdempiereTestWatcher.class) class ADProcessServiceTest { private MockedCustomizedWindowInfoMapRepository customizedWindowInfoMapRepository; private ADProcessService adProcessService; private AdTableId adTableId; @BeforeEach void beforeEach() { AdempiereTestHelper.get().init(); this.customizedWindowInfoMapRepository = new MockedCustomizedWindowInfoMapRepository(); adProcessService = new ADProcessService(customizedWindowInfoMapRepository); adTableId = createTable("Test"); } @SuppressWarnings("SameParameterValue") private AdTableId createTable(final String tableName) { final I_AD_Table adTable = InterfaceWrapperHelper.newInstance(I_AD_Table.class); adTable.setTableName(tableName); InterfaceWrapperHelper.saveRecord(adTable); return AdTableId.ofRepoId(adTable.getAD_Table_ID()); } @Builder(builderMethodName = "relatedProcess", builderClassName = "$RelatedProcessBuilder") private void createRelatedProcess( @NonNull final AdProcessId processId, @Nullable final AdWindowId adWindowId, @Nullable final AdTabId adTabId) { final I_AD_Table_Process record = InterfaceWrapperHelper.newInstance(I_AD_Table_Process.class); record.setAD_Table_ID(adTableId.getRepoId()); record.setAD_Process_ID(processId.getRepoId()); record.setAD_Window_ID(AdWindowId.toRepoId(adWindowId)); record.setAD_Tab_ID(AdTabId.toRepoId(adTabId)); InterfaceWrapperHelper.saveRecord(record); } @Nested class getRelatedProcessDescriptors { @Test void relatedProcessAssignedOnTableLevel() { customizedWindowInfoMapRepository.set(CustomizedWindowInfoMap.empty()); relatedProcess().processId(AdProcessId.ofRepoId(1)).build(); Assertions.assertThat( adProcessService.getRelatedProcessDescriptors(adTableId, AdWindowId.ofRepoId(1), AdTabId.ofRepoId(11))) .hasSize(1) .element(0) .usingRecursiveComparison() .isEqualTo(RelatedProcessDescriptor.builder() .tableId(adTableId) .processId(AdProcessId.ofRepoId(1)) .windowId(null) .tabId(null) .displayPlace(RelatedProcessDescriptor.DisplayPlace.SingleDocumentActionsMenu) .build()); } @Test void relatedProcessAssignedOnWindowLevel() { customizedWindowInfoMapRepository.set(CustomizedWindowInfoMap.empty()); relatedProcess().processId(AdProcessId.ofRepoId(1)).adWindowId(AdWindowId.ofRepoId(1)).build(); Assertions.assertThat( adProcessService.getRelatedProcessDescriptors(adTableId, AdWindowId.ofRepoId(1), AdTabId.ofRepoId(11))) .hasSize(1) .element(0) .usingRecursiveComparison() .isEqualTo(RelatedProcessDescriptor.builder() .tableId(adTableId) .processId(AdProcessId.ofRepoId(1)) .windowId(AdWindowId.ofRepoId(1)) .tabId(null) .displayPlace(RelatedProcessDescriptor.DisplayPlace.SingleDocumentActionsMenu) .build()); } @Test void relatedProcessAssignedOnTabLevel() { customizedWindowInfoMapRepository.set(CustomizedWindowInfoMap.empty()); relatedProcess().processId(AdProcessId.ofRepoId(1)).adWindowId(AdWindowId.ofRepoId(1)).adTabId(AdTabId.ofRepoId(11)).build(); Assertions.assertThat( adProcessService.getRelatedProcessDescriptors(adTableId, AdWindowId.ofRepoId(1), AdTabId.ofRepoId(11))) .hasSize(1) .element(0) .usingRecursiveComparison() .isEqualTo(RelatedProcessDescriptor.builder() .tableId(adTableId) .processId(AdProcessId.ofRepoId(1)) .windowId(AdWindowId.ofRepoId(1)) .tabId(AdTabId.ofRepoId(11)) .displayPlace(RelatedProcessDescriptor.DisplayPlace.SingleDocumentActionsMenu) .build()); } @Test void inheritForBaseWindow() { customizedWindowInfoMapRepository.set(CustomizedWindowInfoMap.ofList( ImmutableList.of( CustomizedWindowInfo.builder() .customizationWindowCaption(ImmutableTranslatableString.builder().defaultValue("test").build()) .baseWindowId(AdWindowId.ofRepoId(1)) .customizationWindowId(AdWindowId.ofRepoId(2)) .build(), CustomizedWindowInfo.builder() .customizationWindowCaption(ImmutableTranslatableString.builder().defaultValue("test").build()) .baseWindowId(AdWindowId.ofRepoId(2)) .customizationWindowId(AdWindowId.ofRepoId(3)) .build() ))); System.out.println("CustomizedWindowInfoMap: " + customizedWindowInfoMapRepository.get()); relatedProcess().processId(AdProcessId.ofRepoId(1)).adWindowId(AdWindowId.ofRepoId(1)).build(); Assertions.assertThat( adProcessService.getRelatedProcessDescriptors(adTableId, AdWindowId.ofRepoId(2), AdTabId.ofRepoId(22))) .hasSize(1) .element(0) .usingRecursiveComparison() .isEqualTo(RelatedProcessDescriptor.builder() .tableId(adTableId) .processId(AdProcessId.ofRepoId(1)) .windowId(AdWindowId.ofRepoId(2)) .tabId(null) .displayPlace(RelatedProcessDescriptor.DisplayPlace.SingleDocumentActionsMenu) .build()); } } }
SchoolPower/SchoolPower-Backend
localization/test_localize.py
<gh_stars>1-10 import unittest from localize import get_equivalent_locale, use_localize class LocalizationTest(unittest.TestCase): def test_equivalent_locale(self): cases = [ ["zh", "zh-Hans"], ["zh_CN", "zh-Hans"], ["zh_TW", "zh-Hant"], ["zh_HK", "zh-Hans"], ["zh_MO", "zh-Hans"], ["zh-CN", "zh-Hans"], ["zh-TW", "zh-Hant"], ["zh-HK", "zh-Hans"], ["zh-MO", "zh-Hans"], ["zh-Hans", "zh-Hans"], ["zh_Hans", "zh-Hans"], ["zh-Hant", "zh-Hant"], ["zh_Hant", "zh-Hant"], ["zh-Hans-CN", "zh-Hans"], ["zh-Hans-HK", "zh-Hans"], ["zh-Hans-TW", "zh-Hans"], ["zh-Hant-TW", "zh-Hant"], ["zh-Hans_CN", "zh-Hans"], ["zh-Hans_HK", "zh-Hans"], ["zh-Hans_TW", "zh-Hans"], ["zh-Hant_TW", "zh-Hant"], ["zh-Hant_CN", "zh-Hant"], ] for case in cases: self.assertEqual(get_equivalent_locale(case[0]), case[1]) def test_localize(self): key = "Error.ConnectionTimedOut.Title" cases = [ [None, "Connection Timed Out"], ["", "Connection Timed Out"], ["fr", "Connection Timed Out"], ["en", "Connection Timed Out"], ["en_US", "Connection Timed Out"], ["en_UK", "Connection Timed Out"], ["zh-Hans", "连接超时"], ["zh-Hant", "連接超時"], ["zh_CN", "连接超时"], ["zh_TW", "連接超時"], ["ja", "接続がタイムアウトしました"], ["ja_JP", "接続がタイムアウトしました"], ] for case in cases: self.assertEqual(use_localize(case[0])(key), case[1]) if __name__ == '__main__': unittest.main()
kjh9267/BOJ_Python
DFS/2146.py
# https://www.acmicpc.net/problem/2146 import sys sys.setrecursionlimit(999999999) def dfs(x, y, cnt): if visited[y][x]: return visited[y][x] = True candi[cnt].append((x, y)) new_grid[y][x] = cnt for i, j in zip(dx, dy): xx = i + x yy = j + y if not (0 <= xx < N and 0 <= yy < N): continue if grid[yy][xx] == '0': continue dfs(xx,yy,cnt) def bfs(cnt): queue = __import__('collections').deque() visited = [[False for _ in range(N)] for __ in range(N)] for i in candi[cnt]: queue.append(i) visited[i[1]][i[0]] = True res = 0 while queue: size = len(queue) res += 1 for _ in range(size): cur = queue.popleft() for i, j in zip(dx, dy): x = cur[0] + i y = cur[1] + j if not (0 <= x < N and 0 <= y < N): continue if visited[y][x]: continue if new_grid[y][x] != cnt and new_grid[y][x] != 0: return res - 1 queue.append((x, y)) visited[y][x] = True if __name__ == '__main__': input = __import__('sys').stdin.readline N = int(input()) grid = [list(input().split()) for _ in range(N)] new_grid = [[0 for _ in range(N)] for __ in range(N)] candi = dict() dx = (1, 0, -1, 0) dy = (0, 1, 0, -1) res = float('inf') visited = [[False for _ in range(N)] for __ in range(N)] cnt = 0 for row in range(N): for col in range(N): if visited[row][col] or grid[row][col] == '0': continue cnt += 1 candi[cnt] = list() dfs(col, row, cnt) for i in candi.keys(): res = min(res, bfs(i)) print(res)
nrgxtra/advanced
Multidimentional Lists Exerscise/07. Bombs.py
<reponame>nrgxtra/advanced def check(row_idx, col_idx): existing = [] if row_idx - 1 >= 0 and col_idx - 1 >= 0: existing.append([row_idx - 1, col_idx - 1]) if row_idx - 1 >= 0: existing.append([row_idx - 1, col_idx]) if row_idx - 1 >= 0 and col_idx + 1 < len(matrix): existing.append([row_idx - 1, col_idx + 1]) if row_idx >= 0 and col_idx - 1 >= 0: existing.append([row_idx, col_idx - 1]) if row_idx >= 0 and col_idx + 1 < len(matrix): existing.append([row_idx, col_idx + 1]) if row_idx + 1 < len(matrix) and col_idx - 1 >= 0: existing.append([row_idx + 1, col_idx - 1]) if row_idx + 1 < len(matrix): existing.append([row_idx + 1, col_idx]) if row_idx + 1 < len(matrix) and col_idx + 1 < len(matrix): existing.append([row_idx + 1, col_idx + 1]) return existing rows_count = int(input()) matrix = [] for _ in range(rows_count): matrix.append([int(x) for x in input().split()]) explosion = [[int(x) for x in j.split(',')] for j in input().split()] dead_cells = [] for bomb in explosion: row_idx = bomb[0] col_idx = bomb[1] current_bomb = matrix[row_idx][col_idx] current_strength = matrix[row_idx][col_idx] if current_bomb > 0: matrix[row_idx][col_idx] = 0 existing_cells = check(row_idx, col_idx) for row in existing_cells: r_ind, c_ind = row current_cell = matrix[r_ind][c_ind] if current_cell > 0: matrix[r_ind][c_ind] -= current_strength alive = 0 alive_cells = [] for row in matrix: for el in row: if el > 0: alive += 1 alive_cells.append(el) sum_alive_cells = sum(alive_cells) print(f'Alive cells: {alive}') print(f'Sum: {sum_alive_cells}') new_matrix = [[str(x) for x in j] for j in matrix] [print(' '.join(row)) for row in new_matrix]
neume/docuko
app/models/data_model.rb
<reponame>neume/docuko class DataModel < ApplicationRecord belongs_to :created_by, class_name: 'User' belongs_to :office has_many :properties, class_name: 'ModelProperty', dependent: :destroy has_many :instances, dependent: :destroy has_many :documents, through: :instances has_many :templates, dependent: :destroy has_many :instance_properties, through: :instances, source: :properties accepts_nested_attributes_for :properties validate :no_duplicate_codes, on: :create validates :name, presence: true def no_duplicate_codes if properties.group_by(&:code).values.detect { |arr| arr.size > 1 } errors.add(:base, 'Field Code should be unique') end end end
drunkwater/leetcode
medium/python3/c0167_334_increasing-triplet-subsequence/00_leetcode_0167.py
<filename>medium/python3/c0167_334_increasing-triplet-subsequence/00_leetcode_0167.py # DRUNKWATER TEMPLATE(add description and prototypes) # Question Title and Description on leetcode.com # Function Declaration and Function Prototypes on leetcode.com #334. Increasing Triplet Subsequence #Given an unsorted array return whether an increasing subsequence of length 3 exists or not in the array. #Formally the function should: #Return true if there exists i, j, k #such that arr[i] < arr[j] < arr[k] given 0 ≤ i < j < k ≤ n-1 else return false. #Your algorithm should run in O(n) time complexity and O(1) space complexity. #Examples: #Given [1, 2, 3, 4, 5], #return true. #Given [5, 4, 3, 2, 1], #return false. #Credits: #Special thanks to @DjangoUnchained for adding this problem and creating all test cases. #class Solution: # def increasingTriplet(self, nums): # """ # :type nums: List[int] # :rtype: bool # """ # Time Is Money
seidu626/vumi
vumi/transports/telnet/__init__.py
"""Telnet server transport.""" from vumi.transports.telnet.telnet import (TelnetServerTransport, AddressedTelnetServerTransport) __all__ = ['TelnetServerTransport', 'AddressedTelnetServerTransport']
SCECcode/cvmhlabn
test/test_cvmhlabn_exec.h
<gh_stars>0 #ifndef TEST_CVMHLABN_EXEC_H #define TEST_CVMHLABN_EXEC_H int suite_cvmhlabn_exec(const char *xmldir); #endif
tamilselvansellamuthu/Insights
PlatformCommons/src/main/java/com/cognizant/devops/platformcommons/config/CorrelationConfig.java
/******************************************************************************* * Copyright 2017 Cognizant Technology Solutions * * 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.cognizant.devops.platformcommons.config; import java.io.Serializable; public class CorrelationConfig implements Serializable { private static final long serialVersionUID = -9222292318762382698L; private int correlationWindow = 48; private int correlationFrequency = 4; private int batchSize = 2000; public int getCorrelationWindow() { return correlationWindow; } public void setCorrelationWindow(int correlationWindow) { this.correlationWindow = correlationWindow; } public int getCorrelationFrequency() { return correlationFrequency; } public void setCorrelationFrequency(int correlationFrequency) { this.correlationFrequency = correlationFrequency; } public int getBatchSize() { return batchSize; } public void setBatchSize(int batchSize) { this.batchSize = batchSize; } }
josehu07/SplitFS
kernel/linux-5.4/sound/soc/intel/common/soc-acpi-intel-ehl-match.c
// SPDX-License-Identifier: GPL-2.0 /* * soc-apci-intel-ehl-match.c - tables and support for EHL ACPI enumeration. * * Copyright (c) 2019, Intel Corporation. * */ #include <sound/soc-acpi.h> #include <sound/soc-acpi-intel-match.h> struct snd_soc_acpi_mach snd_soc_acpi_intel_ehl_machines[] = { {}, }; EXPORT_SYMBOL_GPL(snd_soc_acpi_intel_ehl_machines); MODULE_LICENSE("GPL v2"); MODULE_DESCRIPTION("Intel Common ACPI Match module");
arielerv/hero-journey-be
src/openapi/index.js
const pkg = root_path('package.json'); const components = require('./components'); const publicApi = require('./publicApi'); const api = require('./api'); module.exports = { openapi: '3.0.2', info: {title: pkg.description, version: pkg.version}, servers: [{url: 'http://localhost:3001'}], paths: { '/ping': { get: { description: 'Endpoint ping', operationId: 'ping', security: [], responses: { 200: { description: 'Success', content: { 'application/json': { schema: { type: 'object', properties: {version: {type: 'string'}} } } } }, default: { description: 'Error', content: {'application/json': {schema: {$ref: '#/components/schemas/Error'}}} } } } }, '/ready': { get: { operationId: 'getStatus', security: [], responses: { 200: { description: 'Success', content: { 'application/json': { schema: { type: 'object', properties: { name: {type: 'string'}, status: {type: 'string'}, deps: { type: 'array', items: { type: 'object', properties: {} } } } } } } }, default: { description: 'Error', content: {'application/json': {schema: {$ref: '#/components/schemas/Error'}}} } } } }, '/health': { get: { operationId: 'getHealth', security: [], responses: { 200: { description: 'Success', content: { 'application/json': { schema: { type: 'object', properties: { name: {type: 'string'}, status: {type: 'string'} } } } } }, default: { description: 'Error', content: {'application/json': {schema: {$ref: '#/components/schemas/Error'}}} } } } }, ...publicApi, ...api }, components };
kozlov-a-d/html-template
assets/ds-kit/basis/resize.component.js
<gh_stars>0 /** * Компонент для отслеживания размеров при ресайзе и добавления функций по ресайзу * @method {{setFreezeTime, getScreenWidth, addMediaQuery, resizeForce, debug}} */ var resizeComponent = (function(){ var self = { screenWidth: window.innerWidth, queries: [], freezeTime: 100 }; /** * Заготовка для новых запросов, хранит настройки по умочанию, объединяется с новыми запросами * @type {{min: number, max: number, isEnter: boolean, onEnter: null, onEach: null}} */ var defaultQuery = { min: 0, max: 10000, isEnter: false, onEnter: null, onEach: null, onExit: null }; // PRIVATE ========================================================================================================= /** * установка минимального интервала между ресайзами * @param {*} time */ var setFreezeTime = function (time) { if ( typeof time !== 'number' && typeof time !== 'undefined'){ console.warn('resizeComponent: freezeTime type must be a number, now a ' + typeof time); } else { self.freezeTime = time; } }; /** * проверяем текущий размер экрана */ var checkScreen = function () { self.screenWidth = window.innerWidth; }; /** * выполняем медиа-запрос * @param {*} query */ var triggerQuery = function(query){ // проверяем разрешение if( query.min <= self.screenWidth && self.screenWidth <= query.max ){ // onEnter if( typeof query.onEnter === 'function' && !query.isEnter){ query.onEnter(); query.isEnter = true; } // onEach if( typeof query.onEach === 'function'){ query.onEach(); } } else { if(query.isEnter){ query.onExit(); } query.isEnter = false; } }; /** * проверяем корректность медиа-запроса * @param {*} query */ var validateQuery = function (query) { var validQuery = query; if ( typeof validQuery.min !== 'number' && typeof validQuery.min !== 'undefined'){ console.warn('resizeComponent: query.min type must be a number, now a ' + typeof validQuery.min); validQuery.min = defaultQuery.min; } if ( typeof validQuery.max !== 'number' && typeof validQuery.max !== 'undefined'){ console.warn('resizeComponent: query.max type must be a number, now a ' + typeof validQuery.min); validQuery.max = defaultQuery.max; } if ( typeof validQuery.onEnter !== 'function' && typeof validQuery.onEnter !== 'undefined' ){ console.warn('resizeComponent: query.onEnter type must be a function, now a ' + typeof validQuery.onEnter); validQuery.onEnter = null; } if ( typeof validQuery.onEach !== 'function' && typeof validQuery.onEach !== 'undefined' ){ console.warn('resizeComponent: query.onEach type must be a function, now a ' + typeof validQuery.onEach); validQuery.onEach = null; } if ( typeof validQuery.onExit !== 'function' && typeof validQuery.onExit !== 'undefined' ){ console.warn('resizeComponent: query.onEach type must be a function, now a ' + typeof validQuery.onExit); validQuery.onExit = null; } return validQuery; }; /** * добавляем новый медиа-запрос * @param {*} query */ var addQuery = function(query){ var newQuery = validateQuery(query); self.queries.push(newQuery); triggerQuery(newQuery); }; /** * перебираем все медиа-запросы при ресайзе, используется декоратор throttle */ var onResize = throttle(function(){ self.queries.forEach(function (item) { triggerQuery(item); }) }, self.freezeTime ); // INIT ============================================================================================================ // получаем текущий размер checkScreen(); // навешиваем обработчик window.addEventListener('resize', function() { checkScreen(); onResize(); }); // PUBLIC ========================================================================================================== return Object.freeze({ /** * Установка минимального интервала между ресайзами * @param {number} time */ setFreezeTime: function(time){ setFreezeTime(time); }, /** * Возвращает текущий размер экрана * @returns {number} */ getScreenWidth: function(){ checkScreen(); return screenWidth; }, /** * Добавляет новый медиа-запрос * @param {{min: number, max: number, onEnter: function, onEach: function, onExit: function}} query */ addMediaQuery: function(query){ addQuery(query); }, /** * Принудительно вызывает срабатывание актуальных колбэков */ resizeForce: function () { onResize(); }, /** * Выводит список текущих медаи-запросов */ debug: function () { console.log(self.queries); } }) }());
cflowe/ACE
TAO/tests/Bug_2683_Regression/client.cpp
<filename>TAO/tests/Bug_2683_Regression/client.cpp // $Id: client.cpp 91825 2010-09-17 09:10:22Z johnnyw $ #include "TestC.h" #include "ace/Get_Opt.h" #include "ace/Task.h" #include "ace/OS_NS_unistd.h" class Pinger : public ACE_Task_Base { private: const char * ior_; CORBA::ORB_var orb_; bool do_shutdown_; bool stop_; public: Pinger (CORBA::ORB_var &orb, const char *ior) : ior_ (ior), orb_(orb), do_shutdown_ (false), stop_ (false) { } int svc (void) { bool keep_going = true; while (keep_going && !this->stop_) { try { CORBA::Object_var tmp = this->orb_->string_to_object(this->ior_); Test::IORTable_Shutdown_Race_var target = Test::IORTable_Shutdown_Race::_narrow(tmp.in ()); if (CORBA::is_nil (target.in ())) ACE_ERROR_RETURN ((LM_DEBUG, "(%P|%t) Nil target reference <%s>\n", this->ior_), 1); target->ping(); if (this->do_shutdown_) { ACE_DEBUG ((LM_DEBUG,"(%P|%t) Calling shutdown\n")); this->do_shutdown_ = false; target->shutdown (); } } catch (CORBA::Exception &ex) { ACE_DEBUG ((LM_DEBUG, "(%P|%t) caught an exception - %C\n",ex._name())); keep_going = false; } } return 0; } void killit() { do_shutdown_ = true; } void stop () { stop_ = true; } }; int port = 0; ACE_TCHAR const * target_host = ACE_TEXT("localhost"); int parse_args (int argc, ACE_TCHAR *argv[]) { ACE_Get_Opt get_opts (argc, argv, ACE_TEXT("p:h:")); int c; while ((c = get_opts ()) != -1) switch (c) { case 'p': port = ACE_OS::atoi (get_opts.opt_arg ()); break; case 'h': target_host = get_opts.opt_arg (); break; case '?': default: ACE_ERROR_RETURN ((LM_ERROR, "usage: %s " "-p <server_port> " "\n", argv [0]), -1); } // Indicates successful parsing of the command line return 0; } int ACE_TMAIN(int argc, ACE_TCHAR *argv[]) { try { CORBA::ORB_var orb = CORBA::ORB_init (argc, argv); if (parse_args (argc, argv) != 0) return 1; char ior[100]; ACE_OS::sprintf (ior, "corbaloc::%s:%d/Racer", ACE_TEXT_ALWAYS_CHAR (target_host), port); Pinger pinger(orb, ior); ACE_OS::sleep (1); ACE_DEBUG ((LM_DEBUG,"(%P|%t) client - starting client threads\n")); pinger.activate (THR_NEW_LWP | THR_JOINABLE, 5); ACE_OS::sleep (1); ACE_DEBUG ((LM_DEBUG,"(%P|%t) client - All running, time to shutdown server\n")); pinger.killit(); ACE_OS::sleep (2); ACE_DEBUG ((LM_DEBUG,"(%P|%t) client - Stopping client threads\n")); pinger.stop (); pinger.wait(); ACE_DEBUG ((LM_DEBUG,"(%P|%t) client done\n")); } catch (CORBA::Exception &ex) { ACE_DEBUG ((LM_DEBUG,"Main caught %s\n",ex._name())); return 1; } return 0; }
fabri1983/signaling_server
src/main/java/org/fabri1983/signaling/configuration/HazelcastSignalingConfiguration.java
package org.fabri1983.signaling.configuration; import com.hazelcast.config.Config; import com.hazelcast.config.ReliableTopicConfig; import com.hazelcast.config.SerializerConfig; import com.hazelcast.core.Hazelcast; import com.hazelcast.core.HazelcastInstance; import com.hazelcast.topic.ITopic; import org.fabri1983.signaling.core.distributed.NextRTCDistributedEventBus; import org.fabri1983.signaling.core.distributed.serialization.NextRTCConversationWrapperSerializerV1; import org.fabri1983.signaling.core.distributed.serialization.NextRTCEventWrapperSerializerV1; import org.fabri1983.signaling.core.distributed.serialization.NextRTCMemberWrapperSerializerV1; import org.fabri1983.signaling.core.distributed.wrapper.NextRTCConversationWrapper; import org.fabri1983.signaling.core.distributed.wrapper.NextRTCEventWrapper; import org.fabri1983.signaling.core.distributed.wrapper.NextRTCMemberWrapper; import org.fabri1983.signaling.core.population.ConversationPopulation; import org.nextrtc.signalingserver.Names; import org.nextrtc.signalingserver.api.NextRTCEventBus; import org.nextrtc.signalingserver.repository.ConversationRepository; import org.nextrtc.signalingserver.repository.MemberRepository; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; import org.springframework.context.annotation.Profile; @Configuration @Profile( {"eventbus-hazelcast"} ) public class HazelcastSignalingConfiguration { private final String HZ_INSTANCE_NAME = "signaling-hzc"; private final String TOPIC_CONFIG_NAME = "signaling-hzc-topic"; @Bean public ReliableTopicConfig hazelCastTopicConfig() { // In the reliable topic, global order is always maintained ReliableTopicConfig topicConfig = new ReliableTopicConfig(TOPIC_CONFIG_NAME); return topicConfig; } @Bean(destroyMethod = "shutdown") public HazelcastInstance hazelCastInstance(ReliableTopicConfig hzcTopicConfig) { Config config = new Config(HZ_INSTANCE_NAME); config.addReliableTopicConfig(hzcTopicConfig); config.getNetworkConfig().getJoin().getMulticastConfig().setEnabled(true); registerSerializers(config); HazelcastInstance hzcInstance = Hazelcast.getOrCreateHazelcastInstance(config); return hzcInstance; } @Bean public ITopic<NextRTCEventWrapper> hazelCastTopic(HazelcastInstance hzcInstance) { return hzcInstance.getReliableTopic(TOPIC_CONFIG_NAME); } /** * Override bean definition from @{link org.nextrtc.signalingserver.api.NextRTCEventBus} so we can customize the event bus. * @return */ @Bean(name = Names.EVENT_BUS) @Primary public NextRTCEventBus eventBus(HazelcastInstance hazelcastInstance, ITopic<NextRTCEventWrapper> hzcTopic, ConversationPopulation population, ConversationRepository conversationRepository, MemberRepository members) { return new NextRTCDistributedEventBus(hazelcastInstance, hzcTopic, population, conversationRepository, members); } private void registerSerializers(Config config) { SerializerConfig eventSc = new SerializerConfig() .setImplementation(new NextRTCEventWrapperSerializerV1()) .setTypeClass(NextRTCEventWrapper.class); SerializerConfig memberSc = new SerializerConfig() .setImplementation(new NextRTCMemberWrapperSerializerV1()) .setTypeClass(NextRTCMemberWrapper.class); SerializerConfig conversationSc = new SerializerConfig() .setImplementation(new NextRTCConversationWrapperSerializerV1()) .setTypeClass(NextRTCConversationWrapper.class); config.getSerializationConfig().addSerializerConfig(eventSc); config.getSerializationConfig().addSerializerConfig(memberSc); config.getSerializationConfig().addSerializerConfig(conversationSc); } /** * This class serves the solely purpose of resolve circular bean reference creation, which happens * when two or more beans depend on each other. */ // @Configuration // public static class CircularBeanRefResolver { // // // Inject beans here // // @PostConstruct // public void circularBeanRefResolver() { // // set missing dependencies // } // } }
SteveSmith16384/ChronoCup
core/src/com/scs/splitscreenfps/game/systems/ql/recorddata/BulletFiredRecordData.java
package com.scs.splitscreenfps.game.systems.ql.recorddata; import com.badlogic.gdx.math.Vector3; public class BulletFiredRecordData extends AbstractRecordData { public int playerIdx; public Vector3 start; public Vector3 offset; public BulletFiredRecordData(int phase, float time, int _playerIdx, Vector3 _start, Vector3 _offset) { super(CMD_BULLET_FIRED, phase, time); playerIdx = _playerIdx; start = _start; offset = _offset; } }
sonylomo/Rocket.Chat.ReactNative
app/actions/sortPreferences.js
import * as types from './actionsTypes'; export function setAllPreferences(preferences) { return { type: types.SORT_PREFERENCES.SET_ALL, preferences }; } export function setPreference(preference) { return { type: types.SORT_PREFERENCES.SET, preference }; }
njhoffman/better-musician
src/components/DevTools/Launcher/Launcher.js
<filename>src/components/DevTools/Launcher/Launcher.js import React, { Component } from 'react'; import PropTypes from 'prop-types'; import shouldPureComponentUpdate from 'react-pure-render/function'; import * as themes from 'redux-devtools-themes'; import Button from 'devui/lib/Button'; import SegmentedControl from 'devui/lib/SegmentedControl'; import { withStyles } from '@material-ui/core'; import NewWindow from 'components/NewWindow'; import DevToolsChart from 'components/DevTools/Chart'; import { reducer as chartToolbarReducer } from 'components/DevTools/Chart/Toolbar'; import { init as initLog } from 'shared/logger'; const { info, warn } = initLog('custom-launcher'); const styles = (theme) => ({ container: { fontFamily: 'monaco, Consolas, Lucida Console, monospace', fontSize: '0.8em', position: 'relative', overflowY: 'hidden', height: '100%', direction: 'ltr', color: 'white' }, elements: { display: 'flex', justifyContent: 'space-evenly', overflowX: 'hidden', overflowY: 'auto', verticalAlign: 'middle', top: 30, height: '100%', alignItems: 'center' }, buttonActive: { backgroundColor: '#838184', color: '#0e0e0e' } }); class Launcher extends Component { static update = chartToolbarReducer static defaultProps = { devConfig: { showChart: false } }; static propTypes = { dispatch: PropTypes.func.isRequired, classes: PropTypes.instanceOf(Object).isRequired, devConfig: PropTypes.instanceOf(Object), computedStates: PropTypes.arrayOf(PropTypes.object).isRequired, actionsById: PropTypes.instanceOf(Object).isRequired, stagedActionIds: PropTypes.arrayOf(PropTypes.number).isRequired, skippedActionIds: PropTypes.arrayOf(PropTypes.number).isRequired, monitorState: PropTypes.shape({ initialScrollTop: PropTypes.number, consecutiveToggleStartId: PropTypes.number }).isRequired, theme: PropTypes.oneOfType([ PropTypes.object, PropTypes.string ]) }; static defaultProps = { theme: 'twilight' }; shouldComponentUpdate = shouldPureComponentUpdate; constructor(props) { super(props); const { devConfig } = props; this.getRef = this.getRef.bind(this); this.toggleChart = this.toggleChart.bind(this); this.popupUnload = this.popupUnload.bind(this); this.state = { showChart : devConfig && devConfig.showChart }; } getTheme() { const { theme } = this.props; if (typeof theme !== 'string') { return theme; } if (typeof themes[theme] !== 'undefined') { return themes[theme]; } warn(`DevTools theme ${theme} not found, defaulting to nicinabox`); return themes.nicinabox; } getRef(node) { this.node = node; } toggleChart() { this.setState(state => ({ ...state, showChart: !state.showChart })); } popupUnload() { info('popup unloading...'); this.setState(state => ({ ...state, showChart: false })); } render() { const theme = this.getTheme(); const { classes: { container, elements } } = this.props; const { showChart } = this.state; const winOptions = { menubar: 'no', location: 'no', resizable: 'yes', scrollbars: 'no', statusbar: 'no', toolbar: 'no', width: 1000, height: 1200, left: 3500, top: 50, margin: 0 }; return ( <div className={container} style={{ backgroundColor: theme.base01 }}> <div className={elements} style={{ backgroundColor: theme.base01 }} ref={this.getRef}> <Button theme={theme}>Actions</Button> <Button theme={theme}>Fixtures</Button> <SegmentedControl theme={theme} values={['Chart']} onClick={this.toggleChart} selected={showChart ? 'Chart' : ''} /> </div> {showChart && ( <NewWindow title='DevTools Chart' features={winOptions} onUnload={this.popupUnload}> <DevToolsChart {...this.props} /> </NewWindow> )} </div> ); } } export default withStyles(styles)(Launcher);
hakujitsu/tp
src/test/java/seedu/address/model/sale/UniqueSaleListTest.java
<reponame>hakujitsu/tp<filename>src/test/java/seedu/address/model/sale/UniqueSaleListTest.java package seedu.address.model.sale; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import static seedu.address.testutil.Assert.assertThrows; import static seedu.address.testutil.sale.TypicalSales.APPLE; import static seedu.address.testutil.sale.TypicalSales.BALL; import java.math.BigDecimal; import java.time.Month; import java.time.Year; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import org.junit.jupiter.api.Test; import seedu.address.model.sale.exceptions.DuplicateSaleException; import seedu.address.model.sale.exceptions.SaleNotFoundException; import seedu.address.testutil.sale.SaleBuilder; public class UniqueSaleListTest { private final UniqueSaleList uniqueSaleList = new UniqueSaleList(); @Test public void contains_nullSale_throwsNullPointerException() { assertThrows(NullPointerException.class, () -> uniqueSaleList.contains(null)); } @Test public void contains_saleNotInList_returnsFalse() { assertFalse(uniqueSaleList.contains(APPLE)); } @Test public void contains_saleInList_returnsTrue() { uniqueSaleList.add(APPLE); assertTrue(uniqueSaleList.contains(APPLE)); } @Test public void add_nullSale_throwsNullPointerException() { assertThrows(NullPointerException.class, () -> uniqueSaleList.add(null)); } @Test public void add_duplicateSale_throwsDuplicateSaleException() { Month month = APPLE.getMonth(); Year year = APPLE.getYear(); List<Sale> oldMonthlySaleList = new ArrayList<>(uniqueSaleList.getMonthlySaleList(month, year)); uniqueSaleList.add(APPLE); oldMonthlySaleList.add(APPLE); assertEquals(oldMonthlySaleList, uniqueSaleList.getMonthlySaleList(month, year)); assertThrows(DuplicateSaleException.class, () -> uniqueSaleList.add(APPLE)); } @Test public void setSale_nullTargetSale_throwsNullPointerException() { assertThrows(NullPointerException.class, () -> uniqueSaleList.setSale(null, APPLE)); } @Test public void setSale_nullEditedSale_throwsNullPointerException() { assertThrows(NullPointerException.class, () -> uniqueSaleList.setSale(APPLE, null)); } @Test public void setSale_targetSaleNotInList_throwsSaleNotFoundException() { assertThrows(SaleNotFoundException.class, () -> uniqueSaleList.setSale(APPLE, APPLE)); } @Test public void setSale_editedSaleIsSameSale_success() { Month month = APPLE.getMonth(); Year year = APPLE.getYear(); uniqueSaleList.add(APPLE); List<Sale> oldMonthlySaleList = new ArrayList<>(uniqueSaleList.getMonthlySaleList(month, year)); uniqueSaleList.setSale(APPLE, APPLE); UniqueSaleList expectedUniqueSaleList = new UniqueSaleList(); expectedUniqueSaleList.add(APPLE); assertEquals(expectedUniqueSaleList, uniqueSaleList); assertEquals(oldMonthlySaleList, uniqueSaleList.getMonthlySaleList(month, year)); } @Test public void setSale_editedSaleHasSameIdentity_success() { uniqueSaleList.add(APPLE); Sale editedApple = new SaleBuilder(APPLE).withUnitPrice(new BigDecimal("5.60")).withQuantity(20).build(); uniqueSaleList.setSale(APPLE, editedApple); UniqueSaleList expectedUniqueSaleList = new UniqueSaleList(); expectedUniqueSaleList.add(editedApple); assertEquals(expectedUniqueSaleList, uniqueSaleList); } @Test public void setSale_editedSaleHasDifferentIdentity_success() { uniqueSaleList.add(APPLE); uniqueSaleList.setSale(APPLE, BALL); UniqueSaleList expectedUniqueSaleList = new UniqueSaleList(); expectedUniqueSaleList.add(BALL); assertEquals(expectedUniqueSaleList, uniqueSaleList); } @Test public void setSale_editedSaleHasNonUniqueIdentity_throwsDuplicatePersonException() { uniqueSaleList.add(APPLE); uniqueSaleList.add(BALL); assertThrows(DuplicateSaleException.class, () -> uniqueSaleList.setSale(APPLE, BALL)); } @Test public void remove_nullSale_throwsNullPointerException() { assertThrows(NullPointerException.class, () -> uniqueSaleList.remove(null)); } @Test public void remove_saleDoesNotExist_throwsSaleNotFoundException() { assertThrows(SaleNotFoundException.class, () -> uniqueSaleList.remove(APPLE)); } @Test public void remove_existingSale_removesSale() { Month month = APPLE.getMonth(); Year year = APPLE.getYear(); uniqueSaleList.add(APPLE); uniqueSaleList.remove(APPLE); UniqueSaleList expectedUniqueSaleList = new UniqueSaleList(); assertEquals(expectedUniqueSaleList, uniqueSaleList); assertEquals(Collections.emptyList(), uniqueSaleList.getMonthlySaleList(month, year)); } @Test public void setSales_nullUniqueSaleList_throwsNullPointerException() { assertThrows(NullPointerException.class, () -> uniqueSaleList.setSales((UniqueSaleList) null)); } @Test public void setSales_uniqueSaleList_replacesOwnListWithProvidedUniqueSaleList() { uniqueSaleList.add(APPLE); UniqueSaleList expectedUniqueSaleList = new UniqueSaleList(); expectedUniqueSaleList.add(BALL); uniqueSaleList.setSales(expectedUniqueSaleList); assertEquals(expectedUniqueSaleList, uniqueSaleList); } @Test public void setSales_nullList_throwsNullPointerException() { assertThrows(NullPointerException.class, () -> uniqueSaleList.setSales((List<Sale>) null)); } @Test public void setSales_list_replacesOwnListWithProvidedList() { uniqueSaleList.add(APPLE); List<Sale> saleList = Collections.singletonList(BALL); uniqueSaleList.setSales(saleList); UniqueSaleList expectedUniqueSaleList = new UniqueSaleList(); expectedUniqueSaleList.add(BALL); assertEquals(expectedUniqueSaleList, uniqueSaleList); } @Test public void setSales_listWithDuplicateSales_throwsDuplicateSaleException() { List<Sale> listWithDuplicateSales = Arrays.asList(APPLE, APPLE); assertThrows(DuplicateSaleException.class, () -> uniqueSaleList.setSales(listWithDuplicateSales)); } @Test public void asUnmodifiableObservableList_modifyList_throwsUnsupportedOperationException() { assertThrows(UnsupportedOperationException.class, () -> uniqueSaleList.asUnmodifiableObservableList().remove(0)); } }
ArrogantWombatics/openbsd-src
lib/libradius/radius_local.h
/* $OpenBSD: radius_local.h,v 1.1 2015/07/20 23:52:29 yasuoka Exp $ */ /*- * Copyright (c) 2009 Internet Initiative Japan Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #ifndef RADIUS_LOCAL_H #define RADIUS_LOCAL_H #ifndef countof #define countof(x) (sizeof(x)/sizeof((x)[0])) #endif typedef struct _RADIUS_PACKET_DATA { uint8_t code; uint8_t id; uint16_t length; uint8_t authenticator[16]; char attributes[0]; } RADIUS_PACKET_DATA; #pragma pack(1) typedef struct _RADIUS_ATTRIBUTE { uint8_t type; uint8_t length; char data[0]; uint32_t vendor; uint8_t vtype; uint8_t vlength; char vdata[0]; } RADIUS_ATTRIBUTE; #pragma pack() struct _RADIUS_PACKET { RADIUS_PACKET_DATA *pdata; size_t capacity; const RADIUS_PACKET *request; }; #define RADIUS_PACKET_CAPACITY_INITIAL 64 #define RADIUS_PACKET_CAPACITY_INCREMENT 64 #define ATTRS_BEGIN(pdata) ((RADIUS_ATTRIBUTE*)pdata->attributes) #define ATTRS_END(pdata) \ ((RADIUS_ATTRIBUTE*)(((char*)pdata) + ntohs(pdata->length))) #define ATTRS_NEXT(x) ((RADIUS_ATTRIBUTE*)(((char*)x) + x->length)) /* * must be expression rather than statement * to be used in third expression of for statement. */ #define ATTRS_ADVANCE(x) (x = ATTRS_NEXT(x)) int radius_ensure_add_capacity(RADIUS_PACKET * packet, size_t capacity); #define ROUNDUP(a, b) ((((a) + (b) - 1) / (b)) * (b)) #define MINIMUM(a, b) (((a) < (b))? (a) : (b)) #endif /* RADIUS_LOCAL_H */
leongold/ovirt-engine
backend/manager/modules/dal/src/test/java/org/ovirt/engine/core/dao/gluster/StoageDeviceDaoTest.java
<gh_stars>1-10 package org.ovirt.engine.core.dao.gluster; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import java.util.List; import org.junit.Test; import org.ovirt.engine.core.common.businessentities.gluster.StorageDevice; import org.ovirt.engine.core.compat.Guid; import org.ovirt.engine.core.dao.BaseDaoTestCase; import org.ovirt.engine.core.dao.FixturesTool; public class StoageDeviceDaoTest extends BaseDaoTestCase { private static final Guid NEW_STORAGE_DEVICE_ID = new Guid("00000000-0000-0000-0000-000000000003"); private static final Guid EXISTING_STORAGE_DEVICE_ID_1 = new Guid("00000000-0000-0000-0000-000000000001"); private static final Guid EXISTING_STORAGE_DEVICE_ID_2 = new Guid("00000000-0000-0000-0000-000000000002"); private static final Guid NON_EXISTING_STORAGE_DEVICE_ID = new Guid("00000000-0000-0000-0000-000000000000"); private StorageDeviceDao dao; private StorageDevice getStorageDevice() { StorageDevice storageDevice = new StorageDevice(); storageDevice.setId(NEW_STORAGE_DEVICE_ID); storageDevice.setCanCreateBrick(true); storageDevice.setDescription("Test Device"); storageDevice.setDevPath("/dev/sdc"); storageDevice.setDevType("SCSI"); storageDevice.setDevUuid("ocIYJv-Ej8x-vDPm-kcGr-sHqy-jjeo-Jt2hTj"); storageDevice.setName("sdc"); storageDevice.setSize(10000L); storageDevice.setVdsId(FixturesTool.GLUSTER_BRICK_SERVER1); return storageDevice; } @Override public void setUp() throws Exception { super.setUp(); dao = dbFacade.getStorageDeviceDao(); } @Test public void testGetById(){ StorageDevice storageDevice = dao.get(EXISTING_STORAGE_DEVICE_ID_1); assertNotNull("Failed to retrive storage device", storageDevice); assertEquals("Failed to retrive corrective storage device", EXISTING_STORAGE_DEVICE_ID_1, storageDevice.getId()); storageDevice = dao.get(NON_EXISTING_STORAGE_DEVICE_ID); assertNull(storageDevice); } @Test public void testSave() { StorageDevice storageDevice = getStorageDevice(); dao.save(storageDevice); StorageDevice storageDeviceFromDB = dao.get(storageDevice.getId()); assertEquals("Storage device is not saved correctly", storageDevice, storageDeviceFromDB); } @Test public void testGetStorageDevicesInHost() { List<StorageDevice> storageDevices = dao.getStorageDevicesInHost(FixturesTool.GLUSTER_BRICK_SERVER1); assertEquals("Fails to retrive all the storage devices for host", 2, storageDevices.size()); } @Test public void testRemove() { StorageDevice storageDevice = dao.get(EXISTING_STORAGE_DEVICE_ID_2); assertNotNull("storage device doesn't exists", storageDevice); dao.remove(EXISTING_STORAGE_DEVICE_ID_2); storageDevice = dao.get(EXISTING_STORAGE_DEVICE_ID_2); assertNull("Failed to remove storage device", storageDevice); } @Test public void testUpdateStorageDevice() { StorageDevice storageDevice = dao.get(EXISTING_STORAGE_DEVICE_ID_2); assertNotNull("storage device doesn't exists", storageDevice); storageDevice.setSize(1234567L); storageDevice.setMountPoint("/gluster-bricks/brick1"); storageDevice.setFsType("xfs"); dao.update(storageDevice); StorageDevice storageDeviceFromDB = dao.get(EXISTING_STORAGE_DEVICE_ID_2); assertEquals("Failed to update Storage Device", storageDevice, storageDeviceFromDB); } @Test public void updateIsFreeFlag() { StorageDevice storageDevice = dao.get(EXISTING_STORAGE_DEVICE_ID_2); assertNotNull("storage device doesn't exists", storageDevice); dao.updateIsFreeFlag(EXISTING_STORAGE_DEVICE_ID_2, false); storageDevice = dao.get(EXISTING_STORAGE_DEVICE_ID_2); assertFalse("canCreateBrick is not updated", storageDevice.getCanCreateBrick()); dao.updateIsFreeFlag(EXISTING_STORAGE_DEVICE_ID_2, true); storageDevice = dao.get(EXISTING_STORAGE_DEVICE_ID_2); assertTrue("canCreateBrick is not updated", storageDevice.getCanCreateBrick()); } }
shre2398/openvino
inference-engine/src/vpu/common/src/ngraph/transformations/dynamic_to_static_shape_reduce.cpp
// Copyright (C) 2020 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #include "vpu/ngraph/transformations/dynamic_to_static_shape_reduce.hpp" #include "vpu/ngraph/operations/dynamic_shape_resolver.hpp" #include <vpu/utils/error.hpp> #include "ngraph/graph_util.hpp" #include "ngraph/opsets/opset3.hpp" #include <memory> #include <numeric> #include <ngraph/validation_util.hpp> namespace vpu { void dynamicToStaticShapeReduce(std::shared_ptr<ngraph::Node> target) { const auto dsr = ngraph::as_type_ptr<ngraph::vpu::op::DynamicShapeResolver>(target->input_value(0).get_node_shared_ptr()); VPU_THROW_UNLESS(dsr, "DynamicToStaticShape transformation for {} of type {} expects {} as input with index {}", target->get_friendly_name(), target->get_type_info(), ngraph::vpu::op::DynamicShapeResolver::type_info, 0); VPU_THROW_UNLESS(std::dynamic_pointer_cast<ngraph::op::util::ArithmeticReductionKeepDims>(target) || std::dynamic_pointer_cast<ngraph::op::util::LogicalReductionKeepDims>(target), "dynamicToStaticShapeReduce transformation expects arithmetic or logical reduction, but it got {} node of type {}", target->get_friendly_name(), target->get_type_info()); const auto axes_const_node = ngraph::as_type_ptr<ngraph::opset3::Constant>(target->input_value(1).get_node_shared_ptr()); VPU_THROW_UNLESS(axes_const_node, "dynamicToStaticShapeReduce transformation for {} of type {} expects {} as input with index {}, but it has {} node of type {} instead", target->get_friendly_name(), target->get_type_info(), ngraph::opset3::Constant::type_info, 1, target->input_value(1).get_node_shared_ptr()->get_friendly_name(), target->input_value(1).get_node_shared_ptr()->get_type_info()); const auto axes = axes_const_node->cast_vector<int64_t>(); const auto data_rank = target->get_input_partial_shape(0).rank(); VPU_THROW_UNLESS(data_rank.is_static(), "dynamicToStaticShapeReduce transformation for {} doesn't support dynamic rank", target); const auto data_rank_value = data_rank.get_length(); bool keep_dims = false; if (const auto arithmetic_reduce = std::dynamic_pointer_cast<ngraph::op::util::ArithmeticReductionKeepDims>(target)) { keep_dims = arithmetic_reduce->get_keep_dims(); } else if (const auto logical_reduce = std::dynamic_pointer_cast<ngraph::op::util::LogicalReductionKeepDims>(target)) { keep_dims = logical_reduce->get_keep_dims(); } // assertion earlier excluded other variants const auto data_shape = dsr->input_value(1); ngraph::Output<ngraph::Node> output_shape; if (keep_dims) { output_shape = std::make_shared<ngraph::opset3::ScatterElementsUpdate>( data_shape, ngraph::opset3::Constant::create(ngraph::element::i64, {axes.size()}, axes), ngraph::opset3::Constant::create(ngraph::element::i64, {axes.size()}, std::vector<int64_t>(axes.size(), 1)), ngraph::opset3::Constant::create(ngraph::element::i64, {1}, {0})); } else { std::vector<int64_t> range(data_rank_value); std::iota(range.begin(), range.end(), 0); std::vector<int64_t> indices; std::copy_if(range.cbegin(), range.cend(), std::back_inserter(indices), [&axes](int64_t i) { return std::find(axes.cbegin(), axes.cend(), i) == axes.cend(); }); output_shape = std::make_shared<ngraph::opset3::Gather>( data_shape, ngraph::opset3::Constant::create(ngraph::element::i64, {indices.size()}, indices), ngraph::opset3::Constant::create(ngraph::element::i64, {1}, {0})); } const auto copied = target->clone_with_new_inputs(target->input_values()); auto outDSR = std::make_shared<ngraph::vpu::op::DynamicShapeResolver>(copied, output_shape); outDSR->set_friendly_name(target->get_friendly_name()); ngraph::replace_node(target, std::move(outDSR)); } } // namespace vpu
PlayFab/XPlatCSdk
test/TestApp/AutoGenTests/AutoGenAnalyticsTests.cpp
#include "TestAppPch.h" #include "TestContext.h" #include "TestApp.h" #include "AutoGenAnalyticsTests.h" #include "XAsyncHelper.h" #include "playfab/PFAuthentication.h" namespace PlayFabUnit { using namespace PlayFab::Wrappers; AutoGenAnalyticsTests::AnalyticsTestData AutoGenAnalyticsTests::testData; void AutoGenAnalyticsTests::Log(std::stringstream& ss) { TestApp::LogPut(ss.str().c_str()); ss.str(std::string()); ss.clear(); } HRESULT AutoGenAnalyticsTests::LogHR(HRESULT hr) { if (TestApp::ShouldTrace(PFTestTraceLevel::Information)) { TestApp::Log("Result: 0x%0.8x", hr); } return hr; } void AutoGenAnalyticsTests::AddTests() { // Generated tests AddTest("TestAnalyticsClientReportDeviceInfo", &AutoGenAnalyticsTests::TestAnalyticsClientReportDeviceInfo); #if HC_PLATFORM != HC_PLATFORM_GDK AddTest("TestAnalyticsGetDetails", &AutoGenAnalyticsTests::TestAnalyticsGetDetails); #endif #if HC_PLATFORM != HC_PLATFORM_GDK AddTest("TestAnalyticsGetLimits", &AutoGenAnalyticsTests::TestAnalyticsGetLimits); #endif #if HC_PLATFORM != HC_PLATFORM_GDK AddTest("TestAnalyticsGetOperationStatus", &AutoGenAnalyticsTests::TestAnalyticsGetOperationStatus); #endif #if HC_PLATFORM != HC_PLATFORM_GDK AddTest("TestAnalyticsGetPendingOperations", &AutoGenAnalyticsTests::TestAnalyticsGetPendingOperations); #endif #if HC_PLATFORM != HC_PLATFORM_GDK AddTest("TestAnalyticsSetPerformance", &AutoGenAnalyticsTests::TestAnalyticsSetPerformance); #endif #if HC_PLATFORM != HC_PLATFORM_GDK AddTest("TestAnalyticsSetStorageRetention", &AutoGenAnalyticsTests::TestAnalyticsSetStorageRetention); #endif } void AutoGenAnalyticsTests::ClassSetUp() { HRESULT hr = PFAdminInitialize(testTitleData.titleId.data(), testTitleData.developerSecretKey.data(), testTitleData.connectionString.data(), nullptr, &stateHandle); assert(SUCCEEDED(hr)); if (SUCCEEDED(hr)) { PFAuthenticationLoginWithCustomIDRequest request{}; request.customId = "CustomId"; request.createAccount = true; PFGetPlayerCombinedInfoRequestParams combinedInfoRequestParams{}; combinedInfoRequestParams.getCharacterInventories = true; combinedInfoRequestParams.getCharacterList = true; combinedInfoRequestParams.getPlayerProfile = true; combinedInfoRequestParams.getPlayerStatistics = true; combinedInfoRequestParams.getTitleData = true; combinedInfoRequestParams.getUserAccountInfo = true; combinedInfoRequestParams.getUserData = true; combinedInfoRequestParams.getUserInventory = true; combinedInfoRequestParams.getUserReadOnlyData = true; combinedInfoRequestParams.getUserVirtualCurrency = true; request.infoRequestParameters = &combinedInfoRequestParams; XAsyncBlock async{}; hr = PFAuthenticationClientLoginWithCustomIDAsync(stateHandle, &request, &async); assert(SUCCEEDED(hr)); if (SUCCEEDED(hr)) { // Synchronously wait for login to complete hr = XAsyncGetStatus(&async, true); assert(SUCCEEDED(hr)); if (SUCCEEDED(hr)) { hr = PFAuthenticationClientLoginGetResult(&async, &titlePlayerHandle); assert(SUCCEEDED(hr) && titlePlayerHandle); hr = PFTitlePlayerGetEntityHandle(titlePlayerHandle, &entityHandle); assert(SUCCEEDED(hr) && entityHandle); } } request.customId = "CustomId2"; async = {}; hr = PFAuthenticationClientLoginWithCustomIDAsync(stateHandle, &request, &async); assert(SUCCEEDED(hr)); if (SUCCEEDED(hr)) { // Synchronously what for login to complete hr = XAsyncGetStatus(&async, true); assert(SUCCEEDED(hr)); if (SUCCEEDED(hr)) { hr = PFAuthenticationClientLoginGetResult(&async, &titlePlayerHandle2); assert(SUCCEEDED(hr) && titlePlayerHandle2); hr = PFTitlePlayerGetEntityHandle(titlePlayerHandle2, &entityHandle2); assert(SUCCEEDED(hr) && entityHandle2); } } PFAuthenticationGetEntityTokenRequest titleTokenRequest{}; async = {}; hr = PFAuthenticationGetEntityTokenAsync(stateHandle, &titleTokenRequest, &async); assert(SUCCEEDED(hr)); if (SUCCEEDED(hr)) { // Synchronously wait for login to complete hr = XAsyncGetStatus(&async, true); assert(SUCCEEDED(hr)); if (SUCCEEDED(hr)) { hr = PFAuthenticationGetEntityTokenGetResult(&async, &titleEntityHandle); assert(SUCCEEDED(hr)); } } } } void AutoGenAnalyticsTests::ClassTearDown() { PFTitlePlayerCloseHandle(titlePlayerHandle); PFEntityCloseHandle(entityHandle); PFEntityCloseHandle(titleEntityHandle); XAsyncBlock async{}; HRESULT hr = PFUninitializeAsync(stateHandle, &async); assert(SUCCEEDED(hr)); hr = XAsyncGetStatus(&async, true); assert(SUCCEEDED(hr)); UNREFERENCED_PARAMETER(hr); } void AutoGenAnalyticsTests::SetUp(TestContext& testContext) { if (!entityHandle) { testContext.Skip("Skipping test because login failed"); } } #pragma region ClientReportDeviceInfo void AutoGenAnalyticsTests::TestAnalyticsClientReportDeviceInfo(TestContext& testContext) { auto async = std::make_unique<XAsyncHelper<XAsyncResult>>(testContext); PFAnalyticsDeviceInfoRequestWrapper<> request; FillClientReportDeviceInfoRequest(request); LogDeviceInfoRequest(&request.Model(), "TestAnalyticsClientReportDeviceInfo"); HRESULT hr = PFAnalyticsClientReportDeviceInfoAsync(titlePlayerHandle, &request.Model(), &async->asyncBlock); if (FAILED(hr)) { testContext.Fail("PFAnalyticsAnalyticsClientReportDeviceInfoAsync", hr); return; } async.release(); } #pragma endregion #pragma region GetDetails #if HC_PLATFORM != HC_PLATFORM_GDK void AutoGenAnalyticsTests::TestAnalyticsGetDetails(TestContext& testContext) { struct GetDetailsResultHolderStruct : public InsightsGetDetailsResponseHolder { HRESULT Get(XAsyncBlock* async) override { size_t requiredBufferSize; RETURN_IF_FAILED(LogHR(PFAnalyticsGetDetailsGetResultSize(async, &requiredBufferSize))); resultBuffer.resize(requiredBufferSize); RETURN_IF_FAILED(LogHR(PFAnalyticsGetDetailsGetResult(async, resultBuffer.size(), resultBuffer.data(), &result, nullptr))); LogInsightsGetDetailsResponse(result); return S_OK; } HRESULT Validate() override { return ValidateGetDetailsResponse(result); } }; auto async = std::make_unique<XAsyncHelper<GetDetailsResultHolderStruct>>(testContext); PFAnalyticsInsightsEmptyRequestWrapper<> request; FillGetDetailsRequest(request); LogInsightsEmptyRequest(&request.Model(), "TestAnalyticsGetDetails"); HRESULT hr = PFAnalyticsGetDetailsAsync(entityHandle, &request.Model(), &async->asyncBlock); if (FAILED(hr)) { testContext.Fail("PFAnalyticsAnalyticsGetDetailsAsync", hr); return; } async.release(); } #endif #pragma endregion #pragma region GetLimits #if HC_PLATFORM != HC_PLATFORM_GDK void AutoGenAnalyticsTests::TestAnalyticsGetLimits(TestContext& testContext) { struct GetLimitsResultHolderStruct : public InsightsGetLimitsResponseHolder { HRESULT Get(XAsyncBlock* async) override { size_t requiredBufferSize; RETURN_IF_FAILED(LogHR(PFAnalyticsGetLimitsGetResultSize(async, &requiredBufferSize))); resultBuffer.resize(requiredBufferSize); RETURN_IF_FAILED(LogHR(PFAnalyticsGetLimitsGetResult(async, resultBuffer.size(), resultBuffer.data(), &result, nullptr))); LogInsightsGetLimitsResponse(result); return S_OK; } HRESULT Validate() override { return ValidateGetLimitsResponse(result); } }; auto async = std::make_unique<XAsyncHelper<GetLimitsResultHolderStruct>>(testContext); PFAnalyticsInsightsEmptyRequestWrapper<> request; FillGetLimitsRequest(request); LogInsightsEmptyRequest(&request.Model(), "TestAnalyticsGetLimits"); HRESULT hr = PFAnalyticsGetLimitsAsync(entityHandle, &request.Model(), &async->asyncBlock); if (FAILED(hr)) { testContext.Fail("PFAnalyticsAnalyticsGetLimitsAsync", hr); return; } async.release(); } #endif #pragma endregion #pragma region GetOperationStatus #if HC_PLATFORM != HC_PLATFORM_GDK void AutoGenAnalyticsTests::TestAnalyticsGetOperationStatus(TestContext& testContext) { struct GetOperationStatusResultHolderStruct : public InsightsGetOperationStatusResponseHolder { HRESULT Get(XAsyncBlock* async) override { size_t requiredBufferSize; RETURN_IF_FAILED(LogHR(PFAnalyticsGetOperationStatusGetResultSize(async, &requiredBufferSize))); resultBuffer.resize(requiredBufferSize); RETURN_IF_FAILED(LogHR(PFAnalyticsGetOperationStatusGetResult(async, resultBuffer.size(), resultBuffer.data(), &result, nullptr))); LogInsightsGetOperationStatusResponse(result); return S_OK; } HRESULT Validate() override { return ValidateGetOperationStatusResponse(result); } }; auto async = std::make_unique<XAsyncHelper<GetOperationStatusResultHolderStruct>>(testContext); PFAnalyticsInsightsGetOperationStatusRequestWrapper<> request; FillGetOperationStatusRequest(request); LogInsightsGetOperationStatusRequest(&request.Model(), "TestAnalyticsGetOperationStatus"); HRESULT hr = PFAnalyticsGetOperationStatusAsync(entityHandle, &request.Model(), &async->asyncBlock); if (FAILED(hr)) { testContext.Fail("PFAnalyticsAnalyticsGetOperationStatusAsync", hr); return; } async.release(); } #endif #pragma endregion #pragma region GetPendingOperations #if HC_PLATFORM != HC_PLATFORM_GDK void AutoGenAnalyticsTests::TestAnalyticsGetPendingOperations(TestContext& testContext) { struct GetPendingOperationsResultHolderStruct : public InsightsGetPendingOperationsResponseHolder { HRESULT Get(XAsyncBlock* async) override { size_t requiredBufferSize; RETURN_IF_FAILED(LogHR(PFAnalyticsGetPendingOperationsGetResultSize(async, &requiredBufferSize))); resultBuffer.resize(requiredBufferSize); RETURN_IF_FAILED(LogHR(PFAnalyticsGetPendingOperationsGetResult(async, resultBuffer.size(), resultBuffer.data(), &result, nullptr))); LogInsightsGetPendingOperationsResponse(result); return S_OK; } HRESULT Validate() override { return ValidateGetPendingOperationsResponse(result); } }; auto async = std::make_unique<XAsyncHelper<GetPendingOperationsResultHolderStruct>>(testContext); PFAnalyticsInsightsGetPendingOperationsRequestWrapper<> request; FillGetPendingOperationsRequest(request); LogInsightsGetPendingOperationsRequest(&request.Model(), "TestAnalyticsGetPendingOperations"); HRESULT hr = PFAnalyticsGetPendingOperationsAsync(entityHandle, &request.Model(), &async->asyncBlock); if (FAILED(hr)) { testContext.Fail("PFAnalyticsAnalyticsGetPendingOperationsAsync", hr); return; } async.release(); } #endif #pragma endregion #pragma region SetPerformance #if HC_PLATFORM != HC_PLATFORM_GDK void AutoGenAnalyticsTests::TestAnalyticsSetPerformance(TestContext& testContext) { struct SetPerformanceResultHolderStruct : public InsightsOperationResponseHolder { HRESULT Get(XAsyncBlock* async) override { size_t requiredBufferSize; RETURN_IF_FAILED(LogHR(PFAnalyticsSetPerformanceGetResultSize(async, &requiredBufferSize))); resultBuffer.resize(requiredBufferSize); RETURN_IF_FAILED(LogHR(PFAnalyticsSetPerformanceGetResult(async, resultBuffer.size(), resultBuffer.data(), &result, nullptr))); LogInsightsOperationResponse(result); return S_OK; } HRESULT Validate() override { return ValidateSetPerformanceResponse(result); } }; auto async = std::make_unique<XAsyncHelper<SetPerformanceResultHolderStruct>>(testContext); PFAnalyticsInsightsSetPerformanceRequestWrapper<> request; FillSetPerformanceRequest(request); LogInsightsSetPerformanceRequest(&request.Model(), "TestAnalyticsSetPerformance"); HRESULT hr = PFAnalyticsSetPerformanceAsync(entityHandle, &request.Model(), &async->asyncBlock); if (FAILED(hr)) { testContext.Fail("PFAnalyticsAnalyticsSetPerformanceAsync", hr); return; } async.release(); } #endif #pragma endregion #pragma region SetStorageRetention #if HC_PLATFORM != HC_PLATFORM_GDK void AutoGenAnalyticsTests::TestAnalyticsSetStorageRetention(TestContext& testContext) { struct SetStorageRetentionResultHolderStruct : public InsightsOperationResponseHolder { HRESULT Get(XAsyncBlock* async) override { size_t requiredBufferSize; RETURN_IF_FAILED(LogHR(PFAnalyticsSetStorageRetentionGetResultSize(async, &requiredBufferSize))); resultBuffer.resize(requiredBufferSize); RETURN_IF_FAILED(LogHR(PFAnalyticsSetStorageRetentionGetResult(async, resultBuffer.size(), resultBuffer.data(), &result, nullptr))); LogInsightsOperationResponse(result); return S_OK; } HRESULT Validate() override { return ValidateSetStorageRetentionResponse(result); } }; auto async = std::make_unique<XAsyncHelper<SetStorageRetentionResultHolderStruct>>(testContext); PFAnalyticsInsightsSetStorageRetentionRequestWrapper<> request; FillSetStorageRetentionRequest(request); LogInsightsSetStorageRetentionRequest(&request.Model(), "TestAnalyticsSetStorageRetention"); HRESULT hr = PFAnalyticsSetStorageRetentionAsync(entityHandle, &request.Model(), &async->asyncBlock); if (FAILED(hr)) { testContext.Fail("PFAnalyticsAnalyticsSetStorageRetentionAsync", hr); return; } async.release(); } #endif #pragma endregion }
chrislcs/linear-vegetation-elements
Code/segmentation_pipeline.py
# -*- coding: utf-8 -*- """ @author: <NAME> """ import time import multiprocessing import pickle import pandas as pd import numpy as np from tqdm import tqdm from segmentation.regiongrowing import segment_object PROCESSES = multiprocessing.cpu_count() - 1 INPUT = '../Data/vegetation_dbscan.csv' OUTPUT = '../Data/segments.pkl' min_size = 5 rectangularity_limit = 0.55 alpha = 0.4 k_init = 10 max_dist_init = 15.0 knn = 8 max_dist = 5 point_cloud = pd.read_csv(INPUT) points = point_cloud[['X', 'Y']].values.copy() shift = np.min(points, axis=0) num_clusters = max(point_cloud['cluster']) inputs = point_cloud['cluster'].value_counts().index segments = [] pbar = tqdm(total=point_cloud['cluster'].count()) def run_segmentation(i): cluster = point_cloud.loc[point_cloud['cluster'] == i] cluster_points = cluster[['X', 'Y']].values.copy() cluster_points -= shift cluster_segments = segment_object(cluster_points, min_size, rectangularity_limit, alpha, k_init, max_dist_init, knn, max_dist) return cluster_segments def add_result(result): segments.extend(result) pbar.update(sum([len(r) for r in result])) def run_multi(): with multiprocessing.Pool(processes=PROCESSES) as p: for i in inputs: p.apply_async(run_segmentation, args=(i,), callback=add_result) p.close() p.join() pbar.close() if __name__ == '__main__': t = time.time() run_multi() print('Done! Time elapsed: %.2f' % (time.time() - t)) with open(OUTPUT, 'wb') as f: pickle.dump(segments, f)
Scottx86-64/dotfiles-1
source/pkgsrc/comms/lirc/patches/patch-daemons_hw__default.c
<gh_stars>1-10 $NetBSD: patch-daemons_hw__default.c,v 1.1 2020/03/15 21:08:41 tnn Exp $ Add a missing include. --- daemons/hw_default.c.orig 2011-03-25 22:28:18.000000000 +0000 +++ daemons/hw_default.c @@ -21,6 +21,7 @@ #include <limits.h> #include <signal.h> #include <sys/stat.h> +#include <sys/sysmacros.h> /* for major() */ #include <sys/types.h> #include <sys/ioctl.h> #include <sys/socket.h>
LLNL/devil_ray
src/dray/data_model/subpatch.hpp
<reponame>LLNL/devil_ray<filename>src/dray/data_model/subpatch.hpp // Copyright 2019 Lawrence Livermore National Security, LLC and other // Devil Ray Developers. See the top-level COPYRIGHT file for details. // // SPDX-License-Identifier: (BSD-3-Clause) #ifndef DRAY_SUBPATCH_HPP #define DRAY_SUBPATCH_HPP #include <dray/data_model/bernstein_basis.hpp> namespace dray { // SplitDepth == how many axes, starting from outermost, should be split. template <uint32 SplitDepth, typename Split1DMethod = DeCasteljau> struct SubPatch; // Base case. template <typename Split1DMethod> struct SubPatch<1u, Split1DMethod> { // Computes the Bernstein coefficients of a sub-patch by applying DeCasteljau twice. // If a non-negative argument to POrder is given, // that is used, else the argument to p_order is used. template <typename MultiArrayT, int32 POrder = -1> DRAY_EXEC static void sub_patch_inplace (MultiArrayT &elem_data, const Range *ref_box, uint32 p_order = 0) { const auto t1 = ref_box[0].max (); auto t0 = ref_box[0].min (); // Split left. if (t1 < 1.0) Split1DMethod::template split_inplace_left<MultiArrayT, POrder> (elem_data, t1, p_order); if (t1 > 0.0) t0 /= t1; // Split right. if (t0 > 0.0) Split1DMethod::template split_inplace_right<MultiArrayT, POrder> (elem_data, t0, p_order); } }; // Arbitrary number of splits. template <uint32 SplitDepth, typename Split1DMethod> struct SubPatch { // Computes the Bernstein coefficients of a sub-patch by applying DeCasteljau twice per axis. // If a non-negative argument to POrder is given, // that is used, else the argument to p_order is used. template <typename MultiArrayT, int32 POrder = -1> DRAY_EXEC static void sub_patch_inplace (MultiArrayT &elem_data, const Range *ref_box, uint32 p_order = 0) { using ComponentT = typename FirstComponent<MultiArrayT, SplitDepth - 1>::component_t; const auto t1 = ref_box[0].max (); auto t0 = ref_box[0].min (); // Split left (outer axis). if (t1 < 1.0) for (auto &coeff_list : elem_data.template components<SplitDepth - 1> ()) Split1DMethod::template split_inplace_left<ComponentT, POrder> (coeff_list, t1, p_order); if (t1 > 0.0) t0 /= t1; // Split right (outer axis). if (t0 > 0.0) for (auto &coeff_list : elem_data.template components<SplitDepth - 1> ()) Split1DMethod::template split_inplace_right<ComponentT, POrder> (coeff_list, t0, p_order); // Split left/right (each inner axis). SubPatch<SplitDepth - 1, Split1DMethod>::template sub_patch_inplace<MultiArrayT, POrder> ( elem_data, ref_box + 1, p_order); } }; } // namespace dray #endif // DRAY_SUBPATCH_HPP
ijhajj/JavaRepository
HelloWorld/src/designPatterns/Relationships.java
<filename>HelloWorld/src/designPatterns/Relationships.java package designPatterns; import java.util.List; import java.util.ArrayList; import org.javatuples.Triplet; public class Relationships { private List<Triplet<Person,Relationship,Person>> relations = new ArrayList<>(); public List<Triplet<Person, Relationship, Person>> getRelations() { return relations; } public void addParentAndChild(Person parent,Person child) { relations.add(new Triplet<>(parent,Relationship.PARENT,child)); relations.add(new Triplet<>(child,Relationship.CHILD,parent)); } }
wardat/apache-ant-1.6.2
src/main/org/apache/tools/ant/taskdefs/optional/j2ee/HotDeploymentTool.java
/* * Copyright 2002,2004 The Apache Software 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.apache.tools.ant.taskdefs.optional.j2ee; import org.apache.tools.ant.BuildException; /** * An interface for vendor-specific "hot" deployment tools. * * * @see org.apache.tools.ant.taskdefs.optional.j2ee.AbstractHotDeploymentTool * @see org.apache.tools.ant.taskdefs.optional.j2ee.ServerDeploy */ public interface HotDeploymentTool { /** The delete action String **/ public static final String ACTION_DELETE = "delete"; /** The deploy action String **/ public static final String ACTION_DEPLOY = "deploy"; /** The list action String **/ public static final String ACTION_LIST = "list"; /** The undeploy action String **/ public static final String ACTION_UNDEPLOY = "undeploy"; /** The update action String **/ public static final String ACTION_UPDATE = "update"; /** * Validates the passed in attributes. * @exception org.apache.tools.ant.BuildException if the attributes are invalid or incomplete. */ public void validateAttributes() throws BuildException; /** * Perform the actual deployment. * @exception org.apache.tools.ant.BuildException if the attributes are invalid or incomplete. */ public void deploy() throws BuildException; /** * Sets the parent task. * @param task A ServerDeploy object representing the parent task. */ public void setTask(ServerDeploy task); }
Integreat/integreat-webapp
src/modules/layout/components/__tests__/HeaderActionItemDropDown.spec.js
<reponame>Integreat/integreat-webapp // @flow import React from 'react' import { mount } from 'enzyme' import ClickOutsideHeaderDropDown, { DropDownContainer, HeaderActionItemDropDown } from '../HeaderActionItemDropDown' import fileMock from '../../../../__mocks__/fileMock' import brightTheme from '../../../theme/constants/theme' describe('HeaderActionItemDropDown', () => { const MockNode = () => <div>Here comes the DropDown</div> let wrapperComponent beforeEach(() => { wrapperComponent = mount(<ClickOutsideHeaderDropDown theme={brightTheme} iconSrc='/someImg' text='some text'> <MockNode /> </ClickOutsideHeaderDropDown>) }) it('should pass correct closeDropDown callback', () => { const component = wrapperComponent.find(HeaderActionItemDropDown) const instance = component.instance() const callback = wrapperComponent.find('MockNode').prop('closeDropDownCallback') expect(callback).toEqual(instance?.closeDropDown) }) describe('closeDropDown()', () => { it('should close DropDown if active', () => { const component = wrapperComponent.find(HeaderActionItemDropDown) component.setState({ dropDownActive: true }) const instance: any = component.instance() instance.closeDropDown() expect(instance.state.dropDownActive).toBe(false) }) it('shouldnt open DropDown if inactive', () => { const component = wrapperComponent.find(HeaderActionItemDropDown) const instance: any = component.instance() instance.closeDropDown() instance.closeDropDown() expect(instance.state.dropDownActive).toBe(false) }) }) describe('toggleDropDown()', () => { it('should close DropDown if active', () => { const component = wrapperComponent.find(HeaderActionItemDropDown) component.setState({ dropDownActive: true }) const instance: any = component.instance() instance.toggleDropDown() expect(instance.state.dropDownActive).toBe(false) }) it('should open DropDown if inactive', () => { const component = wrapperComponent.find(HeaderActionItemDropDown) const instance: any = component.instance() instance.toggleDropDown() expect(instance.state.dropDownActive).toBe(true) }) }) it('should toggle when user clicks on button', () => { const component = wrapperComponent.find(HeaderActionItemDropDown) const instance: any = component.instance() const onClick = component.find({ selector: 'button' }).prop('onClick') expect(onClick).toBe(instance.toggleDropDown) }) it('should call closeDropDown when handleClickOutside is called', () => { const component = wrapperComponent.find(HeaderActionItemDropDown) const instance: any = component.instance() instance.closeDropDown = jest.fn() instance.handleClickOutside() expect(instance.closeDropDown).toHaveBeenCalled() }) it('should be closed from the beginning', () => { const component = wrapperComponent.find(HeaderActionItemDropDown) const instance: any = component.instance() expect(instance.state.dropDownActive).toBe(false) }) it('should add class if active', () => { const component = mount(<HeaderActionItemDropDown theme={brightTheme} iconSrc={fileMock} text='some text'><MockNode /></HeaderActionItemDropDown>) expect(component.find(DropDownContainer).prop('active')).toBe(false) component.setState({ dropDownActive: true }) expect(component.find(DropDownContainer).prop('active')).toBe(true) }) })
rook2pawn/password-manager-baseweb
icons/scooter_foot_break_outlined/ScooterFootBreakOutlined.js
<reponame>rook2pawn/password-manager-baseweb import * as React from "react"; function SvgScooterFootBreakOutlined(props) { return ( <svg width={24} height={24} fill="none" xmlns="http://www.w3.org/2000/svg" {...props} > <path d="M14.5 8c-3.07 0-5.64 2.14-6.32 5H6.14c.71-3.97 4.19-7 8.36-7 2.02 0 3.98.73 5.53 2.04l1.94-2.28A11.53 11.53 0 0014.5 3C8.67 3 3.85 7.37 3.11 13H0v3h8.18c.68 2.86 3.25 5 6.32 5 3.58 0 6.5-2.92 6.5-6.5S18.08 8 14.5 8zm0 10c-1.93 0-3.5-1.57-3.5-3.5s1.57-3.5 3.5-3.5 3.5 1.57 3.5 3.5-1.57 3.5-3.5 3.5z" fill="currentColor" /> </svg> ); } export default SvgScooterFootBreakOutlined;
rikhuijzer/u-can-act
config/application.rb
require_relative 'boot' require 'rails/all' # Require the gems listed in Gemfile, including any gems # you've limited to :test, :development, or :production. Bundler.require(*Rails.groups) Mongo::Logger.logger.level = ::Logger::INFO module Vsv class Application < Rails::Application # Initialize configuration defaults for originally generated Rails version. config.load_defaults 6.1 # Application configuration can go into files in config/initializers # -- all .rb files in that directory are automatically loaded after loading # the framework and any gems in your application. Rails.application.routes.default_url_options[:host] = ENV['HOST_URL'] config.time_zone = 'Amsterdam' config.i18n.load_path += Dir[Rails.root.join('config', 'locales', '**', '*.{rb,yml}').to_s] config.i18n.default_locale = :nl config.i18n.available_locales = [:nl, :en] # Rails 6 optimization. # See https://edgeguides.rubyonrails.org/upgrading_ruby_on_rails.html#config-add-autoload-paths-to-load-path config.add_autoload_paths_to_load_path = false config.middleware.use I18n::JS::Middleware config.active_job.queue_adapter = :delayed_job # Enable react addons config.react.addons = true config.generators do |g| # Set basic DBMS as main database g.orm :active_record # set rspec as the testframework g.test_framework :rspec, fixture: true # Define the factories of factory bot (model mock) g.fixture_replacement :factory_bot, dir: 'spec/factories' # Generate specs for helpers and views g.view_specs true g.helper_specs true # Don't generate stylesheets and javascript g.stylesheets = false g.javascripts = false g.helper = false end end end
Cinegy/Cinecoder.Samples
common/conio.h
#ifdef _WIN32 #include <conio.h> #else /** Linux (POSIX) implementation of _kbhit(). <NAME>, <EMAIL> */ #include <stdio.h> #include <sys/select.h> #include <termios.h> //#include <stropts.h> //#include <asm/ioctls.h> #include <sys/ioctl.h> #include <unistd.h> inline int _kbhit() { static const int STDIN = 0; static bool initialized = false; if (! initialized) { // Use termios to turn off line buffering termios term; tcgetattr(STDIN, &term); term.c_lflag &= ~ICANON; tcsetattr(STDIN, TCSANOW, &term); setbuf(stdin, NULL); initialized = true; } int bytesWaiting = 0; ioctl(STDIN, FIONREAD, &bytesWaiting); return bytesWaiting; } int inline _getch() { struct termios oldt, newt; int ch; tcgetattr( STDIN_FILENO, &oldt ); newt = oldt; newt.c_lflag &= ~( ICANON | ECHO ); tcsetattr( STDIN_FILENO, TCSANOW, &newt ); ch = getchar(); tcsetattr( STDIN_FILENO, TCSANOW, &oldt ); return ch; } #endif
zenofewords/thebrushstash
thebrushstash/models.py
<reponame>zenofewords/thebrushstash<gh_stars>0 from django.db import models from django.utils.translation import get_language from thebrushstash.mixins import ( LinkedMixin, PublishedMixin, TimeStampMixin, ) class Country(PublishedMixin): name = models.CharField(max_length=500) name_cro = models.CharField(max_length=500, blank=True) slug = models.CharField(max_length=500) shipping_cost = models.DecimalField( verbose_name='Shipping cost', max_digits=14, decimal_places=2, blank=False, null=True, ) class Meta: verbose_name = 'Country' verbose_name_plural = 'Countries' ordering = ('slug', ) def __str__(self): language = get_language() if language == 'hr': return self.name_cro return self.name class ExchangeRate(TimeStampMixin): currency = models.CharField(max_length=10) currency_code = models.CharField(max_length=10) state_iso = models.CharField(max_length=10) buying_rate = models.DecimalField(max_digits=10, decimal_places=8) middle_rate = models.DecimalField(max_digits=10, decimal_places=8) selling_rate = models.DecimalField(max_digits=10, decimal_places=8) added_value = models.DecimalField( max_digits=5, decimal_places=2, help_text='The percentage added when converting from HRK' ) class Meta: verbose_name = 'Exchange rate' verbose_name_plural = 'Exchange rates' def __str__(self): return '1 {} equals {} HRK'.format(self.currency, self.middle_rate) class TestImage(PublishedMixin): name = models.CharField(max_length=500) def __str__(self): return self.name class CreditCardLogo(LinkedMixin, PublishedMixin): pass class NavigationItem(LinkedMixin, PublishedMixin): name_cro = models.CharField(max_length=500, blank=True) class FooterItem(LinkedMixin, PublishedMixin): name_cro = models.CharField(max_length=500, blank=True) class FooterShareLink(LinkedMixin, PublishedMixin): name_cro = models.CharField(max_length=500, blank=True) class Region(PublishedMixin): name = models.CharField(max_length=10) language = models.CharField(max_length=10) currency = models.CharField(max_length=10) ordering = models.IntegerField(default=0, blank=True) class Meta: verbose_name = 'Region' verbose_name_plural = 'Regions' ordering = ('-ordering', ) def __str__(self): return self.name class StaticPageContent(models.Model): title = models.CharField(max_length=1000) title_cro = models.CharField(max_length=1000) slug = models.CharField(max_length=100) content = models.TextField(max_length=30000) content_cro = models.TextField(max_length=30000) class Meta: verbose_name = 'Static page content' verbose_name_plural = 'Static pages content' def __str__(self): return self.title class Setting(models.Model): name = models.CharField(max_length=50) value = models.DecimalField(max_digits=14, decimal_places=2) class Meta: verbose_name = 'Setting' verbose_name_plural = 'Settings' def __str__(self): return '{} - {}'.format(self.name, self.value) class QandAPair(models.Model): question = models.TextField(max_length=2000) question_cro = models.TextField(max_length=2000) answer = models.TextField(max_length=5000) answer_cro = models.TextField(max_length=5000) ordering = models.IntegerField( default=0, blank=True, help_text='If set to 0, items are ordered by creation date' ) class Meta: verbose_name = 'Question and answer pair' verbose_name = 'Question and answer pair' ordering = ('-ordering', ) def __str__(self): return self.question[:50]
chgogos/oop
uml/composition1.cpp
// HAS-A relationship (composition) #include <iostream> class B { private: int data[100]; public: B() { std::cout << "Object of class B at memory " << this << " having size " << sizeof(*this) << " created" << std::endl; } ~B() { std::cout << "Object of class B at memory " << this << " having size " << sizeof(*this) << " destroyed" << std::endl; } }; class A { private: int x; B b; // composition (strong containment) public: A() { std::cout << "Object of class A at memory " << this << " having size " << sizeof(*this) << " created" << std::endl; } ~A() { std::cout << "Object of class A at memory " << this << " having size " << sizeof(*this) << " destroyed" << std::endl; } }; int main() { A obj1; A obj2; return 0; } /* Object of class B at memory 0x7afc74 having size 400 created Object of class A at memory 0x7afc70 having size 404 created Object of class B at memory 0x7afad4 having size 400 created Object of class A at memory 0x7afad0 having size 404 created Object of class A at memory 0x7afad0 having size 404 destroyed Object of class B at memory 0x7afad4 having size 400 destroyed Object of class A at memory 0x7afc70 having size 404 destroyed Object of class B at memory 0x7afc74 having size 400 destroyed */
urbanjost/M_CLI2
docs/doxygen_out/html/search/all_12.js
var searchData= [ ['unnamed_148',['unnamed',['../namespacem__cli2.html#a5b03781cb432174f4ee8d734ecbb9604',1,'m_cli2']]], ['unquote_149',['unquote',['../namespacem__cli2.html#a150f312a9f4ec6dd58afb58a9a68f26a',1,'m_cli2']]], ['update_150',['update',['../namespacem__cli2.html#a160d56bc4a10faef7e8a8a4f04f4dadb',1,'m_cli2']]], ['upper_151',['upper',['../namespacem__cli2.html#aefaf1e255615ab6ebc1e19fddd795fb8',1,'m_cli2']]] ];
yehzu/vespa
searchlib/src/vespa/searchlib/queryeval/ranksearch.h
// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #pragma once #include "multisearch.h" namespace search::queryeval { /** * A simple implementation of the Rank search operation. **/ class RankSearch : public MultiSearch { protected: void doSeek(uint32_t docid) override; /** * Create a new Rank Search with the given children. A non-strict Rank has * no strictness assumptions about its children. * * @param children the search objects we are rank'ing **/ RankSearch(const Children & children) : MultiSearch(children) { } public: // Caller takes ownership of the returned SearchIterator. static SearchIterator *create(const Children &children, bool strict); }; }
mohdab98/cmps252_hw4.2
src/cmps252/HW4_2/UnitTesting/record_1931.java
package cmps252.HW4_2.UnitTesting; import static org.junit.jupiter.api.Assertions.*; import java.io.FileNotFoundException; import java.util.List; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import cmps252.HW4_2.Customer; import cmps252.HW4_2.FileParser; @Tag("4") class Record_1931 { private static List<Customer> customers; @BeforeAll public static void init() throws FileNotFoundException { customers = FileParser.getCustomers(Configuration.CSV_File); } @Test @DisplayName("Record 1931: FirstName is Sylvester") void FirstNameOfRecord1931() { assertEquals("Sylvester", customers.get(1930).getFirstName()); } @Test @DisplayName("Record 1931: LastName is Hilu") void LastNameOfRecord1931() { assertEquals("Hilu", customers.get(1930).getLastName()); } @Test @DisplayName("Record 1931: Company is Hopkins, Stephen P Esq") void CompanyOfRecord1931() { assertEquals("Hopkins, Stephen P Esq", customers.get(1930).getCompany()); } @Test @DisplayName("Record 1931: Address is 311 Market St") void AddressOfRecord1931() { assertEquals("311 Market St", customers.get(1930).getAddress()); } @Test @DisplayName("Record 1931: City is Kingston") void CityOfRecord1931() { assertEquals("Kingston", customers.get(1930).getCity()); } @Test @DisplayName("Record 1931: County is Luzerne") void CountyOfRecord1931() { assertEquals("Luzerne", customers.get(1930).getCounty()); } @Test @DisplayName("Record 1931: State is PA") void StateOfRecord1931() { assertEquals("PA", customers.get(1930).getState()); } @Test @DisplayName("Record 1931: ZIP is 18704") void ZIPOfRecord1931() { assertEquals("18704", customers.get(1930).getZIP()); } @Test @DisplayName("Record 1931: Phone is 570-283-5211") void PhoneOfRecord1931() { assertEquals("570-283-5211", customers.get(1930).getPhone()); } @Test @DisplayName("Record 1931: Fax is 570-283-2417") void FaxOfRecord1931() { assertEquals("570-283-2417", customers.get(1930).getFax()); } @Test @DisplayName("Record 1931: Email is <EMAIL>") void EmailOfRecord1931() { assertEquals("<EMAIL>", customers.get(1930).getEmail()); } @Test @DisplayName("Record 1931: Web is http://www.sylvesterhilu.com") void WebOfRecord1931() { assertEquals("http://www.sylvesterhilu.com", customers.get(1930).getWeb()); } }
tienpham/oci-go-sdk
analytics/work_request_action_result.go
<filename>analytics/work_request_action_result.go<gh_stars>0 // Copyright (c) 2016, 2018, 2019, Oracle and/or its affiliates. All rights reserved. // Code generated. DO NOT EDIT. // Analytics API // // Analytics API. // package analytics // WorkRequestActionResultEnum Enum with underlying type: string type WorkRequestActionResultEnum string // Set of constants representing the allowable values for WorkRequestActionResultEnum const ( WorkRequestActionResultCompartmentChanged WorkRequestActionResultEnum = "COMPARTMENT_CHANGED" WorkRequestActionResultCreated WorkRequestActionResultEnum = "CREATED" WorkRequestActionResultDeleted WorkRequestActionResultEnum = "DELETED" WorkRequestActionResultStarted WorkRequestActionResultEnum = "STARTED" WorkRequestActionResultStopped WorkRequestActionResultEnum = "STOPPED" WorkRequestActionResultScaled WorkRequestActionResultEnum = "SCALED" WorkRequestActionResultNone WorkRequestActionResultEnum = "NONE" ) var mappingWorkRequestActionResult = map[string]WorkRequestActionResultEnum{ "COMPARTMENT_CHANGED": WorkRequestActionResultCompartmentChanged, "CREATED": WorkRequestActionResultCreated, "DELETED": WorkRequestActionResultDeleted, "STARTED": WorkRequestActionResultStarted, "STOPPED": WorkRequestActionResultStopped, "SCALED": WorkRequestActionResultScaled, "NONE": WorkRequestActionResultNone, } // GetWorkRequestActionResultEnumValues Enumerates the set of values for WorkRequestActionResultEnum func GetWorkRequestActionResultEnumValues() []WorkRequestActionResultEnum { values := make([]WorkRequestActionResultEnum, 0) for _, v := range mappingWorkRequestActionResult { values = append(values, v) } return values }
HappyRay/samza
samza-core/src/main/java/org/apache/samza/util/Util.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.samza.util; import java.net.Inet4Address; import java.net.InetAddress; import java.net.NetworkInterface; import java.net.SocketException; import java.net.UnknownHostException; import java.util.Collections; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; import com.google.common.collect.Lists; import org.apache.samza.SamzaException; import org.apache.samza.config.ApplicationConfig; import org.apache.samza.config.Config; import org.apache.samza.config.TaskConfig; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class Util { private static final Logger LOG = LoggerFactory.getLogger(Util.class); static final String FALLBACK_VERSION = "0.0.1"; /** * Make an environment variable string safe to pass. */ public static String envVarEscape(String str) { return str.replace("\"", "\\\"").replace("'", "\\'"); } public static String getSamzaVersion() { return Optional.ofNullable(Util.class.getPackage().getImplementationVersion()).orElseGet(() -> { LOG.warn("Unable to find implementation samza version in jar's meta info. Defaulting to {}", FALLBACK_VERSION); return FALLBACK_VERSION; }); } public static String getTaskClassVersion(Config config) { try { Optional<String> appClass = Optional.ofNullable(new ApplicationConfig(config).getAppClass()); if (appClass.isPresent()) { return Optional.ofNullable(Class.forName(appClass.get()).getPackage().getImplementationVersion()) .orElse(FALLBACK_VERSION); } else { Optional<String> taskClass = new TaskConfig(config).getTaskClass(); if (taskClass.isPresent()) { return Optional.ofNullable(Class.forName(taskClass.get()).getPackage().getImplementationVersion()) .orElse(FALLBACK_VERSION); } else { LOG.warn("Unable to find app class or task class. Defaulting to {}", FALLBACK_VERSION); return FALLBACK_VERSION; } } } catch (Exception e) { LOG.warn(String.format("Ran into exception while trying to get version of app or task. Defaulting to %s", FALLBACK_VERSION), e); return FALLBACK_VERSION; } } /** * Returns the the first host address which is not the loopback address, or {@link InetAddress#getLocalHost} as a * fallback. * * @return the {@link InetAddress} which represents the localhost */ public static InetAddress getLocalHost() { try { return doGetLocalHost(); } catch (Exception e) { throw new SamzaException("Error while getting localhost", e); } } private static InetAddress doGetLocalHost() throws UnknownHostException, SocketException { InetAddress localHost = InetAddress.getLocalHost(); if (localHost.isLoopbackAddress()) { LOG.debug("Hostname {} resolves to a loopback address, trying to resolve an external IP address.", localHost.getHostName()); List<NetworkInterface> networkInterfaces; if (System.getProperty("os.name").startsWith("Windows")) { networkInterfaces = Collections.list(NetworkInterface.getNetworkInterfaces()); } else { networkInterfaces = Lists.reverse(Collections.list(NetworkInterface.getNetworkInterfaces())); } for (NetworkInterface networkInterface : networkInterfaces) { List<InetAddress> addresses = Collections.list(networkInterface.getInetAddresses()) .stream() .filter(address -> !(address.isLinkLocalAddress() || address.isLoopbackAddress())) .collect(Collectors.toList()); if (!addresses.isEmpty()) { InetAddress address = addresses.stream() .filter(addr -> addr instanceof Inet4Address) .findFirst() .orElseGet(() -> addresses.get(0)); LOG.debug("Found an external IP address {} which represents the localhost.", address.getHostAddress()); return InetAddress.getByAddress(address.getAddress()); } } } return localHost; } }
Be-poz/atdd-subway-fare
src/main/java/wooteco/subway/path/domain/fare/DistanceFareRule.java
<filename>src/main/java/wooteco/subway/path/domain/fare/DistanceFareRule.java package wooteco.subway.path.domain.fare; import java.util.Arrays; import java.util.function.Predicate; public enum DistanceFareRule { BASIC_DISTANCE(distance -> false, 0, 1, 1250, 0), MIDDLE_DISTANCE(distance -> distance > 10 && distance <= 50, 10, 5, 1250, 100), LONG_DISTANCE(distance -> distance > 50, 50, 8, 2050, 100); private final Predicate<Integer> figureOutRule; private final int subtractFormulaValue; private final int divideFormulaValue; private final int defaultFare; private final int fareForDistanceFormulaValue; DistanceFareRule(Predicate<Integer> figureOutRule, int subtractFormulaValue, int divideFormulaValue, int defaultFare, int fareForDistanceFormulaValue) { this.figureOutRule = figureOutRule; this.subtractFormulaValue = subtractFormulaValue; this.divideFormulaValue = divideFormulaValue; this.defaultFare = defaultFare; this.fareForDistanceFormulaValue = fareForDistanceFormulaValue; } public static int calculateFee(int distance) { DistanceFareRule findDistanceRule = findDistanceRule(distance); return additionalDistanceFee(findDistanceRule, distance); } public static DistanceFareRule findDistanceRule(int distance) { return Arrays.stream(DistanceFareRule.values()) .filter(value -> value.figureOutRule.test(distance)) .findAny() .orElse(BASIC_DISTANCE); } public static int additionalDistanceFee(DistanceFareRule rule, int distance) { return rule.defaultFare + (int) Math.ceil((double) (distance - rule.subtractFormulaValue) / rule.divideFormulaValue) * rule.fareForDistanceFormulaValue; } }
phatblat/macOSPrivateFrameworks
PrivateFrameworks/ACDEClient/ACCTicketManagerProtocol-Protocol.h
<filename>PrivateFrameworks/ACDEClient/ACCTicketManagerProtocol-Protocol.h // // Generated by class-dump 3.5 (64 bit). // // class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2013 by <NAME>. // #import "NSObject.h" @class ACFMessage, ACFPrincipal, NSData, NSDictionary, NSNumber, NSString; @protocol ACCTicketManagerProtocol <NSObject> - (void)updateContextWithClientSecretIfAny:(id <ACCAuthContextProtocol>)arg1; - (NSString *)serviceTicketStringWithRequest:(ACFMessage *)arg1 ssoToken:(id <ACCSSOTokenProtocol>)arg2; - (id <ACCAuthContextProtocol>)changePasswordContextWithRequest:(ACFMessage *)arg1 oldPassword:(NSString *)arg2 newPassword:(NSString *)arg3; - (id <ACCSSOTokenProtocol>)fetchSSOTokenForPrincipal:(ACFPrincipal *)arg1 agedLessThan:(double)arg2; - (id <ACCSSOTokenProtocol>)fetchSSOTokenForPrincipal:(ACFPrincipal *)arg1; - (BOOL)storeSSOToken:(id <ACCSSOTokenProtocol>)arg1; - (id <ACCSSOTokenProtocol>)createSSOTokenWithContent:(NSData *)arg1 context:(id <ACCAuthContextProtocol>)arg2; - (NSData *)decryptEncryptedContent:(NSData *)arg1 withHmac:(NSString *)arg2 context:(id <ACCAuthContextProtocol>)arg3; - (id <ACCAuthContextProtocol>)authContextWithRequest:(ACFMessage *)arg1 sessionToken:(NSString *)arg2; - (id <ACCAuthContextProtocol>)authContextWithRequest:(ACFMessage *)arg1 keyCode:(NSString *)arg2 authenticationType:(NSNumber *)arg3; - (id <ACCAuthContextProtocol>)authContextWithRequest:(ACFMessage *)arg1; - (NSDictionary *)envelopeWithContext:(id <ACCAuthContextProtocol>)arg1; - (void)uninstallPublicKeyForRealm:(NSString *)arg1; - (BOOL)installCertificateWithString:(NSString *)arg1 version:(NSString *)arg2 forRealm:(NSString *)arg3; @end
meierhofer08/activemq-artemis
tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/bridge/BridgeFailoverTest.java
<reponame>meierhofer08/activemq-artemis /* * 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.artemis.tests.integration.cluster.bridge; import java.util.ArrayList; import java.util.List; import java.util.concurrent.TimeUnit; import org.apache.activemq.artemis.api.core.QueueConfiguration; import org.apache.activemq.artemis.api.core.client.ClientConsumer; import org.apache.activemq.artemis.api.core.client.ClientMessage; import org.apache.activemq.artemis.api.core.client.ClientProducer; import org.apache.activemq.artemis.api.core.client.ClientSession; import org.apache.activemq.artemis.api.core.client.ClientSessionFactory; import org.apache.activemq.artemis.api.core.client.ServerLocator; import org.apache.activemq.artemis.core.config.BridgeConfiguration; import org.apache.activemq.artemis.core.server.ActiveMQServer; import org.apache.activemq.artemis.core.server.cluster.impl.BridgeImpl; import org.apache.activemq.artemis.tests.integration.cluster.util.MultiServerTestBase; import org.junit.Test; public class BridgeFailoverTest extends MultiServerTestBase { @Test public void testSimpleConnectOnMultipleNodes() throws Exception { BridgeConfiguration bridgeConfiguration = new BridgeConfiguration(); String ORIGINAL_QUEUE = "noCluster.originalQueue"; String TARGET_QUEUE = "noCluster.targetQueue"; bridgeConfiguration.setHA(true); List<String> connectors = new ArrayList<>(); connectors.add("target-4"); connectors.add("backup-4"); bridgeConfiguration.setName("Bridge-for-test"); bridgeConfiguration.setStaticConnectors(connectors); bridgeConfiguration.setQueueName(ORIGINAL_QUEUE); bridgeConfiguration.setForwardingAddress(TARGET_QUEUE); bridgeConfiguration.setRetryInterval(100); bridgeConfiguration.setConfirmationWindowSize(1); bridgeConfiguration.setReconnectAttempts(-1); servers[2].getConfiguration().getBridgeConfigurations().add(bridgeConfiguration); for (ActiveMQServer server : servers) { server.getConfiguration().addQueueConfiguration(new QueueConfiguration(ORIGINAL_QUEUE)); server.getConfiguration().addQueueConfiguration(new QueueConfiguration(TARGET_QUEUE)); } startServers(); // The server where the bridge source is configured at ServerLocator locator = createLocator(false, 2); ClientSessionFactory factory = addSessionFactory(locator.createSessionFactory()); ClientSession session = addClientSession(factory.createSession(false, false)); ClientProducer producer = addClientProducer(session.createProducer(ORIGINAL_QUEUE)); for (int i = 0; i < 100; i++) { ClientMessage msg = session.createMessage(true); msg.putIntProperty("i", i); producer.send(msg); } session.commit(); ServerLocator locatorConsumer = createLocator(false, 4); ClientSessionFactory factoryConsumer = addSessionFactory(locatorConsumer.createSessionFactory()); ClientSession sessionConsumer = addClientSession(factoryConsumer.createSession(false, false)); ClientConsumer consumer = sessionConsumer.createConsumer(TARGET_QUEUE); sessionConsumer.start(); for (int i = 0; i < 100; i++) { ClientMessage message = consumer.receive(10000); assertNotNull(message); message.acknowledge(); } sessionConsumer.commit(); } @Test public void testFailoverOnBridgeNoRetryOnSameNode() throws Exception { internalTestFailoverOnBridge(0); } @Test public void testFailoverOnBridgeForeverRetryOnSameNode() throws Exception { internalTestFailoverOnBridge(-1); } public void internalTestFailoverOnBridge(int retriesSameNode) throws Exception { BridgeConfiguration bridgeConfiguration = new BridgeConfiguration(); String ORIGINAL_QUEUE = "noCluster.originalQueue"; String TARGET_QUEUE = "noCluster.targetQueue"; bridgeConfiguration.setHA(true); List<String> connectors = new ArrayList<>(); connectors.add("target-4"); connectors.add("backup-4"); bridgeConfiguration.setName("Bridge-for-test"); bridgeConfiguration.setStaticConnectors(connectors); bridgeConfiguration.setQueueName(ORIGINAL_QUEUE); bridgeConfiguration.setForwardingAddress(TARGET_QUEUE); bridgeConfiguration.setRetryInterval(100); bridgeConfiguration.setConfirmationWindowSize(1); bridgeConfiguration.setReconnectAttempts(-1); bridgeConfiguration.setReconnectAttemptsOnSameNode(retriesSameNode); bridgeConfiguration.setHA(true); servers[2].getConfiguration().getBridgeConfigurations().add(bridgeConfiguration); for (ActiveMQServer server : servers) { server.getConfiguration().addQueueConfiguration(new QueueConfiguration(ORIGINAL_QUEUE)); server.getConfiguration().addQueueConfiguration(new QueueConfiguration(TARGET_QUEUE)); } startServers(); BridgeImpl bridge = (BridgeImpl) servers[2].getClusterManager().getBridges().get("Bridge-for-test"); assertNotNull(bridge); long timeout = System.currentTimeMillis() + 5000; while (bridge.getTargetNodeFromTopology() == null && timeout > System.currentTimeMillis()) { Thread.sleep(100); } assertNotNull(bridge.getTargetNodeFromTopology()); // The server where the bridge source is configured at ServerLocator locatorProducer = createLocator(false, 2); ClientSessionFactory factory = addSessionFactory(locatorProducer.createSessionFactory()); ClientSession session = addClientSession(factory.createSession(false, false)); ClientProducer producer = addClientProducer(session.createProducer(ORIGINAL_QUEUE)); for (int i = 0; i < 100; i++) { ClientMessage msg = session.createMessage(true); msg.putIntProperty("i", i); producer.send(msg); } session.commit(); ServerLocator locatorConsumer = createLocator(false, 4); ClientSessionFactory factoryConsumer = addSessionFactory(locatorConsumer.createSessionFactory()); ClientSession sessionConsumer = addClientSession(factoryConsumer.createSession(false, false)); ClientConsumer consumer = sessionConsumer.createConsumer(TARGET_QUEUE); sessionConsumer.start(); for (int i = 0; i < 100; i++) { ClientMessage message = consumer.receive(10000); assertNotNull(message); message.acknowledge(); } // We rollback as we will receive them again sessionConsumer.rollback(); factoryConsumer.close(); sessionConsumer.close(); crashAndWaitForFailure(servers[4], locatorConsumer); locatorConsumer.close(); assertTrue("Backup server didn't activate.", backupServers[4].waitForActivation(5, TimeUnit.SECONDS)); for (int i = 100; i < 200; i++) { ClientMessage msg = session.createMessage(true); msg.putIntProperty("i", i); producer.send(msg); } session.commit(); locatorConsumer = createLocator(false, 9); factoryConsumer = addSessionFactory(locatorConsumer.createSessionFactory()); sessionConsumer = addClientSession(factoryConsumer.createSession()); consumer = sessionConsumer.createConsumer(TARGET_QUEUE); sessionConsumer.start(); for (int i = 0; i < 200; i++) { ClientMessage message = consumer.receive(10000); assertNotNull(message); message.acknowledge(); } sessionConsumer.commit(); } @Test public void testInitialConnectionNodeAlreadyDown() throws Exception { BridgeConfiguration bridgeConfiguration = new BridgeConfiguration(); String ORIGINAL_QUEUE = "noCluster.originalQueue"; String TARGET_QUEUE = "noCluster.targetQueue"; bridgeConfiguration.setHA(true); List<String> connectors = new ArrayList<>(); connectors.add("target-4"); connectors.add("backup-4"); bridgeConfiguration.setName("Bridge-for-test"); bridgeConfiguration.setStaticConnectors(connectors); bridgeConfiguration.setQueueName(ORIGINAL_QUEUE); bridgeConfiguration.setForwardingAddress(TARGET_QUEUE); bridgeConfiguration.setRetryInterval(100); bridgeConfiguration.setConfirmationWindowSize(1); bridgeConfiguration.setReconnectAttempts(-1); servers[2].getConfiguration().getBridgeConfigurations().add(bridgeConfiguration); for (ActiveMQServer server : servers) { server.getConfiguration().addQueueConfiguration(new QueueConfiguration(ORIGINAL_QUEUE)); server.getConfiguration().addQueueConfiguration(new QueueConfiguration(TARGET_QUEUE)); } startBackups(0, 1, 3, 4); startServers(0, 1, 3, 4); waitForTopology(servers[4], getNumberOfServers() - 1, getNumberOfServers() - 1); crashAndWaitForFailure(servers[4], createLocator(false, 4)); waitForServerToStart(backupServers[4]); startBackups(2); startServers(2); // The server where the bridge source is configured at ServerLocator locator = createLocator(false, 2); // connecting to the backup ClientSessionFactory factory = addSessionFactory(locator.createSessionFactory()); ClientSession session = addClientSession(factory.createSession(false, false)); ClientProducer producer = addClientProducer(session.createProducer(ORIGINAL_QUEUE)); for (int i = 0; i < 100; i++) { ClientMessage msg = session.createMessage(true); msg.putIntProperty("i", i); producer.send(msg); } session.commit(); ServerLocator locatorConsumer = createLocator(false, 9); ClientSessionFactory factoryConsumer = addSessionFactory(locatorConsumer.createSessionFactory()); ClientSession sessionConsumer = addClientSession(factoryConsumer.createSession(false, false)); ClientConsumer consumer = sessionConsumer.createConsumer(TARGET_QUEUE); sessionConsumer.start(); for (int i = 0; i < 100; i++) { ClientMessage message = consumer.receive(10000); assertNotNull(message); message.acknowledge(); } sessionConsumer.commit(); } }
schgressive/BotFramework-WebChat
packages/core/tests/createFacility.js
<gh_stars>1-10 import mockDirectLine from './mockDirectLine'; import { START_CONNECTION } from '../src/actions/startConnection'; import createStore from '../src/createStore'; const DEFAULT_USER_ID = 'default-user'; jest.mock('../src/util/getTimestamp', () => { let now = 946684800000; // '2000-01-01T00:00:00.000Z' return function () { now += 1000; return new Date(now).toISOString(); }; }); jest.mock('../src/util/uniqueID', () => { let uniqueSeed = 0; const fn = function (length = 7) { uniqueSeed += 0.123; return uniqueSeed.toString(36).substr(2, length); }; fn.reset = () => uniqueSeed = 0; return fn; }); export default async function ({ start = true } = {}) { const actions = []; const directLine = mockDirectLine(); const latestActions = {}; const store = createStore(() => next => action => { actions.push(action); latestActions[action.type] = action; return next(action); }); if (start) { store.dispatch({ type: START_CONNECTION, payload: { directLine, userID: DEFAULT_USER_ID } }); directLine.connectionStatus.next(1); await 0; } return { actions, directLine, latestActions, store }; }
sweetkristas/swiftly
src/kre/ParticleSystemAffectors.hpp
<reponame>sweetkristas/swiftly /* Copyright (C) 2013-2014 by <NAME> <<EMAIL>> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #pragma once #include "ParticleSystemFwd.hpp" namespace KRE { namespace Particles { class Affector : public EmitObject { public: explicit Affector(ParticleSystemContainer* parent, const variant& node); virtual ~Affector(); virtual Affector* clone() = 0; bool isEnabled() const { return enabled_; } void enable(bool en) { enabled_ = en; } Technique* getTechnique() { return technique_; } void setParentTechnique(Technique* tq) { technique_ = tq; } float mass() const { return mass_; } const glm::vec3& getPosition() const { return position_; } void setPosition(const glm::vec3& pos) { position_ = pos; } const glm::vec3& getScale() const { return scale_; } bool isEmitterExcluded(const std::string& name); static Affector* factory(ParticleSystemContainer* parent, const variant& node); protected: virtual void handleEmitProcess(float t); virtual void internalApply(Particle& p, float t) = 0; private: DECLARE_CALLABLE(Affector); bool enabled_; float mass_; glm::vec3 position_; std::vector<std::string> excluded_emitters_; glm::vec3 scale_; Technique* technique_; Affector(); }; } }
DLotts/incubator-rya
dao/mongodb.rya/src/test/java/org/apache/rya/mongodb/MongoDBRyaDAOTest.java
<reponame>DLotts/incubator-rya package org.apache.rya.mongodb; /* * 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. */ import static org.junit.Assert.assertEquals; import java.io.IOException; import org.apache.rya.api.domain.RyaStatement; import org.apache.rya.api.domain.RyaStatement.RyaStatementBuilder; import org.apache.rya.api.domain.RyaURI; import org.apache.rya.api.persist.RyaDAOException; import org.bson.Document; import org.junit.Before; import org.junit.Test; import com.mongodb.MongoClient; import com.mongodb.MongoException; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoDatabase; public class MongoDBRyaDAOTest extends MongoTestBase { private MongoClient client; private MongoDBRyaDAO dao; @Before public void setUp() throws IOException, RyaDAOException{ client = super.getMongoClient(); dao = new MongoDBRyaDAO(conf, client); } @Test public void testDeleteWildcard() throws RyaDAOException { final RyaStatementBuilder builder = new RyaStatementBuilder(); builder.setPredicate(new RyaURI("http://temp.com")); dao.delete(builder.build(), conf); } @Test public void testAdd() throws RyaDAOException, MongoException, IOException { final RyaStatementBuilder builder = new RyaStatementBuilder(); builder.setPredicate(new RyaURI("http://temp.com")); builder.setSubject(new RyaURI("http://subject.com")); builder.setObject(new RyaURI("http://object.com")); final MongoDatabase db = client.getDatabase(conf.get(MongoDBRdfConfiguration.MONGO_DB_NAME)); final MongoCollection<Document> coll = db.getCollection(conf.getTriplesCollectionName()); dao.add(builder.build()); assertEquals(coll.count(),1); } @Test public void testDelete() throws RyaDAOException, MongoException, IOException { final RyaStatementBuilder builder = new RyaStatementBuilder(); builder.setPredicate(new RyaURI("http://temp.com")); builder.setSubject(new RyaURI("http://subject.com")); builder.setObject(new RyaURI("http://object.com")); final RyaStatement statement = builder.build(); final MongoDatabase db = client.getDatabase(conf.get(MongoDBRdfConfiguration.MONGO_DB_NAME)); final MongoCollection<Document> coll = db.getCollection(conf.getTriplesCollectionName()); dao.add(statement); assertEquals(coll.count(),1); dao.delete(statement, conf); assertEquals(coll.count(),0); } @Test public void testDeleteWildcardSubjectWithContext() throws RyaDAOException, MongoException, IOException { final RyaStatementBuilder builder = new RyaStatementBuilder(); builder.setPredicate(new RyaURI("http://temp.com")); builder.setSubject(new RyaURI("http://subject.com")); builder.setObject(new RyaURI("http://object.com")); builder.setContext(new RyaURI("http://context.com")); final RyaStatement statement = builder.build(); final MongoDatabase db = client.getDatabase(conf.get(MongoDBRdfConfiguration.MONGO_DB_NAME)); final MongoCollection<Document> coll = db.getCollection(conf.getTriplesCollectionName()); dao.add(statement); assertEquals(coll.count(),1); final RyaStatementBuilder builder2 = new RyaStatementBuilder(); builder2.setPredicate(new RyaURI("http://temp.com")); builder2.setObject(new RyaURI("http://object.com")); builder2.setContext(new RyaURI("http://context3.com")); final RyaStatement query = builder2.build(); dao.delete(query, conf); assertEquals(coll.count(),1); } }
xsqasxz/2020yu
src/main/java/com/small/dto/after/AfterUserAbilityPowerDto.java
package com.small.dto.after; import lombok.Data; import javax.validation.constraints.NotNull; import java.util.List; @Data public class AfterUserAbilityPowerDto { /**用户id*/ @NotNull(message = "用户id不可为空") private Integer afterUserId; /**岗位集合*/ @NotNull(message = "岗位集合不可为空") private List<Integer> afterAbilityIds; }
thomas779/BackgroundMusic
BGMApp/BGMThreadSafetyAnalysis.h
// This file is part of Background Music. // // Background Music 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. // // Background Music 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 Background Music. If not, see <http://www.gnu.org/licenses/>. // Original licence at the end of this file. // // BGMThreadSafetyAnalysis.h // PublicUtility // // © Copyright 2007-2020, The Clang Team // Copyright © 2020 <NAME> // // Macros that wrap Clang's attributes for statically checking concurrency properties. From // <https://clang.llvm.org/docs/ThreadSafetyAnalysis.html#mutexheader>. // #ifndef PublicUtility__BGMThreadSafetyAnalysis #define PublicUtility__BGMThreadSafetyAnalysis // Enable thread safety attributes only with clang. // The attributes can be safely erased when compiling with other compilers. #if defined(__clang__) && (!defined(SWIG)) #define THREAD_ANNOTATION_ATTRIBUTE__(x) __attribute__((x)) #else #define THREAD_ANNOTATION_ATTRIBUTE__(x) // no-op #endif #define CAPABILITY(x) \ THREAD_ANNOTATION_ATTRIBUTE__(capability(x)) #define SCOPED_CAPABILITY \ THREAD_ANNOTATION_ATTRIBUTE__(scoped_lockable) #define GUARDED_BY(x) \ THREAD_ANNOTATION_ATTRIBUTE__(guarded_by(x)) #define PT_GUARDED_BY(x) \ THREAD_ANNOTATION_ATTRIBUTE__(pt_guarded_by(x)) #define ACQUIRED_BEFORE(...) \ THREAD_ANNOTATION_ATTRIBUTE__(acquired_before(__VA_ARGS__)) #define ACQUIRED_AFTER(...) \ THREAD_ANNOTATION_ATTRIBUTE__(acquired_after(__VA_ARGS__)) #define REQUIRES(...) \ THREAD_ANNOTATION_ATTRIBUTE__(requires_capability(__VA_ARGS__)) #define REQUIRES_SHARED(...) \ THREAD_ANNOTATION_ATTRIBUTE__(requires_shared_capability(__VA_ARGS__)) #define ACQUIRE(...) \ THREAD_ANNOTATION_ATTRIBUTE__(acquire_capability(__VA_ARGS__)) #define ACQUIRE_SHARED(...) \ THREAD_ANNOTATION_ATTRIBUTE__(acquire_shared_capability(__VA_ARGS__)) #define RELEASE(...) \ THREAD_ANNOTATION_ATTRIBUTE__(release_capability(__VA_ARGS__)) #define RELEASE_SHARED(...) \ THREAD_ANNOTATION_ATTRIBUTE__(release_shared_capability(__VA_ARGS__)) #define TRY_ACQUIRE(...) \ THREAD_ANNOTATION_ATTRIBUTE__(try_acquire_capability(__VA_ARGS__)) #define TRY_ACQUIRE_SHARED(...) \ THREAD_ANNOTATION_ATTRIBUTE__(try_acquire_shared_capability(__VA_ARGS__)) #define EXCLUDES(...) \ THREAD_ANNOTATION_ATTRIBUTE__(locks_excluded(__VA_ARGS__)) #define ASSERT_CAPABILITY(x) \ THREAD_ANNOTATION_ATTRIBUTE__(assert_capability(x)) #define ASSERT_SHARED_CAPABILITY(x) \ THREAD_ANNOTATION_ATTRIBUTE__(assert_shared_capability(x)) #define RETURN_CAPABILITY(x) \ THREAD_ANNOTATION_ATTRIBUTE__(lock_returned(x)) #define NO_THREAD_SAFETY_ANALYSIS \ THREAD_ANNOTATION_ATTRIBUTE__(no_thread_safety_analysis) #endif /* PublicUtility__BGMThreadSafetyAnalysis */ /* This file is derived from "mutex.h" from the Clang documentation at <https://clang.llvm.org/docs/ThreadSafetyAnalysis.html>. This is the original license of "mutex.h". ============================================================================== The LLVM Project is under the Apache License v2.0 with LLVM Exceptions: ============================================================================== Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] 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. ---- LLVM Exceptions to the Apache 2.0 License ---- As an exception, if, as a result of your compiling your source code, portions of this Software are embedded into an Object form of such source code, you may redistribute such embedded portions in such Object form without complying with the conditions of Sections 4(a), 4(b) and 4(d) of the License. In addition, if you combine or link compiled forms of this Software with software that is licensed under the GPLv2 ("Combined Software") and if a court of competent jurisdiction determines that the patent provision (Section 3), the indemnity provision (Section 9) or other Section of the License conflicts with the conditions of the GPLv2, you may retroactively and prospectively choose to deem waived or otherwise exclude such Section(s) of the License, but only in their entirety and only with respect to the Combined Software. ============================================================================== Software from third parties included in the LLVM Project: ============================================================================== The LLVM Project contains third party software which is under different license terms. All such code will be identified clearly using at least one of two mechanisms: 1) It will be in a separate directory tree with its own `LICENSE.txt` or `LICENSE` file at the top containing the specific license and restrictions which apply to that software, or 2) It will contain specific license and restriction terms at the top of every file. ============================================================================== Legacy LLVM License (https://llvm.org/docs/DeveloperPolicy.html#legacy): ============================================================================== University of Illinois/NCSA Open Source License Copyright (c) 2007-2019 University of Illinois at Urbana-Champaign. All rights reserved. Developed by: LLVM Team University of Illinois at Urbana-Champaign http://llvm.org Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal with 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: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimers. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimers in the documentation and/or other materials provided with the distribution. * Neither the names of the LLVM Team, University of Illinois at Urbana-Champaign, nor the names of its contributors may be used to endorse or promote products derived from this Software without specific prior written permission. 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 CONTRIBUTORS 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 WITH THE SOFTWARE. */
COVID-IWG/epimargin-studies
bihar/bihar.py
<gh_stars>0 from pathlib import Path from typing import Dict, Optional, Sequence, Tuple from warnings import simplefilter import epimargin.plots as plt import numpy as np import pandas as pd from epimargin.estimators import analytical_MPVS, linear_projection from epimargin.models import SIR, NetworkedSIR from epimargin.smoothing import convolution, notched_smoothing from epimargin.utils import cwd, days, setup from matplotlib import rcParams from statsmodels.regression.linear_model import OLS from statsmodels.tools import add_constant from tqdm import tqdm import etl simplefilter("ignore") (data, figs) = setup() gamma = 0.2 smoothing = 10 CI = 0.95 state_cases = pd.read_csv(data/"Bihar_cases_data_Oct03.csv", parse_dates=["date_reported"], dayfirst=True) state_ts = state_cases["date_reported"].value_counts().sort_index() district_names, population_counts, _ = etl.district_migration_matrix(data/"Migration Matrix - District.csv") populations = dict(zip(district_names, population_counts)) # first, look at state level predictions ( dates, Rt_pred, Rt_CI_upper, Rt_CI_lower, T_pred, T_CI_upper, T_CI_lower, total_cases, new_cases_ts, anomalies, anomaly_dates ) = analytical_MPVS(state_ts, CI = CI, smoothing = notched_smoothing(window = smoothing), totals=False) plt.Rt(dates, Rt_pred[1:], Rt_CI_upper[1:], Rt_CI_lower[1:], CI, ymin=0, ymax=4)\ .title("\nBihar: Reproductive Number Estimate")\ .annotate(f"data from {str(dates[0]).split()[0]} to {str(dates[-1]).split()[0]}")\ .xlabel("date")\ .ylabel("$R_t$", rotation=0, labelpad=20)\ .show() np.random.seed(33) Bihar = SIR("Bihar", 99_000_000, dT0 = T_pred[-1], Rt0 = Rt_pred[-1], lower_CI =T_CI_lower[-1], upper_CI = T_CI_upper[-1], mobility = 0) Bihar.run(14) t_pred = [dates[-1] + pd.Timedelta(days = i) for i in range(len(Bihar.dT))] plt.daily_cases(dates, T_pred[1:], T_CI_upper[1:], T_CI_lower[1:], new_cases_ts[1:], anomaly_dates, anomalies, CI, prediction_ts = [ (Bihar.dT, Bihar.lower_CI, Bihar.upper_CI, None, "predicted cases") ])\ .title("\nBihar: New Daily Cases")\ .annotate(f"data from {str(dates[0]).split()[0]} to {str(dates[-1]).split()[0]}; predictions until {str(t_pred[-1]).split()[0]}")\ .xlabel("date").ylabel("cases")\ .show() # now, do district-level estimation smoothing = 10 state_cases["geo_reported"] = state_cases.geo_reported.str.strip() district_time_series = state_cases.groupby(["geo_reported", "date_reported"])["date_reported"].count().sort_index() migration = np.zeros((len(district_names), len(district_names))) estimates = [] max_len = 1 + max(map(len, district_names)) with tqdm(etl.normalize(district_names)) as districts: for district in districts: districts.set_description(f"{district :<{max_len}}") try: (dates, Rt_pred, Rt_CI_upper, Rt_CI_lower, *_) = analytical_MPVS(district_time_series.loc[district], CI = CI, smoothing = convolution(window = smoothing), totals=False) estimates.append((district, Rt_pred[-1], Rt_CI_lower[-1], Rt_CI_upper[-1], linear_projection(dates, Rt_pred, smoothing))) except (IndexError, ValueError): estimates.append((district, np.nan, np.nan, np.nan, np.nan)) estimates = pd.DataFrame(estimates) estimates.columns = ["district", "Rt", "Rt_CI_lower", "Rt_CI_upper", "Rt_proj"] estimates.set_index("district", inplace=True) estimates.to_csv(data/"Rt_estimates_private.csv") print(estimates)
ydia530/gulimall
gulimall-product/src/main/java/com/atguigu/gulimall/product/dao/SpuInfoDescDao.java
<reponame>ydia530/gulimall package com.atguigu.gulimall.product.dao; import com.atguigu.gulimall.product.entity.SpuInfoDescEntity; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import org.apache.ibatis.annotations.Mapper; /** * spu信息介绍 * * @author DY * @email <EMAIL> * @date 2022-01-08 13:42:55 */ @Mapper public interface SpuInfoDescDao extends BaseMapper<SpuInfoDescEntity> { }
hgtpcastro/bootcamp-gostack-desafio-09
src/pages/_layouts/auth/index.js
// Imports import React from 'react'; import PropTypes from 'prop-types'; // UI Imports import { Wrapper, Content } from './styles'; // Component export default function AuthLayout({ children }) { return ( <Wrapper> <Content>{children}</Content> </Wrapper> ); } // Constraints AuthLayout.propTypes = { children: PropTypes.element.isRequired, };
TzashiNorpu/Algorithm
JavaAlgorithm/src/test/java/algo/tzashinorpu/FirstRound/Chapter12/Exercise/LeetCode_5_198Test.java
<filename>JavaAlgorithm/src/test/java/algo/tzashinorpu/FirstRound/Chapter12/Exercise/LeetCode_5_198Test.java package algo.tzashinorpu.FirstRound.Chapter12.Exercise; import algo.tzashinorpu.FirstRound.Chapter12.Exercise.LeetCode_5_198; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; class LeetCode_5_198Test { @Test void rob() { LeetCode_5_198 ins = new LeetCode_5_198(); int[] nums1 = {2, 1, 1, 2}; System.out.println(ins.robRecursie(nums1)); System.out.println(ins.robBottomUp(nums1)); int[] nums2 = {2, 1, 1, 1, 2}; System.out.println(ins.robRecursie(nums2)); System.out.println(ins.robBottomUp(nums2)); int[] nums3 = {226, 174, 214, 16, 218, 48, 153, 131, 128, 17, 157, 142, 88, 43, 37, 157, 43, 221, 191, 68, 206, 23, 225, 82, 54, 118, 111, 46, 80, 49, 245, 63, 25, 194, 72, 80, 143, 55, 209, 18, 55, 122, 65, 66, 177, 101, 63, 201, 172, 130, 103, 225, 142, 46, 86, 185, 62, 138, 212, 192, 125, 77, 223, 188, 99, 228, 90, 25, 193, 211, 84, 239, 119, 234, 85, 83, 123/*, 120, 131, 203, 219, 10, 82, 35, 120, 180, 249, 106, 37, 169, 225, 54, 103, 55, 166, 124*/}; System.out.println(ins.robRecursie(nums3)); System.out.println(ins.robBottomUp(nums3)); } }
hschwane/offline_production
PROPOSAL/public/PROPOSAL/decay/DecayTable.h
<filename>PROPOSAL/public/PROPOSAL/decay/DecayTable.h<gh_stars>1-10 /****************************************************************************** * * * This file is part of the simulation tool PROPOSAL. * * * * Copyright (C) 2017 TU Dortmund University, Department of Physics, * * Chair Experimental Physics 5b * * * * This software may be modified and distributed under the terms of a * * modified GNU Lesser General Public Licence version 3 (LGPL), * * copied verbatim in the file "LICENSE". * * * * Modifcations to the LGPL License: * * * * 1. The user shall acknowledge the use of PROPOSAL by citing the * * following reference: * * * * <NAME> et al. Comput.Phys.Commun. 184 (2013) 2070-2090 DOI: * * 10.1016/j.cpc.2013.04.001 * * * * 2. The user should report any bugs/errors or improvments to the * * current maintainer of PROPOSAL or open an issue on the * * GitHub webpage * * * * "https://github.com/tudo-astroparticlephysics/PROPOSAL" * * * ******************************************************************************/ #pragma once #include <map> #include <ostream> #include <vector> namespace PROPOSAL { class DecayChannel; class DecayTable; void swap(DecayTable&, DecayTable&); class DecayTable { typedef std::map<double, DecayChannel*> DecayMap; public: DecayTable(); DecayTable(const DecayTable& table); virtual ~DecayTable(); DecayTable& operator=(const DecayTable&); friend void swap(DecayTable&, DecayTable&); bool operator==(const DecayTable&) const; bool operator!=(const DecayTable&) const; friend std::ostream& operator<<(std::ostream&, DecayTable const&); // ---------------------------------------------------------------------------- /// @brief Get a decay channel /// /// The Decay channels will be sampled from the previous given branching ratios /// /// @return Sampled Decay channel // ---------------------------------------------------------------------------- DecayChannel& SelectChannel() const; // ---------------------------------------------------------------------------- /// @brief Add decay channels to the decay table /// /// The given decaychannel will be copied and stored in a map along with /// the branching ration. /// /// @param Br Branching ration of the channel /// @param dc the decay channel // ---------------------------------------------------------------------------- DecayTable& addChannel(double Br, const DecayChannel& dc); // ---------------------------------------------------------------------------- /// @brief Provide a decay table for stable particles /// /// Clears the decay table and adds one stable decay channel with /// branching ration 1.1 therefor it always will be selected. /// The decay channel will return an empty decay product vector. // ---------------------------------------------------------------------------- void SetStable(); // ---------------------------------------------------------------------------- /// @brief Sets the uniform flag in the ManyBodyPhaseSpace channels /// /// If uniform is true, the momenta will be sampled uniform in the phase space. /// This is done by rejection, since the pure raubold lynch algorithm does not /// create a uniform phase space. So enabling uniform sampling comes in with /// a cost of performance. /// /// @param uniform // ---------------------------------------------------------------------------- void SetUniformSampling(bool uniform) const; private: void clearTable(); DecayMap channels_; }; std::ostream& operator<<(std::ostream&, PROPOSAL::DecayTable const&); } // namespace PROPOSAL
windows-development/Windows-classic-samples
Samples/Win7Samples/netds/winsock/ipxchat/Listen.c
<reponame>windows-development/Windows-classic-samples // THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A // PARTICULAR PURPOSE. // // Copyright 1993 - 2000 Microsoft Corporation. All Rights Reserved. // // MODULE: listen.c // // PURPOSE: Displays the "Listen" dialog box // // FUNCTIONS: // CmdListen - Displays the "Listen" dialog box. // Listen - Processes messages for "Listen" dialog box. // MsgListenInit - Centers dialog and initializes edit controls. // MsgListenConnected - Handles Connected message when socket is connected. // MsgListenCommand - Process WM_COMMAND message sent to the listen box. // CmdListenDone - Free the listen box and related data. // CmdListenNow - Sets up listen on specified socket // // COMMENTS: // // #include "globals.h" // prototypes specific to this application #include <windows.h> // required for all Windows applications #include <windowsx.h> #include <stdlib.h> #include <stdio.h> LRESULT CALLBACK Listen(HWND, UINT, WPARAM, LPARAM); LRESULT MsgListenInit(HWND, UINT, WPARAM, LPARAM); LRESULT MsgListenCommand(HWND, UINT, WPARAM, LPARAM); LRESULT MsgListenConnected(HWND, UINT, WPARAM, LPARAM); LRESULT CmdListenNow(HWND, WORD, WORD, HWND); LRESULT CmdListenDone(HWND, WORD, WORD, HWND); // Listen dialog message table definition. MSD rgmsdListen[] = { {WM_COMMAND, MsgListenCommand}, {WM_INITDIALOG, MsgListenInit}, {LDM_CONNECTED, MsgListenConnected} }; MSDI msdiListen = { sizeof(rgmsdListen) / sizeof(MSD), rgmsdListen, edwpNone }; // Listen dialog command table definition. CMD rgcmdListen[] = { {IDOK, CmdListenNow}, {IDCANCEL, CmdListenDone} }; CMDI cmdiListen = { sizeof(rgcmdListen) / sizeof(CMD), rgcmdListen, edwpNone }; // Module specific "globals" Used when a variable needs to be // accessed in more than one handler function. HFONT hfontDlg; // // FUNCTION: CmdListen(HWND, WORD, WORD, HWND) // // PURPOSE: Displays the "Listen" dialog box // // PARAMETERS: // hwnd - Window handle // wCommand - IDM_LISTEN (unused) // wNotify - Notification number (unused) // hwndCtrl - NULL (unused) // // RETURN VALUE: // // Always returns 0 - Message handled // // COMMENTS: // To process the IDM_LISTEN message, call DialogBox() to display the // Listen dialog box. LRESULT CmdListen(HWND hwnd, WORD wCommand, WORD wNotify, HWND hwndCtrl) { HMENU hmenu; hwndCtrl; wNotify; wCommand; SetWindowText(hwnd, "IPX Chat Server"); // Change title bar text // Start Dialog if(DialogBox(hInst, "ListenBox", hwnd, (DLGPROC)Listen)) { // Dialog got a connection! Set Message to indicate // when we have data to read, or if the connection is // closed on us. if (WSAAsyncSelect(sock, hwnd, MW_DATAREADY, FD_READ | FD_CLOSE) == SOCKET_ERROR) { MessageBox(hwnd, "WSAAsyncSelect Failed!", NULL, MB_OK); CleanUp(); return 0; } // Fix menus if(NULL == (hmenu = GetMenu(hwnd))) return 0; EnableMenuItem(hmenu, IDM_CONNECT, MF_GRAYED); EnableMenuItem(hmenu, IDM_LISTEN, MF_GRAYED); EnableMenuItem(hmenu, IDM_DISCONNECT, MF_ENABLED); return 0; } // Listen Failed SetWindowText(hwnd, szTitle); return 0; } // // FUNCTION: Listen(HWND, UINT, WPARAM, LPARAM) // // PURPOSE: Processes messages for "Listen" dialog box. // // PARAMETERS: // hdlg - window handle of the dialog box // wMessage - type of message // wparam - message-specific information // lparam - message-specific information // // RETURN VALUE: // TRUE - message handled // FALSE - message not handled // // COMMENTS: // // Gets port information from user and then listens // // Listen when user clicks on the OK button. Kill Dialog when connection // established. // LRESULT CALLBACK Listen(HWND hdlg, UINT uMessage, WPARAM wparam, LPARAM lparam) { return DispMessage(&msdiListen, hdlg, uMessage, wparam, lparam); } // // FUNCTION: MsgListenInit(HWND, UINT, WPARAM, LPARAM) // // PURPOSE: To center dialog and limit size of edit controls and initialize // // PARAMETERS: // hdlg - The window handing the message. // uMessage - The message number. (unused). // wparam - Message specific data (unused). // lparam - Message specific data (unused). // // RETURN VALUE: // Always returns 0 - message handled. // // COMMENTS: // Set size of edit controls for the following // Socket 4 chars (2 2-digit hex numbers) // LRESULT MsgListenInit(HWND hdlg, UINT uMessage, WPARAM wparam, LPARAM lparam) { lparam; wparam; uMessage; // Create a font to use if(NULL == (hfontDlg = CreateFont(14, 0, 0, 0, 0, 0, 0, 0,0, 0, 0, 0, VARIABLE_PITCH | FF_SWISS, ""))) return FALSE; // Center the dialog over the application window CenterWindow (hdlg, GetWindow (hdlg, GW_OWNER)); // Initialize Socket Addresses SetDlgItemText(hdlg, LD_SOCKET, szListenSocket); // Limit input to proper size strings SendDlgItemMessage(hdlg, LD_SOCKET, EM_LIMITTEXT, 4, 0); return (TRUE); } // // FUNCTION: MsgListenConnected(HWND, UINT, WPARAM, LPARAM) // // PURPOSE: To handle connected message when socket is connected // // PARAMETERS: // hdlg - The window handing the message. // uMessage - The message number. (unused). // wparam - Message specific data (unused). // lparam - Message specific data (unused). // // RETURN VALUE: // Always returns 0 - message handled. // // COMMENTS: // Performs accept() on incoming socket // LRESULT MsgListenConnected(HWND hdlg, UINT uMessage, WPARAM wparam, LPARAM lparam) { char outtext[128]; HRESULT hRet; lparam; wparam; uMessage; SetDlgItemText(hdlg, LD_STATUS, "Client Connected!"); SetDlgItemText(hdlg, LD_STATUS, "Calling accept()"); pRemAddr = (PSOCKADDR_IPX)&addr; addrlen = sizeof(addr); // Accept connection if ((sock = accept(SrvSock, (struct sockaddr *)pRemAddr, &addrlen)) == INVALID_SOCKET) { // accept() failed -- show status and clean up dialog //sprintf(outtext, "Accept() failed, error %u",WSAGetLastError()); hRet = StringCchPrintf(outtext,128,"Accept() failed, error %u",WSAGetLastError()); SetDlgItemText(hdlg, LD_STATUS, outtext); closesocket(SrvSock); WSACleanup(); EnableWindow(GetDlgItem(hdlg, IDOK), TRUE); EnableWindow(GetDlgItem(hdlg, LD_SOCKET), TRUE); SetFocus(GetDlgItem(hdlg, LD_SOCKET)); return(TRUE); } // We're connected! GetAddrString(pRemAddr, outtext); hRet = StringCchCat(outtext,128," connected!"); SetDlgItemText(hdlg, LD_STATUS, outtext); EndDialog(hdlg, TRUE); // Exit the dialog DeleteObject (hfontDlg); // Drop font return (TRUE); } // // FUNCTION: MsgListenCommand(HWND, UINT, WPARAM, LPARAM) // // PURPOSE: Process WM_COMMAND message sent to the Listen box. // // PARAMETERS: // hwnd - The window handing the message. // uMessage - The message number. (unused). // wparam - Message specific data (unused). // lparam - Message specific data (unused). // // RETURN VALUE: // Always returns 0 - message handled. // // COMMENTS: // Uses this DispCommand function defined in wndproc.c combined // with the cmdiListen structure defined in this file to handle // the command messages for the Listen dialog box. // LRESULT MsgListenCommand(HWND hwnd, UINT uMessage, WPARAM wparam, LPARAM lparam) { uMessage; return DispCommand(&cmdiListen, hwnd, wparam, lparam); } // // FUNCTION: CmdListenDone(HWND, WORD, HWND) // // PURPOSE: Free the Listen box and related data. // // PARAMETERS: // hdlg - The window handling the command. // wCommand - The command to be handled (unused). // wNotify - Notification number (unused) // hwndCtrl - NULL (unused). // // RETURN VALUE: // Always returns TRUE. // // COMMENTS: // Cleans up sockets then calls EndDialog to finish the dialog session. // LRESULT CmdListenDone(HWND hdlg, WORD wCommand, WORD wNotify, HWND hwndCtrl) { hwndCtrl; wNotify; wCommand; if (INVALID_SOCKET != SrvSock) { closesocket(SrvSock); // Free any aborted socket resources SrvSock = INVALID_SOCKET; } WSACleanup(); DeleteObject (hfontDlg); // Drop the font EndDialog(hdlg, FALSE); // Exit Dialog -- rtrn false since no connection return TRUE; } // // FUNCTION: CmdListenNow(HWND, WORD, WORD, HWND) // // PURPOSE: Handles ID_OK message and listens on the specified socket // // PARAMETERS: // hwnd - The window handling the command. // wCommand - The command to be handled (unused). // wNotify - Notification number (unused) // hwndCtrl - NULL (unused). // // RETURN VALUE: // Always returns TRUE. // // COMMENTS: // Shows Listening address on status bar when listen is successful. // LRESULT CmdListenNow(HWND hdlg, WORD wCommand, WORD wNotify, HWND hwndCtrl) { char szXferBuffer[5]; WORD wVersionRequested; WSADATA wsaData; char outtext[80]; HRESULT hRet; hwndCtrl; wNotify; wCommand; // Get Socket Address GetDlgItemText(hdlg, LD_SOCKET, szXferBuffer, sizeof(szXferBuffer)); wVersionRequested = MAKEWORD(1, 1); SetDlgItemText(hdlg, LD_STATUS, "Calling WSAStartup"); // Initializes winsock dll if(WSAStartup(wVersionRequested, &wsaData) != 0) { SetDlgItemText(hdlg, LD_STATUS, "WSAStartup failed"); return TRUE; } SetDlgItemText(hdlg, LD_STATUS, "WSAStartup Succeeded"); SetDlgItemText(hdlg, LD_STATUS, "Calling socket()"); // Allocate socket handle SrvSock = socket(AF_IPX, // IPX Family SOCK_SEQPACKET, // Gives message mode transfers NSPROTO_SPX); // SPX is connection oriented transport if(SrvSock == INVALID_SOCKET) { SetDlgItemText(hdlg, LD_STATUS, "ERROR on socket()"); WSACleanup(); return TRUE; } SetDlgItemText(hdlg, LD_STATUS, "socket() Succeeded"); // Set up socket address to bind to memset(&addr, 0, sizeof(addr)); // Clear address pSockAddr = (PSOCKADDR_IPX)&addr; // Set pointer pSockAddr->sa_family = AF_IPX; // IPX Family // Make sure socket number is in network order AtoH(szXferBuffer, (char *)&pSockAddr->sa_socket, 2); SetDlgItemText(hdlg, LD_STATUS, "Calling bind()"); // Bind to socket address if(bind(SrvSock, (PSOCKADDR) pSockAddr, sizeof(SOCKADDR_IPX)) == SOCKET_ERROR) { SetDlgItemText(hdlg, LD_STATUS, "Error on bind()"); if (INVALID_SOCKET != SrvSock) { closesocket(SrvSock); SrvSock = INVALID_SOCKET; } WSACleanup(); return TRUE; } SetDlgItemText(hdlg, LD_STATUS, "bind() Succeeded"); SetDlgItemText(hdlg, LD_STATUS, "Calling listen()"); // Set up listen queue - this app only supports one connection so // queue length is set to 1. if (listen(SrvSock, 1) == SOCKET_ERROR) { hRet = StringCchPrintf(outtext,80,"FAILURE: listen() returned %u", WSAGetLastError()); SetDlgItemText(hdlg, LD_STATUS, outtext); if (INVALID_SOCKET != SrvSock) { closesocket(SrvSock); SrvSock = INVALID_SOCKET; } WSACleanup(); return TRUE; } SetDlgItemText(hdlg, LD_STATUS, "listen() succeeded"); SetDlgItemText(hdlg, LD_STATUS, "Calling WSAAsyncSelect()"); // Specify message to be posted when client connects if(WSAAsyncSelect(SrvSock, hdlg, LDM_CONNECTED, FD_ACCEPT) == SOCKET_ERROR) { SetDlgItemText(hdlg, LD_STATUS, "WSAAsyncSelect() failed"); if (INVALID_SOCKET != SrvSock) { closesocket(SrvSock); SrvSock = INVALID_SOCKET; } WSACleanup(); return TRUE; } SetDlgItemText(hdlg, LD_STATUS, "WSAAsyncSelect() succeeded"); addrlen = sizeof(addr); // Get full network.number.socket address if(getsockname(SrvSock,&addr,&addrlen) == SOCKET_ERROR) { hRet = StringCchCopy(outtext,80,"ERROR getsocketname()"); } else { hRet = StringCchCopy(outtext,80,"Listening on "); GetAddrString((PSOCKADDR_IPX)&addr, outtext + lstrlen(outtext)); } SetDlgItemText(hdlg, LD_STATUS, outtext); SetFocus(GetDlgItem(hdlg, IDCANCEL)); // Give Cancel Button focus EnableWindow(GetDlgItem(hdlg, IDOK), FALSE); // Grey OK button EnableWindow(GetDlgItem(hdlg, LD_SOCKET), FALSE); // Grey Socket Edit control return (TRUE); }
danpbowen/Mallet
src/cc/mallet/classify/constraints/pr/MaxEntFLPRConstraints.java
<filename>src/cc/mallet/classify/constraints/pr/MaxEntFLPRConstraints.java /* Copyright (C) 2011 Univ. of Massachusetts Amherst, Computer Science Dept. This file is part of "MALLET" (MAchine Learning for LanguagE Toolkit). http://www.cs.umass.edu/~mccallum/mallet This software is provided under the terms of the Common Public License, version 1.0, as published by http://www.opensource.org. For further information, see the file `LICENSE' included with this distribution. */ package cc.mallet.classify.constraints.pr; import java.util.BitSet; import com.carrotsearch.hppc.DoubleArrayList; import com.carrotsearch.hppc.IntArrayList; import com.carrotsearch.hppc.IntObjectHashMap; import com.carrotsearch.hppc.cursors.IntObjectCursor; import com.google.errorprone.annotations.Var; import cc.mallet.types.FeatureVector; import cc.mallet.types.Instance; import cc.mallet.types.InstanceList; /** * Abstract expectation constraint for use with Posterior Regularization (PR). * * @author <NAME> */ public abstract class MaxEntFLPRConstraints implements MaxEntPRConstraint { protected boolean useValues; protected int numFeatures; protected int numLabels; // maps between input feature indices and constraints protected IntObjectHashMap<MaxEntFLPRConstraint> constraints; // cache of set of constrained features that fire at last FeatureVector // provided in preprocess call protected IntArrayList indexCache; protected DoubleArrayList valueCache; public MaxEntFLPRConstraints(int numFeatures, int numLabels, boolean useValues) { this.useValues = useValues; this.numFeatures = numFeatures; this.numLabels = numLabels; this.constraints = new IntObjectHashMap<MaxEntFLPRConstraint>(); this.indexCache = new IntArrayList(); this.valueCache = new DoubleArrayList(); } public abstract void addConstraint(int fi, double[] ex, double weight); public void incrementExpectations(FeatureVector input, double[] dist, double weight) { preProcess(input); for (int li = 0; li < numLabels; li++) { double p = weight * dist[li]; for (int i = 0; i < indexCache.size(); i++) { if (useValues) { constraints.get(indexCache.get(i)).expectation[li] += p * valueCache.get(i); } else { constraints.get(indexCache.get(i)).expectation[li] += p; } } } } public void zeroExpectations() { for (IntObjectCursor<MaxEntFLPRConstraint> fi : constraints) { fi.value.expectation = new double[numLabels]; } } public BitSet preProcess(InstanceList data) { // count @Var int ii = 0; @Var int fi; @Var FeatureVector fv; BitSet bitSet = new BitSet(data.size()); for (Instance instance : data) { double weight = data.getInstanceWeight(instance); fv = (FeatureVector)instance.getData(); for (int loc = 0; loc < fv.numLocations(); loc++) { fi = fv.indexAtLocation(loc); if (constraints.containsKey(fi)) { if (useValues) { constraints.get(fi).count += weight * fv.valueAtLocation(loc); } else { constraints.get(fi).count += weight; } bitSet.set(ii); } } ii++; // default feature, for label regularization if (constraints.containsKey(numFeatures)) { bitSet.set(ii); constraints.get(numFeatures).count += weight; } } return bitSet; } public void preProcess(FeatureVector input) { indexCache.clear(); if (useValues) valueCache.clear(); @Var int fi; // cache constrained input features for (int loc = 0; loc < input.numLocations(); loc++) { fi = input.indexAtLocation(loc); if (constraints.containsKey(fi)) { indexCache.add(fi); if (useValues) valueCache.add(input.valueAtLocation(loc)); } } // default feature, for label regularization if (constraints.containsKey(numFeatures)) { indexCache.add(numFeatures); if (useValues) valueCache.add(1); } } protected abstract class MaxEntFLPRConstraint { protected double count; protected double weight; protected double[] target; protected double[] expectation; public MaxEntFLPRConstraint(double[] target, double weight) { this.count = 0; this.weight = weight; this.target = target; this.expectation = null; } public double[] getTarget() { return target; } public double[] getExpectation() { return expectation; } public double getCount() { return count; } public double getWeight() { return weight; } } }
yuanhao2015/acoolQi
acoolqi-admin/router/dict_type_router.go
<filename>acoolqi-admin/router/dict_type_router.go package router import ( "acoolqi-admin/api/v1/system" "github.com/gin-gonic/gin" ) //初始化字典类型路由 func initDictTypeRouter(router *gin.RouterGroup) { v := new(system.DictTypeApi) group := router.Group("/system/dict/type") { //查询字典类型分页数据 group.GET("/list", v.List) //根据id查询字典类型数据 group.GET("/:dictTypeId", v.Get) //修改字典类型 group.PUT("/edit", v.Edit) //新增字典类型 group.POST("/add", v.Add) //删除字典类型 group.DELETE("/remove/:dictId", v.Remove) //刷新缓存 group.DELETE("/refreshCache", v.RefreshCache) //导出excel group.GET("/export", v.Export) } }
jerolba/jfleet
jfleet-samples/src/main/java/org/jfleet/util/CsvSplit.java
<reponame>jerolba/jfleet /** * Copyright 2017 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jfleet.util; public class CsvSplit { public static String[] split(String line, int fieldsNumber) { int col = 0; int idx = 0; String[] cols = new String[fieldsNumber]; while (idx < line.length()) { if (line.charAt(idx)=='"') { idx++; int ini = idx; while (idx<line.length() && line.charAt(idx)!='"') { idx++; } cols[col++] = line.substring(ini, idx); idx++; //Skip " idx++; //Skip , }else { int ini = idx; while (idx<line.length() && line.charAt(idx)!=',') { idx++; } cols[col++] = line.substring(ini, idx); idx++; //Skip , } } return cols; } }
my-references/coursemology2
app/models/components/course/user_email_unsubscriptions_ability_component.rb
<filename>app/models/components/course/user_email_unsubscriptions_ability_component.rb # frozen_string_literal: true module Course::UserEmailUnsubscriptionsAbilityComponent include AbilityHost::Component def define_permissions allow_user_manage_email_subscription if user super end private def allow_user_manage_email_subscription can :manage, Course::UserEmailUnsubscription, course_user: { user_id: user.id } end end
14gollaher/CSC446-Compiler-Construction
CMinusMinusCompiler/CMinusMinusCompiler.Test/LexicalAnalyzer/Source/Tokens2.c
12. .5
jensonwe/mvvmFX
mvvmfx/src/test/java/de/saxsys/mvvmfx/scopes/example4/views/DialogView.java
<gh_stars>100-1000 package de.saxsys.mvvmfx.scopes.example4.views; import de.saxsys.mvvmfx.FxmlView; import de.saxsys.mvvmfx.InjectViewModel; public class DialogView implements FxmlView<DialogViewModel> { @InjectViewModel DialogViewModel viewModel; }
mark-online/server
test/loginserver.test/LoginServiceTestFixture.h
#pragma once #include "loginserver/LoginService.h" #include <gideon/servertest/DatabaseTestFixture.h> #include <gideon/cs/shared/data/Certificate.h> class MockLoginServerSideProxy; using namespace sne; using namespace gideon; /** * @class LoginServiceTestFixture * * 로그인 서비스 테스트 Fixture */ class LoginServiceTestFixture : public servertest::DatabaseTestFixture { protected: virtual void SetUp(); virtual void TearDown(); protected: MockLoginServerSideProxy* createLoginServerSideProxy( sne::server::ServerId serverId, ServerType serverType); protected: const Certificate* getCertificate(ServerType st) const { return gideon::getCertificate(verifiedCertificateMap_, st); } protected: loginserver::LoginService* loginService_; AccountId verifiedAccountId_; CertificateMap verifiedCertificateMap_; };
dmitry-vovk/sql-dataset
client_test.go
<filename>client_test.go package main import ( "fmt" "io/ioutil" "net/http" "net/http/httptest" "strings" "testing" "github.com/geckoboard/sql-dataset/models" ) type request struct { Method string Headers map[string]string Path string Body string } type response struct { code int body string } const ( apiKey = "ap1K3Y" expAuth = "Basic YXAxSzNZOg==" ) func TestFindOrCreateDataset(t *testing.T) { userAgent = "SQL-Dataset/test-fake" testCases := []struct { dataset models.Dataset request request response *response err string }{ { dataset: models.Dataset{ Name: "active.users.count", Fields: []models.Field{ { Name: "mrr", Type: models.MoneyType, CurrencyCode: "USD", }, { Name: "signups", Type: models.NumberType, }, }, }, request: request{ Method: http.MethodPut, Path: "/datasets/active.users.count", Body: `{"id":"active.users.count","fields":{"mrr":{"type":"money","name":"mrr","currency_code":"USD"},"signups":{"type":"number","name":"signups"}}}`, }, }, { dataset: models.Dataset{ Name: "active.users.count", Fields: []models.Field{ { Name: "day", Type: models.DatetimeType, }, { Name: "mrr Percent", Type: models.PercentageType, Optional: true, }, }, }, request: request{ Method: http.MethodPut, Path: "/datasets/active.users.count", Body: `{"id":"active.users.count","fields":{"day":{"type":"datetime","name":"day"},"mrr_percent":{"type":"percentage","name":"mrr Percent","optional":true}}}`, }, }, { dataset: models.Dataset{ Name: "builds.count.by.day", UniqueBy: []string{"day"}, Fields: []models.Field{ { Name: "Builds", Type: models.NumberType, Optional: true, }, { Name: "day", Type: models.DateType, }, }, }, request: request{ Method: http.MethodPut, Path: "/datasets/builds.count.by.day", Body: `{"id":"builds.count.by.day","unique_by":["day"],"fields":{"builds":{"type":"number","name":"Builds","optional":true},"day":{"type":"date","name":"day"}}}`, }, }, { // Verify 50x just returns generic error dataset: models.Dataset{ Name: "active.users.count", Fields: []models.Field{ { Name: "mrr", Type: models.MoneyType, CurrencyCode: "USD", }, { Name: "signups", Type: models.NumberType, }, }, }, response: &response{ code: 500, body: "<html>Internal error</html>", }, err: errUnexpectedResponse.Error(), }, { // Verify 40x response unmarshalled and return message dataset: models.Dataset{ Name: "active.users.count", Fields: []models.Field{ { Name: "mrr", Type: models.MoneyType, CurrencyCode: "USD", }, { Name: "signups", Type: models.NumberType, }, }, }, response: &response{ code: 400, body: `{"error":{"type":"ErrResourceInvalid","message":"Field name too short"}}`, }, err: fmt.Sprintf(errInvalidPayload, "Field name too short"), }, { // Verify 201 response correctly handled dataset: models.Dataset{ Name: "active.users.count", Fields: []models.Field{ { Name: "mrr", Type: models.MoneyType, CurrencyCode: "USD", }, { Name: "signups", Type: models.NumberType, }, }, }, response: &response{ code: 201, body: `{}`, }, }, } for _, tc := range testCases { reqCount := 0 server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { reqCount++ if tc.response != nil { w.WriteHeader(tc.response.code) fmt.Fprintf(w, tc.response.body) return } auth := r.Header.Get("Authorization") if auth != expAuth { t.Errorf("Expected authorization header '%s' but got '%s'", expAuth, auth) } ua := r.Header.Get("User-Agent") if ua != userAgent { t.Errorf("Expected user header '%s' but got '%s'", userAgent, ua) } if r.URL.Path != tc.request.Path { t.Errorf("Expected path '%s' but got '%s'", tc.request.Path, r.URL.Path) } if r.Method != tc.request.Method { t.Errorf("Expected method '%s' but got '%s'", tc.request.Method, r.Method) } b, err := ioutil.ReadAll(r.Body) if err != nil { t.Errorf("Errored while consuming body %s", err) } body := strings.Trim(string(b), "\n") if body != tc.request.Body { t.Errorf("Expected body '%s' but got '%s'", tc.request.Body, body) } })) gbHost = server.URL c := NewClient(apiKey) err := c.FindOrCreateDataset(&tc.dataset) if err != nil && tc.err == "" { t.Errorf("Expected no error but got '%s'", err) } if err == nil && tc.err != "" { t.Errorf("Expected error '%s' but got none", tc.err) } if err != nil && err.Error() != tc.err { t.Errorf("Expected error '%s' but got '%s'", tc.err, err) } if reqCount != 1 { t.Errorf("Expected one request but got %d", reqCount) } server.Close() } } func TestDeleteDataset(t *testing.T) { userAgent = "SQL-Dataset/test-fake" testCases := []struct { name string request request response *response err string }{ { // Dataset not existing response name: "active.users.count", request: request{ Path: "/datasets/active.users.count", }, response: &response{ code: 404, body: `{"error":{"message":"Dataset not found"}}`, }, err: fmt.Sprintf(errInvalidPayload, "Dataset not found"), }, { // Verify bad response name: "active.users.count", request: request{ Path: "/datasets/active.users.count", }, response: &response{ code: 500, body: "<html>Internal error</html>", }, err: errUnexpectedResponse.Error(), }, { // Verify 200 response correctly handled name: "active.users.count", request: request{ Path: "/datasets/active.users.count", }, response: &response{ code: 200, body: `{}`, }, }, } for _, tc := range testCases { reqCount := 0 server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { reqCount++ auth := r.Header.Get("Authorization") if auth != expAuth { t.Errorf("Expected authorization header '%s' but got '%s'", expAuth, auth) } ua := r.Header.Get("User-Agent") if ua != userAgent { t.Errorf("Expected user header '%s' but got '%s'", userAgent, ua) } if r.URL.Path != tc.request.Path { t.Errorf("Expected path '%s' but got '%s'", tc.request.Path, r.URL.Path) } if r.Method != http.MethodDelete { t.Errorf("Expected method '%s' but got '%s'", http.MethodDelete, r.Method) } if tc.response != nil { w.WriteHeader(tc.response.code) fmt.Fprintf(w, tc.response.body) return } })) gbHost = server.URL c := NewClient(apiKey) err := c.DeleteDataset(tc.name) switch { case err == nil && tc.err != "": t.Errorf("Expected error %q but got none", tc.err) case err != nil && (tc.err == "" || tc.err != err.Error()): t.Errorf("Expected error '%s' but got '%s'", tc.err, err) } if reqCount != 1 { t.Errorf("Expected one request but got %d", reqCount) } server.Close() } } // Preset the dataset rows and test we batch correctly return errors on status codes func TestSendAllData(t *testing.T) { testCases := []struct { dataset models.Dataset data models.DatasetRows requests []request maxRows int response *response err string }{ { // Error with 40x dataset: models.Dataset{ Name: "app.build.costs", UpdateType: models.Replace, Fields: []models.Field{ {Name: "App", Type: models.StringType}, {Name: "Run time", Type: models.NumberType}, }, }, data: models.DatasetRows{ { "app": "acceptance", "run_time": 4421, }, }, requests: []request{{}}, response: &response{ code: 400, body: `{"error": {"type":"ErrMissingData", "message": "Missing data for 'app'"}}`, }, err: fmt.Sprintf(errInvalidPayload, "Missing data for 'app'"), }, { // Error with 50x dataset: models.Dataset{ Name: "app.build.costs", UpdateType: models.Replace, Fields: []models.Field{ {Name: "App", Type: models.StringType}, {Name: "Run time", Type: models.NumberType}, }, }, data: models.DatasetRows{ { "app": "acceptance", "run_time": 4421, }, }, requests: []request{{}}, response: &response{ code: 500, body: "<html>Internal Server error</html>", }, err: errUnexpectedResponse.Error(), }, { //Replace dataset with no data dataset: models.Dataset{ Name: "app.no.data", UpdateType: models.Replace, Fields: []models.Field{ {Name: "App", Type: models.StringType}, {Name: "Percent", Type: models.PercentageType}, }, }, data: models.DatasetRows{}, requests: []request{ { Method: http.MethodPut, Path: "/datasets/app.no.data/data", Body: `{"data":[]}`, }, }, }, { //Replace dataset under the batch rows limit doesn't error dataset: models.Dataset{ Name: "app.reliable.percent", UpdateType: models.Replace, Fields: []models.Field{ {Name: "App", Type: models.StringType}, {Name: "Percent", Type: models.PercentageType}, }, }, data: models.DatasetRows{ { "app": "acceptance", "percent": 0.43, }, { "app": "redis", "percent": 0.22, }, { "app": "api", "percent": 0.66, }, }, requests: []request{ { Method: http.MethodPut, Path: "/datasets/app.reliable.percent/data", Body: `{"data":[{"app":"acceptance","percent":0.43},{"app":"redis","percent":0.22},{"app":"api","percent":0.66}]}`, }, }, }, { //Append with no data makes no requests dataset: models.Dataset{ Name: "append.no.data", UpdateType: models.Append, Fields: []models.Field{ {Name: "App", Type: models.StringType}, {Name: "Count", Type: models.NumberType}, }, }, data: models.DatasetRows{}, requests: []request{}, }, { //Append dataset under the batch rows limit dataset: models.Dataset{ Name: "app.builds.count", UpdateType: models.Append, Fields: []models.Field{ {Name: "App", Type: models.StringType}, {Name: "Count", Type: models.NumberType}, }, }, data: models.DatasetRows{ { "app": "acceptance", "count": 88, }, { "app": "redis", "count": 55, }, { "app": "api", "count": 214, }, }, requests: []request{ { Method: http.MethodPost, Path: "/datasets/app.builds.count/data", Body: `{"data":[{"app":"acceptance","count":88},{"app":"redis","count":55},{"app":"api","count":214}]}`, }, }, }, { //Replace dataset over the batch rows limit sends first 3 and errors dataset: models.Dataset{ Name: "app.build.costs", UpdateType: models.Replace, Fields: []models.Field{ {Name: "App", Type: models.StringType}, {Name: "Cost", Type: models.MoneyType}, }, }, data: models.DatasetRows{ { "app": "acceptance", "cost": 4421, }, { "app": "redis", "cost": 221, }, { "app": "api", "cost": 212, }, { "app": "integration", "cost": 121, }, }, requests: []request{ { Method: http.MethodPut, Path: "/datasets/app.build.costs/data", Body: `{"data":[{"app":"acceptance","cost":4421},{"app":"redis","cost":221},{"app":"api","cost":212}]}`, }, }, maxRows: 3, err: fmt.Sprintf(errMoreRowsToSend, 4, 3), }, { //Append dataset sends all data in batches dataset: models.Dataset{ Name: "animal.run.time", UpdateType: models.Append, Fields: []models.Field{ {Name: "animal", Type: models.StringType}, {Name: "Run time", Type: models.NumberType}, }, }, data: models.DatasetRows{ { "animal": "worm", "run_time": 621, }, { "animal": "snail", "run_time": 521, }, { "animal": "duck", "run_time": 41, }, { "animal": "geese", "run_time": 44, }, { "animal": "terrapin", "run_time": 444, }, { "animal": "bird", "run_time": 22, }, }, requests: []request{ { Method: http.MethodPost, Path: "/datasets/animal.run.time/data", Body: `{"data":[{"animal":"worm","run_time":621},{"animal":"snail","run_time":521},{"animal":"duck","run_time":41}]}`, }, { Method: http.MethodPost, Path: "/datasets/animal.run.time/data", Body: `{"data":[{"animal":"geese","run_time":44},{"animal":"terrapin","run_time":444},{"animal":"bird","run_time":22}]}`, }, }, maxRows: 3, }, { //Append dataset sends all data in batches remaining one dataset: models.Dataset{ Name: "animal.run.time", UpdateType: models.Append, Fields: []models.Field{ {Name: "Animal", Type: models.StringType}, {Name: "Run time", Type: models.NumberType}, }, }, data: models.DatasetRows{ { "animal": "worm", "run_time": 621, }, { "animal": "snail", "run_time": 521, }, { "animal": "duck", "run_time": 41, }, { "animal": "geese", "run_time": 44, }, { "animal": "terrapin", "run_time": 444, }, { "animal": "bird", "run_time": 22, }, { "animal": "squirrel", "run_time": 88, }, }, requests: []request{ { Method: http.MethodPost, Path: "/datasets/animal.run.time/data", Body: `{"data":[{"animal":"worm","run_time":621},{"animal":"snail","run_time":521},{"animal":"duck","run_time":41}]}`, }, { Method: http.MethodPost, Path: "/datasets/animal.run.time/data", Body: `{"data":[{"animal":"geese","run_time":44},{"animal":"terrapin","run_time":444},{"animal":"bird","run_time":22}]}`, }, { Method: http.MethodPost, Path: "/datasets/animal.run.time/data", Body: `{"data":[{"animal":"squirrel","run_time":88}]}`, }, }, maxRows: 3, }, } for _, tc := range testCases { reqCount := 0 if tc.maxRows != 0 { maxRows = tc.maxRows } else { maxRows = 500 } server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { reqCount++ if tc.response != nil { w.WriteHeader(tc.response.code) fmt.Fprintf(w, tc.response.body) return } if reqCount > len(tc.requests) { t.Errorf("Got unexpected extra requests") return } tcReq := tc.requests[reqCount-1] auth := r.Header.Get("Authorization") if auth != expAuth { t.Errorf("Expected authorization header '%s' but got '%s'", expAuth, auth) } if r.URL.Path != tcReq.Path { t.Errorf("Expected path '%s' but got '%s'", tcReq.Path, r.URL.Path) } if r.Method != tcReq.Method { t.Errorf("Expected method '%s' but got '%s'", tcReq.Method, r.Method) } b, err := ioutil.ReadAll(r.Body) if err != nil { t.Errorf("Errored while consuming body %s", err) } body := strings.Trim(string(b), "\n") if body != tcReq.Body { t.Errorf("Expected body '%s' but got '%s'", tcReq.Body, body) } })) gbHost = server.URL c := NewClient(apiKey) err := c.SendAllData(&tc.dataset, tc.data) if err != nil && tc.err == "" { t.Errorf("Expected no error but got '%s'", err) } if err == nil && tc.err != "" { t.Errorf("Expected error '%s' but got none", tc.err) } if err != nil && err.Error() != tc.err { t.Errorf("Expected error '%s' but got '%s'", tc.err, err) } if reqCount != len(tc.requests) { t.Errorf("Expected %d requests but got %d", len(tc.requests), reqCount) } server.Close() } }
songlin0203/openzaly
openzaly-message/src/main/java/com/akaxin/site/message/utils/SiteConfigHelper.java
<reponame>songlin0203/openzaly /** * Copyright 2018-2028 Akaxin Group * * 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.akaxin.site.message.utils; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.akaxin.proto.core.ConfigProto; import com.akaxin.site.message.dao.SiteConfigDao; /** * 管理站点配置相关信息 * * @author Sam{@link <EMAIL>} * @since 2018-01-14 21:18:49 */ public class SiteConfigHelper { private static final Logger logger = LoggerFactory.getLogger(SiteConfigHelper.class); private static volatile Map<Integer, String> configMap; private SiteConfigHelper() { } public static Map<Integer, String> getConfigMap() { if (configMap == null) { configMap = SiteConfigDao.getInstance().getSiteConfig(); } return configMap; } public static Map<Integer, String> updateConfig() { try { configMap = SiteConfigDao.getInstance().getSiteConfig(); logger.info("update site config : {}", configMap); } catch (Exception e) { logger.error("update site config error.", e); } return configMap; } public static String getConfig(ConfigProto.ConfigKey configKey) { try { return getConfigMap().get(configKey.getNumber()); } catch (Exception e) { logger.error("get config value error", e); } return null; } }
hhkhub/py-ios-device
ios_device/cli/mobile.py
<filename>ios_device/cli/mobile.py import functools import io import sys import click from ios_device.cli.base import InstrumentsBase from ios_device.cli.cli import Command, print_json from ios_device.servers.Installation import InstallationProxyService from ios_device.servers.crash_log import CrashLogService from ios_device.servers.diagnostics_relay import DiagnosticsRelayService from ios_device.servers.house_arrest import HouseArrestService from ios_device.servers.mc_install import MCInstallService from ios_device.servers.pcapd import PcapdService, PCAPPacketDumper from ios_device.servers.syslog import SyslogServer from ios_device.util import Log from ios_device.util.lockdown import LockdownClient from ios_device.util.usbmux import USBMux from ios_device.util.variables import LOG log = Log.getLogger(LOG.Mobile.value) @click.group() def cli(): """ instruments cli """ @cli.group(short_help='crash report options') def crash(): """ 获取 crash log 相关信息 crash report options """ @crash.command('delete', cls=Command) @click.option('--name', help='crash name') def crash_delete(udid, network, format, name): """ remove crash report """ crash_server = CrashLogService(udid=udid, network=network, logger=log) crash_server.delete_crash(name) @crash.command('export', cls=Command) @click.option('--name', help='crash name') def crash_export(udid, network, format, name): """ pull crash report """ crash_server = CrashLogService(udid=udid, network=network, logger=log) crash_server.export_crash(name) @crash.command('list', cls=Command) def crash_list(udid, network, format): """ Show crash list """ crash_server = CrashLogService(udid=udid, network=network, logger=log) crash_server.get_list() @crash.command('shell', cls=Command) def crash_shell(udid, network, format): """ Open command line mode """ crash_server = CrashLogService(udid=udid, network=network, logger=log) crash_server.shell() ####################################################################### @cli.command('sandbox', cls=Command) @click.option('-b', '--bundle_id', default=None, help='Process app bundleId to filter') @click.option('-a', '--access_type', default='VendDocuments', type=click.Choice(['VendDocuments', 'VendContainer']), help='Type of access sandbox') def sandbox(udid, network, format, bundle_id, access_type): """ open an AFC shell for given bundle_id, assuming its profile is installed """ HouseArrestService(udid=udid, network=network, logger=log).shell(bundle_id, cmd=access_type) ####################################################################### @cli.command('devices', cls=Command) def cmd_devices(udid, network, format): """ get device list """ print_json(USBMux().get_devices(network), format) @cli.command('deviceinfo', cls=Command) def cmd_deviceinfo(udid, network, format): """ open an AFC shell for given bundle_id, assuming its profile is installed """ device_info = LockdownClient(udid=udid, network=network).get_value() print_json(device_info,format=format) ####################################################################### @cli.group(short_help='crash report options') def profiles(): """ 描述文件管理 例如:安装 卸载 Fiddler 证书等 profiles & Device Management """ @profiles.command('list', cls=Command) def profile_list(udid, network, format): """ list installed profiles """ print_json(MCInstallService(udid=udid, network=network, logger=log).get_profile_list(), format) @profiles.command('install', cls=Command) @click.option('--path', type=click.File('rb')) def profile_install(udid, network, format, path): """ install given profile file """ print_json(MCInstallService(udid=udid, network=network, logger=log).install_profile(path.read()), format) @profiles.command('remove', cls=Command) @click.option('--name') def profile_remove(udid, network, format, name): """ remove profile by name """ print_json(MCInstallService(udid=udid, network=network, logger=log).remove_profile(name), format) ####################################################################### @cli.command('syslog', cls=Command) @click.option('--path', type=click.File('wt'), help='full path to the log file') @click.option('--filter', help='filter strings') def cmd_syslog(udid, network, format, path, filter): """ file management per application bundle """ server = SyslogServer(udid=udid, network=network, logger=log) server.watch(log_file=path, filter=filter) ####################################################################### @cli.group() def apps(): """ application options """ pass @apps.command('list', cls=Command) @click.option('-u', '--user', is_flag=True, help='include user apps') @click.option('-s', '--system', is_flag=True, help='include system apps') def apps_list(udid, network, format, user, system): """ list installed apps """ app_types = [] if user: app_types.append('User') if system: app_types.append('System') if not app_types: app_types = ['User', 'System'] print_json(InstallationProxyService(udid=udid, network=network, logger=log).get_apps(app_types),format=format) @apps.command('uninstall', cls=Command) @click.option('-b', '--bundle_id', default=None, help='Process app bundleId to filter') def uninstall(udid, network, format, bundle_id): """ uninstall app by given bundle_id """ print_json(InstallationProxyService(udid=udid, network=network, logger=log).uninstall(bundle_id)) @apps.command('install', cls=Command) @click.argument('ipa_path', required=True,type=click.Path(exists=True)) def install(udid, network, format, ipa_path): """ install given .ipa """ print_json(InstallationProxyService(udid=udid, network=network, logger=log).install(ipa_path)) @apps.command('upgrade', cls=Command) @click.option('--ipa_path', type=click.Path(exists=True)) def upgrade(udid, network, format, ipa_path): """ install given .ipa """ print_json(InstallationProxyService(udid=udid, network=network, logger=log).upgrade(ipa_path)) @apps.command('shell', cls=Command) @click.option('-b', '--bundle_id', default=None,required=True, help='Process app bundleId to filter') @click.option('-a', '--access_type', default='VendDocuments', type=click.Choice(['VendDocuments', 'VendContainer']), help='filter VendDocuments or VendContainer') def shell(udid, network, format, bundle_id, access_type): """ open an AFC shell for given bundle_id, assuming its profile is installed """ HouseArrestService(udid=udid, network=network, logger=log).shell(bundle_id, cmd=access_type) @apps.command('launch', cls=Command) @click.option('--bundle_id', default=None, help='Process app bundleId to filter') @click.option('--app_env', default=None, help='App launch environment variable') def cmd_launch(udid, network, format, bundle_id: str, app_env: dict): """ Launch a process. :param bundle_id: Arguments of process to launch, the first argument is the bundle id. :param app_env: App launch environment variable """ with InstrumentsBase(udid=udid, network=network) as rpc: pid = rpc.launch_app(bundle_id=bundle_id, app_env=app_env) print(f'Process launched with pid {pid}') @apps.command('kill', cls=Command) @click.option('-p', '--pid', type=click.INT, default=None, help='Process ID to filter') @click.option('-n', '--name', default=None, help='Process app name to filter') @click.option('-b', '--bundle_id', default=None, help='Process app bundleId to filter') def cmd_kill(udid, network, format, pid, name, bundle_id): """ Kill a process by its pid. """ with InstrumentsBase(udid=udid, network=network) as rpc: if bundle_id or name: pid = rpc.get_pid(bundle_id, name) if not pid: log.warn(f'The {bundle_id, name, pid} did not start') rpc.kill_app(pid) print(f'Kill {pid} ...') ####################################################################### @cli.command('pcapd', cls=Command) @click.argument('outfile', required=True) def cmd_pcapd(udid, network, format, outfile): """ sniff device traffic :param outfile: output file or (- for stdout) """ if outfile == '-': out_file = sys.stdout.buffer while isinstance(out_file, io.BufferedWriter): out_file = out_file.detach() else: out_file = open(outfile, 'wb', 0) num_packets = 0 stderr_print = functools.partial(print, file=sys.stderr) def packet_callback(pkt): nonlocal num_packets num_packets += 1 stderr_print('\r{} packets captured.'.format(num_packets), end='', flush=True) try: packet_extractor = PcapdService(udid=udid, network=network) packet_dumper = PCAPPacketDumper(packet_extractor, out_file) packet_dumper.run(packet_callback) except KeyboardInterrupt: stderr_print() stderr_print('closing capture ...') out_file.close() except: stderr_print() ####################################################################### @cli.command('battery', cls=Command) def cmd_battery(udid, network, format): """ get device battery """ io_registry = DiagnosticsRelayService(udid=udid, network=network, logger=log).get_battery() print_json(io_registry, format=format) update_time = io_registry.get('UpdateTime') voltage = io_registry.get('Voltage') instant_amperage = io_registry.get('InstantAmperage') temperature = io_registry.get('Temperature') current = abs(instant_amperage) power = current * voltage / 1000 log.info( f"[Battery] time={update_time}, current={current}, voltage={voltage}, power={power}, temperature={temperature}") # # @information.command('battery', cls=Command) # def cmd_battery(udid, network, format): # """ get device battery # """ # return
DT-I/tlap
app/models/resource_category.rb
class ResourceCategory < ApplicationRecord has_many :resources end
DadaIsCrazy/usuba
nist/present/usuba/bench/masked_present_ua_bitslice.c
/* This code was generated by Usuba. See https://github.com/DadaIsCrazy/usuba. From the file "samples/usuba/present.ua" (included below). */ #include <stdint.h> /* Do NOT change the order of those define/include */ #ifndef BITS_PER_REG #define BITS_PER_REG 8 #endif /* including the architecture specific .h */ #include "MASKED_UA.h" /* auxiliary functions */ void sbox__B1 (/*inputs*/ DATATYPE X3__[MASKING_ORDER],DATATYPE X2__[MASKING_ORDER],DATATYPE X1__[MASKING_ORDER],DATATYPE X0__[MASKING_ORDER], /*outputs*/ DATATYPE Y3__[MASKING_ORDER],DATATYPE Y2__[MASKING_ORDER],DATATYPE Y1__[MASKING_ORDER],DATATYPE Y0__[MASKING_ORDER]) { // Variables declaration DATATYPE T1__[MASKING_ORDER]; DATATYPE T2__[MASKING_ORDER]; DATATYPE T3__[MASKING_ORDER]; DATATYPE T4__[MASKING_ORDER]; DATATYPE T5__[MASKING_ORDER]; DATATYPE T6__[MASKING_ORDER]; DATATYPE T7__[MASKING_ORDER]; DATATYPE T8__[MASKING_ORDER]; DATATYPE T9__[MASKING_ORDER]; DATATYPE _tmp1_[MASKING_ORDER]; // Instructions (body) for (int _mask_idx = 0; _mask_idx <= (MASKING_ORDER - 1); _mask_idx++) { T1__[_mask_idx] = XOR(X1__[_mask_idx],X2__[_mask_idx]); } _tmp1_[0] = NOT(X0__[0]); for (int _mask_idx = 1; _mask_idx <= (MASKING_ORDER - 1); _mask_idx++) { _tmp1_[_mask_idx] = X0__[_mask_idx]; } MASKED_AND(T2__,X2__,T1__); for (int _mask_idx = 0; _mask_idx <= (MASKING_ORDER - 1); _mask_idx++) { T3__[_mask_idx] = XOR(X3__[_mask_idx],T2__[_mask_idx]); Y0__[_mask_idx] = XOR(X0__[_mask_idx],T3__[_mask_idx]); } MASKED_AND(T4__,T1__,T3__); for (int _mask_idx = 0; _mask_idx <= (MASKING_ORDER - 1); _mask_idx++) { T5__[_mask_idx] = XOR(T1__[_mask_idx],Y0__[_mask_idx]); T6__[_mask_idx] = XOR(T4__[_mask_idx],X2__[_mask_idx]); } MASKED_OR(T7__,X0__,T6__); for (int _mask_idx = 0; _mask_idx <= (MASKING_ORDER - 1); _mask_idx++) { T8__[_mask_idx] = XOR(T6__[_mask_idx],_tmp1_[_mask_idx]); Y1__[_mask_idx] = XOR(T5__[_mask_idx],T7__[_mask_idx]); } MASKED_OR(T9__,T8__,T5__); for (int _mask_idx = 0; _mask_idx <= (MASKING_ORDER - 1); _mask_idx++) { Y3__[_mask_idx] = XOR(Y1__[_mask_idx],T8__[_mask_idx]); Y2__[_mask_idx] = XOR(T3__[_mask_idx],T9__[_mask_idx]); } } void present_round__B1 (/*inputs*/ DATATYPE inp__[64][MASKING_ORDER],DATATYPE key__[64][MASKING_ORDER], /*outputs*/ DATATYPE out__[64][MASKING_ORDER]) { // Variables declaration DATATYPE sbox_in__[16][4][MASKING_ORDER]; DATATYPE sbox_out__[16][4][MASKING_ORDER]; // Instructions (body) for (int _mask_idx = 0; _mask_idx <= (MASKING_ORDER - 1); _mask_idx++) { sbox_in__[0][0][_mask_idx] = XOR(inp__[0][_mask_idx],key__[0][_mask_idx]); sbox_in__[1][0][_mask_idx] = XOR(inp__[4][_mask_idx],key__[4][_mask_idx]); sbox_in__[2][0][_mask_idx] = XOR(inp__[8][_mask_idx],key__[8][_mask_idx]); sbox_in__[3][0][_mask_idx] = XOR(inp__[12][_mask_idx],key__[12][_mask_idx]); sbox_in__[4][0][_mask_idx] = XOR(inp__[16][_mask_idx],key__[16][_mask_idx]); sbox_in__[5][0][_mask_idx] = XOR(inp__[20][_mask_idx],key__[20][_mask_idx]); sbox_in__[6][0][_mask_idx] = XOR(inp__[24][_mask_idx],key__[24][_mask_idx]); sbox_in__[7][0][_mask_idx] = XOR(inp__[28][_mask_idx],key__[28][_mask_idx]); sbox_in__[8][0][_mask_idx] = XOR(inp__[32][_mask_idx],key__[32][_mask_idx]); sbox_in__[9][0][_mask_idx] = XOR(inp__[36][_mask_idx],key__[36][_mask_idx]); sbox_in__[10][0][_mask_idx] = XOR(inp__[40][_mask_idx],key__[40][_mask_idx]); sbox_in__[11][0][_mask_idx] = XOR(inp__[44][_mask_idx],key__[44][_mask_idx]); sbox_in__[12][0][_mask_idx] = XOR(inp__[48][_mask_idx],key__[48][_mask_idx]); sbox_in__[13][0][_mask_idx] = XOR(inp__[52][_mask_idx],key__[52][_mask_idx]); sbox_in__[14][0][_mask_idx] = XOR(inp__[56][_mask_idx],key__[56][_mask_idx]); sbox_in__[15][0][_mask_idx] = XOR(inp__[60][_mask_idx],key__[60][_mask_idx]); sbox_in__[0][1][_mask_idx] = XOR(inp__[1][_mask_idx],key__[1][_mask_idx]); sbox_in__[1][1][_mask_idx] = XOR(inp__[5][_mask_idx],key__[5][_mask_idx]); sbox_in__[2][1][_mask_idx] = XOR(inp__[9][_mask_idx],key__[9][_mask_idx]); sbox_in__[3][1][_mask_idx] = XOR(inp__[13][_mask_idx],key__[13][_mask_idx]); sbox_in__[4][1][_mask_idx] = XOR(inp__[17][_mask_idx],key__[17][_mask_idx]); sbox_in__[5][1][_mask_idx] = XOR(inp__[21][_mask_idx],key__[21][_mask_idx]); sbox_in__[6][1][_mask_idx] = XOR(inp__[25][_mask_idx],key__[25][_mask_idx]); sbox_in__[7][1][_mask_idx] = XOR(inp__[29][_mask_idx],key__[29][_mask_idx]); sbox_in__[8][1][_mask_idx] = XOR(inp__[33][_mask_idx],key__[33][_mask_idx]); sbox_in__[9][1][_mask_idx] = XOR(inp__[37][_mask_idx],key__[37][_mask_idx]); sbox_in__[10][1][_mask_idx] = XOR(inp__[41][_mask_idx],key__[41][_mask_idx]); sbox_in__[11][1][_mask_idx] = XOR(inp__[45][_mask_idx],key__[45][_mask_idx]); sbox_in__[12][1][_mask_idx] = XOR(inp__[49][_mask_idx],key__[49][_mask_idx]); sbox_in__[13][1][_mask_idx] = XOR(inp__[53][_mask_idx],key__[53][_mask_idx]); sbox_in__[14][1][_mask_idx] = XOR(inp__[57][_mask_idx],key__[57][_mask_idx]); sbox_in__[15][1][_mask_idx] = XOR(inp__[61][_mask_idx],key__[61][_mask_idx]); sbox_in__[0][2][_mask_idx] = XOR(inp__[2][_mask_idx],key__[2][_mask_idx]); sbox_in__[1][2][_mask_idx] = XOR(inp__[6][_mask_idx],key__[6][_mask_idx]); sbox_in__[2][2][_mask_idx] = XOR(inp__[10][_mask_idx],key__[10][_mask_idx]); sbox_in__[3][2][_mask_idx] = XOR(inp__[14][_mask_idx],key__[14][_mask_idx]); sbox_in__[4][2][_mask_idx] = XOR(inp__[18][_mask_idx],key__[18][_mask_idx]); sbox_in__[5][2][_mask_idx] = XOR(inp__[22][_mask_idx],key__[22][_mask_idx]); sbox_in__[6][2][_mask_idx] = XOR(inp__[26][_mask_idx],key__[26][_mask_idx]); sbox_in__[7][2][_mask_idx] = XOR(inp__[30][_mask_idx],key__[30][_mask_idx]); sbox_in__[8][2][_mask_idx] = XOR(inp__[34][_mask_idx],key__[34][_mask_idx]); sbox_in__[9][2][_mask_idx] = XOR(inp__[38][_mask_idx],key__[38][_mask_idx]); sbox_in__[10][2][_mask_idx] = XOR(inp__[42][_mask_idx],key__[42][_mask_idx]); sbox_in__[11][2][_mask_idx] = XOR(inp__[46][_mask_idx],key__[46][_mask_idx]); sbox_in__[12][2][_mask_idx] = XOR(inp__[50][_mask_idx],key__[50][_mask_idx]); sbox_in__[13][2][_mask_idx] = XOR(inp__[54][_mask_idx],key__[54][_mask_idx]); sbox_in__[14][2][_mask_idx] = XOR(inp__[58][_mask_idx],key__[58][_mask_idx]); sbox_in__[15][2][_mask_idx] = XOR(inp__[62][_mask_idx],key__[62][_mask_idx]); sbox_in__[0][3][_mask_idx] = XOR(inp__[3][_mask_idx],key__[3][_mask_idx]); sbox_in__[1][3][_mask_idx] = XOR(inp__[7][_mask_idx],key__[7][_mask_idx]); sbox_in__[2][3][_mask_idx] = XOR(inp__[11][_mask_idx],key__[11][_mask_idx]); sbox_in__[3][3][_mask_idx] = XOR(inp__[15][_mask_idx],key__[15][_mask_idx]); sbox_in__[4][3][_mask_idx] = XOR(inp__[19][_mask_idx],key__[19][_mask_idx]); sbox_in__[5][3][_mask_idx] = XOR(inp__[23][_mask_idx],key__[23][_mask_idx]); sbox_in__[6][3][_mask_idx] = XOR(inp__[27][_mask_idx],key__[27][_mask_idx]); sbox_in__[7][3][_mask_idx] = XOR(inp__[31][_mask_idx],key__[31][_mask_idx]); sbox_in__[8][3][_mask_idx] = XOR(inp__[35][_mask_idx],key__[35][_mask_idx]); sbox_in__[9][3][_mask_idx] = XOR(inp__[39][_mask_idx],key__[39][_mask_idx]); sbox_in__[10][3][_mask_idx] = XOR(inp__[43][_mask_idx],key__[43][_mask_idx]); sbox_in__[11][3][_mask_idx] = XOR(inp__[47][_mask_idx],key__[47][_mask_idx]); sbox_in__[12][3][_mask_idx] = XOR(inp__[51][_mask_idx],key__[51][_mask_idx]); sbox_in__[13][3][_mask_idx] = XOR(inp__[55][_mask_idx],key__[55][_mask_idx]); sbox_in__[14][3][_mask_idx] = XOR(inp__[59][_mask_idx],key__[59][_mask_idx]); sbox_in__[15][3][_mask_idx] = XOR(inp__[63][_mask_idx],key__[63][_mask_idx]); } for (int i__ = 0; i__ <= 15; i__++) { sbox__B1(sbox_in__[i__][0],sbox_in__[i__][1],sbox_in__[i__][2],sbox_in__[i__][3],sbox_out__[i__][0],sbox_out__[i__][1],sbox_out__[i__][2],sbox_out__[i__][3]); } for (int _mask_idx = 0; _mask_idx <= (MASKING_ORDER - 1); _mask_idx++) { out__[0][_mask_idx] = sbox_out__[0][0][_mask_idx]; out__[1][_mask_idx] = sbox_out__[1][0][_mask_idx]; out__[2][_mask_idx] = sbox_out__[2][0][_mask_idx]; out__[3][_mask_idx] = sbox_out__[3][0][_mask_idx]; out__[4][_mask_idx] = sbox_out__[4][0][_mask_idx]; out__[5][_mask_idx] = sbox_out__[5][0][_mask_idx]; out__[6][_mask_idx] = sbox_out__[6][0][_mask_idx]; out__[7][_mask_idx] = sbox_out__[7][0][_mask_idx]; out__[8][_mask_idx] = sbox_out__[8][0][_mask_idx]; out__[9][_mask_idx] = sbox_out__[9][0][_mask_idx]; out__[10][_mask_idx] = sbox_out__[10][0][_mask_idx]; out__[11][_mask_idx] = sbox_out__[11][0][_mask_idx]; out__[12][_mask_idx] = sbox_out__[12][0][_mask_idx]; out__[13][_mask_idx] = sbox_out__[13][0][_mask_idx]; out__[14][_mask_idx] = sbox_out__[14][0][_mask_idx]; out__[15][_mask_idx] = sbox_out__[15][0][_mask_idx]; out__[16][_mask_idx] = sbox_out__[0][1][_mask_idx]; out__[17][_mask_idx] = sbox_out__[1][1][_mask_idx]; out__[18][_mask_idx] = sbox_out__[2][1][_mask_idx]; out__[19][_mask_idx] = sbox_out__[3][1][_mask_idx]; out__[20][_mask_idx] = sbox_out__[4][1][_mask_idx]; out__[21][_mask_idx] = sbox_out__[5][1][_mask_idx]; out__[22][_mask_idx] = sbox_out__[6][1][_mask_idx]; out__[23][_mask_idx] = sbox_out__[7][1][_mask_idx]; out__[24][_mask_idx] = sbox_out__[8][1][_mask_idx]; out__[25][_mask_idx] = sbox_out__[9][1][_mask_idx]; out__[26][_mask_idx] = sbox_out__[10][1][_mask_idx]; out__[27][_mask_idx] = sbox_out__[11][1][_mask_idx]; out__[28][_mask_idx] = sbox_out__[12][1][_mask_idx]; out__[29][_mask_idx] = sbox_out__[13][1][_mask_idx]; out__[30][_mask_idx] = sbox_out__[14][1][_mask_idx]; out__[31][_mask_idx] = sbox_out__[15][1][_mask_idx]; out__[32][_mask_idx] = sbox_out__[0][2][_mask_idx]; out__[33][_mask_idx] = sbox_out__[1][2][_mask_idx]; out__[34][_mask_idx] = sbox_out__[2][2][_mask_idx]; out__[35][_mask_idx] = sbox_out__[3][2][_mask_idx]; out__[36][_mask_idx] = sbox_out__[4][2][_mask_idx]; out__[37][_mask_idx] = sbox_out__[5][2][_mask_idx]; out__[38][_mask_idx] = sbox_out__[6][2][_mask_idx]; out__[39][_mask_idx] = sbox_out__[7][2][_mask_idx]; out__[40][_mask_idx] = sbox_out__[8][2][_mask_idx]; out__[41][_mask_idx] = sbox_out__[9][2][_mask_idx]; out__[42][_mask_idx] = sbox_out__[10][2][_mask_idx]; out__[43][_mask_idx] = sbox_out__[11][2][_mask_idx]; out__[44][_mask_idx] = sbox_out__[12][2][_mask_idx]; out__[45][_mask_idx] = sbox_out__[13][2][_mask_idx]; out__[46][_mask_idx] = sbox_out__[14][2][_mask_idx]; out__[47][_mask_idx] = sbox_out__[15][2][_mask_idx]; out__[48][_mask_idx] = sbox_out__[0][3][_mask_idx]; out__[49][_mask_idx] = sbox_out__[1][3][_mask_idx]; out__[50][_mask_idx] = sbox_out__[2][3][_mask_idx]; out__[51][_mask_idx] = sbox_out__[3][3][_mask_idx]; out__[52][_mask_idx] = sbox_out__[4][3][_mask_idx]; out__[53][_mask_idx] = sbox_out__[5][3][_mask_idx]; out__[54][_mask_idx] = sbox_out__[6][3][_mask_idx]; out__[55][_mask_idx] = sbox_out__[7][3][_mask_idx]; out__[56][_mask_idx] = sbox_out__[8][3][_mask_idx]; out__[57][_mask_idx] = sbox_out__[9][3][_mask_idx]; out__[58][_mask_idx] = sbox_out__[10][3][_mask_idx]; out__[59][_mask_idx] = sbox_out__[11][3][_mask_idx]; out__[60][_mask_idx] = sbox_out__[12][3][_mask_idx]; out__[61][_mask_idx] = sbox_out__[13][3][_mask_idx]; out__[62][_mask_idx] = sbox_out__[14][3][_mask_idx]; out__[63][_mask_idx] = sbox_out__[15][3][_mask_idx]; } } /* main function */ void present__ (/*inputs*/ DATATYPE plain__[64][MASKING_ORDER],DATATYPE key__[32][64][MASKING_ORDER], /*outputs*/ DATATYPE cipher__[64][MASKING_ORDER]) { // Variables declaration DATATYPE tmp__[64][MASKING_ORDER]; // Instructions (body) for (int _mask_idx = 0; _mask_idx <= (MASKING_ORDER - 1); _mask_idx++) { tmp__[0][_mask_idx] = plain__[0][_mask_idx]; tmp__[1][_mask_idx] = plain__[1][_mask_idx]; tmp__[2][_mask_idx] = plain__[2][_mask_idx]; tmp__[3][_mask_idx] = plain__[3][_mask_idx]; tmp__[4][_mask_idx] = plain__[4][_mask_idx]; tmp__[5][_mask_idx] = plain__[5][_mask_idx]; tmp__[6][_mask_idx] = plain__[6][_mask_idx]; tmp__[7][_mask_idx] = plain__[7][_mask_idx]; tmp__[8][_mask_idx] = plain__[8][_mask_idx]; tmp__[9][_mask_idx] = plain__[9][_mask_idx]; tmp__[10][_mask_idx] = plain__[10][_mask_idx]; tmp__[11][_mask_idx] = plain__[11][_mask_idx]; tmp__[12][_mask_idx] = plain__[12][_mask_idx]; tmp__[13][_mask_idx] = plain__[13][_mask_idx]; tmp__[14][_mask_idx] = plain__[14][_mask_idx]; tmp__[15][_mask_idx] = plain__[15][_mask_idx]; tmp__[16][_mask_idx] = plain__[16][_mask_idx]; tmp__[17][_mask_idx] = plain__[17][_mask_idx]; tmp__[18][_mask_idx] = plain__[18][_mask_idx]; tmp__[19][_mask_idx] = plain__[19][_mask_idx]; tmp__[20][_mask_idx] = plain__[20][_mask_idx]; tmp__[21][_mask_idx] = plain__[21][_mask_idx]; tmp__[22][_mask_idx] = plain__[22][_mask_idx]; tmp__[23][_mask_idx] = plain__[23][_mask_idx]; tmp__[24][_mask_idx] = plain__[24][_mask_idx]; tmp__[25][_mask_idx] = plain__[25][_mask_idx]; tmp__[26][_mask_idx] = plain__[26][_mask_idx]; tmp__[27][_mask_idx] = plain__[27][_mask_idx]; tmp__[28][_mask_idx] = plain__[28][_mask_idx]; tmp__[29][_mask_idx] = plain__[29][_mask_idx]; tmp__[30][_mask_idx] = plain__[30][_mask_idx]; tmp__[31][_mask_idx] = plain__[31][_mask_idx]; tmp__[32][_mask_idx] = plain__[32][_mask_idx]; tmp__[33][_mask_idx] = plain__[33][_mask_idx]; tmp__[34][_mask_idx] = plain__[34][_mask_idx]; tmp__[35][_mask_idx] = plain__[35][_mask_idx]; tmp__[36][_mask_idx] = plain__[36][_mask_idx]; tmp__[37][_mask_idx] = plain__[37][_mask_idx]; tmp__[38][_mask_idx] = plain__[38][_mask_idx]; tmp__[39][_mask_idx] = plain__[39][_mask_idx]; tmp__[40][_mask_idx] = plain__[40][_mask_idx]; tmp__[41][_mask_idx] = plain__[41][_mask_idx]; tmp__[42][_mask_idx] = plain__[42][_mask_idx]; tmp__[43][_mask_idx] = plain__[43][_mask_idx]; tmp__[44][_mask_idx] = plain__[44][_mask_idx]; tmp__[45][_mask_idx] = plain__[45][_mask_idx]; tmp__[46][_mask_idx] = plain__[46][_mask_idx]; tmp__[47][_mask_idx] = plain__[47][_mask_idx]; tmp__[48][_mask_idx] = plain__[48][_mask_idx]; tmp__[49][_mask_idx] = plain__[49][_mask_idx]; tmp__[50][_mask_idx] = plain__[50][_mask_idx]; tmp__[51][_mask_idx] = plain__[51][_mask_idx]; tmp__[52][_mask_idx] = plain__[52][_mask_idx]; tmp__[53][_mask_idx] = plain__[53][_mask_idx]; tmp__[54][_mask_idx] = plain__[54][_mask_idx]; tmp__[55][_mask_idx] = plain__[55][_mask_idx]; tmp__[56][_mask_idx] = plain__[56][_mask_idx]; tmp__[57][_mask_idx] = plain__[57][_mask_idx]; tmp__[58][_mask_idx] = plain__[58][_mask_idx]; tmp__[59][_mask_idx] = plain__[59][_mask_idx]; tmp__[60][_mask_idx] = plain__[60][_mask_idx]; tmp__[61][_mask_idx] = plain__[61][_mask_idx]; tmp__[62][_mask_idx] = plain__[62][_mask_idx]; tmp__[63][_mask_idx] = plain__[63][_mask_idx]; } for (int i__ = 1; i__ <= 31; i__++) { present_round__B1(tmp__,key__[(i__ - 1)],tmp__); } for (int _mask_idx = 0; _mask_idx <= (MASKING_ORDER - 1); _mask_idx++) { cipher__[0][_mask_idx] = XOR(tmp__[0][_mask_idx],key__[31][0][_mask_idx]); cipher__[1][_mask_idx] = XOR(tmp__[1][_mask_idx],key__[31][1][_mask_idx]); cipher__[2][_mask_idx] = XOR(tmp__[2][_mask_idx],key__[31][2][_mask_idx]); cipher__[3][_mask_idx] = XOR(tmp__[3][_mask_idx],key__[31][3][_mask_idx]); cipher__[4][_mask_idx] = XOR(tmp__[4][_mask_idx],key__[31][4][_mask_idx]); cipher__[5][_mask_idx] = XOR(tmp__[5][_mask_idx],key__[31][5][_mask_idx]); cipher__[6][_mask_idx] = XOR(tmp__[6][_mask_idx],key__[31][6][_mask_idx]); cipher__[7][_mask_idx] = XOR(tmp__[7][_mask_idx],key__[31][7][_mask_idx]); cipher__[8][_mask_idx] = XOR(tmp__[8][_mask_idx],key__[31][8][_mask_idx]); cipher__[9][_mask_idx] = XOR(tmp__[9][_mask_idx],key__[31][9][_mask_idx]); cipher__[10][_mask_idx] = XOR(tmp__[10][_mask_idx],key__[31][10][_mask_idx]); cipher__[11][_mask_idx] = XOR(tmp__[11][_mask_idx],key__[31][11][_mask_idx]); cipher__[12][_mask_idx] = XOR(tmp__[12][_mask_idx],key__[31][12][_mask_idx]); cipher__[13][_mask_idx] = XOR(tmp__[13][_mask_idx],key__[31][13][_mask_idx]); cipher__[14][_mask_idx] = XOR(tmp__[14][_mask_idx],key__[31][14][_mask_idx]); cipher__[15][_mask_idx] = XOR(tmp__[15][_mask_idx],key__[31][15][_mask_idx]); cipher__[16][_mask_idx] = XOR(tmp__[16][_mask_idx],key__[31][16][_mask_idx]); cipher__[17][_mask_idx] = XOR(tmp__[17][_mask_idx],key__[31][17][_mask_idx]); cipher__[18][_mask_idx] = XOR(tmp__[18][_mask_idx],key__[31][18][_mask_idx]); cipher__[19][_mask_idx] = XOR(tmp__[19][_mask_idx],key__[31][19][_mask_idx]); cipher__[20][_mask_idx] = XOR(tmp__[20][_mask_idx],key__[31][20][_mask_idx]); cipher__[21][_mask_idx] = XOR(tmp__[21][_mask_idx],key__[31][21][_mask_idx]); cipher__[22][_mask_idx] = XOR(tmp__[22][_mask_idx],key__[31][22][_mask_idx]); cipher__[23][_mask_idx] = XOR(tmp__[23][_mask_idx],key__[31][23][_mask_idx]); cipher__[24][_mask_idx] = XOR(tmp__[24][_mask_idx],key__[31][24][_mask_idx]); cipher__[25][_mask_idx] = XOR(tmp__[25][_mask_idx],key__[31][25][_mask_idx]); cipher__[26][_mask_idx] = XOR(tmp__[26][_mask_idx],key__[31][26][_mask_idx]); cipher__[27][_mask_idx] = XOR(tmp__[27][_mask_idx],key__[31][27][_mask_idx]); cipher__[28][_mask_idx] = XOR(tmp__[28][_mask_idx],key__[31][28][_mask_idx]); cipher__[29][_mask_idx] = XOR(tmp__[29][_mask_idx],key__[31][29][_mask_idx]); cipher__[30][_mask_idx] = XOR(tmp__[30][_mask_idx],key__[31][30][_mask_idx]); cipher__[31][_mask_idx] = XOR(tmp__[31][_mask_idx],key__[31][31][_mask_idx]); cipher__[32][_mask_idx] = XOR(tmp__[32][_mask_idx],key__[31][32][_mask_idx]); cipher__[33][_mask_idx] = XOR(tmp__[33][_mask_idx],key__[31][33][_mask_idx]); cipher__[34][_mask_idx] = XOR(tmp__[34][_mask_idx],key__[31][34][_mask_idx]); cipher__[35][_mask_idx] = XOR(tmp__[35][_mask_idx],key__[31][35][_mask_idx]); cipher__[36][_mask_idx] = XOR(tmp__[36][_mask_idx],key__[31][36][_mask_idx]); cipher__[37][_mask_idx] = XOR(tmp__[37][_mask_idx],key__[31][37][_mask_idx]); cipher__[38][_mask_idx] = XOR(tmp__[38][_mask_idx],key__[31][38][_mask_idx]); cipher__[39][_mask_idx] = XOR(tmp__[39][_mask_idx],key__[31][39][_mask_idx]); cipher__[40][_mask_idx] = XOR(tmp__[40][_mask_idx],key__[31][40][_mask_idx]); cipher__[41][_mask_idx] = XOR(tmp__[41][_mask_idx],key__[31][41][_mask_idx]); cipher__[42][_mask_idx] = XOR(tmp__[42][_mask_idx],key__[31][42][_mask_idx]); cipher__[43][_mask_idx] = XOR(tmp__[43][_mask_idx],key__[31][43][_mask_idx]); cipher__[44][_mask_idx] = XOR(tmp__[44][_mask_idx],key__[31][44][_mask_idx]); cipher__[45][_mask_idx] = XOR(tmp__[45][_mask_idx],key__[31][45][_mask_idx]); cipher__[46][_mask_idx] = XOR(tmp__[46][_mask_idx],key__[31][46][_mask_idx]); cipher__[47][_mask_idx] = XOR(tmp__[47][_mask_idx],key__[31][47][_mask_idx]); cipher__[48][_mask_idx] = XOR(tmp__[48][_mask_idx],key__[31][48][_mask_idx]); cipher__[49][_mask_idx] = XOR(tmp__[49][_mask_idx],key__[31][49][_mask_idx]); cipher__[50][_mask_idx] = XOR(tmp__[50][_mask_idx],key__[31][50][_mask_idx]); cipher__[51][_mask_idx] = XOR(tmp__[51][_mask_idx],key__[31][51][_mask_idx]); cipher__[52][_mask_idx] = XOR(tmp__[52][_mask_idx],key__[31][52][_mask_idx]); cipher__[53][_mask_idx] = XOR(tmp__[53][_mask_idx],key__[31][53][_mask_idx]); cipher__[54][_mask_idx] = XOR(tmp__[54][_mask_idx],key__[31][54][_mask_idx]); cipher__[55][_mask_idx] = XOR(tmp__[55][_mask_idx],key__[31][55][_mask_idx]); cipher__[56][_mask_idx] = XOR(tmp__[56][_mask_idx],key__[31][56][_mask_idx]); cipher__[57][_mask_idx] = XOR(tmp__[57][_mask_idx],key__[31][57][_mask_idx]); cipher__[58][_mask_idx] = XOR(tmp__[58][_mask_idx],key__[31][58][_mask_idx]); cipher__[59][_mask_idx] = XOR(tmp__[59][_mask_idx],key__[31][59][_mask_idx]); cipher__[60][_mask_idx] = XOR(tmp__[60][_mask_idx],key__[31][60][_mask_idx]); cipher__[61][_mask_idx] = XOR(tmp__[61][_mask_idx],key__[31][61][_mask_idx]); cipher__[62][_mask_idx] = XOR(tmp__[62][_mask_idx],key__[31][62][_mask_idx]); cipher__[63][_mask_idx] = XOR(tmp__[63][_mask_idx],key__[31][63][_mask_idx]); } } /* Additional functions */ uint32_t bench_speed() { /* inputs */ DATATYPE plain__[64][MASKING_ORDER] = { 0 }; DATATYPE key__[32][64][MASKING_ORDER] = { 0 }; /* Preventing inputs from being optimized out */ asm volatile("" : "+m" (plain__)); asm volatile("" : "+m" (key__)); /* outputs */ DATATYPE cipher__[64][MASKING_ORDER] = { 0 }; /* Primitive call */ present__(plain__, key__,cipher__); /* Preventing outputs from being optimized out */ asm volatile("" : "+m" (cipher__)); /* Returning the number of encrypted bytes */ return 64; } /* **************************************************************** */ /* Usuba source */ /* */ /* _no_inline table sbox(a : v4) returns out : v4 { 12, 5, 6, 11, 9, 0, 10, 13, 3, 14, 15, 8, 4, 7, 1, 2 } _no_inline perm pLayer(a : b64) returns out : b64 { 1, 5, 9, 13, 17, 21, 25, 29, 33, 37, 41, 45, 49, 53, 57, 61, 2, 6, 10, 14, 18, 22, 26, 30, 34, 38, 42, 46, 50, 54, 58, 62, 3, 7, 11, 15, 19, 23, 27, 31, 35, 39, 43, 47, 51, 55, 59, 63, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 44, 48, 52, 56, 60, 64 } _no_inline node present_round(inp : b64,key : b64) returns out : b64 vars sbox_in : b4[16], sbox_out : b4[16] let (sbox_in) = (inp ^ key); forall i in [0,15] { (sbox_out[i]) = sbox(sbox_in[i]) }; (out) = pLayer(sbox_out) tel node present(plain : b64,key : b64[32]) returns cipher : b64 vars tmp : b64[32] let (tmp[0]) = plain; forall i in [1,31] { (tmp[i]) = present_round(tmp[(i - 1)],key[(i - 1)]) }; (cipher) = (tmp[31] ^ key[31]) tel */
Angular2Guy/AngularPortfolioMgr
src/main/java/ch/xxx/manager/domain/utils/MyLogPrintWriter.java
/** * Copyright 2019 <NAME> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package ch.xxx.manager.domain.utils; import java.io.IOException; import java.io.PrintWriter; import java.io.Writer; import org.slf4j.Logger; import org.slf4j.event.Level; public class MyLogPrintWriter extends PrintWriter { public MyLogPrintWriter(final Logger LOGGER, final Level level) { super(new MyLogWriter(LOGGER, level)); } private static class MyLogWriter extends Writer { private final Logger LOGGER; private final Level level; private MyLogWriter(final Logger LOGGER, final Level level) { this.LOGGER = LOGGER; this.level = level; } @Override public void write(char[] cbuf, int off, int len) throws IOException { String line = String.copyValueOf(cbuf, off, len); switch (level) { case DEBUG -> LOGGER.debug(line); case ERROR -> LOGGER.error(line); case INFO -> LOGGER.info(line); case TRACE -> LOGGER.trace(line); case WARN -> LOGGER.warn(line); default -> LOGGER.info(line); } } @Override public void flush() throws IOException { // nothing } @Override public void close() throws IOException { // nothing } } }
Capping-WAR/API
swagger_server/models/reviewer.py
# coding: utf-8 from __future__ import absolute_import from datetime import date, datetime # noqa: F401 from typing import List, Dict # noqa: F401 from swagger_server.models.base_model_ import Model from swagger_server import util class Reviewer(Model): """NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ def __init__(self, reviewer_id: int=None, email_address: str=None, first_name: str=None, last_name: str=None, is_admin: bool=None, reputation: int=None): # noqa: E501 """Reviewer - a model defined in Swagger :param reviewer_id: The reviewer_id of this Reviewer. # noqa: E501 :type reviewer_id: int :param email_address: The email_address of this Reviewer. # noqa: E501 :type email_address: str :param first_name: The first_name of this Reviewer. # noqa: E501 :type first_name: str :param last_name: The last_name of this Reviewer. # noqa: E501 :type last_name: str :param is_admin: The is_admin of this Reviewer. # noqa: E501 :type is_admin: bool :param reputation: The reputation of this Reviewer. # noqa: E501 :type reputation: int """ self.swagger_types = { 'reviewer_id': int, 'email_address': str, 'first_name': str, 'last_name': str, 'is_admin': bool, 'reputation': int } self.attribute_map = { 'reviewer_id': 'reviewerID', 'email_address': 'emailAddress', 'first_name': 'firstName', 'last_name': 'lastName', 'is_admin': 'isAdmin', 'reputation': 'reputation' } self._reviewer_id = reviewer_id self._email_address = email_address self._first_name = first_name self._last_name = last_name self._is_admin = is_admin self._reputation = reputation @classmethod def from_dict(cls, dikt) -> 'Reviewer': """Returns the dict as a model :param dikt: A dict. :type: dict :return: The reviewer of this Reviewer. # noqa: E501 :rtype: Reviewer """ return util.deserialize_model(dikt, cls) @property def reviewer_id(self) -> int: """Gets the reviewer_id of this Reviewer. Unique ID of the reviewer # noqa: E501 :return: The reviewer_id of this Reviewer. :rtype: int """ return self._reviewer_id @reviewer_id.setter def reviewer_id(self, reviewer_id: int): """Sets the reviewer_id of this Reviewer. Unique ID of the reviewer # noqa: E501 :param reviewer_id: The reviewer_id of this Reviewer. :type reviewer_id: int """ self._reviewer_id = reviewer_id @property def email_address(self) -> str: """Gets the email_address of this Reviewer. :\"Email address of the reviewer\" # noqa: E501 :return: The email_address of this Reviewer. :rtype: str """ return self._email_address @email_address.setter def email_address(self, email_address: str): """Sets the email_address of this Reviewer. :\"Email address of the reviewer\" # noqa: E501 :param email_address: The email_address of this Reviewer. :type email_address: str """ if email_address is None: raise ValueError("Invalid value for `email_address`, must not be `None`") # noqa: E501 self._email_address = email_address @property def first_name(self) -> str: """Gets the first_name of this Reviewer. The first name of the user # noqa: E501 :return: The first_name of this Reviewer. :rtype: str """ return self._first_name @first_name.setter def first_name(self, first_name: str): """Sets the first_name of this Reviewer. The first name of the user # noqa: E501 :param first_name: The first_name of this Reviewer. :type first_name: str """ if first_name is None: raise ValueError("Invalid value for `first_name`, must not be `None`") # noqa: E501 self._first_name = first_name @property def last_name(self) -> str: """Gets the last_name of this Reviewer. The last name of the user # noqa: E501 :return: The last_name of this Reviewer. :rtype: str """ return self._last_name @last_name.setter def last_name(self, last_name: str): """Sets the last_name of this Reviewer. The last name of the user # noqa: E501 :param last_name: The last_name of this Reviewer. :type last_name: str """ if last_name is None: raise ValueError("Invalid value for `last_name`, must not be `None`") # noqa: E501 self._last_name = last_name @property def is_admin(self) -> bool: """Gets the is_admin of this Reviewer. Denotes wether this user has admin privileges # noqa: E501 :return: The is_admin of this Reviewer. :rtype: bool """ return self._is_admin @is_admin.setter def is_admin(self, is_admin: bool): """Sets the is_admin of this Reviewer. Denotes wether this user has admin privileges # noqa: E501 :param is_admin: The is_admin of this Reviewer. :type is_admin: bool """ if is_admin is None: raise ValueError("Invalid value for `is_admin`, must not be `None`") # noqa: E501 self._is_admin = is_admin @property def reputation(self) -> int: """Gets the reputation of this Reviewer. The user's ranking as a reviewer # noqa: E501 :return: The reputation of this Reviewer. :rtype: int """ return self._reputation @reputation.setter def reputation(self, reputation: int): """Sets the reputation of this Reviewer. The user's ranking as a reviewer # noqa: E501 :param reputation: The reputation of this Reviewer. :type reputation: int """ if reputation is None: raise ValueError("Invalid value for `reputation`, must not be `None`") # noqa: E501 self._reputation = reputation
chenguiquan1997/sleeve-cms
src/main/java/io/github/talelin/latticy/dto/my/BelongSpec.java
package io.github.talelin.latticy.dto.my; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; /** * @Author <NAME> * @Date 2021/4/21 18:25 * @Version 1.0 */ @AllArgsConstructor @NoArgsConstructor @Builder @Data public class BelongSpec { private Long keyId; private String keyName; private Long valueId; private String valueName; }
yangwawa0323/Learning-Python-Networking-Second-Edition
chapter10/non-blocking/tcp_server_selectors.py
#!/usr/bin/env python3 import selectors import types import socket selector = selectors.DefaultSelector() def accept_connection(sock): connection, address = sock.accept() print('Connection accepted in {}'.format(address)) # We put the socket in non-blocking mode connection.setblocking(False) data = types.SimpleNamespace(addr=address, inb=b'', outb=b'') events = selectors.EVENT_READ | selectors.EVENT_WRITE selector.register(connection, events, data=data) def service_connection(key, mask): sock = key.fileobj data = key.data if mask & selectors.EVENT_READ: recv_data = sock.recv(BUFFER_SIZE) if recv_data: data.outb += recv_data else: print('Closing connection in {}'.format(data.addr)) selector.unregister(sock) sock.close() if mask & selectors.EVENT_WRITE: if data.outb: print('Echo from {} to {}'.format(repr(data.outb), data.addr)) sent = sock.send(data.outb) data.outb = data.outb[sent:] if __name__ == '__main__': host = 'localhost' port = 12345 BUFFER_SIZE = 1024 # We create a TCP socket socket_tcp = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # We configure the socket in non-blocking mode socket_tcp.setblocking(False) socket_tcp.bind((host, port)) socket_tcp.listen() print('Openned socket for listening connections on {} {}'.format(host, port)) socket_tcp.setblocking(False) # We register the socket to be monitored by the selector functions selector.register(socket_tcp, selectors.EVENT_READ, data=None) while socket_tcp: events = selector.select(timeout=None) for key, mask in events: if key.data is None: accept_connection(key.fileobj) else: service_connection(key, mask) socket_tcp.close() print('Connection finished.')
kubeform/provider-oci-api
apis/datascience/v1alpha1/model_deployment_types.go
<reponame>kubeform/provider-oci-api<gh_stars>1-10 /* Copyright AppsCode Inc. and Contributors 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. */ // Code generated by Kubeform. DO NOT EDIT. package v1alpha1 import ( base "kubeform.dev/apimachinery/api/v1alpha1" core "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" kmapi "kmodules.xyz/client-go/api/v1" "sigs.k8s.io/cli-utils/pkg/kstatus/status" ) // +genclient // +k8s:openapi-gen=true // +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object // +kubebuilder:object:root=true // +kubebuilder:subresource:status // +kubebuilder:printcolumn:name="Phase",type=string,JSONPath=`.status.phase` type ModelDeployment struct { metav1.TypeMeta `json:",inline,omitempty"` metav1.ObjectMeta `json:"metadata,omitempty"` Spec ModelDeploymentSpec `json:"spec,omitempty"` Status ModelDeploymentStatus `json:"status,omitempty"` } type ModelDeploymentSpecCategoryLogDetailsAccess struct { LogGroupID *string `json:"logGroupID" tf:"log_group_id"` LogID *string `json:"logID" tf:"log_id"` } type ModelDeploymentSpecCategoryLogDetailsPredict struct { LogGroupID *string `json:"logGroupID" tf:"log_group_id"` LogID *string `json:"logID" tf:"log_id"` } type ModelDeploymentSpecCategoryLogDetails struct { // +optional Access *ModelDeploymentSpecCategoryLogDetailsAccess `json:"access,omitempty" tf:"access"` // +optional Predict *ModelDeploymentSpecCategoryLogDetailsPredict `json:"predict,omitempty" tf:"predict"` } type ModelDeploymentSpecModelDeploymentConfigurationDetailsModelConfigurationDetailsInstanceConfiguration struct { InstanceShapeName *string `json:"instanceShapeName" tf:"instance_shape_name"` } type ModelDeploymentSpecModelDeploymentConfigurationDetailsModelConfigurationDetailsScalingPolicy struct { InstanceCount *int64 `json:"instanceCount" tf:"instance_count"` PolicyType *string `json:"policyType" tf:"policy_type"` } type ModelDeploymentSpecModelDeploymentConfigurationDetailsModelConfigurationDetails struct { // +optional BandwidthMbps *int64 `json:"bandwidthMbps,omitempty" tf:"bandwidth_mbps"` InstanceConfiguration *ModelDeploymentSpecModelDeploymentConfigurationDetailsModelConfigurationDetailsInstanceConfiguration `json:"instanceConfiguration" tf:"instance_configuration"` ModelID *string `json:"modelID" tf:"model_id"` // +optional ScalingPolicy *ModelDeploymentSpecModelDeploymentConfigurationDetailsModelConfigurationDetailsScalingPolicy `json:"scalingPolicy,omitempty" tf:"scaling_policy"` } type ModelDeploymentSpecModelDeploymentConfigurationDetails struct { DeploymentType *string `json:"deploymentType" tf:"deployment_type"` ModelConfigurationDetails *ModelDeploymentSpecModelDeploymentConfigurationDetailsModelConfigurationDetails `json:"modelConfigurationDetails" tf:"model_configuration_details"` } type ModelDeploymentSpec struct { State *ModelDeploymentSpecResource `json:"state,omitempty" tf:"-"` Resource ModelDeploymentSpecResource `json:"resource" tf:"resource"` UpdatePolicy base.UpdatePolicy `json:"updatePolicy,omitempty" tf:"-"` TerminationPolicy base.TerminationPolicy `json:"terminationPolicy,omitempty" tf:"-"` ProviderRef core.LocalObjectReference `json:"providerRef" tf:"-"` BackendRef *core.LocalObjectReference `json:"backendRef,omitempty" tf:"-"` } type ModelDeploymentSpecResource struct { Timeouts *base.ResourceTimeout `json:"timeouts,omitempty" tf:"timeouts"` ID string `json:"id,omitempty" tf:"id,omitempty"` // +optional CategoryLogDetails *ModelDeploymentSpecCategoryLogDetails `json:"categoryLogDetails,omitempty" tf:"category_log_details"` CompartmentID *string `json:"compartmentID" tf:"compartment_id"` // +optional CreatedBy *string `json:"createdBy,omitempty" tf:"created_by"` // +optional DefinedTags map[string]string `json:"definedTags,omitempty" tf:"defined_tags"` // +optional Description *string `json:"description,omitempty" tf:"description"` // +optional DisplayName *string `json:"displayName,omitempty" tf:"display_name"` // +optional FreeformTags map[string]string `json:"freeformTags,omitempty" tf:"freeform_tags"` // +optional LifecycleDetails *string `json:"lifecycleDetails,omitempty" tf:"lifecycle_details"` ModelDeploymentConfigurationDetails *ModelDeploymentSpecModelDeploymentConfigurationDetails `json:"modelDeploymentConfigurationDetails" tf:"model_deployment_configuration_details"` // +optional ModelDeploymentURL *string `json:"modelDeploymentURL,omitempty" tf:"model_deployment_url"` ProjectID *string `json:"projectID" tf:"project_id"` // +optional State *string `json:"state,omitempty" tf:"state"` // +optional TimeCreated *string `json:"timeCreated,omitempty" tf:"time_created"` } type ModelDeploymentStatus struct { // Resource generation, which is updated on mutation by the API Server. // +optional ObservedGeneration int64 `json:"observedGeneration,omitempty"` // +optional Phase status.Status `json:"phase,omitempty"` // +optional Conditions []kmapi.Condition `json:"conditions,omitempty"` } // +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object // +kubebuilder:object:root=true // ModelDeploymentList is a list of ModelDeployments type ModelDeploymentList struct { metav1.TypeMeta `json:",inline"` metav1.ListMeta `json:"metadata,omitempty"` // Items is a list of ModelDeployment CRD objects Items []ModelDeployment `json:"items,omitempty"` }
gparkkii/HelloTube
client/src/styles/typography.js
<filename>client/src/styles/typography.js import styled from 'styled-components'; export const MainTitle = styled.h2` font-size: 56px; font-weight: 500; `; export const LogoTitle = styled.div` display: flex; flex-direction: column; align-items: center; justify-content: center; width: 100%; font-size: 30px; font-weight: 700; margin-bottom: 30px; & img { width: 36px; margin-right: 4px; } `; export const ContentTitle = styled.h2` font-size: 30px; font-weight: 700; margin-bottom: 10px; `; export const ErrorMessage = styled.p` color: #de506b; font-size: 13px; padding: 4px 0px 0px 4px; &:before { display: inline; content: '⚠ '; } `; export const InputAlert = styled.p` color: #999; font-size: 13px; margin: 8px; text-align: left; &:before { display: inline; content: '※ '; } `; export const AlertMessage = styled.p` color: #eb5650; font-size: 14px; width: 100%; text-align: center; `; export const UserTitle = styled.h2` color: #353535; font-size: 22px; font-weight: 500; margin-left: 4px; & strong { color: #eb5650; font-weight: 600; } `; export const ProfileTitle = styled.h2` font-size: 25px; font-weight: 600; width: 100%; text-align: center; margin: 28px 0px; & strong { color: #eb5650; } `; export const LinkFont = styled.a` color: #2b80f2; font-weight: 500; `; export const SmallMessage = styled.div` width: 100%; color: #505050; font-size: 15px; text-align: center; padding: 4px 0px; `; export const FeedHeader = styled.div` width: 100%; height: 40px; display: flex; flex-direction: row; align-items: center; justify-content: space-between; margin-bottom: 15px; & h2 { font-size: 22px; font-weight: 600; } `;
ProjectFurnace/furnace-cli
actions/ignite.js
<gh_stars>0 const gitutils = require("@project-furnace/gitutils"), fsutils = require("@project-furnace/fsutils"), workspace = require("../utils/workspace"), path = require("path"), inquirer = require("inquirer"), chalk = require("chalk"), github = require("../utils/github"), randomstring = require("randomstring"), commandLineArgs = require("command-line-args"), awsBootstrap = require("../bootstrap/aws"), azureBootstrap = require("../bootstrap/azure"), gcpBootstrap = require("../bootstrap/gcp"), awsUtil = require("../utils/aws"), azureUtil = require("../utils/azure"), gcpUtil = require("../utils/gcp"), igniteUtil = require("../utils/ignite"), which = require("which"); module.exports = async argv => { const doBootstrap = argv.bootstrap === undefined ? true : argv.bootstrap; let resume = false; if (doBootstrap) { let status = igniteUtil.getIgniteStatus(), resume = false, initialisedConfig = {}; if (status && status.state !== "complete") { const resultQuestions = [ { type: "confirm", name: "resume", message: "a previous ignite did not complete, resume?" }, { type: "confirm", name: "clear", message: "clear previous attempt?", when: current => !current.resume } ]; const resumeAnswers = await inquirer.prompt(resultQuestions); resume = resumeAnswers.resume; if (!resume) igniteUtil.deleteIgniteStatus(); else initialisedConfig = status.answers; } } if (!resume) { const mainDefinitions = [ { name: "command", defaultOption: true }, { name: "platform", alias: "p", type: String }, { name: "name", alias: "i", type: String }, { name: "gitProvider", alias: "g", type: String }, { name: "gitToken", alias: "t", type: String }, { name: "storeGitHubToken", defaultValue: true, type: Boolean }, { name: "location", alias: "l", type: String } ]; const mainOptions = commandLineArgs(mainDefinitions, { stopAtFirstUnknown: true }); let argv = mainOptions._unknown || []; argv = argv.filter(a => a !== "--no-bootstrap"); let passedOptions = []; let platformDefinitions = []; switch (mainOptions.platform) { case "aws": platformDefinitions = [ { name: "profile", alias: "x", type: String, defaultValue: null }, { name: "accessKeyId", alias: "a", type: String, defaultValue: null }, { name: "secretAccessKey", alias: "p", type: String, defaultValue: null } ]; break; case "azure": platformDefinitions = [ { name: "subscriptionId", alias: "s", type: String } ]; break; case "gcp": platformDefinitions = [{ name: "projectId", alias: "j", type: String }]; break; } const options = commandLineArgs(platformDefinitions, { argv }); passedOptions = Object.assign({}, mainOptions, options); if (passedOptions._unknown) { delete passedOptions._unknown; } questions = []; if (passedOptions.name) config = passedOptions; else { questions = [ { type: "input", name: "name", message: "Name this Furnace Instance:", default: "furnace", validate: validateInstanceName }, { type: "list", name: "platform", message: "Platform:", choices: ["aws", "azure", "gcp"] }, //{ type: 'input', name: 'bucket', message: "Artifact Bucket:", default: current => current.name + "-artifacts" }, { type: "password", name: "gitToken", message: "GitHub Access Token:", default: "", mask: "*", validate: input => (!input ? "GitHub Access Token is Required" : true) }, { type: "password", name: "npmToken", message: "NPM Access Token (enter to skip):", default: "", mask: "*" }, //{ type: 'list', name: 'gitProvider', message: "Git Provider:", choices: ["github"] }, { type: "confirm", name: "storeGitHubToken", message: "Store GitHub Token" } //, when: current => current.gitProvider === "github" } ]; config = await inquirer.prompt(questions); } let platformQuestions = []; // get platform specific properties switch (config.platform) { case "aws": const profiles = awsUtil.getProfiles(); const awsCli = which.sync("aws", { nothrow: true }); const requireCredentials = !awsCli || profiles.length === 0; platformQuestions = [ { type: "list", name: "profile", message: "AWS Profile:", choices: profiles, when: !requireCredentials }, { type: "input", name: "accessKeyId", message: "AWS Access Key:", when: requireCredentials }, { type: "password", name: "secretAccessKey", message: "AWS Secret Access Key:", mask: "*", when: requireCredentials }, { type: "list", name: "location", message: "Region:", choices: awsUtil.getRegions(), default: current => awsUtil.getDefaultRegion(current.profile) } ]; break; case "azure": platformQuestions = [ { type: "input", name: "subscriptionId", message: "Azure Subscription Id:" }, { type: "list", name: "location", message: "Location:", choices: azureUtil.getRegions() } //, default: current => getDefaultRegion(current.profile) } ]; break; case "gcp": platformQuestions = [ { type: "input", name: "projectId", message: "Google Cloud Project Id:" }, { type: "list", name: "location", message: "Location:", choices: gcpUtil.getRegions() } //, default: current => getDefaultRegion(current.profile) } ]; break; } config = await getMissingOptions(platformQuestions, config); // delete when we reenable git provider selection config.gitProvider = "github"; config.doBootstrap = doBootstrap; delete config.command; initialisedConfig = Object.assign( {}, config, await initialiseIgnite(config) ); } let deployResult; if (doBootstrap) { switch (initialisedConfig.platform) { case "aws": // await igniteAws(config, resume, status ? status.awsAnswers : null); deployResult = await awsBootstrap.ignite(initialisedConfig, resume); break; case "azure": deployResult = await azureBootstrap.ignite(initialisedConfig); break; case "gcp": deployResult = await gcpBootstrap.ignite(initialisedConfig); break; default: throw new Error( `platform ${config.platform} is not currently supported` ); } } completeIgnite( initialisedConfig.name, Object.assign({}, initialisedConfig, deployResult) ); }; async function initialiseIgnite(config) { const { name, location, platform, gitProvider, gitToken } = config; const bootstrapRemote = `https://github.com/ProjectFurnace/bootstrap`, workspaceDir = workspace.getWorkspaceDir(), bootstrapDir = path.join(workspaceDir, "bootstrap"), templateDir = path.join(bootstrapDir, platform, "template"), functionsDir = path.join(bootstrapDir, platform, "functions"), coreModulesRemote = "https://github.com/ProjectFurnace/modules-core", coreModulesRepoDir = path.join(workspaceDir, "repo", "module", "core"), gitHookSecret = randomstring.generate(16), apiKey = randomstring.generate(16), bootstrapBucket = name + "-" + location + "-furnace-bootstrap-" + randomstring.generate({ length: 6, capitalization: "lowercase" }), artifactBucket = name + "-" + location + "-furnace-artifacts-" + randomstring.generate({ length: 6, capitalization: "lowercase" }); if (!fsutils.exists(path.join(bootstrapDir, ".git"))) { console.debug(`cloning ${bootstrapRemote} to ${bootstrapDir}...`); if (!fsutils.exists(bootstrapDir)) { fsutils.mkdir(bootstrapDir); } await gitutils.clone(bootstrapDir, bootstrapRemote, "", ""); } else { console.debug(`pulling latest bootstrap templates...`); console.log(bootstrapDir); // await gitutils.pull(bootstrapDir); } if (!fsutils.exists(templateDir)) throw new Error(`unable to find bootstrap template at ${templateDir}`); if (!fsutils.exists(path.join(coreModulesRepoDir, ".git"))) { console.debug(`cloning ${coreModulesRemote} to ${coreModulesRepoDir}...`); if (!fsutils.exists(coreModulesRepoDir)) { fsutils.mkdir(coreModulesRepoDir); } await gitutils.clone(coreModulesRepoDir, coreModulesRemote, "", ""); } else { console.debug(`pulling latest modules...`); await gitutils.pull(coreModulesRepoDir); } if (gitProvider === "github") { try { github.authenticateWithToken(gitToken); } catch (err) { console.log(err); throw new Error( `unable to authenticate with GitHub with the provider token` ); } } return { bootstrapRemote, workspaceDir, bootstrapDir, templateDir, coreModulesRemote, coreModulesRepoDir, gitProvider, gitHookSecret, apiKey, bootstrapBucket, artifactBucket, functionsDir }; } function completeIgnite(name, generatedConfig) { //remove non-required fields in the config delete generatedConfig.bootstrapRemote; delete generatedConfig.workspaceDir; delete generatedConfig.bootstrapDir; delete generatedConfig.templateDir; delete generatedConfig.coreModulesRemote; delete generatedConfig.coreModulesRepoDir; delete generatedConfig.functionsDir; delete generatedConfig.name; delete generatedConfig.storeGitHubToken; delete generatedConfig.bootstrapBucket; if (generatedConfig.npmToken == "") delete generatedConfig.npmToken; const config = workspace.getConfig(); config[name] = generatedConfig; config.current = name; workspace.saveConfig(config); igniteUtil.saveIgniteStatus({ state: "complete", generatedConfig }); console.log( `furnace instance now complete.\nto create a new stack, please run:` ); console.log(chalk.green(`\nfurnace new [stack_name]`)); } async function getMissingOptions(questions, answers) { const missing = []; for (let q of questions) { if (!answers[q.name]) { missing.push(q); } } const missingAnswers = await inquirer.prompt(missing); return Object.assign({}, answers, missingAnswers); } function validateInstanceName(value) { if (value.match(/^([A-Za-z][A-Za-z0-9-_]{1,6}[A-Za-z0-9])$/i)) { return true; } return "Please enter a valid instance name. Maximum 8 chars [A-Za-z0-9-_] starting with a letter and ending with a letter or number"; }
Asymmetric-Effort/asymmetric-toolkit
src/common/source/start.go
package source func (o *Source) Start() { o.isPaused = false }
mohdab98/cmps252_hw4.2
src/cmps252/HW4_2/UnitTesting/record_2368.java
<reponame>mohdab98/cmps252_hw4.2 package cmps252.HW4_2.UnitTesting; import static org.junit.jupiter.api.Assertions.*; import java.io.FileNotFoundException; import java.util.List; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import cmps252.HW4_2.Customer; import cmps252.HW4_2.FileParser; @Tag("34") class Record_2368 { private static List<Customer> customers; @BeforeAll public static void init() throws FileNotFoundException { customers = FileParser.getCustomers(Configuration.CSV_File); } @Test @DisplayName("Record 2368: FirstName is Luigi") void FirstNameOfRecord2368() { assertEquals("Luigi", customers.get(2367).getFirstName()); } @Test @DisplayName("Record 2368: LastName is Schlesier") void LastNameOfRecord2368() { assertEquals("Schlesier", customers.get(2367).getLastName()); } @Test @DisplayName("Record 2368: Company is Cliffs Carpet Outlet") void CompanyOfRecord2368() { assertEquals("Cliffs Carpet Outlet", customers.get(2367).getCompany()); } @Test @DisplayName("Record 2368: Address is 801 Deming Way") void AddressOfRecord2368() { assertEquals("801 Deming Way", customers.get(2367).getAddress()); } @Test @DisplayName("Record 2368: City is Madison") void CityOfRecord2368() { assertEquals("Madison", customers.get(2367).getCity()); } @Test @DisplayName("Record 2368: County is Dane") void CountyOfRecord2368() { assertEquals("Dane", customers.get(2367).getCounty()); } @Test @DisplayName("Record 2368: State is WI") void StateOfRecord2368() { assertEquals("WI", customers.get(2367).getState()); } @Test @DisplayName("Record 2368: ZIP is 53717") void ZIPOfRecord2368() { assertEquals("53717", customers.get(2367).getZIP()); } @Test @DisplayName("Record 2368: Phone is 608-831-6795") void PhoneOfRecord2368() { assertEquals("608-831-6795", customers.get(2367).getPhone()); } @Test @DisplayName("Record 2368: Fax is 608-831-0039") void FaxOfRecord2368() { assertEquals("608-831-0039", customers.get(2367).getFax()); } @Test @DisplayName("Record 2368: Email is <EMAIL>") void EmailOfRecord2368() { assertEquals("<EMAIL>", customers.get(2367).getEmail()); } @Test @DisplayName("Record 2368: Web is http://www.luigischlesier.com") void WebOfRecord2368() { assertEquals("http://www.luigischlesier.com", customers.get(2367).getWeb()); } }
LambentClient/Lambent
src/minecraft/com/jay/immoral/client/module/Module.java
<reponame>LambentClient/Lambent package com.jay.immoral.client.module; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import org.lwjgl.input.Keyboard; import com.darkmagician6.eventapi.EventManager; import net.minecraft.client.Minecraft; public class Module { private String name = getClass().getAnnotation(mod.class).name(); private String description = getClass().getAnnotation(mod.class).description(); private int bind = getClass().getAnnotation(mod.class).bind(); private Category category = getClass().getAnnotation(mod.class).category(); public static Minecraft mc = Minecraft.getMinecraft(); private boolean state; /** * Module Info. * * @author Jay * */ @Retention(RetentionPolicy.RUNTIME) public @interface mod { String name(); String description(); int bind(); Category category(); } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getBind() { return bind; } public void setBind(int bind) { this.bind = bind; } public Category getCategory() { return category; } public void setCategory(Category category) { this.category = category; } public boolean getState() { return state; } public void setState(boolean state) { if (state) { onEnable(); this.state = true; EventManager.register(this); } else { onDisable(); this.state = false; EventManager.unregister(this); } } public void toggle() { setState(!this.getState()); } public final boolean isCategory(Category c) { if (c == this.category) { return true; } return false; } public String getKeyName() { return getBind() == -1 ? "-1" : Keyboard.getKeyName(getBind()); } public void onEnable() { } public void onDisable() { } }
litty-studios/randar
modules/engine/include/randar/Render/Palette/Palette.hpp
<reponame>litty-studios/randar #ifndef RANDAR_RENDER_PALETTE_HPP #define RANDAR_RENDER_PALETTE_HPP #include <randar/Render/Color.hpp> namespace randar { /** * A color palette. * * Used to sample specifically random colors. */ struct Palette { /** * Destructor. */ virtual ~Palette(); /** * Samples a color randomly from the palette. */ virtual Color color() const = 0; }; } #endif
thevpc/nuts
core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/id/NutsIdFilterAnd.java
package net.thevpc.nuts.runtime.core.filters.id; import net.thevpc.nuts.*; import net.thevpc.nuts.runtime.core.util.Simplifiable; import net.thevpc.nuts.runtime.core.util.CoreNutsUtils; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; public class NutsIdFilterAnd extends AbstractIdFilter implements NutsIdFilter, Simplifiable<NutsIdFilter>, NutsScriptAwareIdFilter { private NutsIdFilter[] children; public NutsIdFilterAnd(NutsSession session, NutsIdFilter... all) { super(session, NutsFilterOp.AND); List<NutsIdFilter> valid = new ArrayList<>(); if (all != null) { for (NutsIdFilter filter : all) { if (filter != null) { valid.add(filter); } } } this.children = valid.toArray(new NutsIdFilter[0]); } public NutsIdFilter[] getChildren() { return Arrays.copyOf(children, children.length); } @Override public boolean acceptId(NutsId id, NutsSession session) { if (children.length == 0) { return true; } for (NutsIdFilter filter : children) { if (!filter.acceptId(id, session)) { return false; } } return true; } @Override public NutsIdFilter simplify() { return CoreNutsUtils.simplifyFilterAnd(getSession(),NutsIdFilter.class,this,children); } @Override public String toJsNutsIdFilterExpr() { StringBuilder sb = new StringBuilder(); if (children.length == 0) { return "true"; } if (children.length > 1) { sb.append("("); } for (NutsIdFilter id : children) { if (sb.length() > 0) { sb.append(" && "); } if (id instanceof NutsScriptAwareIdFilter) { NutsScriptAwareIdFilter b = (NutsScriptAwareIdFilter) id; String expr = b.toJsNutsIdFilterExpr(); if (NutsBlankable.isBlank(expr)) { return null; } sb.append("(").append(expr).append("')"); } else { return null; } } if (children.length > 0) { sb.append(")"); } return sb.toString(); } @Override public String toString() { return String.join(" and ", Arrays.asList(children).stream().map(x -> "(" + x.toString() + ")").collect(Collectors.toList())); } @Override public int hashCode() { int hash = 7; hash = 11 * hash + Arrays.deepHashCode(this.children); return hash; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final NutsIdFilterAnd other = (NutsIdFilterAnd) obj; if (!Arrays.deepEquals(this.children, other.children)) { return false; } return true; } public NutsFilter[] getSubFilters() { return children; } }
Minkyu-Jeon/gitlabhq
spec/lib/gitlab/graphql/authorize/authorize_field_service_spec.rb
# frozen_string_literal: true require 'spec_helper' # Also see spec/graphql/features/authorization_spec.rb for # integration tests of AuthorizeFieldService RSpec.describe Gitlab::Graphql::Authorize::AuthorizeFieldService do def type(type_authorizations = []) Class.new(Types::BaseObject) do graphql_name 'TestType' authorize type_authorizations end end def type_with_field(field_type, field_authorizations = [], resolved_value = 'Resolved value', **options) Class.new(Types::BaseObject) do graphql_name 'TestTypeWithField' options.reverse_merge!(null: true) field :test_field, field_type, authorize: field_authorizations, resolve: -> (_, _, _) { resolved_value }, **options end end let(:current_user) { double(:current_user) } subject(:service) { described_class.new(field) } describe '#authorized_resolve' do let(:presented_object) { double('presented object') } let(:presented_type) { double('parent type', object: presented_object) } let(:query_type) { GraphQL::ObjectType.new } let(:schema) { GraphQL::Schema.define(query: query_type, mutation: nil)} let(:query_context) { OpenStruct.new(schema: schema) } let(:context) { GraphQL::Query::Context.new(query: OpenStruct.new(schema: schema, context: query_context), values: { current_user: current_user }, object: nil) } subject(:resolved) { service.authorized_resolve.call(presented_type, {}, context) } context 'scalar types' do shared_examples 'checking permissions on the presented object' do it 'checks the abilities on the object being presented and returns the value' do expected_permissions.each do |permission| spy_ability_check_for(permission, presented_object, passed: true) end expect(resolved).to eq('Resolved value') end it "returns nil if the value wasn't authorized" do allow(Ability).to receive(:allowed?).and_return false expect(resolved).to be_nil end end context 'when the field is a built-in scalar type' do let(:field) { type_with_field(GraphQL::STRING_TYPE, :read_field).fields['testField'].to_graphql } let(:expected_permissions) { [:read_field] } it_behaves_like 'checking permissions on the presented object' end context 'when the field is a list of scalar types' do let(:field) { type_with_field([GraphQL::STRING_TYPE], :read_field).fields['testField'].to_graphql } let(:expected_permissions) { [:read_field] } it_behaves_like 'checking permissions on the presented object' end context 'when the field is sub-classed scalar type' do let(:field) { type_with_field(Types::TimeType, :read_field).fields['testField'].to_graphql } let(:expected_permissions) { [:read_field] } it_behaves_like 'checking permissions on the presented object' end context 'when the field is a list of sub-classed scalar types' do let(:field) { type_with_field([Types::TimeType], :read_field).fields['testField'].to_graphql } let(:expected_permissions) { [:read_field] } it_behaves_like 'checking permissions on the presented object' end end context 'when the field is a connection' do context 'when it resolves to nil' do let(:field) { type_with_field(Types::QueryType.connection_type, :read_field, nil).fields['testField'].to_graphql } it 'does not fail when authorizing' do expect(resolved).to be_nil end end end context 'when the field is a specific type' do let(:custom_type) { type(:read_type) } let(:object_in_field) { double('presented in field') } let(:field) { type_with_field(custom_type, :read_field, object_in_field).fields['testField'].to_graphql } it 'checks both field & type permissions' do spy_ability_check_for(:read_field, object_in_field, passed: true) spy_ability_check_for(:read_type, object_in_field, passed: true) expect(resolved).to eq(object_in_field) end it 'returns nil if viewing was not allowed' do spy_ability_check_for(:read_field, object_in_field, passed: false) spy_ability_check_for(:read_type, object_in_field, passed: true) expect(resolved).to be_nil end context 'when the field is not nullable' do let(:field) { type_with_field(custom_type, [], object_in_field, null: false).fields['testField'].to_graphql } it 'returns nil when viewing is not allowed' do spy_ability_check_for(:read_type, object_in_field, passed: false) expect(resolved).to be_nil end end context 'when the field is a list' do let(:object_1) { double('presented in field 1') } let(:object_2) { double('presented in field 2') } let(:presented_types) { [double(object: object_1), double(object: object_2)] } let(:field) { type_with_field([custom_type], :read_field, presented_types).fields['testField'].to_graphql } it 'checks all permissions' do allow(Ability).to receive(:allowed?) { true } spy_ability_check_for(:read_field, object_1, passed: true) spy_ability_check_for(:read_type, object_1, passed: true) spy_ability_check_for(:read_field, object_2, passed: true) spy_ability_check_for(:read_type, object_2, passed: true) expect(resolved).to eq(presented_types) end it 'filters out objects that the user cannot see' do allow(Ability).to receive(:allowed?) { true } spy_ability_check_for(:read_type, object_1, passed: false) expect(resolved.map(&:object)).to contain_exactly(object_2) end end end end private def spy_ability_check_for(ability, object, passed: true) expect(Ability) .to receive(:allowed?) .with(current_user, ability, object) .and_return(passed) end end
TheRakeshPurohit/CodingSpectator
plug-ins/helios/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/locals_in/A_test534.java
<reponame>TheRakeshPurohit/CodingSpectator<gh_stars>1-10 package locals_in; public class A_test534 { class Inner { public int x; } public void foo() { Inner inner= new Inner(); /*[*/inner.x= 10;/*]*/ int y= inner.x; } }
jomei/iodine
ext/iodine/random.c
/* Copyright: <NAME>, 2016-2017 License: MIT except for any non-public-domain algorithms (none that I'm aware of), which might be subject to their own licenses. Feel free to copy, use and enjoy in accordance with to the license(s). */ #ifndef _GNU_SOURCE #define _GNU_SOURCE #endif #include "random.h" #if defined(USE_ALT_RANDOM) || !defined(HAS_UNIX_FEATURES) #include "sha2.h" #include <time.h> #ifdef RUSAGE_SELF static size_t get_clock_mili(void) { struct rusage rusage; getrusage(RUSAGE_SELF, &rusage); return ((rusage.ru_utime.tv_sec + rusage.ru_stime.tv_sec) * 1000000) + (rusage.ru_utime.tv_usec + rusage.ru_stime.tv_usec); } #elif defined CLOCKS_PER_SEC #define get_clock_mili() (size_t) clock() #else #define get_clock_mili() 0 #error Random alternative failed to find access to the CPU clock state. #endif uint32_t bscrypt_rand32(void) { bits256_u pseudo = bscrypt_rand256(); return pseudo.ints[3]; } uint64_t bscrypt_rand64(void) { bits256_u pseudo = bscrypt_rand256(); return pseudo.words[3]; } bits128_u bscrypt_rand128(void) { bits256_u pseudo = bscrypt_rand256(); bits128_u ret; ret.words[0] = pseudo.words[0]; ret.words[1] = pseudo.words[1]; return ret; } bits256_u bscrypt_rand256(void) { size_t cpu_state = get_clock_mili(); time_t the_time; time(&the_time); bits256_u pseudo; sha2_s sha2 = bscrypt_sha2_init(SHA_256); bscrypt_sha2_write(&sha2, &cpu_state, sizeof(cpu_state)); bscrypt_sha2_write(&sha2, &the_time, sizeof(the_time)); bscrypt_sha2_write(&sha2, ((char *)&cpu_state) - 64, 64); /* the stack */ bscrypt_sha2_result(&sha2); pseudo.words[0] = sha2.digest.i64[0]; pseudo.words[1] = sha2.digest.i64[1]; pseudo.words[2] = sha2.digest.i64[2]; pseudo.words[3] = sha2.digest.i64[3]; return pseudo; } void bscrypt_rand_bytes(void *target, size_t length) { clock_t cpu_state = clock(); time_t the_time; time(&the_time); sha2_s sha2 = bscrypt_sha2_init(SHA_512); bscrypt_sha2_write(&sha2, &cpu_state, sizeof(cpu_state)); bscrypt_sha2_write(&sha2, &the_time, sizeof(the_time)); bscrypt_sha2_write(&sha2, &cpu_state - 2, 64); /* whatever's on the stack */ bscrypt_sha2_result(&sha2); while (length > 64) { memcpy(target, sha2.digest.str, 64); length -= 64; target = (void *)((uintptr_t)target + 64); bscrypt_sha2_write(&sha2, &cpu_state, sizeof(cpu_state)); bscrypt_sha2_result(&sha2); } if (length > 32) { memcpy(target, sha2.digest.str, 32); length -= 32; target = (void *)((uintptr_t)target + 32); bscrypt_sha2_write(&sha2, &cpu_state, sizeof(cpu_state)); bscrypt_sha2_result(&sha2); } if (length > 16) { memcpy(target, sha2.digest.str, 16); length -= 16; target = (void *)((uintptr_t)target + 16); bscrypt_sha2_write(&sha2, &cpu_state, sizeof(cpu_state)); bscrypt_sha2_result(&sha2); } if (length > 8) { memcpy(target, sha2.digest.str, 8); length -= 8; target = (void *)((uintptr_t)target + 8); bscrypt_sha2_write(&sha2, &cpu_state, sizeof(cpu_state)); bscrypt_sha2_result(&sha2); } while (length) { *((uint8_t *)target) = sha2.digest.str[length]; target = (void *)((uintptr_t)target + 1); --length; } } #else /* *************************************************************************** Unix Random Engine (use built in machine) */ #include <errno.h> #include <fcntl.h> #include <pthread.h> #include <unistd.h> /* *************************************************************************** Machine specific changes */ // #ifdef __linux__ // #undef bswap16 // #undef bswap32 // #undef bswap64 // #include <machine/bswap.h> // #endif #ifdef HAVE_X86Intrin // #undef bswap16 /* #undef bswap32 #define bswap32(i) \ { __asm__("bswap %k0" : "+r"(i) :); } */ #undef bswap64 #define bswap64(i) \ { __asm__("bswapq %0" : "+r"(i) :); } // shadow sched_yield as _mm_pause for spinwait #define sched_yield() _mm_pause() #endif /* *************************************************************************** Random ... (why is this not a system call?) */ /* rand generator management */ static int _rand_fd_ = -1; static void close_rand_fd(void) { if (_rand_fd_ >= 0) close(_rand_fd_); _rand_fd_ = -1; } static void init_rand_fd(void) { if (_rand_fd_ < 0) { while ((_rand_fd_ = open("/dev/urandom", O_RDONLY)) == -1) { if (errno == ENXIO) perror("bscrypt fatal error, caanot initiate random generator"), exit(-1); sched_yield(); } } atexit(close_rand_fd); } /* rand function template */ #define MAKE_RAND_FUNC(type, func_name) \ type func_name(void) { \ if (_rand_fd_ < 0) \ init_rand_fd(); \ type ret; \ while (read(_rand_fd_, &ret, sizeof(type)) < 0) \ sched_yield(); \ return ret; \ } /* rand functions */ MAKE_RAND_FUNC(uint32_t, bscrypt_rand32) MAKE_RAND_FUNC(uint64_t, bscrypt_rand64) MAKE_RAND_FUNC(bits128_u, bscrypt_rand128) MAKE_RAND_FUNC(bits256_u, bscrypt_rand256) /* clear template */ #undef MAKE_RAND_FUNC void bscrypt_rand_bytes(void *target, size_t length) { if (_rand_fd_ < 0) init_rand_fd(); while (read(_rand_fd_, target, length) < 0) sched_yield(); } #endif /* Unix Random */ /******************************************************************************* Random */ #if defined(DEBUG) && DEBUG == 1 void bscrypt_test_random(void) { clock_t start, end; bscrypt_rand256(); start = clock(); for (size_t i = 0; i < 100000; i++) { bscrypt_rand256(); } end = clock(); fprintf(stderr, "+ bscrypt Random generator available\n+ bscrypt 100K X 256bit " "Random %lu CPU clock count\n", end - start); } #endif
Prometheus0000/BloodMagic
src/api/java/vazkii/botania/api/mana/spark/SparkHelper.java
/** * This class was created by <Vazkii>. It's distributed as * part of the Botania Mod. Get the Source Code in github: * https://github.com/Vazkii/Botania * * Botania is Open Source and distributed under a * Creative Commons Attribution-NonCommercial-ShareAlike 3.0 License * (http://creativecommons.org/licenses/by-nc-sa/3.0/deed.en_GB) * * File Created @ [Aug 21, 2014, 7:16:11 PM (GMT)] */ package vazkii.botania.api.mana.spark; import java.util.List; import net.minecraft.util.AxisAlignedBB; import net.minecraft.world.World; public final class SparkHelper { public static final int SPARK_SCAN_RANGE = 12; public static List<ISparkEntity> getSparksAround(World world, double x, double y, double z) { return SparkHelper.getEntitiesAround(ISparkEntity.class, world, x, y, z); } public static <T> List<T> getEntitiesAround(Class<? extends T> clazz, World world, double x, double y, double z) { int r = SPARK_SCAN_RANGE; List<T> entities = world.getEntitiesWithinAABB(clazz, AxisAlignedBB.getBoundingBox(x - r, y - r, z - r, x + r, y + r, z + r)); return entities; } }
titilima/blink
src/blinkit/gc/gc_heap.h
<filename>src/blinkit/gc/gc_heap.h<gh_stars>10-100 // ------------------------------------------------- // BlinKit - BlinKit Library // ------------------------------------------------- // File Name: gc_heap.h // Description: GCHeap Class // Author: <NAME> // Created: 2020-11-14 // ------------------------------------------------- // Copyright (C) 2020 MingYang Software Technology. // ------------------------------------------------- #ifndef BLINKIT_BLINKIT_GC_HEAP_H #define BLINKIT_BLINKIT_GC_HEAP_H #pragma once #include <stack> #include "blinkit/gc/lifecycle_data_manager.h" namespace BlinKit { struct GCObjectHeader; class GCVisitor; class GCHeap { public: static void Initialize(void); static void Finalize(void); #ifndef NDEBUG static void TrackObject(GCObject &o); static void UntrackObject(GCObject &o); #endif void AddGlobalFinalizer(const std::function<void()> &finalizer) { m_globalFinalizers.emplace(finalizer); } static void RegisterLifecycleObserver(GCObject *o, GCLifecycleObserver *ob); static void RemoveLifecycleObserverForObject(GCObject *o, GCLifecycleObserver *ob); static void RemoveLifecycleObserver(GCLifecycleObserver *ob); void AttachWeakSlot(GCObject &o, void **slot) { m_lifecycleDataManager.AttachWeakSlot(&o, slot); } void DetachWeakSlot(GCObject &o, void **slot) { m_lifecycleDataManager.DetachWeakSlot(&o, slot); } static void ProcessObjectFinalizing(GCObject &o); private: GCHeap(void); ~GCHeap(void); void CleanupGlobalObjects(void); #ifndef NDEBUG std::unordered_set<GCObject *> m_allObjects; #endif LifecycleDataManager m_lifecycleDataManager; std::stack<std::function<void()>> m_globalFinalizers; }; } // namespace BlinKit #endif // BLINKIT_BLINKIT_GC_HEAP_H
CLUB-INFORMATIQUE/unity-ads-ios
UnityAds/Request/UADSWebRequestEvent.h
#import <Foundation/Foundation.h> typedef NS_ENUM(NSInteger, UnityAdsWebRequestEvent) { kUnityAdsWebRequestEventComplete, kUnityAdsWebRequestEventFailed }; NSString *NSStringFromWebRequestEvent(UnityAdsWebRequestEvent);