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",
// "aaaaaaaaaaaaaa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aaaaaaaaaaaaaaaaaaaaaa",
// "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
|
End of preview. Expand
in Dataset Viewer.
- Downloads last month
- 37