repo_name stringlengths 6 101 | path stringlengths 4 300 | text stringlengths 7 1.31M |
|---|---|---|
ad12/meddlr | meddlr/transforms/base/__init__.py | <reponame>ad12/meddlr
from meddlr.transforms.base.mask import KspaceMaskTransform # noqa
from meddlr.transforms.base.motion import MRIMotionTransform # noqa
from meddlr.transforms.base.noise import NoiseTransform # noqa
from meddlr.transforms.base.spatial import ( # noqa
AffineTransform,
FlipTransform,
Rot90Transform,
TranslationTransform,
)
|
Sheph/TriggerTime | game/TurretComponent.cpp | /*
* Copyright (c) 2014, <NAME>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "TurretComponent.h"
#include "Utils.h"
#include "Settings.h"
#include "SceneObjectFactory.h"
#include "Const.h"
#include "ExplosionComponent.h"
#include "Scene.h"
#include "RenderHealthbarComponent.h"
#include "CameraComponent.h"
#include "AssetManager.h"
#include <boost/make_shared.hpp>
namespace af
{
TurretComponent::TurretComponent(const SceneObjectPtr& tower,
const std::vector<b2Transform>& shotPoses)
: TargetableComponent(phaseThink),
tower_(tower),
hadTarget_(false),
inSight_(false)
{
for (std::vector<b2Transform>::const_iterator it = shotPoses.begin();
it != shotPoses.end(); ++it) {
weapons_.push_back(boost::make_shared<WeaponBlasterComponent>(false, SceneObjectTypeEnemyMissile));
weapons_.back()->setTransform(*it);
weapons_.back()->setDamage(settings.turret1.shootDamage);
weapons_.back()->setVelocity(settings.turret1.shootVelocity);
weapons_.back()->setTurns(1);
weapons_.back()->setShotsPerTurn(1);
weapons_.back()->setLoopDelay(settings.turret1.shootDelay);
weapons_.back()->setHaveSound(false);
}
if (!weapons_.empty()) {
weapons_.front()->setHaveSound(true);
}
}
TurretComponent::~TurretComponent()
{
}
void TurretComponent::accept(ComponentVisitor& visitor)
{
visitor.visitPhasedComponent(shared_from_this());
}
void TurretComponent::update(float dt)
{
if (parent()->life() <= 0) {
RenderHealthbarComponentPtr hc = parent()->findComponent<RenderHealthbarComponent>();
if (hc) {
hc->removeFromParent();
}
SceneObjectPtr explosion = sceneObjectFactory.createExplosion1(zOrderExplosion);
explosion->setTransform(parent()->getTransform());
explosion->findComponent<ExplosionComponent>()->setBlast(parent()->shared_from_this(),
settings.turret1.explosionImpulse, settings.turret1.explosionDamage,
SceneObjectTypeEnemy);
scene()->addObject(explosion);
tower_->removeFromParent();
parent()->findComponent<LightComponent>()->lights()[0]->setVisible(true);
ParticleEffectComponentPtr pec = assetManager.getParticleEffect("fire1.p",
b2Vec2_zero, 0.0f, false);
pec->setFixedAngle(true);
pec->setZOrder(zOrderEffects);
pec->resetEmit();
parent()->addComponent(pec);
scene()->stats()->incEnemiesKilled();
removeFromParent();
return;
}
updateAutoTarget(dt);
if (!target()) {
seekBehavior_->reset();
hadTarget_ = false;
return;
}
if (!hadTarget_) {
seekBehavior_->setAngularVelocity(settings.turret1.turnSpeed);
seekBehavior_->setUseTorque(true);
seekBehavior_->setLoop(true);
seekBehavior_->start();
hadTarget_ = true;
}
seekBehavior_->setTarget(target());
float angle = fabs(angleBetween(tower_->getDirection(1.0f), target()->pos() - tower_->pos()));
bool inSight = scene()->camera()->findComponent<CameraComponent>()->rectVisible(
parent()->pos(), 4.0f, 4.0f);
if (inSight && !inSight_) {
for (std::vector<WeaponBlasterComponentPtr>::const_iterator it = weapons_.begin();
it != weapons_.end(); ++it) {
(*it)->reload();
}
}
inSight_ = inSight;
bool hold = (angle <= settings.turret1.shootAngle) && inSight_;
for (std::vector<WeaponBlasterComponentPtr>::const_iterator it = weapons_.begin();
it != weapons_.end(); ++it) {
(*it)->trigger(hold);
}
}
void TurretComponent::onRegister()
{
scene()->stats()->incEnemiesSpawned();
for (std::vector<WeaponBlasterComponentPtr>::const_iterator it = weapons_.begin();
it != weapons_.end(); ++it) {
tower_->addComponent(*it);
}
seekBehavior_ = tower_->seekBehavior();
}
void TurretComponent::onUnregister()
{
setTarget(SceneObjectPtr());
}
}
|
HPI-Information-Systems/TimeEval | tests/test_algorithm.py | import unittest
import numpy as np
from timeeval import Algorithm, TrainingType
from timeeval.adapters import FunctionAdapter
class TestAlgorithm(unittest.TestCase):
def setUp(self) -> None:
self.data = np.random.rand(10)
self.unsupervised_algorithm = Algorithm(
name="TestAlgorithm",
main=FunctionAdapter.identity(),
training_type=TrainingType.UNSUPERVISED
)
self.supervised_algorithm = Algorithm(
name="TestAlgorithm",
main=FunctionAdapter.identity(),
training_type=TrainingType.SUPERVISED
)
self.semi_supervised_algorithm = Algorithm(
name="TestAlgorithm",
main=FunctionAdapter.identity(),
training_type=TrainingType.SEMI_SUPERVISED
)
def test_execution(self):
result = self.unsupervised_algorithm.execute(self.data)
np.testing.assert_array_equal(self.data, result)
result = self.semi_supervised_algorithm.execute(self.data)
np.testing.assert_array_equal(self.data, result)
result = self.supervised_algorithm.execute(self.data)
np.testing.assert_array_equal(self.data, result)
def test_unsupervised_training(self):
with self.assertRaises(ValueError) as e:
self.unsupervised_algorithm.train(self.data)
self.assertRegex(str(e.exception), r".*[Cc]alling.*train.*unsupervised algorithm.*not supported.*")
def test_semi_and_supervised_training(self):
result = self.semi_supervised_algorithm.train(self.data)
np.testing.assert_array_equal(self.data, result)
result = self.supervised_algorithm.train(self.data)
np.testing.assert_array_equal(self.data, result)
|
garryhvh420/e_xyz | csgocheat/Anti Debug/UnhandledExceptionFilter_Handler.h | <gh_stars>0
#include <Windows.h>
BOOL UnhandledExcepFilterTest(); |
asanoviskhak/Outtalent | Leetcode/724. Find Pivot Index/solution1.py | class Solution:
def pivotIndex(self, nums: List[int]) -> int:
l, r = 0, sum(nums)
for i in range(len(nums)):
r -= nums[i]
if l == r: return i
l += nums[i]
return -1
|
RNCan/WeatherBasedSimulationFramework | wbsModels/IPSTypographus/SBBColdTolerance.h | #pragma once
#include <vector>
#include "basic/ERMsg.h"
#include "basic/utilTime.h"
#include "basic/ModelStat.h"
namespace WBSF
{
enum TSBBSuperCoolingPoint{ TMAX, P1, P2, P3, CT, LT50, PMORT, NB_SUPER_COOLING_POINT };
typedef CModelStatVectorTemplate<NB_SUPER_COOLING_POINT> CSBBSuperCoolingPointStat;
//************************************************************
//CMPBCTResult
/*
class CMPBCTResult
{
public:
CMPBCTResult()
{
Reset();
}
CMPBCTResult(short year, double Tmin, double Psurv)
{
Reset();
m_year=year;
m_Tmin=Tmin;
m_Psurv=Psurv;
}
CMPBCTResult(short year, short day, double Tmin, double Tmax, double p1, double p3, double Ct, double LT50, double Psurv, double Pmort)
{
Reset();
m_year=year;
m_day=day;
m_Tmin=Tmin;
m_Tmax=Tmax;
m_p1=p1;
m_p3=p3;
m_Ct=Ct;
m_LT50=LT50;
m_Psurv=Psurv;
m_Pmort=Pmort;
}
void Reset()
{
m_year=m_day=-999;
m_Tmin=m_Tmax=m_p1=m_p3=m_Ct=m_LT50=m_Psurv=m_Pmort=-999;
}
//annual result
short m_year;
double m_Tmin;
double m_Psurv;
//additionnal daily result
short m_day;
double m_Tmax;
double m_p1;
double m_p3;
double m_Ct;
double m_LT50;
double m_Pmort;
};
typedef std::vector<CMPBCTResult> CMPBCTResultVector;
*/
//************************************************************
//CSBBColdTolerance
class CWeather;
class CSBBColdTolerance
{
public:
//input parameter
bool m_bMicroClimate;
CSBBColdTolerance();
void ExecuteDaily(const CWeatherStation& weather, CSBBSuperCoolingPointStat& stat);
protected:
double m_RhoG;
double m_MuG;
double m_SigmaG;
double m_KappaG;
double m_RhoL;
double m_MuL;
double m_SigmaL;
double m_KappaL;
double m_Lambda0;
double m_Lambda1;
};
} |
juanfelipe82193/opensap | sapui5-sdk-1.74.0/resources/sap/ushell/appRuntime/ui5/services/UserInfo-dbg.js | // Copyright (c) 2009-2017 SAP SE, All Rights Reserved
sap.ui.define([
"sap/ushell/services/UserInfo",
"sap/ushell/appRuntime/ui5/AppRuntimeService",
"sap/base/Log"
], function (UserInfo, AppRuntimeService, Log) {
"use strict";
function UserInfoProxy (oAdapter, oContainerInterface) {
UserInfo.call(this, oAdapter, oContainerInterface);
this.getUser = function () {
Log.warning("'UserInfo.getUser' is private API and should not be called");
};
this.getThemeList = function () {
Log.warning("'UserInfo.getThemeList' is private API and should not be called");
};
this.updateUserPreferences = function () {
Log.warning("'UserInfo.updateUserPreferences' is private API and should not be called");
};
this.getLanguageList = function () {
Log.warning("'UserInfo.getLanguageList' is private API and should not be called");
};
}
UserInfoProxy.prototype = Object.create(UserInfo.prototype);
UserInfoProxy.hasNoAdapter = UserInfo.hasNoAdapter;
return UserInfoProxy;
}, true);
|
ckxy/part-of-hitogata | datasetsnx/bamboo/color.py | <filename>datasetsnx/bamboo/color.py
import random
from PIL import Image
from .base_internode import BaseInternode
from torchvision.transforms.functional import normalize, to_grayscale, adjust_brightness, adjust_contrast, adjust_saturation, adjust_hue
__all__ = ['BrightnessEnhancement', 'ContrastEnhancement', 'SaturationEnhancement', 'HueEnhancement', 'RandomGrayscale']
class BrightnessEnhancement(BaseInternode):
def __init__(self, brightness, p=1):
assert len(brightness) == 2
assert brightness[1] >= brightness[0]
assert brightness[0] > 0
assert 0 < p <= 1
self.brightness = brightness
self.p = p
# self.ColorJitter = torchvision.transforms.ColorJitter(self.brightness, 0, 0, 0)
def __call__(self, data_dict):
# data_dict = super(BrightnessEnhancement, self).__call__(data_dict)
if random.random() < self.p:
# data_dict['image'] = self.ColorJitter(data_dict['image'])
factor = random.uniform(self.brightness[0], self.brightness[1])
data_dict['image'] = adjust_brightness(data_dict['image'], factor)
return data_dict
def __repr__(self):
return 'BrightnessEnhancement(p={}, brightness={})'.format(self.p, self.brightness)
def rper(self):
return 'BrightnessEnhancement(not available)'
class ContrastEnhancement(BaseInternode):
def __init__(self, contrast, p=1):
assert len(contrast) == 2
assert contrast[1] >= contrast[0]
assert contrast[0] > 0
assert 0 < p <= 1
self.contrast = contrast
self.p = p
# self.ColorJitter = torchvision.transforms.ColorJitter(0, self.contrast, 0, 0)
def __call__(self, data_dict):
# data_dict = super(ContrastEnhancement, self).__call__(data_dict)
if random.random() < self.p:
# data_dict['image'] = self.ColorJitter(data_dict['image'])
factor = random.uniform(self.contrast[0], self.contrast[1])
data_dict['image'] = adjust_contrast(data_dict['image'], factor)
return data_dict
def __repr__(self):
return 'ContrastEnhancement(p={}, contrast={})'.format(self.p, self.contrast)
def rper(self):
return 'ContrastEnhancement(not available)'
class SaturationEnhancement(BaseInternode):
def __init__(self, saturation, p=1):
assert len(saturation) == 2
assert saturation[1] >= saturation[0]
assert saturation[0] > 0
assert 0 < p <= 1
self.saturation = saturation
self.p = p
# self.ColorJitter = torchvision.transforms.ColorJitter(0, 0, self.saturation, 0)
def __call__(self, data_dict):
# data_dict = super(SaturationEnhancement, self).__call__(data_dict)
if random.random() < self.p:
# data_dict['image'] = self.ColorJitter(data_dict['image'])
factor = random.uniform(self.saturation[0], self.saturation[1])
data_dict['image'] = adjust_saturation(data_dict['image'], factor)
return data_dict
def __repr__(self):
return 'SaturationEnhancement(p={}, saturation={})'.format(self.p, self.saturation)
def rper(self):
return 'SaturationEnhancement(not available)'
class HueEnhancement(BaseInternode):
def __init__(self, hue, p=1):
assert len(hue) == 2
assert hue[1] >= hue[0]
assert hue[0] >= -0.5 and hue[1] <= 0.5
assert 0 < p <= 1
self.hue = hue
self.p = p
# self.ColorJitter = torchvision.transforms.ColorJitter(0, 0, 0, self.hue)
def __call__(self, data_dict):
# data_dict = super(HueEnhancement, self).__call__(data_dict)
if random.random() < self.p:
# data_dict['image'] = self.ColorJitter(data_dict['image'])
factor = random.uniform(self.hue[0], self.hue[1])
data_dict['image'] = adjust_hue(data_dict['image'], factor)
return data_dict
def __repr__(self):
return 'HueEnhancement(p={}, hue={})'.format(self.p, self.hue)
def rper(self):
return 'HueEnhancement(not available)'
class RandomGrayscale(BaseInternode):
def __init__(self, ch, p=1):
assert 0 < p <= 1
assert self.ch == 1 or self.ch == 3
self.p = p
self.ch = ch
def __call__(self, data_dict):
# data_dict = super(RandomGrayscale, self).__call__(data_dict)
if random.random() < self.p:
data_dict['image'] = to_grayscale(data_dict['image'], num_output_channels=self.ch)
return data_dict
def __repr__(self):
return 'RandomGrayscale(p={}, ch={})'.format(self.p, self.ch)
def rper(self):
return 'RandomGrayscale(not available)'
|
chpatel3/coherence-cpp-extend-client | src/coherence/component/net/extend/protocol/PingRequest.cpp | <filename>src/coherence/component/net/extend/protocol/PingRequest.cpp
/*
* Copyright (c) 2000, 2020, Oracle and/or its affiliates.
*
* Licensed under the Universal Permissive License v 1.0 as shown at
* http://oss.oracle.com/licenses/upl.
*/
#include "private/coherence/component/net/extend/protocol/PingRequest.hpp"
#include "private/coherence/component/net/extend/protocol/PingResponse.hpp"
#include "private/coherence/component/util/Peer.hpp"
COH_OPEN_NAMESPACE5(coherence,component,net,extend,protocol)
using coherence::component::util::Peer;
// ----- constructors -------------------------------------------------------
PingRequest::PingRequest()
{
}
// ----- AbstractPofRequest interface ---------------------------------------
AbstractPofResponse::Handle PingRequest::instantiateResponse(
Protocol::MessageFactory::View vFactory) const
{
return cast<AbstractPofResponse::Handle>(
vFactory->createMessage(PingResponse::type_id));
}
void PingRequest::onRun(AbstractPofResponse::Handle)
{
COH_ENSURE_EQUALITY(getChannel()->getId(), 0);
}
// ----- Message interface --------------------------------------------------
int32_t PingRequest::getTypeId() const
{
return type_id;
}
COH_CLOSE_NAMESPACE5
|
dhis2/approvals-app | src/top-bar/index.js | export { TopBar } from './top-bar.js'
|
AlexandrPristupa/Today-I-Learned- | javascript/codesignal/sameElementsNaive.js | export const sameElementsNaive = (a, b) => {
let sameElementsCounts = 0;
for (let i = 0; i < a.length; i++) {
for (let j = 0; j < b.length; j++) {
if (a[i] === b[j]) {
sameElementsCounts += 1;
}
}
}
return sameElementsCounts;
}
|
RocketfarmAS/jrosbridge | src/test/java/edu/wpi/rail/jrosbridge/TestTopic.java | package edu.wpi.rail.jrosbridge;
import static org.junit.Assert.*;
import javax.json.Json;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import edu.wpi.rail.jrosbridge.JRosbridge;
import edu.wpi.rail.jrosbridge.Ros;
import edu.wpi.rail.jrosbridge.Topic;
import edu.wpi.rail.jrosbridge.callback.TopicCallback;
import edu.wpi.rail.jrosbridge.messages.Message;
public class TestTopic {
private Ros ros;
private DummyServer server;
private Topic t1, t2, t3, t4;
@Before
public void setUp() {
ros = new Ros();
server = new DummyServer(ros.getPort());
server.start();
ros.connect();
t1 = new Topic(ros, "myTopic1", "myType1");
t2 = new Topic(ros, "myTopic2", "myType2",
JRosbridge.CompressionType.png);
t3 = new Topic(ros, "myTopic3", "myType3", 10);
t4 = new Topic(ros, "myTopic4", "myType4",
JRosbridge.CompressionType.png, 20);
}
@After
public void tearDown() {
ros.disconnect();
server.stop();
DummyHandler.latest = null;
}
@Test
public void testRosStringAndStringConstructor() {
assertEquals(ros, t1.getRos());
assertEquals("myTopic1", t1.getName());
assertEquals("myType1", t1.getType());
assertFalse(t1.isAdvertised());
assertFalse(t1.isSubscribed());
assertEquals(JRosbridge.CompressionType.none, t1.getCompression());
assertEquals(0, t1.getThrottleRate());
}
@Test
public void testRosStringStringAndCompressionTypeConstructor() {
assertEquals(ros, t2.getRos());
assertEquals("myTopic2", t2.getName());
assertEquals("myType2", t2.getType());
assertFalse(t2.isAdvertised());
assertFalse(t2.isSubscribed());
assertEquals(JRosbridge.CompressionType.png, t2.getCompression());
assertEquals(0, t2.getThrottleRate());
}
@Test
public void testRosStringStringAndIntConstructor() {
assertEquals(ros, t3.getRos());
assertEquals("myTopic3", t3.getName());
assertEquals("myType3", t3.getType());
assertFalse(t3.isAdvertised());
assertFalse(t3.isSubscribed());
assertEquals(JRosbridge.CompressionType.none, t3.getCompression());
assertEquals(10, t3.getThrottleRate());
}
@Test
public void testRosStringStringCompressionTypeAndIntConstructor() {
assertEquals(ros, t4.getRos());
assertEquals("myTopic4", t4.getName());
assertEquals("myType4", t4.getType());
assertFalse(t4.isAdvertised());
assertFalse(t4.isSubscribed());
assertEquals(JRosbridge.CompressionType.png, t4.getCompression());
assertEquals(20, t4.getThrottleRate());
}
@Test
public void testSubscribe() {
DummyTopicCallback cb = new DummyTopicCallback();
t1.subscribe(cb);
assertNull(cb.latest);
ros.send(Json
.createObjectBuilder()
.add("echo",
"{\"" + JRosbridge.FIELD_OP + "\":\""
+ JRosbridge.OP_CODE_PUBLISH + "\",\""
+ JRosbridge.FIELD_TOPIC + "\":\"myTopic1\",\""
+ JRosbridge.FIELD_MESSAGE
+ "\":{\"test1\":\"test2\"}}").build());
while (cb.latest == null) {
Thread.yield();
}
assertNotNull(DummyHandler.latest);
assertEquals(
"{\"op\":\"subscribe\",\"id\":\"subscribe:myTopic1:0\",\"type\":\"myType1\","
+ "\"topic\":\"myTopic1\",\"compression\":\"none\",\"throttle_rate\":0}",
DummyHandler.latest.toString());
assertNotNull(cb.latest);
assertEquals("{\"test1\":\"test2\"}", cb.latest.toString());
assertFalse(t1.isAdvertised());
assertTrue(t1.isSubscribed());
}
@Test
public void testUnsubscribe() {
DummyTopicCallback cb = new DummyTopicCallback();
t1.subscribe(cb);
assertFalse(t1.isAdvertised());
assertTrue(t1.isSubscribed());
assertNull(cb.latest);
t1.unsubscribe();
ros.send(Json
.createObjectBuilder()
.add("echo",
"{\"" + JRosbridge.FIELD_OP + "\":\""
+ JRosbridge.OP_CODE_PUBLISH + "\",\""
+ JRosbridge.FIELD_TOPIC + "\":\"myTopic1\",\""
+ JRosbridge.FIELD_MESSAGE
+ "\":{\"test1\":\"test2\"}}").build());
Thread.yield();
assertNotNull(DummyHandler.latest);
assertEquals(
"{\"op\":\"subscribe\",\"id\":\"subscribe:myTopic1:0\",\"type\":\"myType1\","
+ "\"topic\":\"myTopic1\",\"compression\":\"none\",\"throttle_rate\":0}",
DummyHandler.latest.toString());
assertNull(cb.latest);
assertFalse(t1.isAdvertised());
assertFalse(t1.isSubscribed());
}
@Test
public void testUnsubscribeNoSubscribe() {
DummyTopicCallback cb = new DummyTopicCallback();
assertNull(cb.latest);
t1.unsubscribe();
assertNull(DummyHandler.latest);
assertNull(cb.latest);
assertFalse(t1.isAdvertised());
assertFalse(t1.isSubscribed());
}
@Test
public void testAdvertise() {
t1.advertise();
while (DummyHandler.latest == null) {
Thread.yield();
}
assertNotNull(DummyHandler.latest);
assertEquals(
"{\"op\":\"advertise\",\"id\":\"advertise:myTopic1:0\",\"type\":\"myType1\","
+ "\"topic\":\"myTopic1\"}",
DummyHandler.latest.toString());
assertTrue(t1.isAdvertised());
assertFalse(t1.isSubscribed());
}
@Test
public void testUnadvertise() {
t1.unadvertise();
while (DummyHandler.latest == null) {
Thread.yield();
}
assertNotNull(DummyHandler.latest);
assertEquals(
"{\"op\":\"unadvertise\",\"id\":\"unadvertise:myTopic1:0\",\"topic\":\"myTopic1\"}",
DummyHandler.latest.toString());
assertFalse(t1.isAdvertised());
assertFalse(t1.isSubscribed());
}
@Test
public void testPublish() {
t1.advertise();
while (DummyHandler.latest == null) {
Thread.yield();
}
DummyHandler.latest = null;
t1.publish(new Message("{\"test1\":\"test2\"}"));
while (DummyHandler.latest == null) {
Thread.yield();
}
assertNotNull(DummyHandler.latest);
assertEquals(
"{\"op\":\"publish\",\"id\":\"publish:myTopic1:1\",\"topic\":\"myTopic1\""
+ ",\"msg\":{\"test1\":\"test2\"}}",
DummyHandler.latest.toString());
assertTrue(t1.isAdvertised());
assertFalse(t1.isSubscribed());
}
private class DummyTopicCallback implements TopicCallback {
public Message latest = null;
public void handleMessage(Message message) {
this.latest = message;
}
}
}
|
hsanchez/vesper | src/edu/ucsc/refactor/internal/changers/RemoveMagicNumber.java | package edu.ucsc.refactor.internal.changers;
import edu.ucsc.refactor.Cause;
import edu.ucsc.refactor.Change;
import edu.ucsc.refactor.Parameter;
import edu.ucsc.refactor.Source;
import edu.ucsc.refactor.internal.SourceChange;
import edu.ucsc.refactor.internal.visitors.FieldDeclarationVisitor;
import edu.ucsc.refactor.spi.Smell;
import edu.ucsc.refactor.spi.SourceChanger;
import edu.ucsc.refactor.internal.util.AstUtil;
import edu.ucsc.refactor.util.Parameters;
import org.eclipse.jdt.core.dom.*;
import org.eclipse.jdt.core.dom.rewrite.ASTRewrite;
import org.eclipse.jdt.core.dom.rewrite.ListRewrite;
import java.util.Map;
/**
* Responsible for replacing a magic number with symbolic constant.
*
* @author <EMAIL> (<NAME>)
*/
public class RemoveMagicNumber extends SourceChanger {
@Override public boolean canHandle(Cause cause) {
return cause.isSame(Smell.MAGIC_NUMBER);
}
@Override protected Change initChanger(Cause cause,
Map<String, Parameter> parameters) {
final SourceChange change = new SourceChange(cause, this, parameters);
try {
final ChangeBuilder changeBuilder = new ChangeBuilder(cause, parameters);
return changeBuilder.build(change);
} catch (Throwable ex){
change.getErrors().add(ex.getMessage());
return change;
}
}
@Override protected Map<String, Parameter> defaultParameters() {
return Parameters.newRandomConstantName();
}
static class ChangeBuilder {
private final Cause cause;
private final Map<String, Parameter> parameters;
ChangeBuilder(Cause cause,
Map<String, Parameter> parameters){
this.cause = cause;
this.parameters = parameters;
}
Change build(SourceChange change){
final NumberLiteral literal = (NumberLiteral) cause.getAffectedNodes().get(0);
final TypeDeclaration literalClass = AstUtil.parent(TypeDeclaration.class, literal);
final ASTRewrite rewrite = ASTRewrite.create(literalClass.getAST());
String name = (String) parameters.get(Parameters.PARAMETER_CONSTANT_NAME).getValue();
String value = literal.getToken();
if (!existingConstantExists(literalClass, name)) {
createConstant(literalClass, rewrite, name, value);
}
replaceMagicNumberWithConstant(literal, rewrite, name);
return buildSolution(literalClass, change);
}
static void createConstant(final TypeDeclaration literalClass, ASTRewrite rewrite,
final String name,
final String value) {
AST ast = literalClass.getAST();
final ListRewrite listRewrite = rewrite.getListRewrite(
literalClass,
TypeDeclaration.BODY_DECLARATIONS_PROPERTY
);
final VariableDeclarationFragment variable = ast.newVariableDeclarationFragment();
variable.setName(ast.newSimpleName(name));
variable.setInitializer(ast.newNumberLiteral(value));
final FieldDeclaration field = ast.newFieldDeclaration(variable);
field.setType(ast.newPrimitiveType(PrimitiveType.INT));
//noinspection unchecked
field.modifiers().addAll( // unchecked warning
ast.newModifiers(Modifier.PRIVATE | Modifier.STATIC | Modifier.FINAL)
);
listRewrite.insertFirst(field, null);
}
static void replaceMagicNumberWithConstant(final NumberLiteral literal,
final ASTRewrite rewrite,
final String name) {
SimpleName constantReference = literal.getAST().newSimpleName(name);
rewrite.replace(literal, constantReference, null);
}
SourceChange buildSolution(TypeDeclaration literalClass, SourceChange change){
final Source code = Source.from(literalClass);
change.getDeltas().add(change.createDelta(code));
return change;
}
private static boolean existingConstantExists(final TypeDeclaration literalClass, final
String name) {
final FieldDeclarationVisitor visitor = new FieldDeclarationVisitor();
literalClass.accept(visitor);
return visitor.hasFieldName(name);
}
}
}
|
stefankolb/work-core | source/class/core/testrunner/reporter/Html.js | /*
==================================================================================================
Core - JavaScript Foundation
Copyright 2012-2014 <NAME>
==================================================================================================
*/
"use strict";
/**
* Reporter which produces visual HTML output into the document.
*/
core.Class("core.testrunner.reporter.Html",
{
implement: [core.testrunner.reporter.IReporter],
/**
* @suites {core.testrunner.Suite[]} Array of suites to report for
*/
construct : function(suites)
{
var root = document.getElementById("reporter");
if (!root)
{
root = document.createElement("div");
root.id = "reporter";
document.body.appendChild(root);
}
var suitesTemplate =
core.template.Compiler.compile(
'<ul class="suites">' +
'{{#suites}}<li class="suite running" id="suite-{{id}}">' +
'<h3>{{caption}}' +
'<span class="running">running</span>' +
'<span class="result">' +
'<span class="passed">0</span>+' +
'<span class="failed">0</span>→' +
'<span class="total">{{total}}</span>' +
'</span>' +
'</h3>' +
'<ul class="tests">{{#tests}}' +
'<li class="test" id="test-{{id}}">' +
'<h4>{{title}}' +
'<span class="running">running</span>' +
'<span class="result">' +
'<span class="passed">0</span>+' +
'<span class="failed">0</span>→' +
'<span class="total">{{total}}</span>' +
'</span>' +
'</h4>' +
'</li>' +
'{{/tests}}</ul>' +
'</li>{{/suites}}' +
'</ul>');
var suitesData =
{
suites : suites.map(function(suite)
{
return {
id : suite.getId(),
caption : suite.getCaption(),
total : suite.getTests().length,
tests : suite.getTests().map(function(test)
{
return {
id : test.getId(),
total : test.getTotalCount(),
title : test.getTitle()
};
})
};
})
};
root.innerHTML = suitesTemplate.render(suitesData);
if (typeof console == "object") {
this.__consoleReporter = new core.testrunner.reporter.Console(suites);
}
},
members :
{
// interface implementation
start : function() {
},
// interface implementation
finished : function(successfully) {
},
// interface implementation
suiteStarted : function(suite)
{
var li = document.getElementById("suite-" + suite.getId());
core.bom.ClassName.add(li, "running");
li.scrollIntoView();
},
// interface implementation
suiteFinished : function(suite)
{
var li = document.getElementById("suite-" + suite.getId());
core.bom.ClassName.remove(li, "running");
if (suite.wasSuccessful()) {
core.bom.ClassName.add(li, "successful");
} else {
core.bom.ClassName.add(li, "failed");
}
var tests = suite.getTests();
var failed = 0;
var passed = 0;
for (var i=0, l=tests.length; i<l; i++) {
tests[i].wasSuccessful() ? passed++ : failed++;
}
li.querySelector(".result .passed").innerHTML = passed;
li.querySelector(".result .failed").innerHTML = failed;
},
// interface implementation
testStarted : function(test)
{
var li = document.getElementById("test-" + test.getId());
core.bom.ClassName.add(li, "running");
},
// interface implementation
testFinished : function(test)
{
var li = document.getElementById("test-" + test.getId());
core.bom.ClassName.remove(li, "running");
if (test.wasSuccessful()) {
core.bom.ClassName.add(li, "successful");
} else {
core.bom.ClassName.add(li, "failed");
}
var assertions = test.getAssertions();
var failed = 0;
var passed = 0;
for (var i=0, l=assertions.length; i<l; i++) {
assertions[i].passed ? passed++ : failed++;
}
li.querySelector(".result .passed").innerHTML = passed;
li.querySelector(".result .failed").innerHTML = failed;
// Be sure that total number is correct
li.querySelector(".result .total").innerHTML = test.getTotalCount();
// Forward to console reporter for details
if (!test.wasSuccessful() && this.__consoleReporter) {
this.__consoleReporter.testFinished(test);
}
}
}
});
if (jasy.Env.isSet("runtime", "browser"))
{
/** #asset(core/testrunner/index.css) */
core.io.StyleSheet.load(jasy.Asset.toUri("core/testrunner/index.css"));
} |
zhuxinkai/python3-book-practice | beginning-python-3ed-master/Chapter15/listing15-6.py | #!/usr/bin/env python
import cgi
form = cgi.FieldStorage()
name = form.getvalue('name', 'world')
print('Content-type: text/plain\n')
print('Hello, {}!'.format(name)) |
splhack/loam | tests/megawing/spartan6/ram/ram32.py | import magma as m
from mantle.xilinx.spartan6.RAM import RAM32
from loam.boards.papiliopro import PapilioPro
from loam.shields.megawing import MegaWing
megawing = MegaWing(PapilioPro)
megawing.Clock.on()
megawing.Switch.on(8)
megawing.LED.on(1)
main = megawing.main()
ram = RAM32(16*[0,1])
m.wire(main.SWITCH[:5], ram.A)
m.wire(main.SWITCH[6], ram.I)
m.wire(main.SWITCH[7], ram.WE)
m.wire(ram.O, main.LED)
|
axs1088/EMRMS | src/main/java/edu/psu/sweng500/emrms/util/PersonPatientUtils.java | package edu.psu.sweng500.emrms.util;
import edu.psu.sweng500.emrms.mappers.PatientDemographicsMapper;
import edu.psu.sweng500.emrms.model.HName;
import edu.psu.sweng500.emrms.model.HPatient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service("personPatientUtils")
public class PersonPatientUtils {
@Autowired
private PatientDemographicsMapper patientDemographicsMapper;
public String getPatientName (int patientObjectID) {
HPatient patient = patientDemographicsMapper.getPatientDetails(patientObjectID);
int personId = patient.getPersonId();
HName personName = patientDemographicsMapper.getPersonName(personId);
String patientLastName = personName.getLastName();
String patientFirstName = personName.getFirstName();
String patientMiddleName = personName.getMiddleName();
String patientName = patientLastName + ", " + patientFirstName + " " + patientMiddleName;
return patientName;
}
public String getPersonName (int personId) {
HName personName = patientDemographicsMapper.getPersonName(personId);
String patientLastName = personName.getLastName();
String patientFirstName = personName.getFirstName();
String patientMiddleName = personName.getMiddleName();
String patientName = patientLastName + ", " + patientFirstName + " " + patientMiddleName;
return patientName;
}
}
|
EricVanEldik/openui5 | src/sap.ui.webc.common/src/sap/ui/webc/common/thirdparty/icons/v4/photo-voltaic.js | sap.ui.define(['sap/ui/webc/common/thirdparty/base/asset-registries/Icons'], function (Icons) { 'use strict';
const name = "photo-voltaic";
const pathData = "M152 0v52h-16V0h16zm88 37l12 11-37 37q-5-6-11-11zM37 48l11-11 37 37q-4 2-6.5 5T73 85zm27 88q4-29 23.5-48.5T136 64h16q35 4 54 30 15 16 18 42v16q-4 29-23.5 48.5T152 224h-16q-25-3-42-18-25-20-30-54v-16zm32 8q0 7 1 8 3 19 19 32 9 6 20 7 1 1 8 1t8-1q15-2 26-13t13-26q1-1 1-8t-1-8q-1-11-7-20-13-16-32-19-1-1-8-1t-8 1q-15 2-26 13t-13 26q-1 1-1 8zm-44-8v16H0v-16h52zm184 0h52v16h-52q1-1 1-8t-1-8zm-65 286l250-251q5-5 11-5t11 5q6 6 6 12 0 5-6 11L193 444q-5 5-11 5-3 0-11-5-5-6-5-11 0-6 5-11zm44-218l37 37-12 11-36-37q6-5 11-11zM37 241l36-37q3 3 5.5 6t6.5 5l-37 37zm188 239l255-254q13 0 22.5 9t9.5 23v222q0 14-9.5 23t-22.5 9H257q-14 0-23-9t-9-23zm-73-243v51h-16v-51h16zm328 243V271L270 480h210z";
const ltr = false;
const collection = "SAP-icons";
const packageName = "@ui5/webcomponents-icons";
Icons.registerIcon(name, { pathData, ltr, collection, packageName });
var pathDataV5 = { pathData };
return pathDataV5;
});
|
sixin-zh/kymatio_wph | example/cartoond/test_mean_bump_chunkid.py | # TEST ON GPU
#import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import scipy.optimize as opt
import scipy.io as sio
import torch
from torch.autograd import Variable, grad
from time import time
import gc
#---- create image without/with marks----#
size=256
# --- Dirac example---#
data = sio.loadmat('./example/cartoond/demo_toy7d_N' + str(size) + '.mat')
im = data['imgs']
im = torch.tensor(im, dtype=torch.float).unsqueeze(0).unsqueeze(0) # .cuda()
recim = torch.load('./results/test_rec_bump_chunkid_lbfgs_gpu_N256_dj1_restart.pt')
# Parameters for transforms
J = 8
L = 8
M, N = im.shape[-2], im.shape[-1]
delta_j = 1
delta_l = L/2
delta_k = 1
nb_chunks = 50
# kymatio scattering
from kymatio.phaseharmonics2d.phase_harmonics_k_bump_chunkid \
import PhaseHarmonics2d
for chunk_id in range(nb_chunks):
wph_op = PhaseHarmonics2d(M, N, J, L, delta_j, delta_l, delta_k, nb_chunks, chunk_id)
Sim = wph_op.compute_mean(im)
Srec = wph_op.compute_mean(recim)
plt.figure()
S1 = Sim[1,:,:,:,:,:,0].squeeze().numpy()
S2 = Srec[1,:,:,:,:,:,0].squeeze().numpy()
plt.plot(S1)
plt.plot((S2-S1))
plt.show()
|
sean5470/panda3d | direct/src/interval/cConstraintInterval.h | <filename>direct/src/interval/cConstraintInterval.h
/**
* PANDA 3D SOFTWARE
* Copyright (c) Carnegie Mellon University. All rights reserved.
*
* All use of this software is subject to the terms of the revised BSD
* license. You should have received a copy of this license along
* with this source code in a file named "LICENSE."
*
* @file cConstraintInterval.h
* @author pratt
* @date 2006-09-29
*/
#ifndef CCONSTRAINTINTERVAL_H
#define CCONSTRAINTINTERVAL_H
#include "directbase.h"
#include "cInterval.h"
/**
* The base class for a family of intervals that constrain some property to a
* value over time.
*/
class EXPCL_DIRECT_INTERVAL CConstraintInterval : public CInterval {
PUBLISHED:
bool bogus_variable;
public:
CConstraintInterval(const string &name, double duration);
public:
static TypeHandle get_class_type() {
return _type_handle;
}
static void init_type() {
CInterval::init_type();
register_type(_type_handle, "CConstraintInterval",
CInterval::get_class_type());
}
virtual TypeHandle get_type() const {
return get_class_type();
}
virtual TypeHandle force_init_type() {init_type(); return get_class_type();}
private:
static TypeHandle _type_handle;
};
#include "cConstraintInterval.I"
#endif
|
AndreasFagschlunger/o2xfs-xfs-api | src/test/java/at/o2xfs/xfs/api/UndeliverableMessageTest.java | <filename>src/test/java/at/o2xfs/xfs/api/UndeliverableMessageTest.java
package at.o2xfs.xfs.api;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.io.IOException;
import org.junit.jupiter.api.Test;
import at.o2xfs.common.Hex;
import at.o2xfs.memory.core.Address;
import at.o2xfs.memory.core.util.ByteArrayMemoryGenerator;
import at.o2xfs.memory.core.util.ByteArrayMemorySystem;
import at.o2xfs.memory.databind.MemoryMapper;
import at.o2xfs.xfs.ptr.PtrMessage;
class UndeliverableMessageTest {
private MemoryMapper memoryMapper;
private ByteArrayMemorySystem memorySystem;
public UndeliverableMessageTest() {
memoryMapper = new MemoryMapper();
memorySystem = new ByteArrayMemorySystem();
}
@Test
final void test() throws IOException {
UndeliverableMessage expected = new UndeliverableMessage.Builder()
.logicalName("PASSBOOKPTR3")
.workstationName("ATM_XYZ")
.appId("APP_XYZ")
.description(Hex.decode("CAFEBABE"))
.msg(PtrMessage.SRVE_PTR_MEDIATAKEN.getValue())
.wfsResult(new WfsResult.Builder()
.requestId(RequestId.of(123L))
.serviceId(ServiceId.of(1))
.eventId(XfsMessage.EXECUTE_EVENT.getValue())
.build())
.build();
Address address;
try (ByteArrayMemoryGenerator gen = memorySystem.createGenerator()) {
memoryMapper.write(gen, expected);
address = gen.allocate();
}
UndeliverableMessage actual = memoryMapper.read(memorySystem.dereference(address), UndeliverableMessage.class);
assertEquals(expected, actual);
}
}
|
Nelsondmondragon/challenge-backend | src/test/java/com/nedacort/challengespringbackend/domain/service/UserDetailServiceTest.java | package com.nedacort.challengespringbackend.domain.service;
import com.nedacort.challengespringbackend.domain.UserDto;
import com.nedacort.challengespringbackend.domain.repository.UserDtoRepository;
import com.nedacort.challengespringbackend.email.EmailSender;
import com.nedacort.challengespringbackend.persistence.UserRepository;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.*;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import java.util.Optional;
import static org.mockito.Mockito.verify;
@ExtendWith(MockitoExtension.class)
class UserDetailServiceTest {
@Mock
private EmailSender emailSender;
@Mock
private BCryptPasswordEncoder bCryptPasswordEncoder;
@Mock
private UserDtoRepository userDtoRepository;
@InjectMocks
private UserDetailService userDetailService;
@Captor
private ArgumentCaptor<UserDto> argumentCaptor;
@Test
void load_user_by_username() {
Mockito.when(userDtoRepository.getByUsername("nedacort"))
.thenReturn(Optional.of(
UserDto.builder()
.id(1)
.username("nedacort")
.email("<EMAIL>")
.password("<PASSWORD>")
.enable(true)
.locked(false)
.build()
));
userDetailService.loadUserByUsername("nedacort");
verify(userDtoRepository).getByUsername("nedacort");
}
@Test
void save() {
UserDto userDto = UserDto.builder()
.id(1)
.username("nedacort")
.email("<EMAIL>")
.password("<PASSWORD>")
.enable(true)
.locked(false)
.build();
userDetailService.save(userDto);
argumentCaptor = ArgumentCaptor.forClass(UserDto.class);
verify(userDtoRepository).save(argumentCaptor.capture());
Assertions.assertThat(userDto).isEqualTo(argumentCaptor.getValue());
}
} |
ptahchiev/jackson-dataformats-text | properties/src/test/java/com/fasterxml/jackson/dataformat/javaprop/MapParsingTest.java | package com.fasterxml.jackson.dataformat.javaprop;
import java.util.Map;
import com.fasterxml.jackson.databind.ObjectMapper;
public class MapParsingTest extends ModuleTestBase
{
static class MapWrapper {
public Map<String,String> map;
}
private final ObjectMapper MAPPER = mapperForProps();
/*
/**********************************************************************
/* Test methods
/**********************************************************************
*/
public void testMapWithBranch() throws Exception
{
// basically "extra" branch should become as first element, and
// after that ordering by numeric value
final String INPUT = "map=first\n"
+"map.b=second\n"
+"map.xyz=third\n"
;
MapWrapper w = MAPPER.readValue(INPUT, MapWrapper.class);
assertNotNull(w.map);
assertEquals(3, w.map.size());
assertEquals("first", w.map.get(""));
assertEquals("second", w.map.get("b"));
assertEquals("third", w.map.get("xyz"));
}
}
|
OfficialWiddin/pokeraidbot | src/main/java/pokeraidbot/jda/StartUpEventListener.java | <reponame>OfficialWiddin/pokeraidbot
package pokeraidbot.jda;
import main.BotServerMain;
import net.dv8tion.jda.core.entities.Guild;
import net.dv8tion.jda.core.entities.MessageChannel;
import net.dv8tion.jda.core.entities.TextChannel;
import net.dv8tion.jda.core.events.Event;
import net.dv8tion.jda.core.events.ReadyEvent;
import net.dv8tion.jda.core.exceptions.ErrorResponseException;
import net.dv8tion.jda.core.hooks.EventListener;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import pokeraidbot.BotService;
import pokeraidbot.commands.NewRaidGroupCommand;
import pokeraidbot.commands.RaidOverviewCommand;
import pokeraidbot.domain.config.ClockService;
import pokeraidbot.domain.config.LocaleService;
import pokeraidbot.domain.errors.UserMessedUpException;
import pokeraidbot.domain.gym.GymRepository;
import pokeraidbot.domain.pokemon.PokemonRepository;
import pokeraidbot.domain.raid.PokemonRaidStrategyService;
import pokeraidbot.domain.raid.Raid;
import pokeraidbot.domain.raid.RaidRepository;
import pokeraidbot.domain.raid.signup.EmoticonSignUpMessageListener;
import pokeraidbot.infrastructure.jpa.config.Config;
import pokeraidbot.infrastructure.jpa.config.ServerConfigRepository;
import pokeraidbot.infrastructure.jpa.raid.RaidGroup;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;
public class StartUpEventListener implements EventListener {
private static final Logger LOGGER = LoggerFactory.getLogger(StartUpEventListener.class);
private ServerConfigRepository serverConfigRepository;
private final RaidRepository raidRepository;
private final LocaleService localeService;
private final ClockService clockService;
private final ExecutorService executorService;
private final BotService botService;
private final GymRepository gymRepository;
private final PokemonRepository pokemonRepository;
private final PokemonRaidStrategyService pokemonRaidStrategyService;
public StartUpEventListener(ServerConfigRepository serverConfigRepository,
RaidRepository raidRepository, LocaleService localeService,
ClockService clockService, ExecutorService executorService, BotService botService,
GymRepository gymRepository, PokemonRepository pokemonRepository,
PokemonRaidStrategyService pokemonRaidStrategyService) {
this.serverConfigRepository = serverConfigRepository;
this.raidRepository = raidRepository;
this.localeService = localeService;
this.clockService = clockService;
this.executorService = executorService;
this.botService = botService;
this.gymRepository = gymRepository;
this.pokemonRepository = pokemonRepository;
this.pokemonRaidStrategyService = pokemonRaidStrategyService;
}
@Override
public void onEvent(Event event) {
if (event instanceof ReadyEvent) {
final List<Guild> guilds = event.getJDA().getGuilds();
for (Guild guild : guilds) {
Config config = serverConfigRepository.getConfigForServer(guild.getName().trim().toLowerCase());
if (config != null) {
final String messageId = config.getOverviewMessageId();
if (!StringUtils.isEmpty(messageId)) {
for (MessageChannel channel : guild.getTextChannels()) {
if (attachToOverviewMessageIfExists(guild, config, messageId, channel,
pokemonRaidStrategyService)) {
break;
} else {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Didn't find overview in channel " + channel.getName());
}
}
}
}
final List<RaidGroup> groupsForServer = raidRepository.getGroupsForServer(config.getServer());
for (RaidGroup group : groupsForServer) {
attachToGroupMessage(guild, config, group);
}
}
}
}
}
private boolean attachToGroupMessage(Guild guild, Config config,
RaidGroup raidGroup) {
MessageChannel channel = null;
try {
final List<TextChannel> textChannels = guild.getTextChannels();
for (TextChannel textChannel : textChannels) {
if (textChannel.getName().equalsIgnoreCase(raidGroup.getChannel())) {
channel = textChannel;
break;
}
}
final Locale locale = config.getLocale();
Raid raid = raidRepository.getById(raidGroup.getRaidId());
final EmoticonSignUpMessageListener emoticonSignUpMessageListener =
new EmoticonSignUpMessageListener(botService, localeService, serverConfigRepository,
raidRepository, pokemonRepository, gymRepository, raid.getId(), raidGroup.getStartsAt(),
raidGroup.getCreatorId());
emoticonSignUpMessageListener.setEmoteMessageId(raidGroup.getEmoteMessageId());
emoticonSignUpMessageListener.setInfoMessageId(raidGroup.getInfoMessageId());
final int delayTime = raid.isExRaid() ? 1 : 15;
final TimeUnit delayTimeUnit = raid.isExRaid() ? TimeUnit.MINUTES : TimeUnit.SECONDS;
final Callable<Boolean> groupEditTask =
NewRaidGroupCommand.getMessageRefreshingTaskToSchedule(channel, raid,
emoticonSignUpMessageListener,
raidGroup.getInfoMessageId(), locale, raidRepository,
localeService,
clockService, executorService, botService, delayTimeUnit, delayTime, raidGroup.getId());
executorService.submit(groupEditTask);
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Found group message for raid " + raid + " in channel " +
(channel == null ? "N/A" : channel.getName()) +
" (server " + guild.getName() + "). Attaching to it.");
}
return true;
} catch (UserMessedUpException e) {
if (channel != null)
channel.sendMessage(e.getMessage()).queue(m -> {
m.delete().queueAfter(BotServerMain.timeToRemoveFeedbackInSeconds, TimeUnit.SECONDS);
});
} catch (ErrorResponseException e) {
// We couldn't find the message in this channel or had permission issues, ignore
LOGGER.info("Caught exception during startup: " + e.getMessage());
LOGGER.warn("Cleaning up raidgroup...");
cleanUpRaidGroup(raidGroup);
LOGGER.debug("Stacktrace:", e);
} catch (Throwable e) {
LOGGER.warn("Cleaning up raidgroup due to exception: " + e.getMessage());
cleanUpRaidGroup(raidGroup);
}
return false;
}
private void cleanUpRaidGroup(RaidGroup raidGroup) {
try {
RaidGroup deletedRaidGroup = raidRepository.deleteGroupInNewTransaction(raidGroup.getRaidId(), raidGroup.getId());
if (deletedRaidGroup != null) {
LOGGER.debug("Cleaned up raid group: " + deletedRaidGroup);
} else {
LOGGER.debug("Didn't delete raid group, it was apparantly deleted already.");
}
} catch (Throwable t) {
// Ignore any other error and try the other server channels
LOGGER.warn("Exception when cleaning up group " + raidGroup + ": " + t.getMessage());
}
}
private boolean attachToOverviewMessageIfExists(Guild guild, Config config, String messageId,
MessageChannel channel, PokemonRaidStrategyService raidStrategyService) {
try {
if (channel.getMessageById(messageId).complete() != null) {
final Locale locale = config.getLocale();
final Callable<Boolean> overviewTask =
RaidOverviewCommand.getMessageRefreshingTaskToSchedule(
null, config.getServer(), messageId, localeService, locale, serverConfigRepository,
raidRepository, clockService, channel,
executorService, raidStrategyService);
executorService.submit(overviewTask);
LOGGER.info("Found overview message for channel " + channel.getName() +
" (server " + guild.getName() + "). Attaching to it.");
return true;
}
} catch (UserMessedUpException e) {
LOGGER.warn("Could not attach to message due to an error: " + e.getMessage());
} catch (ErrorResponseException e) {
// We couldn't find the message in this channel or had permission issues, ignore
} catch (Throwable e) {
// Ignore any other error and try the other server channels
}
return false;
}
}
|
yslai/AliPhysics | PWGCF/FEMTOSCOPY/FemtoDream/AliFemtoDreamv0Cuts.cxx | /*
* AliFemtoDreamv0Cuts.cxx
*
* Created on: Dec 12, 2017
* Author: gu74req
*/
#include "AliFemtoDreamv0Cuts.h"
#include "TDatabasePDG.h"
#include "AliLog.h"
ClassImp(AliFemtoDreamv0Cuts)
AliFemtoDreamv0Cuts::AliFemtoDreamv0Cuts()
: fHistList(),
fMCHistList(),
fMCHist(nullptr),
fHist(nullptr),
fPosCuts(0),
fNegCuts(0),
fMinimalBooking(false),
fMCData(false),
fCPAPlots(false),
fContribSplitting(false),
fRunNumberQA(false),
fMinRunNumber(0),
fMaxRunNumber(0),
fCutOnFlyStatus(false),
fOnFlyStatus(false),
fCutCharge(false),
fCharge(0),
fCutPt(false),
fpTmin(0),
fpTmax(0),
fKaonRejection(false),
fKaonRejLow(0),
fKaonRejUp(0),
fCutDecayVtxXYZ(false),
fMaxDecayVtxXYZ(0),
fCutTransRadius(false),
fMinTransRadius(0),
fMaxTransRadius(0),
fCutMinDCADaugPrimVtx(false),
fMinDCADaugToPrimVtx(0),
fCutMaxDCADaugToDecayVtx(false),
fMaxDCADaugToDecayVtx(0),
fCutCPA(false),
fMinCPA(0),
fCutInvMass(false),
fInvMassCutWidth(0),
fAxisMinMass(0),
fAxisMaxMass(1),
fNumberXBins(1),
fPDGv0(0),
fPDGDaugP(0),
fPDGDaugN(0) {
}
AliFemtoDreamv0Cuts::AliFemtoDreamv0Cuts(const AliFemtoDreamv0Cuts& cuts)
: fHistList(cuts.fHistList),
fMCHistList(cuts.fMCHistList),
fMCHist(cuts.fMCHist),
fHist(cuts.fHist),
fPosCuts(cuts.fPosCuts),
fNegCuts(cuts.fNegCuts),
fMinimalBooking(cuts.fMinimalBooking),
fMCData(cuts.fMCData),
fCPAPlots(cuts.fCPAPlots),
fContribSplitting(cuts.fContribSplitting),
fRunNumberQA(cuts.fRunNumberQA),
fMinRunNumber(cuts.fMinRunNumber),
fMaxRunNumber(cuts.fMaxRunNumber),
fCutOnFlyStatus(cuts.fCutOnFlyStatus),
fOnFlyStatus(cuts.fOnFlyStatus),
fCutCharge(cuts.fCutCharge),
fCharge(cuts.fCharge),
fCutPt(cuts.fCutPt),
fpTmin(cuts.fpTmin),
fpTmax(cuts.fpTmax),
fKaonRejection(cuts.fKaonRejection),
fKaonRejLow(cuts.fKaonRejLow),
fKaonRejUp(cuts.fKaonRejUp),
fCutDecayVtxXYZ(cuts.fCutDecayVtxXYZ),
fMaxDecayVtxXYZ(cuts.fMaxDecayVtxXYZ),
fCutTransRadius(cuts.fCutTransRadius),
fMinTransRadius(cuts.fMinTransRadius),
fMaxTransRadius(cuts.fMaxTransRadius),
fCutMinDCADaugPrimVtx(cuts.fCutMinDCADaugPrimVtx),
fMinDCADaugToPrimVtx(cuts.fMinDCADaugToPrimVtx),
fCutMaxDCADaugToDecayVtx(cuts.fCutMaxDCADaugToDecayVtx),
fMaxDCADaugToDecayVtx(cuts.fMaxDCADaugToDecayVtx),
fCutCPA(cuts.fCutCPA),
fMinCPA(cuts.fMinCPA),
fCutInvMass(cuts.fCutInvMass),
fInvMassCutWidth(cuts.fInvMassCutWidth),
fAxisMinMass(cuts.fAxisMinMass),
fAxisMaxMass(cuts.fAxisMaxMass),
fNumberXBins(cuts.fNumberXBins),
fPDGv0(cuts.fPDGv0),
fPDGDaugP(cuts.fPDGDaugP),
fPDGDaugN(cuts.fPDGDaugN) {
}
AliFemtoDreamv0Cuts& AliFemtoDreamv0Cuts::operator=(
const AliFemtoDreamv0Cuts& cuts) {
if (this != &cuts) {
this->fHistList = cuts.fHistList;
this->fMCHistList = cuts.fMCHistList;
this->fMCHist = cuts.fMCHist;
this->fHist = cuts.fHist;
this->fPosCuts = cuts.fPosCuts;
this->fNegCuts = cuts.fNegCuts;
this->fMinimalBooking = cuts.fMinimalBooking;
this->fMCData = cuts.fMCData;
this->fCPAPlots = cuts.fCPAPlots;
this->fContribSplitting = cuts.fContribSplitting;
this->fRunNumberQA = cuts.fRunNumberQA;
this->fMinRunNumber = cuts.fMinRunNumber;
this->fMaxRunNumber = cuts.fMaxRunNumber;
this->fCutOnFlyStatus = cuts.fCutOnFlyStatus;
this->fOnFlyStatus = cuts.fOnFlyStatus;
this->fCutCharge = cuts.fCutCharge;
this->fCharge = cuts.fCharge;
this->fCutPt = cuts.fCutPt;
this->fpTmin = cuts.fpTmin;
this->fpTmax = cuts.fpTmax;
this->fKaonRejection = cuts.fKaonRejection;
this->fKaonRejLow = cuts.fKaonRejLow;
this->fKaonRejUp = cuts.fKaonRejUp;
this->fCutDecayVtxXYZ = cuts.fCutDecayVtxXYZ;
this->fMaxDecayVtxXYZ = cuts.fMaxDecayVtxXYZ;
this->fCutTransRadius = cuts.fCutTransRadius;
this->fMinTransRadius = cuts.fMinTransRadius;
this->fMaxTransRadius = cuts.fMaxTransRadius;
this->fCutMinDCADaugPrimVtx = cuts.fCutMinDCADaugPrimVtx;
this->fMinDCADaugToPrimVtx = cuts.fMinDCADaugToPrimVtx;
this->fCutMaxDCADaugToDecayVtx = cuts.fCutMaxDCADaugToDecayVtx;
this->fMaxDCADaugToDecayVtx = cuts.fMaxDCADaugToDecayVtx;
this->fCutCPA = cuts.fCutCPA;
this->fMinCPA = cuts.fMinCPA;
this->fCutInvMass = cuts.fCutInvMass;
this->fInvMassCutWidth = cuts.fInvMassCutWidth;
this->fAxisMinMass = cuts.fAxisMinMass;
this->fAxisMaxMass = cuts.fAxisMaxMass;
this->fNumberXBins = cuts.fNumberXBins;
this->fPDGv0 = cuts.fPDGv0;
this->fPDGDaugP = cuts.fPDGDaugP;
this->fPDGDaugN = cuts.fPDGDaugN;
}
return *this;
}
AliFemtoDreamv0Cuts::~AliFemtoDreamv0Cuts() {
if (fHist) {
delete fHist;
}
// if (fMCHist) {
// delete fMCHist;
// }
}
AliFemtoDreamv0Cuts* AliFemtoDreamv0Cuts::LambdaCuts(bool isMC, bool CPAPlots,
bool SplitContrib) {
AliFemtoDreamv0Cuts *LambdaCuts = new AliFemtoDreamv0Cuts();
LambdaCuts->SetIsMonteCarlo(isMC);
LambdaCuts->SetPlotCPADist(CPAPlots);
LambdaCuts->SetPlotContrib(SplitContrib);
LambdaCuts->SetCheckOnFlyStatus(false); //online = kTRUE, offline = kFALSE
LambdaCuts->SetCutCharge(0);
LambdaCuts->SetPtRange(0.3, 999.);
LambdaCuts->SetKaonRejection(0.48, 0.515);
LambdaCuts->SetCutMaxDecayVtx(100);
LambdaCuts->SetCutTransverseRadius(0.2, 100);
LambdaCuts->SetCutDCADaugToPrimVtx(0.05);
LambdaCuts->SetCutDCADaugTov0Vtx(1.5);
LambdaCuts->SetCutCPA(0.99);
LambdaCuts->SetCutInvMass(0.004);
LambdaCuts->SetAxisInvMassPlots(400, 1.0, 1.2);
return LambdaCuts;
}
bool AliFemtoDreamv0Cuts::isSelected(AliFemtoDreamv0 *v0) {
bool pass = true;
if (!v0->IsSet()) {
pass = false;
} else {
if (!fMinimalBooking)
fHist->FillTrackCounter(0);
}
if (pass) {
if (!DaughtersPassCuts(v0)) {
pass = false;
}
}
if (pass) {
if (!MotherPassCuts(v0)) {
pass = false;
}
}
if (pass) {
if (fKaonRejection && !RejectAsKaon(v0)) {
pass = false;
}
}
if (pass) {
if (!CPAandMassCuts(v0)) {
pass = false;
}
}
v0->SetUse(pass);
BookQA(v0);
if (!fMinimalBooking) {
if (fMCData) {
BookMC(v0);
}
}
return pass;
}
bool AliFemtoDreamv0Cuts::DaughtersPassCuts(AliFemtoDreamv0 *v0) {
bool pass = true;
bool passD1 = true;
bool passD2 = true;
if (!v0->GetHasDaughters()) {
pass = false;
} else {
if (!fMinimalBooking)
fHist->FillTrackCounter(1);
}
if (pass) {
if (v0->GetCharge().at(1) < 0 && v0->GetCharge().at(2) > 0) {
//at 1: Negative daughter, at 2: Positive Daughter should be the way it
//was set, but sometimes it it stored in the wrong way
if (!fMinimalBooking)
fHist->FillTrackCounter(13);
v0->Setv0Mass(CalculateInvMass(v0, fPDGDaugP, fPDGDaugN));
passD1 = fNegCuts->isSelected(v0->GetNegDaughter());
passD2 = fPosCuts->isSelected(v0->GetPosDaughter());
if (passD1 && passD2) {
if (!fMinimalBooking)
fHist->FillTrackCounter(14);
}
} else {
if (!fMinimalBooking)
fHist->FillTrackCounter(15);
v0->Setv0Mass(CalculateInvMass(v0, fPDGDaugN, fPDGDaugP));
passD1 = fPosCuts->isSelected(v0->GetNegDaughter());
passD2 = fNegCuts->isSelected(v0->GetPosDaughter());
if (passD1 && passD2) {
if (!fMinimalBooking)
fHist->FillTrackCounter(16);
}
}
if (!(passD1 && passD2)) {
pass = false;
} else {
if (!fMinimalBooking)
fHist->FillTrackCounter(2);
}
}
pass = passD1 && passD2;
return pass;
}
bool AliFemtoDreamv0Cuts::MotherPassCuts(AliFemtoDreamv0 *v0) {
//all topological and kinematic cuts on the mother except for the CPA, this
//will be filled later, in case also the CPA distributions are required.
//Special CPA checks impelemented in the RejKaons later, to still ensure
//proper Invariant Mass Plots.
bool pass = true;
if (fCutOnFlyStatus) {
if (!(v0->GetOnlinev0() == fOnFlyStatus)) {
pass = false;
} else {
if (!fMinimalBooking)
fHist->FillTrackCounter(3);
}
}
if (pass && fCutCharge) {
if (v0->GetCharge().at(0) != fCharge) {
pass = false;
} else {
if (!fMinimalBooking)
fHist->FillTrackCounter(4);
}
}
if (pass && fCutPt) {
if ((v0->GetPt() < fpTmin) || (v0->GetPt() > fpTmax)) {
pass = false;
} else {
if (!fMinimalBooking)
fHist->FillTrackCounter(5);
}
}
if (pass && fCutDecayVtxXYZ) {
if ((v0->GetDCAv0Vtx(0) > fMaxDecayVtxXYZ)
|| (v0->GetDCAv0Vtx(1) > fMaxDecayVtxXYZ)
|| (v0->GetDCAv0Vtx(2) > fMaxDecayVtxXYZ)) {
pass = false;
} else {
if (!fMinimalBooking)
fHist->FillTrackCounter(6);
}
}
if (pass && fCutTransRadius) {
if ((v0->GetTransverseRadius() < fMinTransRadius)
|| (v0->GetTransverseRadius() > fMaxTransRadius)) {
pass = false;
} else {
if (!fMinimalBooking)
fHist->FillTrackCounter(7);
}
}
if (pass && fCutMinDCADaugPrimVtx) {
if ((v0->GetDCADaugPosVtx() < fMinDCADaugToPrimVtx)
|| (v0->GetDCADaugNegVtx() < fMinDCADaugToPrimVtx)) {
pass = false;
} else {
if (!fMinimalBooking)
fHist->FillTrackCounter(8);
}
}
if (pass && fCutMaxDCADaugToDecayVtx) {
if (v0->GetDaugDCA() > fMaxDCADaugToDecayVtx) {
pass = false;
} else {
if (!fMinimalBooking)
fHist->FillTrackCounter(9);
}
}
return pass;
}
bool AliFemtoDreamv0Cuts::RejectAsKaon(AliFemtoDreamv0 *v0) {
bool pass = true;
bool cpaPass = true;
if (v0->GetCPA() < fMinCPA) {
cpaPass = false;
}
float massKaon = CalculateInvMass(v0, 211, 211);
if (cpaPass) {
if (!fMinimalBooking)
fHist->FillInvMassBefKaonRej(v0->Getv0Mass());
if (!fMinimalBooking)
fHist->FillInvMassKaon(massKaon);
}
if (fKaonRejLow < massKaon && massKaon < fKaonRejUp) {
pass = false;
} else {
if (!fMinimalBooking)
fHist->FillTrackCounter(10);
}
return pass;
}
bool AliFemtoDreamv0Cuts::CPAandMassCuts(AliFemtoDreamv0 *v0) {
//here we cut mass and cpa to fill the cpa distribution properly
bool cpaPass = true;
bool massPass = true;
if (fCutCPA && (v0->GetCPA() < fMinCPA)) {
cpaPass = false;
}
if (fCutInvMass) {
float massv0 = TDatabasePDG::Instance()->GetParticle(fPDGv0)->Mass();
if ((v0->Getv0Mass() < massv0 - fInvMassCutWidth)
|| (massv0 + fInvMassCutWidth < v0->Getv0Mass())) {
massPass = false;
}
}
//now with this information fill the histograms
if (cpaPass) {
fHist->FillInvMassPtBins(v0->GetPt(), v0->Getv0Mass());
if (!fMinimalBooking)
fHist->Fillv0MassDist(v0->Getv0Mass());
if (fRunNumberQA) {
fHist->FillInvMassPerRunNumber(v0->GetEvtNumber(), v0->Getv0Mass());
}
}
if (massPass && fCPAPlots && !fMinimalBooking) {
fHist->FillCPAPtBins(v0->GetPt(), v0->GetCPA(), v0->GetEventMultiplicity());
if (fMCData) {
fMCHist->FillMCCPAPtBins(v0->GetParticleOrigin(), v0->GetPt(),
v0->GetCPA(), v0->GetEventMultiplicity());
}
}
if (massPass) {
if (!fMinimalBooking)
fHist->FillTrackCounter(11);
}
if (massPass && cpaPass) {
if (!fMinimalBooking)
fHist->FillTrackCounter(12);
}
bool pass = massPass && cpaPass;
return pass;
}
void AliFemtoDreamv0Cuts::Init() {
//Cant be set externally cause else the lists don't exist. Needs to be changed in case
//it is needed
fPosCuts->SetMinimalBooking(fMinimalBooking);
fPosCuts->Init();
fNegCuts->SetMinimalBooking(fMinimalBooking);
fNegCuts->Init();
if (!fMinimalBooking) {
fHist = new AliFemtoDreamv0Hist(fNumberXBins, fAxisMinMass, fAxisMaxMass,
fCPAPlots, fRunNumberQA, fMinRunNumber,
fMaxRunNumber);
BookTrackCuts();
fHistList = new TList();
fHistList->SetOwner();
fHistList->SetName("v0Cuts");
fHistList->Add(fHist->GetHistList());
fPosCuts->SetName("PosCuts");
fHistList->Add(fPosCuts->GetQAHists());
fNegCuts->SetName("NegCuts");
fHistList->Add(fNegCuts->GetQAHists());
if (fMCData) {
fMCHist = new AliFemtoDreamv0MCHist(fNumberXBins, fAxisMinMass,
fAxisMaxMass, fContribSplitting,
fCPAPlots);
fMCHistList = new TList();
fMCHistList->SetOwner();
fMCHistList->SetName("v0MCCuts");
fMCHistList->Add(fMCHist->GetHistList());
fPosCuts->SetMCName("PosCuts");
fMCHistList->Add(fPosCuts->GetMCQAHists());
fNegCuts->SetMCName("NegCuts");
fMCHistList->Add(fNegCuts->GetMCQAHists());
}
} else {
fHist = new AliFemtoDreamv0Hist("MinimalBooking", fNumberXBins,
fAxisMinMass, fAxisMaxMass);
fHistList = new TList();
fHistList->SetOwner();
fHistList->SetName("v0Cuts");
fHistList->Add(fHist->GetHistList());
fPosCuts->SetName("PosCuts");
fHistList->Add(fPosCuts->GetQAHists());
fNegCuts->SetName("NegCuts");
fHistList->Add(fNegCuts->GetQAHists());
}
}
void AliFemtoDreamv0Cuts::BookQA(AliFemtoDreamv0 *v0) {
if (!fMinimalBooking) {
for (int i = 0; i < 2; ++i) {
if (i == 0 || (i == 1 && v0->UseParticle())) {
if (!v0->GetOnlinev0()) {
fHist->FillOnFlyStatus(i, 1);
} else if (v0->GetOnlinev0()) {
fHist->FillOnFlyStatus(i, 0);
}
fHist->FillpTCut(i, v0->GetPt());
fHist->FillPhi(i, v0->GetPhi().at(0));
fHist->FillEtaCut(i, v0->GetEta().at(0));
fHist->Fillv0DecayVtxXCut(i, v0->GetDCAv0Vtx(0));
fHist->Fillv0DecayVtxYCut(i, v0->GetDCAv0Vtx(1));
fHist->Fillv0DecayVtxZCut(i, v0->GetDCAv0Vtx(2));
fHist->FillTransverRadiusCut(i, v0->GetTransverseRadius());
fHist->FillDCAPosDaugToPrimVtxCut(i, v0->GetDCADaugPosVtx());
fHist->FillDCANegDaugToPrimVtxCut(i, v0->GetDCADaugNegVtx());
fHist->FillDCADaugTov0VtxCut(i, v0->GetDaugDCA());
fHist->FillCPACut(i, v0->GetCPA());
fHist->FillInvMass(i, v0->Getv0Mass());
}
}
}
v0->GetPosDaughter()->SetUse(v0->UseParticle());
v0->GetNegDaughter()->SetUse(v0->UseParticle());
fPosCuts->BookQA(v0->GetPosDaughter());
fNegCuts->BookQA(v0->GetNegDaughter());
}
void AliFemtoDreamv0Cuts::BookMC(AliFemtoDreamv0 *v0) {
if (!fMinimalBooking) {
float pT = v0->GetPt();
if (v0->GetHasDaughters()) {
float etaNegDaug = v0->GetEta().at(1);
float etaPosDaug = v0->GetEta().at(2);
if (v0->GetMCPDGCode() == fPDGv0) {
if (fpTmin < pT && pT < fpTmax) {
if (fPosCuts->GetEtaMin() < etaPosDaug
&& etaPosDaug < fPosCuts->GetEtaMax()) {
if (fNegCuts->GetEtaMin() < etaNegDaug
&& etaNegDaug < fNegCuts->GetEtaMax()) {
fMCHist->FillMCGen(pT);
}
}
}
}
}
if (v0->UseParticle()) {
fMCHist->FillMCIdent(pT);
AliFemtoDreamBasePart::PartOrigin tmpOrg = v0->GetParticleOrigin();
if (v0->GetMCPDGCode() == fPDGv0) {
fMCHist->FillMCCorr(pT);
if (tmpOrg == AliFemtoDreamBasePart::kPhysPrimary) {
fMCHist->FillMCPtResolution(v0->GetMCPt(), v0->GetPt());
fMCHist->FillMCThetaResolution(v0->GetMCTheta().at(0),
v0->GetTheta().at(0), v0->GetMCPt());
fMCHist->FillMCPhiResolution(v0->GetMCPhi().at(0), v0->GetPhi().at(0),
v0->GetMCPt());
}
} else {
v0->SetParticleOrigin(AliFemtoDreamBasePart::kContamination);
}
if (fContribSplitting) {
FillMCContributions(v0);
}
v0->GetPosDaughter()->SetParticleOrigin(v0->GetParticleOrigin());
v0->GetNegDaughter()->SetParticleOrigin(v0->GetParticleOrigin());
fPosCuts->BookMC(v0->GetPosDaughter());
fNegCuts->BookMC(v0->GetNegDaughter());
v0->SetParticleOrigin(tmpOrg);
fMCHist->FillMCMother(v0->GetPt(), v0->GetMotherPDG());
}
}
}
void AliFemtoDreamv0Cuts::FillMCContributions(AliFemtoDreamv0 *v0) {
if (!fMinimalBooking) {
Double_t pT = v0->GetPt();
Int_t iFill = -1;
switch (v0->GetParticleOrigin()) {
case AliFemtoDreamBasePart::kPhysPrimary:
fMCHist->FillMCPrimary(pT);
iFill = 0;
break;
case AliFemtoDreamBasePart::kWeak:
fMCHist->FillMCFeeddown(pT, TMath::Abs(v0->GetMotherWeak()));
iFill = 1;
break;
case AliFemtoDreamBasePart::kMaterial:
fMCHist->FillMCMaterial(pT);
iFill = 2;
break;
case AliFemtoDreamBasePart::kContamination:
fMCHist->FillMCCont(pT);
iFill = 3;
break;
case AliFemtoDreamBasePart::kFake:
fMCHist->FillMCCont(pT);
iFill = 3;
break;
default:
AliFatal("Type Not implemented");
break;
}
if (iFill != -1) {
fMCHist->FillMCpT(iFill, pT);
fMCHist->FillMCEta(iFill, v0->GetEta().at(0));
fMCHist->FillMCPhi(iFill, v0->GetPhi().at(0));
fMCHist->FillMCDCAVtxX(iFill, pT, v0->GetDCAv0Vtx(0));
fMCHist->FillMCDCAVtxY(iFill, pT, v0->GetDCAv0Vtx(1));
fMCHist->FillMCDCAVtxZ(iFill, pT, v0->GetDCAv0Vtx(2));
fMCHist->FillMCTransverseRadius(iFill, pT, v0->GetTransverseRadius());
fMCHist->FillMCDCAPosDaugPrimVtx(iFill, pT, v0->GetDCADaugPosVtx());
fMCHist->FillMCDCANegDaugPrimVtx(iFill, pT, v0->GetDCADaugNegVtx());
fMCHist->FillMCDCADaugVtx(iFill, pT, v0->GetDaugDCA());
fMCHist->FillMCCosPoint(iFill, pT, v0->GetCPA());
fMCHist->FillMCInvMass(iFill, v0->Getv0Mass());
} else {
std::cout << "this should not happen \n";
}
}
}
void AliFemtoDreamv0Cuts::BookTrackCuts() {
if (!fMinimalBooking) {
if (!fHist) {
AliFatal("No Histograms available");
}
if (fCutOnFlyStatus) {
fHist->FillConfig(0, 1);
}
if (fCutCharge) {
fHist->FillConfig(1, fCharge);
}
if (fCutPt) {
fHist->FillConfig(2, fpTmin);
fHist->FillConfig(3, fpTmax);
}
if (fKaonRejection) {
fHist->FillConfig(4, 1);
}
if (fCutDecayVtxXYZ) {
fHist->FillConfig(5, fMaxDecayVtxXYZ);
}
if (fCutTransRadius) {
fHist->FillConfig(6, fMinTransRadius);
fHist->FillConfig(7, fMaxTransRadius);
}
if (fCutMinDCADaugPrimVtx) {
fHist->FillConfig(8, fMinDCADaugToPrimVtx);
}
if (fCutMaxDCADaugToDecayVtx) {
fHist->FillConfig(9, fMaxDCADaugToDecayVtx);
}
if (fCutInvMass) {
fHist->FillConfig(10, fInvMassCutWidth);
}
if (fCutCPA) {
fHist->FillConfig(11, fMinCPA);
}
}
}
float AliFemtoDreamv0Cuts::CalculateInvMass(AliFemtoDreamv0 *v0, int PDGPosDaug,
int PDGNegDaug) {
Double_t invMass = 0;
float massDP = TDatabasePDG::Instance()->GetParticle(PDGPosDaug)->Mass();
float massDN = TDatabasePDG::Instance()->GetParticle(PDGNegDaug)->Mass();
float EDaugP = TMath::Sqrt(
massDP * massDP
+ v0->GetPosDaughter()->GetMomentum().X()
* v0->GetPosDaughter()->GetMomentum().X()
+ v0->GetPosDaughter()->GetMomentum().Y()
* v0->GetPosDaughter()->GetMomentum().Y()
+ v0->GetPosDaughter()->GetMomentum().Z()
* v0->GetPosDaughter()->GetMomentum().Z());
float EDaugN = TMath::Sqrt(
massDN * massDN
+ v0->GetNegDaughter()->GetMomentum().X()
* v0->GetNegDaughter()->GetMomentum().X()
+ v0->GetNegDaughter()->GetMomentum().Y()
* v0->GetNegDaughter()->GetMomentum().Y()
+ v0->GetNegDaughter()->GetMomentum().Z()
* v0->GetNegDaughter()->GetMomentum().Z());
float energysum = EDaugP + EDaugN;
float pSum2 = (v0->GetNegDaughter()->GetMomentum().X()
+ v0->GetPosDaughter()->GetMomentum().X())
* (v0->GetNegDaughter()->GetMomentum().X()
+ v0->GetPosDaughter()->GetMomentum().X())
+
(v0->GetNegDaughter()->GetMomentum().Y()
+ v0->GetPosDaughter()->GetMomentum().Y())
* (v0->GetNegDaughter()->GetMomentum().Y()
+ v0->GetPosDaughter()->GetMomentum().Y())
+
(v0->GetNegDaughter()->GetMomentum().Z()
+ v0->GetPosDaughter()->GetMomentum().Z())
* (v0->GetNegDaughter()->GetMomentum().Z()
+ v0->GetPosDaughter()->GetMomentum().Z());
invMass = TMath::Sqrt(energysum * energysum - pSum2);
return invMass;
}
|
FGtatsuro/myatcoder | beginner_contest/141/B.py | s = input()
import sys
for i in range(len(s)):
if (i + 1) % 2 == 1 and s[i] not in 'RUD':
print('No')
sys.exit(0)
if (i + 1) % 2 == 0 and s[i] not in 'LUD':
print('No')
sys.exit(0)
print('Yes')
|
fkolacek/FIT-VUT | bp-revok/ruby/lib/ruby/gems/2.1.0/gems/rkelly-1.0.7/test/test_runtime.rb | require File.dirname(__FILE__) + "/helper"
class RuntimeTest < Test::Unit::TestCase
def setup
@runtime = RKelly::Runtime.new
end
def test_call_function
@runtime.execute("function foo(a) { return a + 2; }")
assert_equal(12, @runtime.call_function("foo", 10))
end
end
|
carldea/jenetics | jenetics/src/main/java/io/jenetics/DoubleChromosome.java | <filename>jenetics/src/main/java/io/jenetics/DoubleChromosome.java
/*
* Java Genetic Algorithm Library (@__identifier__@).
* Copyright (c) @__year__@ <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Author:
* <NAME> (<EMAIL>)
*/
package io.jenetics;
import static java.util.Objects.requireNonNull;
import static io.jenetics.internal.util.SerialIO.readInt;
import static io.jenetics.internal.util.SerialIO.writeInt;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.io.InvalidObjectException;
import java.io.ObjectInputStream;
import java.io.Serializable;
import java.util.function.Function;
import java.util.stream.DoubleStream;
import java.util.stream.IntStream;
import java.util.stream.Stream;
import io.jenetics.util.DoubleRange;
import io.jenetics.util.ISeq;
import io.jenetics.util.IntRange;
import io.jenetics.util.MSeq;
/**
* Numeric chromosome implementation which holds 64 bit floating point numbers.
*
* @see DoubleGene
*
* @implNote
* This class is immutable and thread-safe.
*
* @author <a href="mailto:<EMAIL>"><NAME></a>
* @since 1.6
* @version 6.1
*/
public class DoubleChromosome
extends AbstractBoundedChromosome<Double, DoubleGene>
implements
NumericChromosome<Double, DoubleGene>,
Serializable
{
private static final long serialVersionUID = 3L;
/**
* Create a new chromosome from the given {@code genes} and the allowed
* length range of the chromosome.
*
* @since 4.0
*
* @param genes the genes that form the chromosome.
* @param lengthRange the allowed length range of the chromosome
* @throws NullPointerException if one of the arguments is {@code null}.
* @throws IllegalArgumentException if the length of the gene sequence is
* empty, doesn't match with the allowed length range, the minimum
* or maximum of the range is smaller or equal zero or the given
* range size is zero.
*/
protected DoubleChromosome(
final ISeq<DoubleGene> genes,
final IntRange lengthRange
) {
super(genes, lengthRange);
}
@Override
public DoubleChromosome newInstance(final ISeq<DoubleGene> genes) {
return new DoubleChromosome(genes, lengthRange());
}
@Override
public DoubleChromosome newInstance() {
return of(_min, _max, lengthRange());
}
/**
* Maps the gene alleles of this chromosome, given as {@code double[]} array,
* by applying the given mapper function {@code f}. The mapped gene values
* are then wrapped into a newly created chromosome.
*
* <pre>{@code
* final DoubleChromosome chromosome = ...;
* final DoubleChromosome normalized = chromosome.map(Main::normalize);
*
* static double[] normalize(final double[] values) {
* final double sum = sum(values);
* for (int i = 0; i < values.length; ++i) {
* values[i] /= sum;
* }
* return values;
* }
* }</pre>
*
* @since 6.1
*
* @param f the mapper function
* @return a newly created chromosome with the mapped gene values
* @throws NullPointerException if the mapper function is {@code null}.
* @throws IllegalArgumentException if the length of the mapped
* {@code double[]} array is empty or doesn't match with the allowed
* length range
*/
public DoubleChromosome map(final Function<? super double[], double[]> f) {
requireNonNull(f);
final var range = DoubleRange.of(_min, _max);
final var genes = DoubleStream.of(f.apply(toArray()))
.mapToObj(v -> DoubleGene.of(v, range))
.collect(ISeq.toISeq());
return newInstance(genes);
}
/**
* Returns a sequential stream of the alleles with this chromosome as its
* source.
*
* @since 4.3
*
* @return a sequential stream of alleles
*/
public DoubleStream doubleStream() {
return IntStream.range(0, length()).mapToDouble(this::doubleValue);
}
/**
* Returns an double array containing all of the elements in this chromosome
* in proper sequence. If the chromosome fits in the specified array, it is
* returned therein. Otherwise, a new array is allocated with the length of
* this chromosome.
*
* @since 3.0
*
* @param array the array into which the elements of this chromosomes are to
* be stored, if it is big enough; otherwise, a new array is
* allocated for this purpose.
* @return an array containing the elements of this chromosome
* @throws NullPointerException if the given {@code array} is {@code null}
*/
public double[] toArray(final double[] array) {
final double[] a = array.length >= length()
? array
: new double[length()];
for (int i = length(); --i >= 0;) {
a[i] = doubleValue(i);
}
return a;
}
/**
* Returns an double array containing all of the elements in this chromosome
* in proper sequence.
*
* @since 3.0
*
* @return an array containing the elements of this chromosome
*/
public double[] toArray() {
return toArray(new double[length()]);
}
/* *************************************************************************
* Static factory methods.
* ************************************************************************/
/**
* Create a new {@code DoubleChromosome} with the given genes.
*
* @param genes the genes of the chromosome.
* @return a new chromosome with the given genes.
* @throws IllegalArgumentException if the length of the genes array is
* empty or the given {@code genes} doesn't have the same range.
* @throws NullPointerException if the given {@code genes} array is
* {@code null}
*/
public static DoubleChromosome of(final DoubleGene... genes) {
checkGeneRange(Stream.of(genes).map(DoubleGene::range));
return new DoubleChromosome(ISeq.of(genes), IntRange.of(genes.length));
}
/**
* Create a new {@code DoubleChromosome} with the given genes.
*
* @since 4.3
*
* @param genes the genes of the chromosome.
* @return a new chromosome with the given genes.
* @throws NullPointerException if the given {@code genes} are {@code null}
* @throws IllegalArgumentException if the of the genes iterable is empty or
* the given {@code genes} doesn't have the same range.
*/
public static DoubleChromosome of(final Iterable<DoubleGene> genes) {
final ISeq<DoubleGene> values = ISeq.of(genes);
checkGeneRange(values.stream().map(DoubleGene::range));
return new DoubleChromosome(values, IntRange.of(values.length()));
}
/**
* Create a new random chromosome.
*
* @since 4.0
*
* @param min the min value of the {@link DoubleGene}s (inclusively).
* @param max the max value of the {@link DoubleGene}s (exclusively).
* @param lengthRange the allowed length range of the chromosome.
* @return a new {@code DoubleChromosome} with the given parameter
* @throws IllegalArgumentException if the length of the gene sequence is
* empty, doesn't match with the allowed length range, the minimum
* or maximum of the range is smaller or equal zero or the given
* range size is zero.
* @throws NullPointerException if the given {@code lengthRange} is
* {@code null}
*/
public static DoubleChromosome of(
final double min,
final double max,
final IntRange lengthRange
) {
final ISeq<DoubleGene> genes = DoubleGene.seq(min, max, lengthRange);
return new DoubleChromosome(genes, lengthRange);
}
/**
* Create a new random {@code DoubleChromosome}.
*
* @param min the min value of the {@link DoubleGene}s (inclusively).
* @param max the max value of the {@link DoubleGene}s (exclusively).
* @param length the length of the chromosome.
* @return a new {@code DoubleChromosome} with the given parameter
* @throws IllegalArgumentException if the {@code length} is smaller than
* one.
*/
public static DoubleChromosome of(
final double min,
final double max,
final int length
) {
return of(min, max, IntRange.of(length));
}
/**
* Create a new random chromosome.
*
* @since 4.0
*
* @param range the integer range of the chromosome.
* @param lengthRange the allowed length range of the chromosome.
* @return a new {@code DoubleChromosome} with the given parameter
* @throws IllegalArgumentException if the length of the gene sequence is
* empty, doesn't match with the allowed length range, the minimum
* or maximum of the range is smaller or equal zero or the given
* range size is zero.
* @throws NullPointerException if the given {@code lengthRange} is
* {@code null}
*/
public static DoubleChromosome of(
final DoubleRange range,
final IntRange lengthRange
) {
return of(range.min(), range.max(), lengthRange);
}
/**
* Create a new random {@code DoubleChromosome}.
*
* @since 3.2
*
* @param range the integer range of the chromosome.
* @param length the length of the chromosome.
* @return a new random {@code DoubleChromosome}
* @throws NullPointerException if the given {@code range} is {@code null}
* @throws IllegalArgumentException if the {@code length} is smaller than
* one.
*/
public static DoubleChromosome of(final DoubleRange range, final int length) {
return of(range.min(), range.max(), length);
}
/**
* Create a new random {@code DoubleChromosome} of length one.
*
* @param min the minimal value of this chromosome (inclusively).
* @param max the maximal value of this chromosome (exclusively).
* @return a new {@code DoubleChromosome} with the given parameter
*/
public static DoubleChromosome of(final double min, final double max) {
return of(min, max, 1);
}
/**
* Create a new random {@code DoubleChromosome} of length one.
*
* @since 3.2
*
* @param range the double range of the chromosome.
* @return a new random {@code DoubleChromosome} of length one
* @throws NullPointerException if the given {@code range} is {@code null}
*/
public static DoubleChromosome of(final DoubleRange range) {
return of(range.min(), range.max());
}
/* *************************************************************************
* Java object serialization
* ************************************************************************/
private Object writeReplace() {
return new Serial(Serial.DOUBLE_CHROMOSOME, this);
}
private void readObject(final ObjectInputStream stream)
throws InvalidObjectException
{
throw new InvalidObjectException("Serialization proxy required.");
}
void write(final DataOutput out) throws IOException {
writeInt(length(), out);
writeInt(lengthRange().min(), out);
writeInt(lengthRange().max(), out);
out.writeDouble(_min);
out.writeDouble(_max);
for (int i = 0, n = length(); i < n; ++i) {
out.writeDouble(doubleValue(i));
}
}
static DoubleChromosome read(final DataInput in) throws IOException {
final var length = readInt(in);
final var lengthRange = IntRange.of(readInt(in), readInt(in));
final var min = in.readDouble();
final var max = in.readDouble();
final MSeq<DoubleGene> values = MSeq.ofLength(length);
for (int i = 0; i < length; ++i) {
values.set(i, DoubleGene.of(in.readDouble(), min, max));
}
return new DoubleChromosome(values.toISeq(), lengthRange);
}
}
|
ingchips/SDK_SOURCE | examples/mesh-light/src/profile.h | #ifndef _PROFILESTASK_H_
#define _PROFILESTASK_H_
#include <stdint.h>
uint32_t setup_profile(void *data, void *user_data);
#endif
|
cleberecht/singa | singa-mathematics/src/main/java/bio/singa/mathematics/matrices/SymmetricMatrix.java | package bio.singa.mathematics.matrices;
import bio.singa.mathematics.exceptions.IncompatibleDimensionsException;
import bio.singa.mathematics.exceptions.MalformedMatrixException;
import bio.singa.mathematics.vectors.RegularVector;
/**
* The {@code SymmetricMatrix} implementation only stores a the main diagonal and one copy of the symmetric values.
*
* @author cl
* @see <a href="https://en.wikipedia.org/wiki/Symmetric_matrix">Wikipedia: Symmetric matrix</a>
*/
public class SymmetricMatrix extends SquareMatrix {
private static final long serialVersionUID = -6578419947334743873L;
/**
* Creates a new {@code SymmetricMatrix} with the given double values. The first index of the double array
* represents the row index and the second index represents the column index. <br> <p> The following array:
* <pre>
* {{1.0, 2.0, 3.0}, {2.0, 5.0, 6.0}, {3.0, 6.0, 9.0}} </pre>
* result in the matrix:
* <pre>
* 1.0 2.0 3.0
* 2.0 5.0 6.0
* 3.0 6.0 9.0 </pre>
*
* @param values The values of the matrix.
*/
public SymmetricMatrix(double[][] values) {
super(values, true);
}
SymmetricMatrix(double[][] values, int rowDimension, int columnDimension) {
super(values, rowDimension, columnDimension);
}
/**
* Returns {@code true} if the potential values are square and symmetric (mirrored at the main diagonal) and {@code
* false} otherwise.
*
* @param potentialValues The potential values of a symmetric matrix.
* @return {@code true} if the potential values are square and symmetric and {@code false} otherwise.
*/
public static boolean isSymmetric(double[][] potentialValues) {
if (!isSquare(potentialValues)) {
return false;
} else {
for (int rowIndex = 0; rowIndex < potentialValues.length; rowIndex++) {
for (int columnIndex = 0; columnIndex < potentialValues[0].length; columnIndex++) {
if (potentialValues[columnIndex][rowIndex] != potentialValues[rowIndex][columnIndex]) {
return false;
}
}
}
return true;
}
}
/**
* Returns {@code true} if the given matrix is square and symmetric (mirrored at the main diagonal) and {@code
* false} otherwise.
*
* @param matrix The matrix to be checked.
* @return {@code true} if the given matrix is square and symmetric and {@code false} otherwise.
*/
public static boolean isSymmetric(Matrix matrix) {
return isSymmetric(matrix.getElements());
}
/**
* Asserts that the given potential values are square and symmetric and throws an {@link
* IncompatibleDimensionsException} otherwise.
*
* @param potentialValues The potential values of a symmetric matrix.
* @throws IncompatibleDimensionsException if the given matrix is not square and symmetric.
*/
public static void assertThatValuesAreSymmetric(double[][] potentialValues) {
if (!SymmetricMatrix.isSymmetric(potentialValues)) {
throw new MalformedMatrixException(potentialValues);
}
}
/**
* Returns {@code true} if the values are already arranged in an jagged array and {@code false} otherwise.
*
* @param potentialValues The potential values.
* @return {@code true} if the values are already arranged in an jagged array and {@code false} otherwise.
*/
public static boolean isCompact(double[][] potentialValues) {
int rowLength = 1;
for (double[] potentialValue : potentialValues) {
if (potentialValue.length != rowLength) {
return false;
}
rowLength++;
}
return true;
}
/**
* Compacts the values of a symmetric matrix into a jagged array, that represents the lower triangular part of a
* symmetric matrix. <br> <p> The following array:
* <pre>
* {{1.0, 2.0, 3.0}, {2.0, 5.0, 6.0}, {3.0, 6.0, 9.0}} </pre>
* compacts to the array:
* <pre>
* {{1.0}, {2.0, 5.0}, {3.0, 6.0, 9.0}} </pre>
* which results in the matrix:
* <pre>
* 1.0
* 2.0 5.0
* 3.0 6.0 9.0 </pre>
*
* @param potentialValues The potentially compact values to be converted
* @return The compacted values.
*/
public static double[][] compactToSymmetricMatrix(double[][] potentialValues) {
assertThatValuesAreSymmetric(potentialValues);
// initialize jagged array
double[][] compactedValues = new double[potentialValues.length][];
for (int rowIndex = 0; rowIndex < potentialValues.length; rowIndex++) {
compactedValues[rowIndex] = new double[rowIndex + 1];
}
// fill array with values
for (int rowIndex = 0; rowIndex < potentialValues.length; rowIndex++) {
System.arraycopy(potentialValues[rowIndex], 0, compactedValues[rowIndex], 0, rowIndex + 1);
}
return compactedValues;
}
@Override
public RegularVector getColumn(int columnIndex) {
return getRow(columnIndex);
}
@Override
public RegularVector getRow(int rowIndex) {
double[] rowElements = new double[getRowDimension()];
System.arraycopy(getElements()[rowIndex], 0, rowElements, 0, rowIndex + 1);
for (int j = rowIndex + 1; j < getRowDimension(); j++) {
rowElements[j] = getElements()[j][rowIndex];
}
return new RegularVector(rowElements);
}
@Override
public double getElement(int rowIndex, int columnIndex) {
if (rowIndex >= columnIndex) {
return super.getElement(rowIndex, columnIndex);
} else {
return super.getElement(columnIndex, rowIndex);
}
}
/**
* Returns the complete instead of the compact array of elements.
*
* @return The complete array of elements.
*/
public double[][] getCompleteElements() {
double[][] values = new double[getRowDimension()][getColumnDimension()];
for (int rowIndex = 0; rowIndex < getRowDimension(); rowIndex++) {
for (int columnIndex = 0; columnIndex < getColumnDimension(); columnIndex++) {
values[rowIndex][columnIndex] = getElement(rowIndex, columnIndex);
}
}
return values;
}
@Override
public Matrix transpose() {
return FastMatrices.createSymmetricMatrix(getElements());
}
}
|
vadkasevas/BAS | Engine/idatabaseschemaeditor.cpp | #include "idatabaseschemaeditor.h"
#include "every_cpp.h"
namespace BrowserAutomationStudioFramework
{
IDatabaseSchemaEditor::IDatabaseSchemaEditor(QObject *parent) :
QObject(parent)
{
}
}
|
FringeY/alibabacloud-console-design | packages/xconsole-effect-creator/config/config.js | module.exports = {
presets: [
[
'@alicloud/console-toolkit-preset-wind-component',
{
moduleName: '@alicloud/xconsole-effect-creator',
},
],
],
}; |
NuolanNuolan/IPAPatch-master | Assets/header/MMKSMusicPlayer.h | <gh_stars>1-10
//
// Generated by class-dump 3.5 (64 bit) (Debug version compiled Mar 29 2017 23:22:24).
//
// class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2015 by <NAME>.
//
#import "MMService.h"
#import "IRemoteControlMusicPlayerExt-Protocol.h"
#import "KSAudioLogProtocol-Protocol.h"
#import "KSAudioPlayerDelegate-Protocol.h"
#import "KSAudioPlayerUserDefineProtocol-Protocol.h"
#import "MMMusicPlayerNotifyExt-Protocol.h"
#import "MMService-Protocol.h"
#import "WCAudioSessionExt-Protocol.h"
@class KSAudioPlayer, MMMusicInfo, MMTimer, NSObject, NSString;
@interface MMKSMusicPlayer : MMService <MMMusicPlayerNotifyExt, WCAudioSessionExt, IRemoteControlMusicPlayerExt, KSAudioPlayerDelegate, KSAudioPlayerUserDefineProtocol, KSAudioLogProtocol, MMService>
{
KSAudioPlayer *m_audioPlayer;
_Bool m_isQQMusicWifiPlay;
_Bool m_isCyclePlay;
_Bool m_isNeedRestartByOthers;
MMMusicInfo *m_musicInfo;
MMTimer *m_playPercentTimer;
NSObject *m_clientInfo;
_Bool m_isQQMusicPlay;
_Bool m_isPlayerResuming;
}
- (void).cxx_destruct;
- (id)bcdStringFromUrl_WechatMusicUrl:(id)arg1;
- (id)bcdStringFromUrl_QQMusic:(id)arg1;
- (id)bcdStringHanding:(id)arg1;
- (void)onSetNeedRestartMusicByOthers:(_Bool)arg1;
- (void)onPlayPreviousMusic;
- (void)onPlayNextMusic;
- (void)onWCAudioSessionOverride;
- (void)onWCAudioSessionCategoryChange:(unsigned long long)arg1;
- (void)onWCAudioSessionOldDeviceUnavailable;
- (void)onWCAudioSessionNewDeviceAvailable;
- (void)notifyMusicPlayerRestartMusic;
- (void)notifyMusicPlayerPauseMusic;
- (void)log:(long long)arg1 file:(const char *)arg2 func:(const char *)arg3 line:(int)arg4 module:(id)arg5 EFDict:(id)arg6 fullmsg:(id)arg7;
- (id)limitNetParam;
- (unsigned int)downloadRetryCnt;
- (id)createAudioDownloader;
- (_Bool)isNetOk;
- (void)audioPlayer:(id)arg1 dataBuffering:(double)arg2;
- (void)audioPlayer:(id)arg1 status:(unsigned long long)arg2 params:(id)arg3;
- (double)getBufferPercent;
- (double)getDuration;
- (double)getCurTime;
- (_Bool)isQQMusicWifiPlay;
- (_Bool)isNeedRestartByOthers;
- (void)setNeedRestartByOthers:(_Bool)arg1;
- (long long)status;
- (_Bool)isIdle;
- (_Bool)isPaused;
- (_Bool)isPlaying;
- (_Bool)isWaiting;
- (void)resume;
- (void)pause;
- (void)tryStopClientId:(id)arg1;
- (void)seekToTime:(double)arg1;
- (void)forceStopMusic;
- (void)stop;
- (void)start:(id)arg1;
- (void)playWithUrl:(id)arg1 MusicID:(id)arg2 isQQMusic:(_Bool)arg3;
- (void)ignoreCurrentMusicItem;
- (void)addMusicItem:(id)arg1;
- (void)destroyStreamer;
- (void)dealloc;
- (void)onServiceInit;
- (id)init;
- (id)cachePathForMusicFromUrl:(id)arg1;
- (id)getUrlPathExt:(id)arg1;
- (id)hashForUrl:(id)arg1;
- (id)cacheRootPath;
// Remaining properties
@property(readonly, copy) NSString *debugDescription;
@property(readonly, copy) NSString *description;
@property(readonly) unsigned long long hash;
@property(readonly) Class superclass;
@end
|
ckamtsikis/cmssw | DQM/BeamMonitor/python/BeamMonitor_Pixel_cff.py | import FWCore.ParameterSet.Config as cms
from DQMServices.Core.DQMEDAnalyzer import DQMEDAnalyzer
dqmBeamMonitor = DQMEDAnalyzer("BeamMonitor",
monitorName = cms.untracked.string('BeamMonitor'),
beamSpot = cms.untracked.InputTag('offlineBeamSpot'), ## hltOfflineBeamSpot for HLTMON
primaryVertex = cms.untracked.InputTag('pixelVertices'),
timeInterval = cms.untracked.int32(920),
fitEveryNLumi = cms.untracked.int32(1),
resetEveryNLumi = cms.untracked.int32(20),
fitPVEveryNLumi = cms.untracked.int32(1),
resetPVEveryNLumi = cms.untracked.int32(5),
Debug = cms.untracked.bool(False),
OnlineMode = cms.untracked.bool(True),
recordName = cms.untracked.string('BeamSpotOnlineHLTObjectsRcd'),
BeamFitter = cms.PSet(
Debug = cms.untracked.bool(False),
TrackCollection = cms.untracked.InputTag('pixelTracks'),
IsMuonCollection = cms.untracked.bool(False),
WriteAscii = cms.untracked.bool(False),
AsciiFileName = cms.untracked.string('BeamFit.txt'), ## all results
AppendRunToFileName = cms.untracked.bool(True), #runnumber will be inserted to the file name
WriteDIPAscii = cms.untracked.bool(False),
DIPFileName = cms.untracked.string('BeamFitDIP.txt'),
SaveNtuple = cms.untracked.bool(False),
SavePVVertices = cms.untracked.bool(False),
SaveFitResults = cms.untracked.bool(False),
OutputFileName = cms.untracked.string('BeamFit.root'), ## ntuple filename
MinimumPt = cms.untracked.double(1.0),
MaximumEta = cms.untracked.double(2.4),
MaximumImpactParameter = cms.untracked.double(1.0),
MaximumZ = cms.untracked.double(60),
MinimumTotalLayers = cms.untracked.int32(3),
MinimumPixelLayers = cms.untracked.int32(3),
MaximumNormChi2 = cms.untracked.double(30.0),
TrackAlgorithm = cms.untracked.vstring(), ## ctf,rs,cosmics,initialStep,lowPtTripletStep...; for all algos, leave it blank
TrackQuality = cms.untracked.vstring(), ## loose, tight, highPurity...; for all qualities, leave it blank
InputBeamWidth = cms.untracked.double(0.0060), ## beam width used for Trk fitter, used only when result from PV is not available
FractionOfFittedTrks = cms.untracked.double(0.9),
MinimumInputTracks = cms.untracked.int32(150),
deltaSignificanceCut = cms.untracked.double(10)
),
PVFitter = cms.PSet(
Debug = cms.untracked.bool(False),
Apply3DFit = cms.untracked.bool(True),
VertexCollection = cms.untracked.InputTag('pixelVertices'),
#WriteAscii = cms.untracked.bool(True),
#AsciiFileName = cms.untracked.string('PVFit.txt'),
maxNrStoredVertices = cms.untracked.uint32(1000000),
minNrVerticesForFit = cms.untracked.uint32(50),
minVertexNdf = cms.untracked.double(4.),
#--Not used
maxVertexNormChi2 = cms.untracked.double(30.),
minVertexNTracks = cms.untracked.uint32(0),
minVertexMeanWeight = cms.untracked.double(0.0),
maxVertexR = cms.untracked.double(2.),
maxVertexZ = cms.untracked.double(10.),
#---------------
errorScale = cms.untracked.double(1.23),
nSigmaCut = cms.untracked.double(50.0),
FitPerBunchCrossing = cms.untracked.bool(False),
useOnlyFirstPV = cms.untracked.bool(False),
minSumPt = cms.untracked.double(0.)
),
dxBin = cms.int32(200),
dxMin = cms.double(-1.0),
dxMax = cms.double(1.0),
vxBin = cms.int32(200),
vxMin = cms.double(-0.5),
vxMax = cms.double(0.5),
dzBin = cms.int32(80),
dzMin = cms.double(-20),
dzMax = cms.double(20),
phiBin = cms.int32(63),
phiMin = cms.double(-3.15),
phiMax = cms.double(3.15)
)
|
xiaowei20152012/LeeMedia | YouMedia/app/src/main/java/com/umedia/android/ui/activities/tageditor/AbsTagEditorActivity.java | package com.umedia.android.ui.activities.tageditor;
import android.app.Activity;
import android.app.Dialog;
import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.view.animation.OvershootInterpolator;
import android.widget.ImageView;
import android.widget.LinearLayout;
import com.afollestad.materialdialogs.MaterialDialog;
import com.github.ksoichiro.android.observablescrollview.ObservableScrollView;
import com.kabouzeid.appthemehelper.ThemeStore;
import com.kabouzeid.appthemehelper.util.ColorUtil;
import com.kabouzeid.appthemehelper.util.TintHelper;
import com.umedia.android.R;
import com.umedia.android.misc.DialogAsyncTask;
import com.umedia.android.misc.SimpleObservableScrollViewCallbacks;
import com.umedia.android.misc.UpdateToastMediaScannerCompletionListener;
import com.umedia.android.ui.activities.base.AbsBaseActivity;
import com.umedia.android.util.MusicUtil;
import com.umedia.android.util.Util;
import org.jaudiotagger.audio.AudioFile;
import org.jaudiotagger.audio.AudioFileIO;
import org.jaudiotagger.audio.exceptions.CannotReadException;
import org.jaudiotagger.audio.exceptions.CannotWriteException;
import org.jaudiotagger.audio.exceptions.InvalidAudioFrameException;
import org.jaudiotagger.audio.exceptions.ReadOnlyFileException;
import org.jaudiotagger.tag.FieldKey;
import org.jaudiotagger.tag.Tag;
import org.jaudiotagger.tag.TagException;
import org.jaudiotagger.tag.images.Artwork;
import org.jaudiotagger.tag.images.ArtworkFactory;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import butterknife.BindView;
import butterknife.ButterKnife;
/**
* @author Lee (kabouzeid)
*/
public abstract class AbsTagEditorActivity extends AbsBaseActivity {
public static final String EXTRA_ID = "extra_id";
public static final String EXTRA_PALETTE = "extra_palette";
private static final String TAG = AbsTagEditorActivity.class.getSimpleName();
private static final int REQUEST_CODE_SELECT_IMAGE = 1000;
@BindView(R.id.play_pause_fab)
FloatingActionButton fab;
@BindView(R.id.observableScrollView)
ObservableScrollView observableScrollView;
@BindView(R.id.toolbar)
Toolbar toolbar;
@BindView(R.id.image)
ImageView image;
@BindView(R.id.header)
LinearLayout header;
private int id;
private int headerVariableSpace;
private int paletteColorPrimary;
private boolean isInNoImageMode;
private final SimpleObservableScrollViewCallbacks observableScrollViewCallbacks = new SimpleObservableScrollViewCallbacks() {
@Override
public void onScrollChanged(int scrollY, boolean b, boolean b2) {
float alpha;
if (!isInNoImageMode) {
alpha = 1 - (float) Math.max(0, headerVariableSpace - scrollY) / headerVariableSpace;
} else {
header.setTranslationY(scrollY);
alpha = 1;
}
toolbar.setBackgroundColor(ColorUtil.withAlpha(paletteColorPrimary, alpha));
image.setTranslationY(scrollY / 2);
}
};
private List<String> songPaths;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(getContentViewLayout());
ButterKnife.bind(this);
getIntentExtras();
songPaths = getSongPaths();
if (songPaths.isEmpty()) {
finish();
return;
}
headerVariableSpace = getResources().getDimensionPixelSize(R.dimen.tagEditorHeaderVariableSpace);
setUpViews();
setSupportActionBar(toolbar);
//noinspection ConstantConditions
getSupportActionBar().setTitle(null);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
private void setUpViews() {
setUpScrollView();
setUpFab();
setUpImageView();
}
private void setUpScrollView() {
observableScrollView.setScrollViewCallbacks(observableScrollViewCallbacks);
}
private void setUpImageView() {
loadCurrentImage();
final CharSequence[] items = new CharSequence[]{
getString(R.string.download_from_last_fm),
getString(R.string.pick_from_local_storage),
getString(R.string.web_search),
getString(R.string.remove_cover)
};
image.setOnClickListener(v -> new MaterialDialog.Builder(AbsTagEditorActivity.this)
.title(R.string.update_image)
.items(items)
.itemsCallback((dialog, view, which, text) -> {
switch (which) {
case 0:
getImageFromLastFM();
break;
case 1:
startImagePicker();
break;
case 2:
searchImageOnWeb();
break;
case 3:
deleteImage();
break;
}
}).show());
}
private void startImagePicker() {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(Intent.createChooser(intent, getString(R.string.pick_from_local_storage)), REQUEST_CODE_SELECT_IMAGE);
}
protected abstract void loadCurrentImage();
protected abstract void getImageFromLastFM();
protected abstract void searchImageOnWeb();
protected abstract void deleteImage();
private void setUpFab() {
fab.setScaleX(0);
fab.setScaleY(0);
fab.setEnabled(false);
fab.setOnClickListener(v -> save());
TintHelper.setTintAuto(fab, ThemeStore.accentColor(this), true);
}
protected abstract void save();
private void getIntentExtras() {
Bundle intentExtras = getIntent().getExtras();
if (intentExtras != null) {
id = intentExtras.getInt(EXTRA_ID);
}
}
protected abstract int getContentViewLayout();
@NonNull
protected abstract List<String> getSongPaths();
protected void searchWebFor(String... keys) {
StringBuilder stringBuilder = new StringBuilder();
for (String key : keys) {
stringBuilder.append(key);
stringBuilder.append(" ");
}
Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
intent.putExtra(SearchManager.QUERY, stringBuilder.toString());
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
int id = item.getItemId();
switch (id) {
case android.R.id.home:
super.onBackPressed();
return true;
}
return super.onOptionsItemSelected(item);
}
protected void setNoImageMode() {
isInNoImageMode = true;
image.setVisibility(View.GONE);
image.setEnabled(false);
observableScrollView.setPadding(0, Util.getActionBarSize(this), 0, 0);
observableScrollViewCallbacks.onScrollChanged(observableScrollView.getCurrentScrollY(), false, false);
setColors(getIntent().getIntExtra(EXTRA_PALETTE, ThemeStore.primaryColor(this)));
toolbar.setBackgroundColor(paletteColorPrimary);
}
protected void dataChanged() {
showFab();
}
private void showFab() {
fab.animate()
.setDuration(500)
.setInterpolator(new OvershootInterpolator())
.scaleX(1)
.scaleY(1)
.start();
fab.setEnabled(true);
}
protected void setImageBitmap(@Nullable final Bitmap bitmap, int bgColor) {
if (bitmap == null) {
image.setImageResource(R.drawable.default_album_art);
} else {
image.setImageBitmap(bitmap);
}
setColors(bgColor);
}
protected void setColors(int color) {
paletteColorPrimary = color;
observableScrollViewCallbacks.onScrollChanged(observableScrollView.getCurrentScrollY(), false, false);
header.setBackgroundColor(paletteColorPrimary);
setStatusbarColor(paletteColorPrimary);
setNavigationbarColor(paletteColorPrimary);
setTaskDescriptionColor(paletteColorPrimary);
}
protected void writeValuesToFiles(@NonNull final Map<FieldKey, String> fieldKeyValueMap, @Nullable final ArtworkInfo artworkInfo) {
Util.hideSoftKeyboard(this);
new WriteTagsAsyncTask(this).execute(new WriteTagsAsyncTask.LoadingInfo(getSongPaths(), fieldKeyValueMap, artworkInfo));
}
private static class WriteTagsAsyncTask extends DialogAsyncTask<WriteTagsAsyncTask.LoadingInfo, Integer, String[]> {
Context applicationContext;
public WriteTagsAsyncTask(Context context) {
super(context);
applicationContext = context;
}
@Override
protected String[] doInBackground(LoadingInfo... params) {
try {
LoadingInfo info = params[0];
Artwork artwork = null;
File albumArtFile = null;
if (info.artworkInfo != null && info.artworkInfo.artwork != null) {
try {
albumArtFile = MusicUtil.createAlbumArtFile().getCanonicalFile();
info.artworkInfo.artwork.compress(Bitmap.CompressFormat.PNG, 0, new FileOutputStream(albumArtFile));
artwork = ArtworkFactory.createArtworkFromFile(albumArtFile);
} catch (IOException e) {
e.printStackTrace();
}
}
int counter = 0;
boolean wroteArtwork = false;
boolean deletedArtwork = false;
for (String filePath : info.filePaths) {
publishProgress(++counter, info.filePaths.size());
try {
AudioFile audioFile = AudioFileIO.read(new File(filePath));
Tag tag = audioFile.getTagOrCreateAndSetDefault();
if (info.fieldKeyValueMap != null) {
for (Map.Entry<FieldKey, String> entry : info.fieldKeyValueMap.entrySet()) {
try {
tag.setField(entry.getKey(), entry.getValue());
} catch (Exception e) {
e.printStackTrace();
}
}
}
if (info.artworkInfo != null) {
if (info.artworkInfo.artwork == null) {
tag.deleteArtworkField();
deletedArtwork = true;
} else if (artwork != null) {
tag.deleteArtworkField();
tag.setField(artwork);
wroteArtwork = true;
}
}
audioFile.commit();
} catch (@NonNull CannotReadException | IOException | CannotWriteException | TagException | ReadOnlyFileException | InvalidAudioFrameException e) {
e.printStackTrace();
}
}
Context context = getContext();
if (context != null) {
if (wroteArtwork) {
MusicUtil.insertAlbumArt(context, info.artworkInfo.albumId, albumArtFile.getPath());
} else if (deletedArtwork) {
MusicUtil.deleteAlbumArt(context, info.artworkInfo.albumId);
}
}
return info.filePaths.toArray(new String[info.filePaths.size()]);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
@Override
protected void onPostExecute(String[] toBeScanned) {
super.onPostExecute(toBeScanned);
scan(toBeScanned);
}
@Override
protected void onCancelled(String[] toBeScanned) {
super.onCancelled(toBeScanned);
scan(toBeScanned);
}
private void scan(String[] toBeScanned) {
Context context = getContext();
MediaScannerConnection.scanFile(applicationContext, toBeScanned, null, context instanceof Activity ? new UpdateToastMediaScannerCompletionListener((Activity) context, toBeScanned) : null);
}
@Override
protected Dialog createDialog(@NonNull Context context) {
return new MaterialDialog.Builder(context)
.title(R.string.saving_changes)
.cancelable(false)
.progress(false, 0)
.build();
}
@Override
protected void onProgressUpdate(@NonNull Dialog dialog, Integer... values) {
super.onProgressUpdate(dialog, values);
((MaterialDialog) dialog).setMaxProgress(values[1]);
((MaterialDialog) dialog).setProgress(values[0]);
}
public static class LoadingInfo {
public final Collection<String> filePaths;
@Nullable
public final Map<FieldKey, String> fieldKeyValueMap;
@Nullable
private ArtworkInfo artworkInfo;
private LoadingInfo(Collection<String> filePaths, @Nullable Map<FieldKey, String> fieldKeyValueMap, @Nullable ArtworkInfo artworkInfo) {
this.filePaths = filePaths;
this.fieldKeyValueMap = fieldKeyValueMap;
this.artworkInfo = artworkInfo;
}
}
}
public static class ArtworkInfo {
public final int albumId;
public final Bitmap artwork;
public ArtworkInfo(int albumId, Bitmap artwork) {
this.albumId = albumId;
this.artwork = artwork;
}
}
protected int getId() {
return id;
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @NonNull Intent imageReturnedIntent) {
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
switch (requestCode) {
case REQUEST_CODE_SELECT_IMAGE:
if (resultCode == RESULT_OK) {
Uri selectedImage = imageReturnedIntent.getData();
loadImageFromFile(selectedImage);
}
break;
}
}
protected abstract void loadImageFromFile(Uri selectedFile);
@NonNull
private AudioFile getAudioFile(@NonNull String path) {
try {
return AudioFileIO.read(new File(path));
} catch (Exception e) {
Log.e(TAG, "Could not read audio file " + path, e);
return new AudioFile();
}
}
@Nullable
protected String getSongTitle() {
try {
return getAudioFile(songPaths.get(0)).getTagOrCreateAndSetDefault().getFirst(FieldKey.TITLE);
} catch (Exception ignored) {
return null;
}
}
@Nullable
protected String getAlbumTitle() {
try {
return getAudioFile(songPaths.get(0)).getTagOrCreateAndSetDefault().getFirst(FieldKey.ALBUM);
} catch (Exception ignored) {
return null;
}
}
@Nullable
protected String getArtistName() {
try {
return getAudioFile(songPaths.get(0)).getTagOrCreateAndSetDefault().getFirst(FieldKey.ARTIST);
} catch (Exception ignored) {
return null;
}
}
@Nullable
protected String getAlbumArtistName() {
try {
return getAudioFile(songPaths.get(0)).getTagOrCreateAndSetDefault().getFirst(FieldKey.ALBUM_ARTIST);
} catch (Exception ignored) {
return null;
}
}
@Nullable
protected String getGenreName() {
try {
return getAudioFile(songPaths.get(0)).getTagOrCreateAndSetDefault().getFirst(FieldKey.GENRE);
} catch (Exception ignored) {
return null;
}
}
@Nullable
protected String getSongYear() {
try {
return getAudioFile(songPaths.get(0)).getTagOrCreateAndSetDefault().getFirst(FieldKey.YEAR);
} catch (Exception ignored) {
return null;
}
}
@Nullable
protected String getTrackNumber() {
try {
return getAudioFile(songPaths.get(0)).getTagOrCreateAndSetDefault().getFirst(FieldKey.TRACK);
} catch (Exception ignored) {
return null;
}
}
@Nullable
protected String getLyrics() {
try {
return getAudioFile(songPaths.get(0)).getTagOrCreateAndSetDefault().getFirst(FieldKey.LYRICS);
} catch (Exception ignored) {
return null;
}
}
@Nullable
protected Bitmap getAlbumArt() {
try {
Artwork artworkTag = getAudioFile(songPaths.get(0)).getTagOrCreateAndSetDefault().getFirstArtwork();
if (artworkTag != null) {
byte[] artworkBinaryData = artworkTag.getBinaryData();
return BitmapFactory.decodeByteArray(artworkBinaryData, 0, artworkBinaryData.length);
}
return null;
} catch (Exception ignored) {
return null;
}
}
}
|
PRX/activewarehouse | test/setup/salesperson_hierarchy_bridge_populate.rb | <reponame>PRX/activewarehouse
ETL::Engine.process(File.dirname(__FILE__) + '/salesperson_hierarchy_bridge.ctl') |
uk-gov-mirror/dvsa.cvs-auto-mobile-app | src/main/java/pages/AdvisoryDetailsPage.java | <filename>src/main/java/pages/AdvisoryDetailsPage.java
package pages;
import org.openqa.selenium.WebElement;
public class AdvisoryDetailsPage extends BasePage {
public static final String ADVISORY_DETAILS_PAGE_ID = "Advisory details";
public static final String ADD_NOTES_TEXT_FIELD_ID = "Add Notes";
public static final String ADD_NOTES_CONFIRM_ID = "Add Note";
public static final String DONE_BUTTON_ID = "Done";
public void waitUntilPageIsLoaded() {
waitUntilPageIsLoadedById(ADVISORY_DETAILS_PAGE_ID);
}
public void sendTextOnAddNote(String data) {
WebElement element = findElementByAccessibilityId(ADD_NOTES_TEXT_FIELD_ID);
element.clear();
element.sendKeys(data);
}
public void tapAddNote() {
findElementById(ADD_NOTES_CONFIRM_ID).click();
}
public void tapDone() {
findElementById(DONE_BUTTON_ID).click();
}
public String getCurrentNote() {
return findElementByAccessibilityId(ADD_NOTES_TEXT_FIELD_ID).getAttribute("value");
}
}
|
rsaihe/Storage-Network | src/main/java/com/lothrazar/storagenetwork/registry/ClientEventRegistry.java | package com.lothrazar.storagenetwork.registry;
import org.lwjgl.glfw.GLFW;
import com.mojang.blaze3d.platform.InputConstants;
import net.minecraft.client.KeyMapping;
import net.minecraftforge.client.settings.KeyConflictContext;
public class ClientEventRegistry {
public static final KeyMapping INVENTORY_KEY = new KeyMapping("key.storagenetwork.remote", KeyConflictContext.UNIVERSAL, InputConstants.Type.KEYSYM, GLFW.GLFW_KEY_I, "key.categories.inventory");
}
|
xianglesong/learning-hbase | src/java/org/apache/hadoop/hbase/master/ProcessRegionClose.java | /**
* Copyright 2008 The Apache Software Foundation
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.hbase.master;
import java.io.IOException;
import org.apache.hadoop.hbase.regionserver.HRegion;
import org.apache.hadoop.hbase.HRegionInfo;
/**
* ProcessRegionClose is the way we do post-processing on a closed region. We
* only spawn one of these asynchronous tasks when the region needs to be
* either offlined or deleted. We used to create one of these tasks whenever
* a region was closed, but since closing a region that isn't being offlined
* or deleted doesn't actually require post processing, it's no longer
* necessary.
*/
class ProcessRegionClose extends ProcessRegionStatusChange {
protected final boolean offlineRegion;
protected final boolean reassignRegion;
/**
* @param master
* @param regionInfo Region to operate on
* @param offlineRegion if true, set the region to offline in meta
* @param reassignRegion if true, region is to be reassigned
*/
public ProcessRegionClose(HMaster master, HRegionInfo regionInfo,
boolean offlineRegion, boolean reassignRegion) {
super(master, regionInfo);
this.offlineRegion = offlineRegion;
this.reassignRegion = reassignRegion;
}
@Override
public String toString() {
return "ProcessRegionClose of " + this.regionInfo.getRegionNameAsString() +
", " + this.offlineRegion + ", reassign: " + this.reassignRegion;
}
@Override
protected boolean process() throws IOException {
if (!metaRegionAvailable()) {
// We can't proceed unless the meta region we are going to update
// is online. metaRegionAvailable() has put this operation on the
// delayedToDoQueue, so return true so the operation is not put
// back on the toDoQueue
return true;
}
Boolean result = null;
if (offlineRegion || reassignRegion) {
result =
new RetryableMetaOperation<Boolean>(getMetaRegion(), this.master) {
public Boolean call() throws IOException {
// We can't proceed unless the meta region we are going to update
// is online. metaRegionAvailable() will put this operation on the
// delayedToDoQueue, so return true so the operation is not put
// back on the toDoQueue
if(offlineRegion) {
// offline the region in meta and then remove it from the
// set of regions in transition
HRegion.offlineRegionInMETA(server, metaRegionName,
regionInfo);
master.regionManager.removeRegion(regionInfo);
LOG.info("region closed: " + regionInfo.getRegionNameAsString());
} else {
// we are reassigning the region eventually, so set it unassigned
// and remove the server info
HRegion.cleanRegionInMETA(server, metaRegionName,
regionInfo);
master.regionManager.setUnassigned(regionInfo, false);
LOG.info("region set as unassigned: " + regionInfo.getRegionNameAsString());
}
return true;
}
}.doWithRetries();
result = result == null ? true : result;
} else {
LOG.info("Region was neither offlined, or asked to be reassigned, what gives: " +
regionInfo.getRegionNameAsString());
}
return result == null ? true : result;
}
}
|
riag23/AdaptiveCards | source/ios/AdaptiveCards/AdaptiveCards/AdaptiveCards/ACRQuickReplyMultilineView.h | <filename>source/ios/AdaptiveCards/AdaptiveCards/AdaptiveCards/ACRQuickReplyMultilineView.h
//
// ACRQuickReplyMultilineView
// ACRQuickReplyMultilineView.h
//
// Copyright © 2018 Microsoft. All rights reserved.
//
#import "ACRButton.h"
#import "ACRTextView.h"
#import <UIKit/UIKit.h>
@protocol ACRIQuickReply
- (ACRButton *) getButton;
@end
@interface ACRQuickReplyMultilineView : UIView <ACRIQuickReply>
@property (strong, nonatomic) IBOutlet UIView *contentView;
@property (weak, nonatomic) IBOutlet ACRTextView *textView;
@property (weak, nonatomic) IBOutlet UIView *spacing;
@property (weak, nonatomic) IBOutlet ACRButton *button;
@end
|
vaginessa/ServeStream | app/src/main/java/net/sourceforge/servestream/utils/SleepTimerDialog.java | <filename>app/src/main/java/net/sourceforge/servestream/utils/SleepTimerDialog.java
/*
* ServeStream: A HTTP stream browser/player for Android
* Copyright 2013 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.sourceforge.servestream.utils;
import net.sourceforge.servestream.R;
import net.sourceforge.servestream.service.MediaPlaybackService;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.SeekBar.OnSeekBarChangeListener;
public class SleepTimerDialog extends DialogFragment implements DialogInterface.OnCancelListener {
private int mSleepTimerMode;
/* The activity that creates an instance of this dialog fragment must
* implement this interface in order to receive event callbacks.
* Each method passes the DialogFragment in case the host needs to query it. */
public interface SleepTimerDialogListener {
public void onSleepTimerSet(DialogFragment dialog, int pos);
}
// Use this instance of the interface to deliver action events
static SleepTimerDialogListener mListener;
/* Call this to instantiate a new SleepTimerDialog.
* @param activity The activity hosting the dialog, which must implement the
* SleepTimerDialogListener to receive event callbacks.
* @returns A new instance of SleepTimerDialog.
* @throws ClassCastException if the host activity does not
* implement SleepTimerDialogListener
*/
public static SleepTimerDialog newInstance(Activity activity, int sleepTimerMode) {
// Verify that the host activity implements the callback interface
try {
// Instantiate the SleepTimerDialogListener so we can send events with it
mListener = (SleepTimerDialogListener) activity;
} catch (ClassCastException e) {
// The activity doesn't implement the interface, throw exception
throw new ClassCastException(activity.toString()
+ " must implement SleepTimerDialogListener");
}
SleepTimerDialog frag = new SleepTimerDialog();
// Supply dialog text as an argument.
Bundle args = new Bundle();
args.putInt("sleep_timer_mode", sleepTimerMode);
frag.setArguments(args);
return frag;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mSleepTimerMode = getArguments().getInt("sleep_timer_mode");
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
int MAX_SLEEP_TIMER_MINUTES = 120;
LayoutInflater factory = LayoutInflater.from(getActivity());
final View sleepTimerView = factory.inflate(R.layout.alert_dialog_sleep_timer, null);
final TextView sleepTimerText = (TextView) sleepTimerView.findViewById(R.id.sleep_timer_text);
final SeekBar seekbar = (SeekBar) sleepTimerView.findViewById(R.id.seekbar);
sleepTimerText.setText(makeTimeString(mSleepTimerMode));
seekbar.setProgress(mSleepTimerMode);
seekbar.setMax(MAX_SLEEP_TIMER_MINUTES);
seekbar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
sleepTimerText.setText(makeTimeString(progress));
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
// Use the Builder class for convenient dialog construction
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder = new AlertDialog.Builder(getActivity());
builder.setTitle(R.string.sleep_timer_label);
builder.setCancelable(true);
builder.setView(sleepTimerView);
builder.setOnCancelListener(this);
builder.setPositiveButton(R.string.enable_sleeptimer_label, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
mListener.onSleepTimerSet(SleepTimerDialog.this, seekbar.getProgress());
}
});
return builder.create();
}
public void onCancel(DialogInterface dialog) {
}
private String makeTimeString(int pos) {
String minuteText;
if (pos == MediaPlaybackService.SLEEP_TIMER_OFF) {
minuteText = getResources().getString(R.string.disable_sleeptimer_label);
} else if (pos == 1) {
minuteText = getResources().getString(R.string.minute);
} else if (pos % 60 == 0 && pos > 60) {
minuteText = getResources().getString(R.string.hours, String.valueOf(pos / 60));
} else if (pos % 60 == 0) {
minuteText = getResources().getString(R.string.hour);
} else {
minuteText = getResources().getString(R.string.minutes, String.valueOf(pos));
}
return minuteText;
}
} |
apollo13/lightbus | lightbus/utilities/django.py | <reponame>apollo13/lightbus<filename>lightbus/utilities/django.py
from django import db
def uses_django_db(f):
"""Ensures Django discards any broken database connections
Django normally cleans up connections once a web request has
been processed. However, here we are not serving web requests
and are outside of Django's request handling logic. We therefore
need to make sure we cleanup any broken database connections.
"""
# TODO: Move this into middleware
# (Tracked in: https://github.com/adamcharnock/lightbus/issues/6)
def wrapped(*args, **kwargs):
try:
return f(*args, **kwargs)
except (db.InterfaceError, db.OperationalError):
db.connection.close()
raise
return wrapped
|
Greedylightning/LeetCode_Second | String/ValidPalindrome.java | <reponame>Greedylightning/LeetCode_Second<filename>String/ValidPalindrome.java<gh_stars>0
class ValidPalindrome{
public boolean isPalindrome(String s) {
if(s == null || s.length() == 0) return true;
StringBuffer temp = new StringBuffer();
for(char x : s.toCharArray()){
if((x >= 'a' && x <= 'z') || (x >= 'A' && x <= 'Z') || (x >= '0' && x <='9')) temp.append(x);
}
return temp.toString().toLowerCase().equals(temp.reverse().toString().toLowerCase());
}
} |
palfibeni/turing-with-two-stack-server | src/main/java/com/palfib/turingWithTwoStack/entity/turing/TuringTape.java | <filename>src/main/java/com/palfib/turingWithTwoStack/entity/turing/TuringTape.java
package com.palfib.turingWithTwoStack.entity.turing;
import com.palfib.turingWithTwoStack.entity.Condition;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.ToString;
import java.util.ArrayDeque;
import static java.util.stream.Collectors.toList;
/**
* The TuringTape has a currentPosition priority character, which is the one, the cursor points at.
*/
@NoArgsConstructor
@ToString
@Getter
public class TuringTape {
private final ArrayDeque<Character> charactersAhead = new ArrayDeque<>();
private final ArrayDeque<Character> charactersBehind = new ArrayDeque<>();
@Getter
private Character currentPosition;
TuringTape(final String input) {
this.currentPosition = input.charAt(0);
this.charactersAhead.addAll(input.substring(1).chars()
.mapToObj(ch -> (char) ch)
.collect(toList()));
}
TuringTape(final TuringTape turingTape) {
this.currentPosition = turingTape.currentPosition;
this.charactersAhead.addAll(turingTape.charactersAhead);
this.charactersBehind.addAll(turingTape.charactersBehind);
}
Character moveCursorForward(final Character characterToWrite) {
if (!charactersBehind.isEmpty() || !Condition.EMPTY.equals(characterToWrite)) {
this.charactersBehind.addLast(characterToWrite);
}
this.currentPosition = getFirstFromAhead();
return currentPosition;
}
Character moveCursorBackward(final Character characterToWrite) {
if (!charactersAhead.isEmpty() || !Condition.EMPTY.equals(characterToWrite)) {
this.charactersAhead.addFirst(characterToWrite);
}
this.currentPosition = getLastFromBehind();
return currentPosition;
}
Character stayWithCursor(final Character characterToWrite) {
this.currentPosition = characterToWrite;
return currentPosition;
}
private Character getFirstFromAhead() {
if (charactersAhead.isEmpty()) {
return Condition.EMPTY;
}
return charactersAhead.removeFirst();
}
private Character getLastFromBehind() {
if (charactersBehind.isEmpty()) {
return Condition.EMPTY;
}
return charactersBehind.removeLast();
}
}
|
leopardoooo/cambodia | ycsoft-lib/src/main/java/com/ycsoft/beans/prod/PProdTariffDisct.java | <filename>ycsoft-lib/src/main/java/com/ycsoft/beans/prod/PProdTariffDisct.java
/**
* PProdTariffDisct.java 2010/07/06
*/
package com.ycsoft.beans.prod;
import java.io.Serializable;
import java.util.Date;
import com.ycsoft.beans.base.OptrBase;
import com.ycsoft.commons.constants.DictKey;
import com.ycsoft.commons.store.MemoryDict;
import com.ycsoft.daos.config.POJO;
/**
* PProdTariffDisct -> P_PROD_TARIFF_DISCT mapping
*/
@POJO(tn = "P_PROD_TARIFF_DISCT", sn = "SEQ_DISCT_ID", pk = "DISCT_ID")
public class PProdTariffDisct extends OptrBase implements Serializable {
// PProdTariffDisct all properties
/**
*
*/
private static final long serialVersionUID = 2929576243950773257L;
private String disct_id;
private String disct_name;
private String tariff_id;
private Integer disct_rent;
private Integer min_pay;
private String status;
private Date create_time;
private String rule_id;
private Date eff_date;
private Date exp_date;
private String refund;
private String trans;
private Integer billing_cycle;
private Integer max_cycle_order;
private String billing_type;
private String refund_text;
private String trans_text;
private String status_text;
private String rule_name;
private String rule_id_text;
private String disct_name_all;
/**
* 废弃的属性
*/
@Deprecated
private Integer final_rent;
@Deprecated
public Integer getFinal_rent() {
return final_rent;
}
@Deprecated
public void setFinal_rent(Integer final_rent) {
this.final_rent = final_rent;
}
public String getBilling_type() {
return billing_type;
}
public void setBilling_type(String billing_type) {
this.billing_type = billing_type;
}
public String getRule_name() {
return rule_name;
}
public void setRule_name(String rule_name) {
this.rule_name = rule_name;
}
public Integer getBilling_cycle() {
return billing_cycle;
}
public void setBilling_cycle(Integer billing_cycle) {
this.billing_cycle = billing_cycle;
}
public Integer getMax_cycle_order() {
return max_cycle_order;
}
public void setMax_cycle_order(Integer max_cycle_order) {
this.max_cycle_order = max_cycle_order;
}
public String getStatus_text() {
return status_text;
}
public void setStatus_text(String status_text) {
this.status_text = status_text;
}
/**
* @return the rule_id
*/
public String getRule_id() {
return rule_id;
}
/**
* @param rule_id
* the rule_id to set
*/
public void setRule_id(String rule_id) {
this.rule_id = rule_id;
}
/**
* default empty constructor
*/
public PProdTariffDisct() {
}
// disct_id getter and setter
public String getDisct_id() {
return disct_id;
}
public void setDisct_id(String disct_id) {
this.disct_id = disct_id;
}
// disct_name getter and setter
public String getDisct_name() {
return disct_name;
}
public void setDisct_name(String disct_name) {
this.disct_name = disct_name;
}
// tariff_id getter and setter
public String getTariff_id() {
return tariff_id;
}
public void setTariff_id(String tariff_id) {
this.tariff_id = tariff_id;
}
// final_rent getter and setter
// disct_rent getter and setter
public Integer getDisct_rent() {
return disct_rent;
}
public void setDisct_rent(Integer disct_rent) {
this.disct_rent = disct_rent;
}
// min_pay getter and setter
public Integer getMin_pay() {
return min_pay;
}
public void setMin_pay(Integer min_pay) {
this.min_pay = min_pay;
}
// status getter and setter
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
status_text= MemoryDict.getDictName(DictKey.STATUS, status);
}
// create_time getter and setter
public Date getCreate_time() {
return create_time;
}
public void setCreate_time(Date create_time) {
this.create_time = create_time;
}
/**
* @return the rule_id_text
*/
public String getRule_id_text() {
return rule_id_text;
}
/**
* @param rule_id_text the rule_id_text to set
*/
public void setRule_id_text(String rule_id_text) {
this.rule_id_text = rule_id_text;
}
public String getDisct_name_all() {
return disct_name_all;
}
public void setDisct_name_all(String disctNameAll) {
disct_name_all = disctNameAll;
}
public Date getEff_date() {
return eff_date;
}
public void setEff_date(Date effDate) {
eff_date = effDate;
}
public Date getExp_date() {
return exp_date;
}
public void setExp_date(Date expDate) {
exp_date = expDate;
}
public String getRefund() {
return refund;
}
public void setRefund(String refund) {
this.refund = refund;
refund_text = MemoryDict.getDictName(DictKey.BOOLEAN, this.refund);
}
public String getTrans() {
return trans;
}
public void setTrans(String trans) {
this.trans = trans;
trans_text = MemoryDict.getDictName(DictKey.BOOLEAN, this.trans);
}
public String getRefund_text() {
return refund_text;
}
public void setRefund_text(String refundText) {
refund_text = refundText;
}
public String getTrans_text() {
return trans_text;
}
public void setTrans_text(String transText) {
trans_text = transText;
}
} |
FMMazur/skift | userspace/libraries/libsystem/plugs/__plug_memory.cpp | <gh_stars>1-10
#include <abi/Syscalls.h>
#include <libsystem/Result.h>
#include <libsystem/system/Memory.h>
Result memory_alloc(size_t size, uintptr_t *out_address)
{
return hj_memory_alloc(size, out_address);
}
Result memory_free(uintptr_t address)
{
return hj_memory_free(address);
}
Result memory_include(int handle, uintptr_t *out_address, size_t *out_size)
{
return hj_memory_include(handle, out_address, out_size);
}
Result memory_get_handle(uintptr_t address, int *out_handle)
{
return hj_memory_get_handle(address, out_handle);
}
|
onap/msb-apigateway | apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/util/RegExpTestUtil.java | /*******************************************************************************
* Copyright 2016-2017 ZTE, Inc. and others.
*
* 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.onap.msb.apiroute.wrapper.util;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegExpTestUtil {
private final static String API_KEY_PATTERN = "/api/(?<servicename>[^/]+)(/(?<version>[^/]*)).*";
private final static String IUI_KEY_PATTERN = "/iui/(?<servicename>[^/]+)/.*";
public static boolean hostRegExpTest(String host) {
String hostReg = "^(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|[1-9])\\."
+ "(00?\\d|1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\."
+ "(00?\\d|1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\."
+ "(00?\\d|1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)" + ":(\\d{1,5})$";
return Pattern.matches(hostReg, host);
}
public static boolean ipRegExpTest(String ip) {
String hostReg = "^(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|[1-9])\\."
+ "(00?\\d|1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\."
+ "(00?\\d|1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\."
+ "(00?\\d|1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)$";
return Pattern.matches(hostReg, ip);
}
public static boolean portRegExpTest(String port) {
String hostReg = "^\\d{1,5}$";
return Pattern.matches(hostReg, port);
}
public static boolean versionRegExpTest(String version) {
String versionReg = "^v\\d+(\\.\\d+)?$";
return Pattern.matches(versionReg, version);
}
public static boolean urlRegExpTest(String url) {
if (url.equals("/"))
return true;
String urlReg = "^\\/.*((?!\\/).)$";
return Pattern.matches(urlReg, url);
}
public static boolean apiRouteUrlRegExpTest(String url) {
String urlReg = "^\\/" + ConfigUtil.getInstance().getAPI_ROOT_PATH() + "\\/.*$";
return Pattern.matches(urlReg, url);
}
public static boolean iuiRouteUrlRegExpTest(String url) {
String urlReg = "^\\/" + ConfigUtil.getInstance().getIUI_ROOT_PATH() + "\\/.*$";
return Pattern.matches(urlReg, url);
}
public static String[] apiServiceNameMatch4URL(String url) {
Pattern redisKeyPattern = Pattern.compile(API_KEY_PATTERN);
Matcher matcher = redisKeyPattern.matcher(url + "/");
if (matcher.matches()) {
String version;
if (versionRegExpTest(matcher.group("version"))) {
version = matcher.group("version");
} else {
version = "";
}
return new String[] {matcher.group("servicename"), version};
} else {
return null;
}
}
public static String iuiServiceNameMatch4URL(String url) {
Pattern redisKeyPattern = Pattern.compile(IUI_KEY_PATTERN);
Matcher matcher = redisKeyPattern.matcher(url + "/");
if (matcher.matches()) {
return matcher.group("servicename");
} else {
return null;
}
}
}
|
Andreas237/AndroidPolicyAutomation | ExtractedJars/RT_News_com.rt.mobile.english/javafiles/com/comscore/utils/Base64Coder.java | <filename>ExtractedJars/RT_News_com.rt.mobile.english/javafiles/com/comscore/utils/Base64Coder.java
// Decompiled by Jad v1.5.8g. Copyright 2001 <NAME>.
// Jad home page: http://www.kpdus.com/jad.html
// Decompiler options: packimports(3) annotate safe
package com.comscore.utils;
public class Base64Coder
{
private Base64Coder()
{
// 0 0:aload_0
// 1 1:invokespecial #18 <Method void Object()>
// 2 4:return
}
public static byte[] decode(String s)
{
return decode(s.toCharArray());
// 0 0:aload_0
// 1 1:invokevirtual #26 <Method char[] String.toCharArray()>
// 2 4:invokestatic #29 <Method byte[] decode(char[])>
// 3 7:areturn
}
public static byte[] decode(char ac[])
{
int i = ac.length;
// 0 0:aload_0
// 1 1:arraylength
// 2 2:istore_1
int l = i;
// 3 3:iload_1
// 4 4:istore_3
if(i % 4 != 0)
//* 5 5:iload_1
//* 6 6:iconst_4
//* 7 7:irem
//* 8 8:ifeq 21
throw new IllegalArgumentException("Length of Base64 encoded input string is not a multiple of 4.");
// 9 11:new #31 <Class IllegalArgumentException>
// 10 14:dup
// 11 15:ldc1 #33 <String "Length of Base64 encoded input string is not a multiple of 4.">
// 12 17:invokespecial #36 <Method void IllegalArgumentException(String)>
// 13 20:athrow
for(; l > 0 && ac[l - 1] == '='; l--);
// 14 21:iload_3
// 15 22:ifle 42
// 16 25:aload_0
// 17 26:iload_3
// 18 27:iconst_1
// 19 28:isub
// 20 29:caload
// 21 30:bipush 61
// 22 32:icmpne 42
// 23 35:iload_3
// 24 36:iconst_1
// 25 37:isub
// 26 38:istore_3
//* 27 39:goto 21
int j1 = (l * 3) / 4;
// 28 42:iload_3
// 29 43:iconst_3
// 30 44:imul
// 31 45:iconst_4
// 32 46:idiv
// 33 47:istore 7
byte abyte0[] = new byte[j1];
// 34 49:iload 7
// 35 51:newarray byte[]
// 36 53:astore 10
i = 0;
// 37 55:iconst_0
// 38 56:istore_1
int i1 = 0;
// 39 57:iconst_0
// 40 58:istore 4
while(i < l)
//* 41 60:iload_1
//* 42 61:iload_3
//* 43 62:icmpge 324
{
int j = i + 1;
// 44 65:iload_1
// 45 66:iconst_1
// 46 67:iadd
// 47 68:istore_2
char c2 = ac[i];
// 48 69:aload_0
// 49 70:iload_1
// 50 71:caload
// 51 72:istore 8
i = j + 1;
// 52 74:iload_2
// 53 75:iconst_1
// 54 76:iadd
// 55 77:istore_1
char c3 = ac[j];
// 56 78:aload_0
// 57 79:iload_2
// 58 80:caload
// 59 81:istore 9
char c1 = 'A';
// 60 83:bipush 65
// 61 85:istore 6
char c;
if(i < l)
//* 62 87:iload_1
//* 63 88:iload_3
//* 64 89:icmpge 104
{
j = i + 1;
// 65 92:iload_1
// 66 93:iconst_1
// 67 94:iadd
// 68 95:istore_2
c = ac[i];
// 69 96:aload_0
// 70 97:iload_1
// 71 98:caload
// 72 99:istore 5
} else
//* 73 101:goto 110
{
j = i;
// 74 104:iload_1
// 75 105:istore_2
c = 'A';
// 76 106:bipush 65
// 77 108:istore 5
}
i = j;
// 78 110:iload_2
// 79 111:istore_1
if(j < l)
//* 80 112:iload_2
//* 81 113:iload_3
//* 82 114:icmpge 126
{
c1 = ac[j];
// 83 117:aload_0
// 84 118:iload_2
// 85 119:caload
// 86 120:istore 6
i = j + 1;
// 87 122:iload_2
// 88 123:iconst_1
// 89 124:iadd
// 90 125:istore_1
}
if(c2 <= '\177' && c3 <= '\177' && c <= '\177' && c1 <= '\177')
//* 91 126:iload 8
//* 92 128:bipush 127
//* 93 130:icmpgt 314
//* 94 133:iload 9
//* 95 135:bipush 127
//* 96 137:icmpgt 314
//* 97 140:iload 5
//* 98 142:bipush 127
//* 99 144:icmpgt 314
//* 100 147:iload 6
//* 101 149:bipush 127
//* 102 151:icmple 157
//* 103 154:goto 314
{
c2 = ((char) (b[c2]));
// 104 157:getstatic #14 <Field byte[] b>
// 105 160:iload 8
// 106 162:baload
// 107 163:istore 8
c3 = ((char) (b[c3]));
// 108 165:getstatic #14 <Field byte[] b>
// 109 168:iload 9
// 110 170:baload
// 111 171:istore 9
c = ((char) (b[c]));
// 112 173:getstatic #14 <Field byte[] b>
// 113 176:iload 5
// 114 178:baload
// 115 179:istore 5
c1 = ((char) (b[c1]));
// 116 181:getstatic #14 <Field byte[] b>
// 117 184:iload 6
// 118 186:baload
// 119 187:istore 6
if(c2 >= 0 && c3 >= 0 && c >= 0 && c1 >= 0)
//* 120 189:iload 8
//* 121 191:iflt 304
//* 122 194:iload 9
//* 123 196:iflt 304
//* 124 199:iload 5
//* 125 201:iflt 304
//* 126 204:iload 6
//* 127 206:ifge 212
//* 128 209:goto 304
{
int k = i1 + 1;
// 129 212:iload 4
// 130 214:iconst_1
// 131 215:iadd
// 132 216:istore_2
abyte0[i1] = (byte)(c2 << 2 | c3 >>> 4);
// 133 217:aload 10
// 134 219:iload 4
// 135 221:iload 8
// 136 223:iconst_2
// 137 224:ishl
// 138 225:iload 9
// 139 227:iconst_4
// 140 228:iushr
// 141 229:ior
// 142 230:int2byte
// 143 231:bastore
if(k < j1)
//* 144 232:iload_2
//* 145 233:iload 7
//* 146 235:icmpge 266
{
i1 = k + 1;
// 147 238:iload_2
// 148 239:iconst_1
// 149 240:iadd
// 150 241:istore 4
abyte0[k] = (byte)((c3 & 0xf) << 4 | c >>> 2);
// 151 243:aload 10
// 152 245:iload_2
// 153 246:iload 9
// 154 248:bipush 15
// 155 250:iand
// 156 251:iconst_4
// 157 252:ishl
// 158 253:iload 5
// 159 255:iconst_2
// 160 256:iushr
// 161 257:ior
// 162 258:int2byte
// 163 259:bastore
k = i1;
// 164 260:iload 4
// 165 262:istore_2
}
//* 166 263:goto 266
if(k < j1)
//* 167 266:iload_2
//* 168 267:iload 7
//* 169 269:icmpge 298
{
i1 = k + 1;
// 170 272:iload_2
// 171 273:iconst_1
// 172 274:iadd
// 173 275:istore 4
abyte0[k] = (byte)((c & 3) << 6 | c1);
// 174 277:aload 10
// 175 279:iload_2
// 176 280:iload 5
// 177 282:iconst_3
// 178 283:iand
// 179 284:bipush 6
// 180 286:ishl
// 181 287:iload 6
// 182 289:ior
// 183 290:int2byte
// 184 291:bastore
k = i1;
// 185 292:iload 4
// 186 294:istore_2
}
//* 187 295:goto 298
i1 = k;
// 188 298:iload_2
// 189 299:istore 4
} else
//* 190 301:goto 60
{
throw new IllegalArgumentException("Illegal character in Base64 encoded data.");
// 191 304:new #31 <Class IllegalArgumentException>
// 192 307:dup
// 193 308:ldc1 #38 <String "Illegal character in Base64 encoded data.">
// 194 310:invokespecial #36 <Method void IllegalArgumentException(String)>
// 195 313:athrow
}
} else
{
throw new IllegalArgumentException("Illegal character in Base64 encoded data.");
// 196 314:new #31 <Class IllegalArgumentException>
// 197 317:dup
// 198 318:ldc1 #38 <String "Illegal character in Base64 encoded data.">
// 199 320:invokespecial #36 <Method void IllegalArgumentException(String)>
// 200 323:athrow
}
}
return abyte0;
// 201 324:aload 10
// 202 326:areturn
}
public static String decodeString(String s)
{
return new String(decode(s));
// 0 0:new #22 <Class String>
// 1 3:dup
// 2 4:aload_0
// 3 5:invokestatic #42 <Method byte[] decode(String)>
// 4 8:invokespecial #45 <Method void String(byte[])>
// 5 11:areturn
}
public static char[] encode(byte abyte0[])
{
return encode(abyte0, abyte0.length);
// 0 0:aload_0
// 1 1:aload_0
// 2 2:arraylength
// 3 3:invokestatic #50 <Method char[] encode(byte[], int)>
// 4 6:areturn
}
public static char[] encode(byte abyte0[], int i)
{
int l1 = (i * 4 + 2) / 3;
// 0 0:iload_1
// 1 1:iconst_4
// 2 2:imul
// 3 3:iconst_2
// 4 4:iadd
// 5 5:iconst_3
// 6 6:idiv
// 7 7:istore 9
char ac[] = new char[((i + 2) / 3) * 4];
// 8 9:iload_1
// 9 10:iconst_2
// 10 11:iadd
// 11 12:iconst_3
// 12 13:idiv
// 13 14:iconst_4
// 14 15:imul
// 15 16:newarray char[]
// 16 18:astore 11
int j = 0;
// 17 20:iconst_0
// 18 21:istore 4
for(int k = j; j < i; k++)
//* 19 23:iload 4
//* 20 25:istore 5
//* 21 27:iload 4
//* 22 29:iload_1
//* 23 30:icmpge 238
{
int l = j + 1;
// 24 33:iload 4
// 25 35:iconst_1
// 26 36:iadd
// 27 37:istore 6
int i2 = abyte0[j] & 0xff;
// 28 39:aload_0
// 29 40:iload 4
// 30 42:baload
// 31 43:sipush 255
// 32 46:iand
// 33 47:istore 10
if(l < i)
//* 34 49:iload 6
//* 35 51:iload_1
//* 36 52:icmpge 74
{
j = l + 1;
// 37 55:iload 6
// 38 57:iconst_1
// 39 58:iadd
// 40 59:istore 4
l = abyte0[l] & 0xff;
// 41 61:aload_0
// 42 62:iload 6
// 43 64:baload
// 44 65:sipush 255
// 45 68:iand
// 46 69:istore 6
} else
//* 47 71:goto 81
{
j = l;
// 48 74:iload 6
// 49 76:istore 4
l = 0;
// 50 78:iconst_0
// 51 79:istore 6
}
int i1;
if(j < i)
//* 52 81:iload 4
//* 53 83:iload_1
//* 54 84:icmpge 110
{
int j1 = j + 1;
// 55 87:iload 4
// 56 89:iconst_1
// 57 90:iadd
// 58 91:istore 8
i1 = abyte0[j] & 0xff;
// 59 93:aload_0
// 60 94:iload 4
// 61 96:baload
// 62 97:sipush 255
// 63 100:iand
// 64 101:istore 7
j = j1;
// 65 103:iload 8
// 66 105:istore 4
} else
//* 67 107:goto 113
{
i1 = 0;
// 68 110:iconst_0
// 69 111:istore 7
}
int k1 = k + 1;
// 70 113:iload 5
// 71 115:iconst_1
// 72 116:iadd
// 73 117:istore 8
ac[k] = a[i2 >>> 2];
// 74 119:aload 11
// 75 121:iload 5
// 76 123:getstatic #12 <Field char[] a>
// 77 126:iload 10
// 78 128:iconst_2
// 79 129:iushr
// 80 130:caload
// 81 131:castore
k = k1 + 1;
// 82 132:iload 8
// 83 134:iconst_1
// 84 135:iadd
// 85 136:istore 5
ac[k1] = a[(i2 & 3) << 4 | l >>> 4];
// 86 138:aload 11
// 87 140:iload 8
// 88 142:getstatic #12 <Field char[] a>
// 89 145:iload 10
// 90 147:iconst_3
// 91 148:iand
// 92 149:iconst_4
// 93 150:ishl
// 94 151:iload 6
// 95 153:iconst_4
// 96 154:iushr
// 97 155:ior
// 98 156:caload
// 99 157:castore
byte byte0 = 61;
// 100 158:bipush 61
// 101 160:istore_3
char c;
if(k < l1)
//* 102 161:iload 5
//* 103 163:iload 9
//* 104 165:icmpge 189
c = a[(l & 0xf) << 2 | i1 >>> 6];
// 105 168:getstatic #12 <Field char[] a>
// 106 171:iload 6
// 107 173:bipush 15
// 108 175:iand
// 109 176:iconst_2
// 110 177:ishl
// 111 178:iload 7
// 112 180:bipush 6
// 113 182:iushr
// 114 183:ior
// 115 184:caload
// 116 185:istore_2
else
//* 117 186:goto 192
c = '=';
// 118 189:bipush 61
// 119 191:istore_2
ac[k] = c;
// 120 192:aload 11
// 121 194:iload 5
// 122 196:iload_2
// 123 197:castore
k++;
// 124 198:iload 5
// 125 200:iconst_1
// 126 201:iadd
// 127 202:istore 5
c = ((char) (byte0));
// 128 204:iload_3
// 129 205:istore_2
if(k < l1)
//* 130 206:iload 5
//* 131 208:iload 9
//* 132 210:icmpge 223
c = a[i1 & 0x3f];
// 133 213:getstatic #12 <Field char[] a>
// 134 216:iload 7
// 135 218:bipush 63
// 136 220:iand
// 137 221:caload
// 138 222:istore_2
ac[k] = c;
// 139 223:aload 11
// 140 225:iload 5
// 141 227:iload_2
// 142 228:castore
}
// 143 229:iload 5
// 144 231:iconst_1
// 145 232:iadd
// 146 233:istore 5
//* 147 235:goto 27
return ac;
// 148 238:aload 11
// 149 240:areturn
}
public static String encodeString(String s)
{
return new String(encode(s.getBytes()));
// 0 0:new #22 <Class String>
// 1 3:dup
// 2 4:aload_0
// 3 5:invokevirtual #55 <Method byte[] String.getBytes()>
// 4 8:invokestatic #57 <Method char[] encode(byte[])>
// 5 11:invokespecial #60 <Method void String(char[])>
// 6 14:areturn
}
private static char a[];
private static byte b[];
static
{
a = new char[64];
// 0 0:bipush 64
// 1 2:newarray char[]
// 2 4:putstatic #12 <Field char[] a>
boolean flag = false;
// 3 7:iconst_0
// 4 8:istore_3
char c = 'A';
// 5 9:bipush 65
// 6 11:istore_0
int i;
for(i = 0; c <= 'Z'; i++)
//* 7 12:iconst_0
//* 8 13:istore_1
//* 9 14:iload_0
//* 10 15:bipush 90
//* 11 17:icmpgt 38
{
a[i] = c;
// 12 20:getstatic #12 <Field char[] a>
// 13 23:iload_1
// 14 24:iload_0
// 15 25:castore
c++;
// 16 26:iload_0
// 17 27:iconst_1
// 18 28:iadd
// 19 29:int2char
// 20 30:istore_0
}
// 21 31:iload_1
// 22 32:iconst_1
// 23 33:iadd
// 24 34:istore_1
//* 25 35:goto 14
for(char c1 = 'a'; c1 <= 'z';)
//* 26 38:bipush 97
//* 27 40:istore_0
//* 28 41:iload_0
//* 29 42:bipush 122
//* 30 44:icmpgt 65
{
a[i] = c1;
// 31 47:getstatic #12 <Field char[] a>
// 32 50:iload_1
// 33 51:iload_0
// 34 52:castore
c1++;
// 35 53:iload_0
// 36 54:iconst_1
// 37 55:iadd
// 38 56:int2char
// 39 57:istore_0
i++;
// 40 58:iload_1
// 41 59:iconst_1
// 42 60:iadd
// 43 61:istore_1
}
//* 44 62:goto 41
for(char c2 = '0'; c2 <= '9';)
//* 45 65:bipush 48
//* 46 67:istore_0
//* 47 68:iload_0
//* 48 69:bipush 57
//* 49 71:icmpgt 92
{
a[i] = c2;
// 50 74:getstatic #12 <Field char[] a>
// 51 77:iload_1
// 52 78:iload_0
// 53 79:castore
c2++;
// 54 80:iload_0
// 55 81:iconst_1
// 56 82:iadd
// 57 83:int2char
// 58 84:istore_0
i++;
// 59 85:iload_1
// 60 86:iconst_1
// 61 87:iadd
// 62 88:istore_1
}
//* 63 89:goto 68
a[i] = '+';
// 64 92:getstatic #12 <Field char[] a>
// 65 95:iload_1
// 66 96:bipush 43
// 67 98:castore
a[i + 1] = '/';
// 68 99:getstatic #12 <Field char[] a>
// 69 102:iload_1
// 70 103:iconst_1
// 71 104:iadd
// 72 105:bipush 47
// 73 107:castore
b = new byte[128];
// 74 108:sipush 128
// 75 111:newarray byte[]
// 76 113:putstatic #14 <Field byte[] b>
i = 0;
// 77 116:iconst_0
// 78 117:istore_1
int j;
do
{
j = ((int) (flag));
// 79 118:iload_3
// 80 119:istore_2
if(i >= b.length)
break;
// 81 120:iload_1
// 82 121:getstatic #14 <Field byte[] b>
// 83 124:arraylength
// 84 125:icmpge 141
b[i] = -1;
// 85 128:getstatic #14 <Field byte[] b>
// 86 131:iload_1
// 87 132:iconst_m1
// 88 133:bastore
i++;
// 89 134:iload_1
// 90 135:iconst_1
// 91 136:iadd
// 92 137:istore_1
} while(true);
// 93 138:goto 118
for(; j < 64; j++)
//* 94 141:iload_2
//* 95 142:bipush 64
//* 96 144:icmpge 165
b[a[j]] = (byte)j;
// 97 147:getstatic #14 <Field byte[] b>
// 98 150:getstatic #12 <Field char[] a>
// 99 153:iload_2
// 100 154:caload
// 101 155:iload_2
// 102 156:int2byte
// 103 157:bastore
// 104 158:iload_2
// 105 159:iconst_1
// 106 160:iadd
// 107 161:istore_2
//* 108 162:goto 141
//* 109 165:return
}
}
|
manuel103/Healthy-Mind | Android/Healthy Mind/app/src/main/java/com/example/healthymind/mvp/Presenter.java | package com.example.healthymind.mvp;
public interface Presenter<V extends BaseMvpView> {
void attachView(V mvpView);
void detachView();
}
|
CEOALT1/RefindPlusUDK | StdLib/LibC/Stdio/fgetstr.c | /*
Copyright (c) 2010 - 2011, Intel Corporation. All rights reserved.<BR>
This program and the accompanying materials are licensed and made available
under the terms and conditions of the BSD License that accompanies this
distribution. The full text of the license may be found at
http://opensource.org/licenses/bsd-license.
THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
* Copyright (c) 1990, 1993
* The Regents of the University of California. All rights reserved.
*
* This code is derived from software contributed to Berkeley by
* <NAME>.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
$NetBSD: fgetstr.c,v 1.4 2006/11/24 19:46:58 christos Exp $
fgetline.c 8.1 (Berkeley) 6/4/93
*/
/*-
*/
#include <LibConfig.h>
#include <sys/EfiCdefs.h>
#include "namespace.h"
#include <assert.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "reentrant.h"
#include "local.h"
/*
* Expand the line buffer. Return -1 on error.
#ifdef notdef
* The `new size' does not account for a terminating '\0',
* so we add 1 here.
#endif
*/
int
__slbexpand(FILE *fp, size_t newsize)
{
void *p;
#ifdef notdef
++newsize;
#endif
_DIAGASSERT(fp != NULL);
if(fp == NULL) {
errno = EINVAL;
return (-1);
}
if ((size_t)fp->_lb._size >= newsize)
return (0);
if ((p = realloc(fp->_lb._base, newsize)) == NULL)
return (-1);
fp->_lb._base = p;
fp->_lb._size = (int)newsize;
return (0);
}
/*
* Get an input line. The returned pointer often (but not always)
* points into a stdio buffer. Fgetline does not alter the text of
* the returned line (which is thus not a C string because it will
* not necessarily end with '\0'), but does allow callers to modify
* it if they wish. Thus, we set __SMOD in case the caller does.
*/
char *
__fgetstr(FILE *fp, size_t *lenp, int sep)
{
unsigned char *p;
size_t len;
size_t off;
_DIAGASSERT(fp != NULL);
_DIAGASSERT(lenp != NULL);
if(fp == NULL) {
errno = EINVAL;
return (NULL);
}
/* make sure there is input */
if (fp->_r <= 0 && __srefill(fp)) {
*lenp = 0;
return (NULL);
}
/* look for a newline in the input */
if ((p = memchr((void *)fp->_p, sep, (size_t)fp->_r)) != NULL) {
char *ret;
/*
* Found one. Flag buffer as modified to keep fseek from
* `optimising' a backward seek, in case the user stomps on
* the text.
*/
p++; /* advance over it */
ret = (char *)fp->_p;
*lenp = len = p - fp->_p;
fp->_flags |= __SMOD;
fp->_r -= (int)len;
fp->_p = p;
return (ret);
}
/*
* We have to copy the current buffered data to the line buffer.
* As a bonus, though, we can leave off the __SMOD.
*
* OPTIMISTIC is length that we (optimistically) expect will
* accommodate the `rest' of the string, on each trip through the
* loop below.
*/
#define OPTIMISTIC 80
for (len = fp->_r, off = 0;; len += fp->_r) {
size_t diff;
/*
* Make sure there is room for more bytes. Copy data from
* file buffer to line buffer, refill file and look for
* newline. The loop stops only when we find a newline.
*/
if (__slbexpand(fp, len + OPTIMISTIC))
goto error;
(void)memcpy((void *)(fp->_lb._base + off), (void *)fp->_p,
len - off);
off = len;
if (__srefill(fp))
break; /* EOF or error: return partial line */
if ((p = memchr((void *)fp->_p, sep, (size_t)fp->_r)) == NULL)
continue;
/* got it: finish up the line (like code above) */
p++;
diff = p - fp->_p;
len += diff;
if (__slbexpand(fp, len))
goto error;
(void)memcpy((void *)(fp->_lb._base + off), (void *)fp->_p,
diff);
fp->_r -= (int)diff;
fp->_p = p;
break;
}
*lenp = len;
#ifdef notdef
fp->_lb._base[len] = 0;
#endif
return ((char *)fp->_lb._base);
error:
*lenp = 0; /* ??? */
return (NULL); /* ??? */
}
|
MrBattary/darkest-castle | include/game/systems/elementsInterfaceSystem/messageBoxes/LeaderboardBox.h | <reponame>MrBattary/darkest-castle
//
// Created by Battary on 29.07.2020.
//
#pragma once
#include <fstream>
#include <map>
#include <string>
#include <utility>
// Internal templates
#include "../IMessageBoxElement.h"
// Entities
#include "game/entities/PlayerEntity.h"
// Components
#include "game/components/StatisticsComponent.h"
// Таблица рекордов
class LeaderboardBox : public IMessageBoxElement {
private:
int openStream(std::ifstream& stream);
int openStream(std::ofstream& stream);
public:
std::map<size_t, std::pair<size_t, std::string>> leaderboard_;
LeaderboardBox();
void updateElement(ecs::World&) override;
~LeaderboardBox() override = default;
};
|
zjzh/chainer | tests/onnx_chainer_tests/functions_tests/test_rnn.py | import chainer
import chainer.functions as F
import chainer.links as L
from chainer import testing
import numpy as np
from onnx_chainer import onnx_helper
from onnx_chainer.testing import input_generator
from onnx_chainer_tests.helper import ONNXModelTest
@testing.parameterize(
{'n_layers': 1, 'name': 'n_step_gru_1_layer'},
{'n_layers': 2, 'name': 'n_step_gru_2_layer'},
)
class TestNStepGRU(ONNXModelTest):
def test_output(self):
n_layers = self.n_layers
dropout_ratio = 0.0
batch_size = 3
input_size = 4
hidden_size = 5
seq_length = 6
class Model(chainer.Chain):
def __init__(self):
super().__init__()
def __call__(self, hx, ws1, ws2, ws3, bs, xs):
ws = [F.separate(ws1) + F.separate(ws2)]
if n_layers > 1:
ws.extend([F.separate(w) for w in F.separate(ws3)])
bs = [F.separate(b) for b in F.separate(bs)]
xs = F.separate(xs)
hy, ys = F.n_step_gru(n_layers, dropout_ratio,
hx, ws, bs, xs)
return hy, F.stack(ys, axis=0)
model = Model()
hx = input_generator.increasing(n_layers, batch_size, hidden_size)
ws1 = input_generator.increasing(3, hidden_size, input_size)
ws2 = input_generator.increasing(3, hidden_size, hidden_size)
ws3 = input_generator.increasing(
n_layers - 1, 6, hidden_size, hidden_size)
bs = input_generator.increasing(n_layers, 6, hidden_size)
xs = input_generator.increasing(seq_length, batch_size, input_size)
self.expect(model, (hx, ws1, ws2, ws3, bs, xs))
def convert_Permutate(params):
gb = onnx_helper.GraphBuilder()
# indices_name = params.context.get_name(func.indices)
indices_name = params.context.add_const(params.func.indices,
'indices') # XXX
if params.func.inv:
empty = params.context.add_const(
np.zeros(dtype=np.int64, shape=params.func.indices.shape), 'empty')
r = params.context.add_const(
np.arange(len(params.func.indices), dtype=np.int64),
'range')
op = 'ScatterElements' if params.opset_version == 11 else 'Scatter'
indices_name = gb.op(op, [empty, indices_name, r])
params.input_names.append(indices_name)
gb.op_output_named('Gather', params.input_names, params.output_names,
axis=params.func.axis)
return gb.nodes()
@testing.parameterize(
{'n_layers': 1, 'name': 'TestNStepGRU_1_layer'},
{'n_layers': 2, 'name': 'TestNStepGRU_2_layer'},
)
class TestNStepGRULink(ONNXModelTest):
def test_output(self):
n_layers = self.n_layers
dropout_ratio = 0.0
batch_size = 3
input_size = 4
hidden_size = 5
seq_length = 6
class Model(chainer.Chain):
def __init__(self):
super().__init__()
with self.init_scope():
self.gru = L.NStepGRU(
n_layers, input_size, hidden_size, dropout_ratio)
def __call__(self, *xs):
hy, ys = self.gru(None, xs)
return [hy] + ys
model = Model()
xs = [input_generator.increasing(seq_length, input_size)
for i in range(batch_size)]
# NOTE(msakai): Replace Permutate converter for avoiding error like:
# ValidationError: Nodes in a graph must be topologically sorted, \
# however input 'v330' of node:
# input: "Permutate_0_const_empty" input: "v330" \
# input: "Permutate_0_const_range" output: "Permutate_0_tmp_0" \
# name: "Permutate_0_tmp_0" op_type: "Scatter"
# is not output of any previous nodes.
addon_converters = {
'Permutate': convert_Permutate,
}
self.expect(model, xs, skip_opset_version=[7, 8],
external_converters=addon_converters)
|
LorianeE/connect | boot/keys.js | /* global process */
/**
* Module dependencies
*/
var AnvilConnectKeys = require('anvil-connect-keys')
/**
* Create a keypair client
*/
var keygen = new AnvilConnectKeys()
/**
* Attempt to load the key pairs
*/
var keys
try { keys = keygen.loadKeyPairs() } catch (e) {}
/**
* If the keypairs don't exist, try to create them
*/
if (!keys) {
try {
keygen.generateKeyPairs()
keys = keygen.loadKeyPairs()
} catch (e) {
console.log(e)
process.exit(1)
}
}
/**
* Export
*/
module.exports = keys
|
UniversalAvenue/redux-lager | src/reducer.js | import { combineReducers } from 'redux';
import meta from './meta-reducer';
import entities from './entities-reducer';
import result from './result-reducer';
import pagination from './pagination-reducer';
export default combineReducers({
meta,
entities,
result,
pagination,
});
|
mplibunao/auth | test/external-policy.js | <filename>test/external-policy.js
'use strict'
const t = require('tap')
const Fastify = require('fastify')
const mercurius = require('mercurius')
const mercuriusAuth = require('..')
const schema = `
type Message {
title: String!
public: String!
private: String
}
type Query {
add(x: Int, y: Int): Int
subtract(x: Int, y: Int): Int
messages: [Message!]!
adminMessages: [Message!]
}
`
const resolvers = {
Query: {
add: async (_, obj) => {
const { x, y } = obj
return x + y
},
subtract: async (_, obj) => {
const { x, y } = obj
return x - y
},
messages: async () => {
return [
{
title: 'one',
public: 'public one',
private: 'private one'
},
{
title: 'two',
public: 'public two',
private: 'private two'
}
]
},
adminMessages: async () => {
return [
{
title: 'admin one',
public: 'admin public one',
private: 'admin private one'
},
{
title: '<NAME>',
public: 'admin public two',
private: 'admin private two'
}
]
}
}
}
t.test('external policy', t => {
t.plan(8)
t.test('should protect the schema and not affect queries when everything is okay', async (t) => {
t.plan(8)
const app = Fastify()
t.teardown(app.close.bind(app))
app.register(mercurius, {
schema,
resolvers
})
app.register(mercuriusAuth, {
authContext (context) {
return {
identity: context.reply.request.headers['x-user']
}
},
async applyPolicy (policy, parent, args, context, info) {
t.ok(policy)
return context.auth.identity.includes(policy.requires)
},
mode: 'external',
policy: {
Wrong: {},
Message: {
private: { requires: 'admin' },
wrong: { requires: '' }
},
Query: {
add: { requires: 'admin' },
adminMessages: { requires: 'admin' }
}
}
})
const query = `query {
four: add(x: 2, y: 2)
six: add(x: 3, y: 3)
subtract(x: 3, y: 3)
messages {
title
public
private
}
adminMessages {
title
public
private
}
}`
const response = await app.inject({
method: 'POST',
headers: { 'content-type': 'application/json', 'X-User': 'admin' },
url: '/graphql',
body: JSON.stringify({ query })
})
t.same(JSON.parse(response.body), {
data: {
four: 4,
six: 6,
subtract: 0,
messages: [
{
title: 'one',
public: 'public one',
private: 'private one'
},
{
title: 'two',
public: 'public two',
private: 'private two'
}
],
adminMessages: [
{
title: 'admin one',
public: 'admin public one',
private: 'admin private one'
},
{
title: 'admin two',
public: 'admin public two',
private: 'admin private two'
}
]
}
})
})
t.test('should protect the schema and error accordingly', async (t) => {
t.plan(1)
const app = Fastify()
t.teardown(app.close.bind(app))
app.register(mercurius, {
schema,
resolvers
})
app.register(mercuriusAuth, {
authContext (context) {
return {
identity: context.reply.request.headers['x-user']
}
},
async applyPolicy (policy, parent, args, context, info) {
return context.auth.identity.includes(policy.requires)
},
mode: 'external',
policy: {
Wrong: {},
Message: {
private: { requires: 'admin' },
wrong: { requires: '' }
},
Query: {
add: { requires: 'admin' },
adminMessages: { requires: 'admin' }
}
}
})
const query = `query {
four: add(x: 2, y: 2)
six: add(x: 3, y: 3)
subtract(x: 3, y: 3)
messages {
title
public
private
}
adminMessages {
title
public
private
}
}`
const response = await app.inject({
method: 'POST',
headers: { 'content-type': 'application/json', 'X-User': 'user' },
url: '/graphql',
body: JSON.stringify({ query })
})
t.same(JSON.parse(response.body), {
data: {
four: null,
six: null,
subtract: 0,
messages: [
{
title: 'one',
public: 'public one',
private: null
},
{
title: 'two',
public: 'public two',
private: null
}
],
adminMessages: null
},
errors: [
{ message: 'Failed auth policy check on add', locations: [{ line: 2, column: 7 }], path: ['four'] },
{ message: 'Failed auth policy check on add', locations: [{ line: 3, column: 7 }], path: ['six'] },
{ message: 'Failed auth policy check on adminMessages', locations: [{ line: 10, column: 7 }], path: ['adminMessages'] },
{ message: 'Failed auth policy check on private', locations: [{ line: 8, column: 9 }], path: ['messages', 0, 'private'] },
{ message: 'Failed auth policy check on private', locations: [{ line: 8, column: 9 }], path: ['messages', 1, 'private'] }
]
})
})
t.test('should handle when no fields within a type are allowed', async (t) => {
t.plan(1)
const schema = `
type Message {
title: String
private: String
}
type Query {
add(x: Int, y: Int): Int
subtract(x: Int, y: Int): Int
messages: [Message!]!
}
`
const resolvers = {
Query: {
add: async (_, obj) => {
const { x, y } = obj
return x + y
},
subtract: async (_, obj) => {
const { x, y } = obj
return x - y
},
messages: async () => {
return [
{
title: 'one',
private: 'private one'
},
{
title: 'two',
private: 'private two'
}
]
}
}
}
const query = `query {
four: add(x: 2, y: 2)
six: add(x: 3, y: 3)
subtract(x: 3, y: 3)
messages {
title
private
}
}`
const app = Fastify()
t.teardown(app.close.bind(app))
app.register(mercurius, {
schema,
resolvers
})
app.register(mercuriusAuth, {
authContext (context) {
return {
identity: context.reply.request.headers['x-user']
}
},
async applyPolicy (policy, parent, args, context, info) {
return context.auth.identity.includes(policy.requires)
},
mode: 'external',
policy: {
Message: {
private: { requires: 'admin' },
title: { requires: 'admin' }
},
Query: {
add: { requires: 'admin' }
}
}
})
const response = await app.inject({
method: 'POST',
headers: { 'content-type': 'application/json', 'X-User': 'user' },
url: '/graphql',
body: JSON.stringify({ query })
})
t.same(JSON.parse(response.body), {
data: {
four: null,
six: null,
subtract: 0,
messages: [
{
title: null,
private: null
},
{
title: null,
private: null
}
]
},
errors: [
{ message: 'Failed auth policy check on add', locations: [{ line: 2, column: 7 }], path: ['four'] },
{ message: 'Failed auth policy check on add', locations: [{ line: 3, column: 7 }], path: ['six'] },
{ message: 'Failed auth policy check on title', locations: [{ line: 6, column: 9 }], path: ['messages', 0, 'title'] },
{ message: 'Failed auth policy check on private', locations: [{ line: 7, column: 9 }], path: ['messages', 0, 'private'] },
{ message: 'Failed auth policy check on title', locations: [{ line: 6, column: 9 }], path: ['messages', 1, 'title'] },
{ message: 'Failed auth policy check on private', locations: [{ line: 7, column: 9 }], path: ['messages', 1, 'private'] }
]
})
})
t.test('should support jit', async (t) => {
t.plan(2)
const app = Fastify()
t.teardown(app.close.bind(app))
app.register(mercurius, {
schema,
resolvers,
jit: 1
})
app.register(mercuriusAuth, {
authContext (context) {
return {
identity: context.reply.request.headers['x-user']
}
},
async applyPolicy (policy, parent, args, context, info) {
return context.auth.identity.includes(policy.requires)
},
mode: 'external',
policy: {
Wrong: {},
Message: {
private: { requires: 'admin' },
wrong: { requires: '' }
},
Query: {
add: { requires: 'admin' },
adminMessages: { requires: 'admin' }
}
}
})
const query = `query {
four: add(x: 2, y: 2)
six: add(x: 3, y: 3)
subtract(x: 3, y: 3)
messages {
title
public
private
}
adminMessages {
title
public
private
}
}`
{
const response = await app.inject({
method: 'POST',
headers: { 'content-type': 'application/json', 'X-User': 'user' },
url: '/graphql',
body: JSON.stringify({ query })
})
t.same(JSON.parse(response.body), {
data: {
four: null,
six: null,
subtract: 0,
messages: [
{
title: 'one',
public: 'public one',
private: null
},
{
title: 'two',
public: 'public two',
private: null
}
],
adminMessages: null
},
errors: [
{
message: 'Failed auth policy check on add',
locations: [
{
line: 2,
column: 7
}
],
path: [
'four'
]
},
{
message: 'Failed auth policy check on add',
locations: [
{
line: 3,
column: 7
}
],
path: [
'six'
]
},
{
message: 'Failed auth policy check on adminMessages',
locations: [
{
line: 10,
column: 7
}
],
path: [
'adminMessages'
]
},
{
message: 'Failed auth policy check on private',
locations: [
{
line: 8,
column: 9
}
],
path: [
'messages',
'0',
'private'
]
},
{
message: 'Failed auth policy check on private',
locations: [
{
line: 8,
column: 9
}
],
path: [
'messages',
'1',
'private'
]
}
]
})
}
// Trigger JIT compilation
{
const response = await app.inject({
method: 'POST',
headers: { 'content-type': 'application/json', 'X-User': 'user' },
url: '/graphql',
body: JSON.stringify({ query })
})
t.same(JSON.parse(response.body), {
data: {
four: null,
six: null,
subtract: 0,
messages: [
{
title: 'one',
public: 'public one',
private: null
},
{
title: 'two',
public: 'public two',
private: null
}
],
adminMessages: null
},
errors: [
{
message: 'Failed auth policy check on add',
locations: [
{
line: 2,
column: 7
}
],
path: [
'four'
]
},
{
message: 'Failed auth policy check on add',
locations: [
{
line: 3,
column: 7
}
],
path: [
'six'
]
},
{
message: 'Failed auth policy check on adminMessages',
locations: [
{
line: 10,
column: 7
}
],
path: [
'adminMessages'
]
},
{
message: 'Failed auth policy check on private',
locations: [
{
line: 8,
column: 9
}
],
path: [
'messages',
'0',
'private'
]
},
{
message: 'Failed auth policy check on private',
locations: [
{
line: 8,
column: 9
}
],
path: [
'messages',
'1',
'private'
]
}
]
})
}
})
t.test('should work at type level with field resolvers', async (t) => {
t.plan(1)
const schema = `
type Query {
getUser: User
}
type User {
id: Int
name: String
}`
const resolvers = {
Query: {
getUser: async (_, obj) => ({
id: 1,
name: 'test user',
test: 'TEST'
})
},
User: {
id: async (src) => src.id
}
}
const query = `query {
getUser {
id
name
}
}`
const app = Fastify()
t.teardown(app.close.bind(app))
app.register(mercurius, {
schema,
resolvers
})
app.register(mercuriusAuth, {
authContext (context) {
return {
identity: context.reply.request.headers['x-user']
}
},
async applyPolicy (policy, parent, args, context, info) {
return context.auth.identity.includes(policy.requires)
},
mode: 'external',
policy: {
User: {
__typePolicy: { requires: 'admin' }
}
}
})
const response = await app.inject({
method: 'POST',
headers: { 'content-type': 'application/json', 'X-User': 'admin' },
url: '/graphql',
body: JSON.stringify({ query })
})
t.same(JSON.parse(response.body), {
data: {
getUser: {
id: 1,
name: 'test user'
}
}
})
})
t.test('should work at type level with nested directive', async (t) => {
t.plan(1)
const schema = `
type Query {
getUser: User
}
type User {
id: Int
name: String
protected: String
}`
const resolvers = {
Query: {
getUser: async (_, obj) => ({
id: 1,
name: 'test user',
protected: 'protected data'
})
},
User: {
id: async (src) => src.id
}
}
const query = `query {
getUser {
id
name
protected
}
}`
const app = Fastify()
t.teardown(app.close.bind(app))
app.register(mercurius, {
schema,
resolvers
})
app.register(mercuriusAuth, {
authContext (context) {
return {
identity: context.reply.request.headers['x-user']
}
},
async applyPolicy (policy, parent, args, context, info) {
return context.auth.identity.includes(policy.requires)
},
mode: 'external',
policy: {
User: {
__typePolicy: { requires: 'user' },
protected: { requires: 'admin' }
}
}
})
const response = await app.inject({
method: 'POST',
headers: { 'content-type': 'application/json', 'X-User': 'user' },
url: '/graphql',
body: JSON.stringify({ query })
})
t.same(JSON.parse(response.body), {
data: {
getUser: {
id: 1,
name: 'test user',
protected: null
}
},
errors: [
{ message: 'Failed auth policy check on protected', locations: [{ line: 5, column: 9 }], path: ['getUser', 'protected'] }
]
})
})
t.test('should error for all fields in type', async (t) => {
t.plan(1)
const schema = `
type Query {
getUser: User
}
type User {
id: Int
name: String
}`
const resolvers = {
Query: {
getUser: async (_, obj) => ({
id: 1,
name: 'testuser'
})
},
User: {
id: async (src) => src.id
}
}
const query = `query {
getUser {
id
name
}
}`
const app = Fastify()
t.teardown(app.close.bind(app))
app.register(mercurius, {
schema,
resolvers
})
app.register(mercuriusAuth, {
authContext (context) {
return {
identity: context.reply.request.headers['x-user']
}
},
async applyPolicy (policy, parent, args, context, info) {
return context.auth.identity.includes(policy.requires)
},
mode: 'external',
policy: {
User: {
__typePolicy: { requires: 'admin' }
}
}
})
const response = await app.inject({
method: 'POST',
headers: { 'content-type': 'application/json', 'X-User': 'user' },
url: '/graphql',
body: JSON.stringify({ query })
})
t.same(JSON.parse(response.body), {
data: {
getUser: {
id: null,
name: null
}
},
errors: [
{ message: 'Failed auth policy check on id', locations: [{ line: 3, column: 9 }], path: ['getUser', 'id'] },
{ message: 'Failed auth policy check on name', locations: [{ line: 4, column: 9 }], path: ['getUser', 'name'] }
]
})
})
t.test('should work at type level for reference resolvers', async (t) => {
t.plan(2)
const schema = `
type Query {
getUser: User
}
type User @key(fields: "id") {
id: Int
name: String
protected: String
}`
const resolvers = {
Query: {
getUser: async (_, obj) => ({
id: 1,
name: 'test user',
protected: 'protected data'
})
},
User: {
__resolveReference ({ id }) {
return {
id,
name: 'test user'
}
}
}
}
const variables = {
representations: [
{
__typename: 'User',
id: 1
}
]
}
const query = `query GetEntities($representations: [_Any!]!) {
_entities(representations: $representations) {
__typename
... on User {
id
name
}
}
}`
const app = Fastify()
t.teardown(app.close.bind(app))
app.register(mercurius, {
schema,
resolvers,
federationMetadata: true
})
app.register(mercuriusAuth, {
authContext (context) {
return {
identity: context.reply.request.headers['x-user']
}
},
async applyPolicy (policy, parent, args, context, info) {
return context.auth.identity.includes(policy.requires)
},
mode: 'external',
policy: {
User: {
__typePolicy: { requires: 'user' },
protected: { requires: 'admin' }
}
}
})
const response = await app.inject({
method: 'POST',
headers: { 'content-type': 'application/json', 'x-user': 'user' },
url: '/graphql',
body: JSON.stringify({ variables, query })
})
t.same(JSON.parse(response.body), {
data: {
_entities: [
{
__typename: 'User',
id: 1,
name: 'test user'
}
]
}
})
const responseBad = await app.inject({
method: 'POST',
headers: { 'content-type': 'application/json', 'x-user': 'guest' },
url: '/graphql',
body: JSON.stringify({ variables, query })
})
t.same(JSON.parse(responseBad.body), {
data: {
_entities: [
null
]
},
errors: [
{
message: 'Failed auth policy check on _entities',
locations: [
{
line: 2,
column: 7
}
],
path: [
'_entities',
'0'
]
}
]
})
})
})
|
omegachyll/wg-manager | wg_dashboard_backend/script/obfuscate/obfs4.py | from script.obfuscate import BaseObfuscation
import re
class ObfuscateOBFS4(BaseObfuscation):
def __init__(self):
super().__init__(
binary_name="obfs4proxy",
binary_path="/usr/bin/obfs4proxy",
algorithm="obfs4"
)
self.ensure_installed()
def ensure_installed(self):
super().ensure_installed()
output, code = self.execute("-version")
if re.match(f'{self.binary_name}-[0-9]+.[0-9]+.[0-9]+', output) and code == 0:
return True
else:
raise RuntimeError(f"Could not verify that {self.binary_name} is installed correctly.")
if __name__ == "__main__":
x = ObfuscateOBFS4()
x.ensure_installed() |
ryleykimmel/brandywine | game/src/main/java/me/ryleykimmel/brandywine/game/model/player/PlayerCredentials.java | <gh_stars>1-10
package me.ryleykimmel.brandywine.game.model.player;
import com.google.common.base.MoreObjects;
import java.util.Arrays;
import me.ryleykimmel.brandywine.common.util.NameUtil;
/**
* Represents the credentials of a Player.
*/
public final class PlayerCredentials {
/**
* The user id.
*/
private final int userId;
/**
* The username.
*/
private final String username;
/**
* The password.
*/
private final String password;
/**
* The encoded username
*/
private final long encodedUsername;
/**
* The session ids.
*/
private final int[] sessionIds;
/**
* Constructs a new {@link PlayerCredentials} with the specified user id, username, password and session ids.
*
* @param userId The user id.
* @param username The username.
* @param password The password.
* @param sessionIds The session ids.
*/
public PlayerCredentials(int userId, String username, String password, int[] sessionIds) {
this.userId = userId;
this.username = username;
this.password = password;
this.sessionIds = sessionIds;
this.encodedUsername = NameUtil.encodeBase37(username);
}
/**
* Gets the user id.
*
* @return The user id.
*/
public int getUserId() {
return userId;
}
/**
* Gets the username.
*
* @return The username.
*/
public String getUsername() {
return username;
}
/**
* Gets the password.
*
* @return The password.
*/
public String getPassword() {
return password;
}
/**
* Gets the encoded username.
*
* @return The encoded username.
*/
public long getEncodedUsername() {
return encodedUsername;
}
/**
* Gets the session ids.
*
* @return The session ids.
*/
public int[] getSessionIds() {
return sessionIds;
}
@Override
public String toString() {
return MoreObjects.toStringHelper(this)
.add("userId", userId)
.add("username", username)
.add("password", password)
.add("encodedUsername", encodedUsername)
.add("sessionIds", Arrays.toString(sessionIds))
.toString();
}
}
|
zcgitzc/qaplus | src/main/java/com/qaplus/constant/ErrorCode.java | package com.qaplus.constant;
public enum ErrorCode {
SUCCESS("SUCCESS", "操作成功"),
NOT_LOGIN("NOT_LOGIN", "没有登陆"),
FAUILURE("FAUILURE", "操作失败"),
PAGE_PARAM_NOT_FOUND("PAGE_PARAM_NOT_FOUND", "分页参数未找到"),
NOT_DATA_FOUND("NOT_DATA_FOUND", "数据不存在"),
NO_ATTACHMENT("NO_ATTACHMENT", "不好意思,没有附件"),
LOGIN_FAIL("LOGIN_FAIL", "登录失败,可能没有注册,或者用户名密码错误"),
USER_VALIDATE_NULL("LOGIN_VALIDATE_FAIL", "用户名或密码不能为空"),
USER_VALIDATE_LENGTH("USER_VALIDATE_LENGTH", "密码长度必须为6-22位"),
CLASS_NOT_FOUND("CLASS_NOT_FOUND", "没有选择班级"),
DELETE_OLD_FILE_FAIL("DELETE_OLD_FILE_FAIL", "删除原来文件失败"),
GET_PHONE_INFO_FAIL("GET_PHONE_INFO_FAIL", "获取手机号信息失败"),
USERNAME_EXIST("USERNAME_EXIST", "用户已存在"),
USERNAME_VALIDATE("USERNAME_VALIDATE", "用户名可用"),
ALL_QUESTION_SOLVE("ALL_QUESTION_SOLVE", "感谢您这么积极的解决问题,可是没有待解决问题了,您辛苦了,休息一下吧 ^_^"),
QUESTION_COUNT_TOO_LARGE("QUESTION_COUNT_TOO_LARGE", "每天只能提三个问题,别贪心,自己思考一下,也让老师休息一下,明日再战 ^_^ "),;
private String value;
private String desc;
ErrorCode(String value, String desc) {
this.value = value;
this.desc = desc;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
}
|
PeachOS/zserio | compiler/extensions/java/src/zserio/emit/java/ConstEmitter.java | package zserio.emit.java;
import zserio.ast.ConstType;
import zserio.emit.common.ZserioEmitException;
import zserio.tools.Parameters;
class ConstEmitter extends JavaDefaultEmitter
{
public ConstEmitter(Parameters extensionParameters, JavaExtensionParameters javaParameters)
{
super(extensionParameters, javaParameters);
}
@Override
public void beginConst(ConstType constType) throws ZserioEmitException
{
final ConstEmitterTemplateData templateData =
new ConstEmitterTemplateData(getTemplateDataContext(), constType);
processTemplate(TEMPLATE_NAME, templateData, constType);
}
private static final String TEMPLATE_NAME = "ConstType.java.ftl";
}
|
hmcts/prl-ccd-definitions | test/end-to-end/pages/DOScreens/ApplicantsFamily.js | <gh_stars>0
const I = actor();
module.exports = {
fields: { submit: 'button[type="submit"]' },
async triggerEvent() {
await I.triggerEvent('Applicant’s family');
},
async applicantFamily() {
const retryCount = 3;
await I.waitForText('Does the applicant have any children, have parental responsibility for any children or need to protect other children with this application?');
await I.click('#applicantFamilyDetails_doesApplicantHaveChildren_Yes');
await I.waitForText('Child');
await I.click('Add new');
I.wait('2');
await I.fillField('#applicantChildDetails_0_fullName', 'Child Name1');
await I.retry(retryCount).fillField('#dateOfBirth-day', '10');
await I.retry(retryCount).fillField('#dateOfBirth-month', '10');
await I.retry(retryCount).fillField('#dateOfBirth-year', '2010');
await I.fillField('#applicantChildDetails_0_applicantChildRelationship', 'Mother');
await I.click('#applicantChildDetails_0_applicantRespondentShareParental_Yes');
await I.fillField('#applicantChildDetails_0_respondentChildRelationship', 'Father');
await I.click('Add new');
I.wait('2');
await I.fillField('#applicantChildDetails_1_fullName', 'Child Name2');
await I.fillField('#applicantChildDetails_1_applicantChildRelationship', 'Mother');
await I.click('#applicantChildDetails_1_applicantRespondentShareParental_Yes');
await I.fillField('#applicantChildDetails_1_respondentChildRelationship', 'Father');
await I.click('Continue');
},
async runEventApplicantsFamily() {
await this.triggerEvent();
await this.applicantFamily();
I.wait('2');
await I.click('Save and continue');
await I.submitEvent();
await I.amOnHistoryPageWithSuccessNotification();
}
};
|
georgianapopescu/Redmine | apps/redmine/htdocs/db/migrate/085_add_role_tracker_old_status_index_to_workflows.rb | <filename>apps/redmine/htdocs/db/migrate/085_add_role_tracker_old_status_index_to_workflows.rb
class AddRoleTrackerOldStatusIndexToWorkflows < ActiveRecord::Migration
def self.up
add_index :workflows, [:role_id, :tracker_id, :old_status_id], :name => :wkfs_role_tracker_old_status
end
def self.down
remove_index(:workflows, :name => :wkfs_role_tracker_old_status); rescue
end
end
|
Luo1Xiong/glide | library/src/main/java/com/bumptech/glide/load/engine/prefill/BitmapPreFiller.java | <reponame>Luo1Xiong/glide
package com.bumptech.glide.load.engine.prefill;
import android.graphics.Bitmap;
import androidx.annotation.VisibleForTesting;
import com.bumptech.glide.load.DecodeFormat;
import com.bumptech.glide.load.engine.bitmap_recycle.BitmapPool;
import com.bumptech.glide.load.engine.cache.MemoryCache;
import com.bumptech.glide.util.Util;
import java.util.HashMap;
import java.util.Map;
/**
* A class for pre-filling {@link android.graphics.Bitmap Bitmaps} in a {@link com.bumptech.glide.load.engine.bitmap_recycle.BitmapPool}.
*/
public final class BitmapPreFiller {
private final MemoryCache memoryCache;
private final BitmapPool bitmapPool;
private final DecodeFormat defaultFormat;
private BitmapPreFillRunner current;
public BitmapPreFiller(
MemoryCache memoryCache, BitmapPool bitmapPool, DecodeFormat defaultFormat) {
this.memoryCache = memoryCache;
this.bitmapPool = bitmapPool;
this.defaultFormat = defaultFormat;
}
@SuppressWarnings("deprecation")
public void preFill(PreFillType.Builder... bitmapAttributeBuilders) {
if (current != null) {
current.cancel();
}
PreFillType[] bitmapAttributes = new PreFillType[bitmapAttributeBuilders.length];
for (int i = 0; i < bitmapAttributeBuilders.length; i++) {
PreFillType.Builder builder = bitmapAttributeBuilders[i];
if (builder.getConfig() == null) {
builder.setConfig(
defaultFormat == DecodeFormat.PREFER_ARGB_8888
? Bitmap.Config.ARGB_8888
: Bitmap.Config.RGB_565);
}
bitmapAttributes[i] = builder.build();
}
PreFillQueue allocationOrder = generateAllocationOrder(bitmapAttributes);
current = new BitmapPreFillRunner(bitmapPool, memoryCache, allocationOrder);
Util.postOnUiThread(current);
}
@VisibleForTesting
PreFillQueue generateAllocationOrder(PreFillType... preFillSizes) {
final long maxSize =
memoryCache.getMaxSize() - memoryCache.getCurrentSize() + bitmapPool.getMaxSize();
int totalWeight = 0;
for (PreFillType size : preFillSizes) {
totalWeight += size.getWeight();
}
final float bytesPerWeight = maxSize / (float) totalWeight;
Map<PreFillType, Integer> attributeToCount = new HashMap<>();
for (PreFillType size : preFillSizes) {
int bytesForSize = Math.round(bytesPerWeight * size.getWeight());
int bytesPerBitmap = getSizeInBytes(size);
int bitmapsForSize = bytesForSize / bytesPerBitmap;
attributeToCount.put(size, bitmapsForSize);
}
return new PreFillQueue(attributeToCount);
}
private static int getSizeInBytes(PreFillType size) {
return Util.getBitmapByteSize(size.getWidth(), size.getHeight(), size.getConfig());
}
}
|
TsvetanMilanov/TelerikAcademyHW | 06_JavaScript/07_UsingObjects/UsingObjects/03.DeepCopy/DeepCopy.js | function deepCopy(objectToCopy) {
var newObject = {};
for (var prop in objectToCopy) {
if (objectToCopy[prop] instanceof Object) {
newObject[prop] = deepCopy(objectToCopy[prop]);
}
else {
newObject[prop] = objectToCopy[prop];
}
}
return newObject;
}
var firstObject = {
id: 0,
type: {
name: 'someType',
description: 'someDescription'
}
};
var secondObject = deepCopy(firstObject);
firstObject.id = 1;
firstObject.type.name = 'changedType';
firstObject.type.description = 'changedDescription';
console.log(firstObject.id + ' ' + firstObject.type.name + ' ' + firstObject.type.description);
console.log(secondObject.id + ' ' + secondObject.type.name + ' ' + secondObject.type.description); |
NouemanKHAL/steps | steps/istio/proxy-status/main.go | <gh_stars>0
package main
import (
"fmt"
envconf "github.com/caarlos0/env/v6"
jsonFormatter "github.com/stackpulse/steps-sdk-go/formats/json"
"github.com/stackpulse/steps-sdk-go/parsers"
"github.com/stackpulse/steps-sdk-go/step"
"github.com/stackpulse/steps/istio/base"
)
const proxyStatusArgument = "proxy-status"
type Args struct {
base.Args
Pod string `env:"POD" envDefault:""`
}
type ProxyStatus struct {
args Args
*base.IstioCtlBase
kubeconfigPath string
}
func (p *ProxyStatus) Init() error {
err := envconf.Parse(&p.args)
if err != nil {
return err
}
err = p.args.Validate()
if err != nil {
return err
}
if !p.args.UseLocalToken {
p.kubeconfigPath, err = base.DecodeKubeConfigContent(p.args.KubeconfigContent)
if err != nil {
return fmt.Errorf("failed decoding kubeconfig: %w", err)
}
}
return nil
}
func (p *ProxyStatus) Run() (int, []byte, error) {
args := p.args.BuildCommand(p.kubeconfigPath)
args = append(args, proxyStatusArgument)
if p.args.Pod != "" {
args = append(args, p.args.Pod)
}
exitCode, output, executionError := base.Execute(p.args.BinaryName, args)
if executionError != nil {
return exitCode, output, executionError
}
// when pod is empty it returns a table
if p.args.Pod == "" {
parsedOutput, err := parsers.ParseTableToJSON(string(output))
if err == nil {
return exitCode, parsedOutput, executionError
}
}
encodedOutput, err := jsonFormatter.FormatAsJSONOutput(output)
if err == nil {
return exitCode, encodedOutput, executionError
}
// fallback
return exitCode, output, executionError
}
func main() {
step.Run(&ProxyStatus{})
}
|
cserverpaasshow/smart-OA | src/main/web/cn/com/smart/web/dao/impl/CusIndexMinWinDao.java | <reponame>cserverpaasshow/smart-OA
package cn.com.smart.web.dao.impl;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.stereotype.Repository;
import com.mixsmart.utils.StringUtils;
import cn.com.smart.dao.impl.BaseDaoImpl;
import cn.com.smart.exception.DaoException;
import cn.com.smart.res.SQLResUtil;
import cn.com.smart.res.sqlmap.SqlMapping;
import cn.com.smart.web.bean.entity.TNCusIndexMinWin;
/**
*
* @author lmq
*
*/
@Repository
public class CusIndexMinWinDao extends BaseDaoImpl<TNCusIndexMinWin> {
private SqlMapping sqlMap;
private Map<String, Object> params;
public CusIndexMinWinDao() {
sqlMap = SQLResUtil.getBaseSqlMap();
}
/**
*
* @param cusIndexId
* @return
*/
public List<TNCusIndexMinWin> queryByCusIndex(String cusIndexId) throws DaoException {
List<TNCusIndexMinWin> lists = null;
String sql = sqlMap.getSQL("cus_index_minwin");
if(StringUtils.isNotEmpty(sql)) {
params = new HashMap<String, Object>();
params.put("cusIndexId", cusIndexId);
lists = queryHql(sql, params);
params = null;
} else {
throw new DaoException("[cus_index_minwin]值为空");
}
return lists;
}
}
|
cf-unik/gorump | go1.5/test/fixedbugs/bug088.dir/bug0.go | // Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package bug0
var V0 func() int;
var V1 func() (a int);
var V2 func() (a, b int);
|
hufan520xuanxuan/web-all-controller | res/app/func/funcsConfig/comment/index.js | require('./comment.css')
module.exports = angular.module('ccp.func-autocomment', [
require('stf/common-ui').name,
require('stf/admin-mode').name,
require('./setting').name,
require('../logs').name,
require('./resource-setting').name
])
.directive('autoComment', require('./comment-directive'))
|
semper24/R-Type | engine/include/Storage.hpp | /*
** EPITECH PROJECT, 2020
** B-CPP-501-NAN-5-1-rtype-arthur.bertaud
** File description:
** Storage.hpp
*/
#ifndef STORAGE_HPP_
#define STORAGE_HPP_
#include "IStorage.hpp"
#include "EntityManager.hpp"
#include <unordered_map>
#include <memory>
#include <iostream>
namespace ECS {
template <typename T>
class Storage : public IStorage
{
public:
Storage(const componentType& type) : _size(0), _type(type){};
~Storage() = default;
Storage(const Storage& other) = default;
Storage& operator=(const Storage& other) = default;
void linkEntityToComponent(Entity entityID, const T& component)
{
Entity newIndex = _size;
_entityToIndex[entityID] = newIndex;
_indexToEntity[newIndex] = entityID;
_componentArray[newIndex] = component;
_size++;
}
T &getComponent(Entity entityID)
{
return (_componentArray[_entityToIndex[entityID]]);
}
bool destroyEntity(Entity entityID)
{
if (_entityToIndex.find(entityID) != _entityToIndex.end()) {
removeEntity(entityID);
return (true);
}
return (false);
}
bool hasComponent(Entity entityID)
{
if (_entityToIndex.find(entityID) != _entityToIndex.end())
return (true);
return (false);
}
componentType getType() const
{
return (_type);
}
private:
std::array<T, 5000> _componentArray;
std::unordered_map<Entity, size_t> _entityToIndex;
std::unordered_map<size_t, Entity> _indexToEntity;
size_t _size;
componentType _type;
void removeEntity(size_t entityID)
{
size_t indexOfRemovedEntity = _entityToIndex[entityID];
size_t indexOfLastElement = _size - 1;
size_t entityOfLastElement = _indexToEntity[indexOfLastElement];
_componentArray[indexOfRemovedEntity] = _componentArray[indexOfLastElement];
_entityToIndex[entityOfLastElement] = indexOfRemovedEntity;
_indexToEntity[indexOfRemovedEntity] = entityOfLastElement;
_entityToIndex.erase(entityID);
_indexToEntity.erase(indexOfLastElement);
--_size;
}
};
}
#endif /*!STORAGE_HPP_*/ |
tank-dev/tank | dist/templates/src/MainWorld.hpp | #ifndef MAINWORLD_HPP
#define MAINWORLD_HPP
#include <Tank/System/World.hpp>
class MainWorld : public tank::World
{
public:
MainWorld();
};
#endif //MAINWORLD_HPP
|
hdpolover/ybb-scholarship-web | assets/plugin/ckeditor/plugins/pastefromlibreoffice/filter/default.js | /**
* @license Copyright (c) 2003-2021, CKSource - <NAME>. All rights reserved.
* For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
*/
/* globals CKEDITOR */
( function() {
'use strict';
var pastetools = CKEDITOR.plugins.pastetools,
commonFilter = pastetools.filters.common,
Style = commonFilter.styles;
/**
* A set of Paste from LibreOffice plugin helpers.
*
* @since 4.14.0
* @private
* @member CKEDITOR.plugins.pastetools.filters
*/
CKEDITOR.plugins.pastetools.filters.libreoffice = {
/**
* Rules for the Paste from LibreOffice filter.
*
* @since 4.14.0
* @private
* @member CKEDITOR.plugins.pastetools.filters.libreoffice
*/
rules: function( html, editor, filter ) {
return {
root: function( element ) {
element.filterChildren( filter );
},
comment: function() {
return false;
},
elementNames: [
[ /^head$/i, '' ],
[ /^meta$/i, '' ],
[ /^strike$/i, 's' ]
],
elements: {
// Required due to bug (#3664).
'!doctype': function( el ) {
el.replaceWithChildren();
},
'span': function( element ) {
if ( element.attributes.style ) {
element.attributes.style = Style.normalizedStyles( element, editor );
Style.createStyleStack( element, filter, editor );
}
replaceEmptyElementWithChildren( element );
},
'p': function( element ) {
var styles = CKEDITOR.tools.parseCssText( element.attributes.style );
if ( editor.plugins.pagebreak &&
( styles[ 'page-break-before' ] === 'always' || styles[ 'break-before' ] === 'page' )
) {
insertPageBreakBefore( editor, element );
}
element.attributes.style = CKEDITOR.tools.writeCssText( styles );
element.filterChildren( filter );
Style.createStyleStack( element, filter, editor );
},
'div': function( element ) {
Style.createStyleStack( element, filter, editor );
},
'a': function( el ) {
if ( el.attributes.style ) {
el.attributes.style = removeDefaultLinkStyles( el.attributes.style );
}
},
'h1': function( el ) {
Style.createStyleStack( el, filter, editor );
},
'h2': function( el ) {
Style.createStyleStack( el, filter, editor );
},
'h3': function( el ) {
Style.createStyleStack( el, filter, editor );
},
'h4': function( el ) {
Style.createStyleStack( el, filter, editor );
},
'h5': function( el ) {
Style.createStyleStack( el, filter, editor );
},
'h6': function( el ) {
Style.createStyleStack( el, filter, editor );
},
'pre': function( el ) {
Style.createStyleStack( el, filter, editor );
},
'font': function( el ) {
if ( shouldReplaceFontWithChildren( el ) ) {
el.replaceWithChildren();
}
// 1. Case there is no style stack
// 2. font-size is child of this node
// 3. font-size is parent of this node
var styles = CKEDITOR.tools.parseCssText( el.attributes.style );
var firstChild = el.getFirst();
if ( el.attributes.size &&
firstChild &&
firstChild.type === CKEDITOR.NODE_ELEMENT &&
/font-size/.test( firstChild.attributes.style )
) {
el.replaceWithChildren();
}
if ( styles[ 'font-size' ] ) {
// We need to remove 'size' and transform font to span with 'font-size'.
delete el.attributes.size;
el.name = 'span';
if ( firstChild && firstChild.type === CKEDITOR.NODE_ELEMENT && firstChild.attributes.size ) {
firstChild.replaceWithChildren();
}
}
},
'ul': function( el ) {
if ( listMerger( el, filter ) ) {
return false;
}
},
'ol': function( el ) {
if ( listMerger( el, filter ) ) {
return false;
}
},
'img': function( el ) {
var src = el.attributes.src;
if ( !src ) {
return false;
}
},
// All tables in LO assume collapsed borders, but the style is
// not always provided during the paste.
'table': function( element ) {
element.attributes.style = addBorderCollapse( element.attributes.style );
}
},
attributes: {
'style': function( styles, element ) {
// Returning false deletes the attribute.
return Style.normalizedStyles( element, editor ) || false;
},
// Many elements can have [align] attribute. Let's make it a wildcard
// transformation then!
'align': function( align, element ) {
// Images have their own handling logic.
if ( element.name === 'img' ) {
return;
}
var styles = CKEDITOR.tools.parseCssText( element.attributes.style );
styles[ 'text-align' ] = element.attributes.align;
element.attributes.style = CKEDITOR.tools.writeCssText( styles );
return false;
},
'cellspacing': remove,
'cellpadding': remove,
'border': remove
}
};
}
};
function replaceEmptyElementWithChildren( element ) {
if ( !CKEDITOR.tools.object.entries( element.attributes ).length ) {
element.replaceWithChildren();
}
}
function shouldReplaceFontWithChildren( element ) {
// Anchor is additionally styled with font.
if ( element.parent.name === 'a' && element.attributes.color === '#000080' ) {
return true;
}
// Sub or sup is additionally styled with font.
if ( element.parent.children.length === 1 && ( element.parent.name === 'sup' || element.parent.name === 'sub' ) && element.attributes.size === '2' ) {
return true;
}
return false;
}
// Return true if a list is successfully merged to the previous item..
function listMerger( el, filter ) {
if ( !shouldMergeToPreviousList( el ) ) {
return false;
}
var previous = el.previous,
lastLi = getLastListItem( previous ),
liDepthValue = checkDepth( lastLi ),
innerList = unwrapList( el, liDepthValue );
if ( innerList ) {
lastLi.add( innerList );
innerList.filterChildren( filter );
return true;
}
return false;
}
function shouldMergeToPreviousList( element ) {
// There needs to be a previous list that the element should be merged to.
if ( !element.previous || !isList( element.previous ) ) {
return false;
}
// There might be cases in PFW where a li element has no children (test Tickets/7131 word2013 chrome).
if ( !element.getFirst().children.length ) {
return false;
}
// The current list needs to be a nested list, what points that is sublist.
if ( element.children.length !== 1 || !isList( element.getFirst().getFirst() ) ) {
return false;
}
return true;
}
// Checks the evel of nested list for a given element.
// It's exepected that the argument is the `li` element.
function checkDepth( element ) {
var level = 0,
currentElement = element,
listEvaluator = getListEvaluator();
while ( ( currentElement = currentElement.getAscendant( listEvaluator ) ) ) {
level++;
}
return level;
}
function getLastListItem( el ) {
var lastChild = el.children[ el.children.length - 1 ];
if ( !isList( lastChild ) && lastChild.name !== 'li' ) {
return el;
}
return getLastListItem( lastChild );
}
function getListEvaluator() {
var isInBlock = false;
return function( element ) {
// There might be situation that the list is somehow nested in another type of element, quotes, div, table, etc.
// When such situation happens, we should not search for any above list.
if ( isInBlock ) {
return false;
}
if ( !isList( element ) && element.name !== 'li' ) {
isInBlock = true;
return false;
}
return isList( element );
};
}
// Get a nested list by first items.
function unwrapList( list, count ) {
if ( count ) {
return unwrapList( list.getFirst().getFirst(), --count );
}
return list;
}
function isList( element ) {
return element.name === 'ol' || element.name === 'ul';
}
function remove() {
return false;
}
function removeDefaultLinkStyles( styles ) {
var parsedStyles = CKEDITOR.tools.parseCssText( styles );
if ( parsedStyles.color === '#000080' ) {
delete parsedStyles.color;
}
if ( parsedStyles[ 'text-decoration' ] === 'underline' ) {
delete parsedStyles[ 'text-decoration' ];
}
return CKEDITOR.tools.writeCssText( parsedStyles );
}
function insertPageBreakBefore( editor, element ) {
var pagebreakEl = CKEDITOR.plugins.pagebreak.createElement( editor );
pagebreakEl = CKEDITOR.htmlParser.fragment.fromHtml( pagebreakEl.getOuterHtml() ).children[ 0 ];
pagebreakEl.insertBefore( element );
}
function addBorderCollapse( styles ) {
var parsedStyles = CKEDITOR.tools.parseCssText( styles );
if ( parsedStyles[ 'border-collapse' ] ) {
return styles;
}
parsedStyles[ 'border-collapse' ] = 'collapse';
return CKEDITOR.tools.writeCssText( parsedStyles );
}
CKEDITOR.pasteFilters.libreoffice = pastetools.createFilter( {
rules: [
commonFilter.rules,
CKEDITOR.plugins.pastetools.filters.libreoffice.rules
]
} );
} )();
|
Gaoyc1/Aspose.Diagram | Examples/src/main/java/com/aspose/diagram/examples/Comments/AddPageLevelCommentInVisio.java | package com.aspose.diagram.examples.Comments;
import com.aspose.diagram.Diagram;
import com.aspose.diagram.SaveFileFormat;
import com.aspose.diagram.examples.Utils;
import com.aspose.diagram.examples.Diagrams.CreateDiagram;
public class AddPageLevelCommentInVisio {
public static void main(String[] args) throws Exception {
// The path to the documents directory.
String dataDir = Utils.getSharedDataDir(AddPageLevelCommentInVisio.class) + "Comments/";
// Call the diagram constructor to load diagram
Diagram diagram = new Diagram(dataDir + "Drawing1.vsdx");
// Add comment
diagram.getPages().getPage(0).addComment(7.205905511811023, 3.880708661417323, "test@");
// Save diagram
diagram.save(dataDir + "AddPageLevelCommentInVisio-out.vdx", SaveFileFormat.VSDX);
}
}
|
xthecoolboy/Atlantav2 | commands/disable-group.js | const Discord = require("discord.js");
const config = require("../data/config.json")
quickdb = require('quick.db'),
errors = require('../utils/errors.js');
quickdb.init('./data/atlanta.sqlite');
var servers_data = new quickdb.table('serversdata');
module.exports.run = async (message, args, bot, emotes, data) => {
var the_module = args[0];
if(!args[0]) return errors.utilisation(message, data, emotes);
var groups = [];
if(the_module === "administration"){
return message.channel.send(emotes[0] +' | Le groupe Administration ne peut être désactivé !');
}
bot.commands.forEach(element => {
_the_group = element.help.group;
if(groups.indexOf(_the_group) < 0){
groups.push(_the_group);
}
});
if(groups.indexOf(the_module) < 0){
return message.channel.send(emotes[0] + ' | Le groupe `'+the_module+'` n\'existe pas !');
} else {
if(data.guild_data.disabled_modules.indexOf(the_module) < 0){
servers_data.push(message.guild.id+'.disabled_modules', the_module);
return message.channel.send(emotes[1] +' | Le groupe de commandes `'+the_module+'` a été désactivé sur '+message.guild.name+' !');
} else {
return message.channel.send(emotes[0] + ' | Le module `'+the_module+'` est déjà désactivé !');
}
}
}
module.exports.help = {
name:"disable-group",
desc:"Désactive un groupe de commande sur le serveur",
usage:"disable-group [module]",
group:"administration",
examples:"$disable-group modération"
}
module.exports.settings = {
permissions:"MANAGE_GUILD",
nsfw:"false",
support_only:"false",
disabled:"false",
premium:"false",
owner:"false"
} |
VancySavoki/heaven | src/main/java/com/github/houbb/heaven/response/exception/CommonRuntimeException.java | package com.github.houbb.heaven.response.exception;
/**
* 通用的运行时异常
* @author binbin.hou
* @since 0.0.5
*/
public final class CommonRuntimeException extends RuntimeException {
public CommonRuntimeException() {
}
public CommonRuntimeException(String message) {
super(message);
}
public CommonRuntimeException(String message, Throwable cause) {
super(message, cause);
}
public CommonRuntimeException(Throwable cause) {
super(cause);
}
public CommonRuntimeException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
}
|
scana/ok-gradle | plugin/src/main/java/me/scana/okgradle/internal/dsl/parser/android/SigningConfigsDslElement.java | /*
* Copyright (C) 2016 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package me.scana.okgradle.internal.dsl.parser.android;
import me.scana.okgradle.internal.dsl.api.android.SigningConfigModel;
import me.scana.okgradle.internal.dsl.model.android.SigningConfigModelImpl;
import me.scana.okgradle.internal.dsl.parser.android.SigningConfigDslElement;
import me.scana.okgradle.internal.dsl.parser.elements.GradleDslElement;
import me.scana.okgradle.internal.dsl.parser.elements.GradleDslElementMap;
import com.google.common.collect.Lists;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import java.util.List;
public final class SigningConfigsDslElement extends GradleDslElementMap {
@NonNls public static final String SIGNING_CONFIGS_BLOCK_NAME = "signingConfigs";
public SigningConfigsDslElement(@NotNull GradleDslElement parent) {
super(parent, SIGNING_CONFIGS_BLOCK_NAME);
}
@Override
public boolean isBlockElement() {
return true;
}
@NotNull
public List<SigningConfigModel> get() {
List<SigningConfigModel> result = Lists.newArrayList();
for (me.scana.okgradle.internal.dsl.parser.android.SigningConfigDslElement dslElement : getValues(SigningConfigDslElement.class)) {
result.add(new SigningConfigModelImpl(dslElement));
}
return result;
}
}
|
Releed/Construct-2 | plugins/@Circle Menu/circle.js | <reponame>Releed/Construct-2
;(function($, window, document, undefined) {
var pluginName = 'circleMenu',
defaults = {
angle: {
start: 0,
end: 90
},
circle_radius: 80,
delay: 1000,
depth: 0,
item_diameter: 30,
speed: 500,
step_in: -20,
step_out: 20,
transition_function: 'ease',
trigger: 'hover'
};
function vendorPrefixes(items, prop, value) {
['-webkit-','-moz-','-o-','-ms-',''].forEach(function(prefix) {
items.css(prefix+prop, value);
});
};
function CircleMenu(element, options) {
this._delete = [];
this._state = 'closed';
this._timeouts = [];
this.element = $(element);
this.options = $.extend({}, defaults, options);
this.update();
this.hook();
};
CircleMenu.prototype.trigger = function() {
var args = [];
for(var i = 0; i < arguments.length; i++) {
args.push(arguments[i]);
};
this.element.trigger(pluginName+'-'+args.shift(), args);
};
CircleMenu.prototype.hook = function() {
var self = this;
if(self.options.trigger === 'hover') {
self.element.on('mouseenter', function() {
if(self._state === 'open' && !self._delete.length) self.clearTimeouts();
else if(self._state === 'closed') self.open();
}).on('mouseleave', function() {
self.close(false, true);
});
} else if(self.options.trigger === 'click') {
self.element.children('li:first-child').on('click', function(evt) {
evt.preventDefault();
if(self._state === 'closed') self.open();
else if(self._state === 'open') self.close(false, true);
return false;
});
} else if(self.options.trigger === 'none') { /* Do nothing */ };
};
CircleMenu.prototype.clearTimeouts = function() {
var timeout;
while(timeout = this._timeouts.shift()) {
clearTimeout(timeout);
};
};
CircleMenu.prototype.initCss = function(immediate) {
var self = this, $items = self.element.children('li');
self.element.removeClass(pluginName+'-open');
self.element.css({
'list-style': 'none',
'margin': 0,
'padding': 0,
'width': self.options.item_diameter+'px'
});
$items.css({
'display': 'block',
'width': self.options.item_diameter+'px',
'height': self.options.item_diameter+'px',
'text-align': 'center',
'line-height': self.options.item_diameter+'px',
'position': 'absolute',
'z-index': 1
});
self.element.children('li:first-child').css({'z-index': 1000 - self.options.depth});
self.menu_items.css({top: 0, left: 0});
vendorPrefixes($items, 'border-radius', self.options.item_diameter+'px');
vendorPrefixes(self.menu_items, 'transform', 'scale(.5)');
if(immediate) {
vendorPrefixes(self.menu_items, 'transition', 'all 0ms '+self.options.transition_function);
setTimeout(function() {
vendorPrefixes($items, 'transition', 'all '+self.options.speed+'ms '+self.options.transition_function);
vendorPrefixes($items, 'opacity', '');
}, 50);
} else {
vendorPrefixes($items, 'transition', 'all '+self.options.speed+'ms '+self.options.transition_function);
setTimeout(function() { vendorPrefixes($items, 'opacity', ''); }, self.options.speed);
};
};
CircleMenu.prototype.update = function() {
var self = this, dir,
directions = {
'bottom-left':[180,90],
'bottom':[135,45],
'right':[-45,45],
'left':[225,135],
'top':[225,315],
'bottom-half':[180,0],
'right-half':[-90,90],
'left-half':[270,90],
'top-half':[180,360],
'top-left':[270,180],
'top-right':[270,360],
'full':[-90,270-Math.floor(360/(self.element.children('li').length - 1))],
'bottom-right':[0,90]
};
self.element.addClass(pluginName+'-closed');
if(typeof self.options.direction === 'string') {
dir = directions[self.options.direction.toLowerCase()];
if(dir) {
self.options.angle.start = dir[0];
self.options.angle.end = dir[1];
};
};
self.menu_items = self.element.children('li:not(:first-child)');
self.initCss();
self._step = (self.options.angle.end - self.options.angle.start) / (self.menu_items.length-1);
self.menu_items.each(function(i) {
var $item = $(self.menu_items[i]);
angle = (self.options.angle.start + (self._step * i)) * (Math.PI/180),
x = Math.round(self.options.circle_radius * Math.cos(angle)),
y = Math.round(self.options.circle_radius * Math.sin(angle));
$item.data('plugin_'+pluginName+'-pos-x', x);
$item.data('plugin_'+pluginName+'-pos-y', y);
if(self.options.trigger === 'hover') {
$item.on('mouseenter', function() {
if(self._state === 'open' && !self._delete.length) self.clearTimeouts();
}).on('mouseleave', function() {
self.close(false, true);
});
};
if(i === self.menu_items.length - 1) {
$item.on('click', function() {
self.select($item.index() + 1);
});
};
});
// Initialize event hooks from options
['update','open','close','select','delete','clear'].forEach(function(evt) {
if(self.options[evt]) {
self.element.on(pluginName+'-'+evt, function() {
return self.options[evt].apply(self, arguments);
});
delete self.options[evt];
};
});
self.submenus = self.menu_items.children('ul');
self.submenus.circleMenu($.extend({}, self.options, {depth: self.options.depth + 1}));
self._state = 'closed';
self.trigger('update');
};
CircleMenu.prototype.open = function() {
if(this._state != 'closed' || this._delete.length)
return this;
/////////////////////////////////////
var self = this, set = self.options.step_out >= 0 ? self.menu_items : $(self.menu_items.get().reverse());
self.clearTimeouts();
self._state = 'opening';
set.each(function(index) {
var $item = $(this);
self._timeouts.push(setTimeout(function() {
$item.css({
left: $item.data('plugin_'+pluginName+'-pos-x')+'px',
top: $item.data('plugin_'+pluginName+'-pos-y')+'px'
});
vendorPrefixes($item, 'transform', 'scale(1)');
}, Math.abs(self.options.step_out) * index));
});
self._timeouts.push(setTimeout(function() {
if(self._state === 'opening') self._state = 'open';
self.trigger('open');
}, Math.abs(self.options.step_out) * set.length));
self.element.removeClass(pluginName+'-closed');
self.element.addClass(pluginName+'-open');
return self;
};
CircleMenu.prototype.close = function(immediate, close) {
if(this._state != 'open' && this._state != 'opening')
return this;
if(this._state === 'opening' && !close)
return this;
/////////////////////////////////////
var self = this,
do_animation = function do_animation() {
self.clearTimeouts();
if(self._state != 'clear') self._state = 'closing';
self.submenus.circleMenu('close');
var set = self.options.step_in >= 0 ? self.menu_items : $(self.menu_items.get().reverse());
set.each(function(index) {
var $item = $(this);
self._timeouts.push(setTimeout(function() {
$item.css({top:0,left:0});
vendorPrefixes($item, 'transform', 'scale(.5)');
}, Math.abs(self.options.step_in) * index));
});
/////////////////////////////////////
self._timeouts.push(setTimeout(function() {
self.trigger('close');
}, Math.abs(self.options.step_in) * set.length));
self._timeouts.push(setTimeout(function() {
if(self._state === 'closing' && close) self._state = 'closed';
}, Math.abs(self.options.step_in) * set.length + self.options.speed));
/////////////////////////////////////
self.element.removeClass(pluginName+'-open');
self.element.addClass(pluginName+'-closed');
return self;
};
if(immediate)
do_animation();
else {
var speed = self._state === 'opening' ? (Math.abs(self.options.step_out) * self.menu_items.length) + self.options.speed : 0;
self._timeouts.push(setTimeout(function() { do_animation(); }, self.options.delay + speed));
};
return self;
};
CircleMenu.prototype.select = function(index) {
var self = this, selected, set_other;
if(self._state === 'open') {
self.clearTimeouts();
self._state = 'select';
set_other = self.element.children('li:not(:nth-child('+index+'),:first-child)');
selected = self.element.children('li:nth-child('+index+')');
vendorPrefixes(selected.add(set_other), 'transition', 'all 500ms ease-out');
vendorPrefixes(selected, 'transform', 'scale(2)');
vendorPrefixes(set_other, 'transform', 'scale(0)');
selected.css('opacity', '0');
set_other.css('opacity', '0');
self.element.removeClass(pluginName+'-open');
setTimeout(function() {
self._state = 'closed';
self.initCss(true);
self.trigger('select', index - 2);
}, 500);
};
};
CircleMenu.prototype.delete = function(index) {
if(this._state === 'clear')
return this;
/////////////////////////////////////
var self = this, speed = 0;
if(!self._delete.length) {
self._delete.push(index);
if(self._state != 'closed') {
if(self._state === 'opening') speed = (Math.abs(self.options.step_out) * self.menu_items.length) + self.options.speed + self.options.delay;
speed += (Math.abs(self.options.step_in) * self.menu_items.length) + self.options.speed;
self.close(true, false);
};
setTimeout(function() {
while(self._delete.length) {
$(self.element).find('li:eq('+self._delete[0]+')').remove();
self.trigger('delete', self._delete[0]);
self._delete.splice(0, 1);
};
self.update();
}, speed);
} else {
for(var i = 0; i < self._delete.length; i++) { if(index > self._delete[i]) index--; };
self._delete.push(index);
};
};
CircleMenu.prototype.clear = function() {
var self = this, speed = 0;
if(self._state != 'closed') {
if(self._state === 'opening') speed = (Math.abs(self.options.step_out) * self.menu_items.length) + self.options.speed + self.options.delay;
speed += (Math.abs(self.options.step_in) * self.menu_items.length) + self.options.speed;
self.close(true, false);
};
self._state = 'clear';
setTimeout(function() {
$(self.element).find('li:not(:first-child)').remove();
self.update();
self.trigger('clear');
}, speed);
};
$.fn[pluginName] = function(options, evt) {
return this.each(function() {
var obj = $.data(this, 'plugin_'+pluginName),
commands = {
'update':function() {obj.update();},
'open':function() {obj.open();},
'close':function() {obj.close();},
'delete':function() {obj.delete(evt);},
'clear':function() {obj.clear();}
};
if(typeof options === 'string' && obj && commands[options]) {
commands[options]();
}
if(!obj) {
$.data(this, 'plugin_' + pluginName, new CircleMenu(this, options));
}
});
};
})(jQuery, window, document); |
AlexRogalskiy/DevArtifacts | master/examples-4/examples/chapter08/addressbook/main.cpp | <reponame>AlexRogalskiy/DevArtifacts<filename>master/examples-4/examples/chapter08/addressbook/main.cpp
#include <QtGui>
#include "addressbookmodel.h"
int main( int argc, char* argv[] )
{
QApplication app( argc, argv );
// Open the addressbook file in the working directory
QFile file("addressbook.csv");
if ( !file.open(QIODevice::ReadOnly|QIODevice::Text) )
return 1;
// Read its content into a string
QString addresses = QString::fromUtf8(file.readAll());
AddressbookModel model(addresses);
QListView listView;
listView.setModel(&model);
listView.setModelColumn(0);
listView.show();
QTreeView treeView;
treeView.setModel(&model);
treeView.show();
QTableView tableView;
tableView.setModel(&model);
tableView.show();
return app.exec();
}
|
kamotos/aws-sdk-go-mocks | service/codeguruprofilermock/mock.go | <reponame>kamotos/aws-sdk-go-mocks
// Code generated by MockGen. DO NOT EDIT.
// Source: github.com/aws/aws-sdk-go/service/codeguruprofiler/codeguruprofileriface (interfaces: CodeGuruProfilerAPI)
// Package codeguruprofilermock is a generated GoMock package.
package codeguruprofilermock
import (
context "context"
reflect "reflect"
request "github.com/aws/aws-sdk-go/aws/request"
codeguruprofiler "github.com/aws/aws-sdk-go/service/codeguruprofiler"
gomock "github.com/golang/mock/gomock"
)
// MockCodeGuruProfilerAPI is a mock of CodeGuruProfilerAPI interface.
type MockCodeGuruProfilerAPI struct {
ctrl *gomock.Controller
recorder *MockCodeGuruProfilerAPIMockRecorder
}
// MockCodeGuruProfilerAPIMockRecorder is the mock recorder for MockCodeGuruProfilerAPI.
type MockCodeGuruProfilerAPIMockRecorder struct {
mock *MockCodeGuruProfilerAPI
}
// NewMockCodeGuruProfilerAPI creates a new mock instance.
func NewMockCodeGuruProfilerAPI(ctrl *gomock.Controller) *MockCodeGuruProfilerAPI {
mock := &MockCodeGuruProfilerAPI{ctrl: ctrl}
mock.recorder = &MockCodeGuruProfilerAPIMockRecorder{mock}
return mock
}
// EXPECT returns an object that allows the caller to indicate expected use.
func (m *MockCodeGuruProfilerAPI) EXPECT() *MockCodeGuruProfilerAPIMockRecorder {
return m.recorder
}
// AddNotificationChannels mocks base method.
func (m *MockCodeGuruProfilerAPI) AddNotificationChannels(arg0 *codeguruprofiler.AddNotificationChannelsInput) (*codeguruprofiler.AddNotificationChannelsOutput, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "AddNotificationChannels", arg0)
ret0, _ := ret[0].(*codeguruprofiler.AddNotificationChannelsOutput)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// AddNotificationChannels indicates an expected call of AddNotificationChannels.
func (mr *MockCodeGuruProfilerAPIMockRecorder) AddNotificationChannels(arg0 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddNotificationChannels", reflect.TypeOf((*MockCodeGuruProfilerAPI)(nil).AddNotificationChannels), arg0)
}
// AddNotificationChannelsRequest mocks base method.
func (m *MockCodeGuruProfilerAPI) AddNotificationChannelsRequest(arg0 *codeguruprofiler.AddNotificationChannelsInput) (*request.Request, *codeguruprofiler.AddNotificationChannelsOutput) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "AddNotificationChannelsRequest", arg0)
ret0, _ := ret[0].(*request.Request)
ret1, _ := ret[1].(*codeguruprofiler.AddNotificationChannelsOutput)
return ret0, ret1
}
// AddNotificationChannelsRequest indicates an expected call of AddNotificationChannelsRequest.
func (mr *MockCodeGuruProfilerAPIMockRecorder) AddNotificationChannelsRequest(arg0 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddNotificationChannelsRequest", reflect.TypeOf((*MockCodeGuruProfilerAPI)(nil).AddNotificationChannelsRequest), arg0)
}
// AddNotificationChannelsWithContext mocks base method.
func (m *MockCodeGuruProfilerAPI) AddNotificationChannelsWithContext(arg0 context.Context, arg1 *codeguruprofiler.AddNotificationChannelsInput, arg2 ...request.Option) (*codeguruprofiler.AddNotificationChannelsOutput, error) {
m.ctrl.T.Helper()
varargs := []interface{}{arg0, arg1}
for _, a := range arg2 {
varargs = append(varargs, a)
}
ret := m.ctrl.Call(m, "AddNotificationChannelsWithContext", varargs...)
ret0, _ := ret[0].(*codeguruprofiler.AddNotificationChannelsOutput)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// AddNotificationChannelsWithContext indicates an expected call of AddNotificationChannelsWithContext.
func (mr *MockCodeGuruProfilerAPIMockRecorder) AddNotificationChannelsWithContext(arg0, arg1 interface{}, arg2 ...interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
varargs := append([]interface{}{arg0, arg1}, arg2...)
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddNotificationChannelsWithContext", reflect.TypeOf((*MockCodeGuruProfilerAPI)(nil).AddNotificationChannelsWithContext), varargs...)
}
// BatchGetFrameMetricData mocks base method.
func (m *MockCodeGuruProfilerAPI) BatchGetFrameMetricData(arg0 *codeguruprofiler.BatchGetFrameMetricDataInput) (*codeguruprofiler.BatchGetFrameMetricDataOutput, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "BatchGetFrameMetricData", arg0)
ret0, _ := ret[0].(*codeguruprofiler.BatchGetFrameMetricDataOutput)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// BatchGetFrameMetricData indicates an expected call of BatchGetFrameMetricData.
func (mr *MockCodeGuruProfilerAPIMockRecorder) BatchGetFrameMetricData(arg0 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "BatchGetFrameMetricData", reflect.TypeOf((*MockCodeGuruProfilerAPI)(nil).BatchGetFrameMetricData), arg0)
}
// BatchGetFrameMetricDataRequest mocks base method.
func (m *MockCodeGuruProfilerAPI) BatchGetFrameMetricDataRequest(arg0 *codeguruprofiler.BatchGetFrameMetricDataInput) (*request.Request, *codeguruprofiler.BatchGetFrameMetricDataOutput) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "BatchGetFrameMetricDataRequest", arg0)
ret0, _ := ret[0].(*request.Request)
ret1, _ := ret[1].(*codeguruprofiler.BatchGetFrameMetricDataOutput)
return ret0, ret1
}
// BatchGetFrameMetricDataRequest indicates an expected call of BatchGetFrameMetricDataRequest.
func (mr *MockCodeGuruProfilerAPIMockRecorder) BatchGetFrameMetricDataRequest(arg0 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "BatchGetFrameMetricDataRequest", reflect.TypeOf((*MockCodeGuruProfilerAPI)(nil).BatchGetFrameMetricDataRequest), arg0)
}
// BatchGetFrameMetricDataWithContext mocks base method.
func (m *MockCodeGuruProfilerAPI) BatchGetFrameMetricDataWithContext(arg0 context.Context, arg1 *codeguruprofiler.BatchGetFrameMetricDataInput, arg2 ...request.Option) (*codeguruprofiler.BatchGetFrameMetricDataOutput, error) {
m.ctrl.T.Helper()
varargs := []interface{}{arg0, arg1}
for _, a := range arg2 {
varargs = append(varargs, a)
}
ret := m.ctrl.Call(m, "BatchGetFrameMetricDataWithContext", varargs...)
ret0, _ := ret[0].(*codeguruprofiler.BatchGetFrameMetricDataOutput)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// BatchGetFrameMetricDataWithContext indicates an expected call of BatchGetFrameMetricDataWithContext.
func (mr *MockCodeGuruProfilerAPIMockRecorder) BatchGetFrameMetricDataWithContext(arg0, arg1 interface{}, arg2 ...interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
varargs := append([]interface{}{arg0, arg1}, arg2...)
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "BatchGetFrameMetricDataWithContext", reflect.TypeOf((*MockCodeGuruProfilerAPI)(nil).BatchGetFrameMetricDataWithContext), varargs...)
}
// ConfigureAgent mocks base method.
func (m *MockCodeGuruProfilerAPI) ConfigureAgent(arg0 *codeguruprofiler.ConfigureAgentInput) (*codeguruprofiler.ConfigureAgentOutput, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "ConfigureAgent", arg0)
ret0, _ := ret[0].(*codeguruprofiler.ConfigureAgentOutput)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// ConfigureAgent indicates an expected call of ConfigureAgent.
func (mr *MockCodeGuruProfilerAPIMockRecorder) ConfigureAgent(arg0 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ConfigureAgent", reflect.TypeOf((*MockCodeGuruProfilerAPI)(nil).ConfigureAgent), arg0)
}
// ConfigureAgentRequest mocks base method.
func (m *MockCodeGuruProfilerAPI) ConfigureAgentRequest(arg0 *codeguruprofiler.ConfigureAgentInput) (*request.Request, *codeguruprofiler.ConfigureAgentOutput) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "ConfigureAgentRequest", arg0)
ret0, _ := ret[0].(*request.Request)
ret1, _ := ret[1].(*codeguruprofiler.ConfigureAgentOutput)
return ret0, ret1
}
// ConfigureAgentRequest indicates an expected call of ConfigureAgentRequest.
func (mr *MockCodeGuruProfilerAPIMockRecorder) ConfigureAgentRequest(arg0 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ConfigureAgentRequest", reflect.TypeOf((*MockCodeGuruProfilerAPI)(nil).ConfigureAgentRequest), arg0)
}
// ConfigureAgentWithContext mocks base method.
func (m *MockCodeGuruProfilerAPI) ConfigureAgentWithContext(arg0 context.Context, arg1 *codeguruprofiler.ConfigureAgentInput, arg2 ...request.Option) (*codeguruprofiler.ConfigureAgentOutput, error) {
m.ctrl.T.Helper()
varargs := []interface{}{arg0, arg1}
for _, a := range arg2 {
varargs = append(varargs, a)
}
ret := m.ctrl.Call(m, "ConfigureAgentWithContext", varargs...)
ret0, _ := ret[0].(*codeguruprofiler.ConfigureAgentOutput)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// ConfigureAgentWithContext indicates an expected call of ConfigureAgentWithContext.
func (mr *MockCodeGuruProfilerAPIMockRecorder) ConfigureAgentWithContext(arg0, arg1 interface{}, arg2 ...interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
varargs := append([]interface{}{arg0, arg1}, arg2...)
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ConfigureAgentWithContext", reflect.TypeOf((*MockCodeGuruProfilerAPI)(nil).ConfigureAgentWithContext), varargs...)
}
// CreateProfilingGroup mocks base method.
func (m *MockCodeGuruProfilerAPI) CreateProfilingGroup(arg0 *codeguruprofiler.CreateProfilingGroupInput) (*codeguruprofiler.CreateProfilingGroupOutput, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "CreateProfilingGroup", arg0)
ret0, _ := ret[0].(*codeguruprofiler.CreateProfilingGroupOutput)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// CreateProfilingGroup indicates an expected call of CreateProfilingGroup.
func (mr *MockCodeGuruProfilerAPIMockRecorder) CreateProfilingGroup(arg0 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CreateProfilingGroup", reflect.TypeOf((*MockCodeGuruProfilerAPI)(nil).CreateProfilingGroup), arg0)
}
// CreateProfilingGroupRequest mocks base method.
func (m *MockCodeGuruProfilerAPI) CreateProfilingGroupRequest(arg0 *codeguruprofiler.CreateProfilingGroupInput) (*request.Request, *codeguruprofiler.CreateProfilingGroupOutput) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "CreateProfilingGroupRequest", arg0)
ret0, _ := ret[0].(*request.Request)
ret1, _ := ret[1].(*codeguruprofiler.CreateProfilingGroupOutput)
return ret0, ret1
}
// CreateProfilingGroupRequest indicates an expected call of CreateProfilingGroupRequest.
func (mr *MockCodeGuruProfilerAPIMockRecorder) CreateProfilingGroupRequest(arg0 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CreateProfilingGroupRequest", reflect.TypeOf((*MockCodeGuruProfilerAPI)(nil).CreateProfilingGroupRequest), arg0)
}
// CreateProfilingGroupWithContext mocks base method.
func (m *MockCodeGuruProfilerAPI) CreateProfilingGroupWithContext(arg0 context.Context, arg1 *codeguruprofiler.CreateProfilingGroupInput, arg2 ...request.Option) (*codeguruprofiler.CreateProfilingGroupOutput, error) {
m.ctrl.T.Helper()
varargs := []interface{}{arg0, arg1}
for _, a := range arg2 {
varargs = append(varargs, a)
}
ret := m.ctrl.Call(m, "CreateProfilingGroupWithContext", varargs...)
ret0, _ := ret[0].(*codeguruprofiler.CreateProfilingGroupOutput)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// CreateProfilingGroupWithContext indicates an expected call of CreateProfilingGroupWithContext.
func (mr *MockCodeGuruProfilerAPIMockRecorder) CreateProfilingGroupWithContext(arg0, arg1 interface{}, arg2 ...interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
varargs := append([]interface{}{arg0, arg1}, arg2...)
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CreateProfilingGroupWithContext", reflect.TypeOf((*MockCodeGuruProfilerAPI)(nil).CreateProfilingGroupWithContext), varargs...)
}
// DeleteProfilingGroup mocks base method.
func (m *MockCodeGuruProfilerAPI) DeleteProfilingGroup(arg0 *codeguruprofiler.DeleteProfilingGroupInput) (*codeguruprofiler.DeleteProfilingGroupOutput, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "DeleteProfilingGroup", arg0)
ret0, _ := ret[0].(*codeguruprofiler.DeleteProfilingGroupOutput)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// DeleteProfilingGroup indicates an expected call of DeleteProfilingGroup.
func (mr *MockCodeGuruProfilerAPIMockRecorder) DeleteProfilingGroup(arg0 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeleteProfilingGroup", reflect.TypeOf((*MockCodeGuruProfilerAPI)(nil).DeleteProfilingGroup), arg0)
}
// DeleteProfilingGroupRequest mocks base method.
func (m *MockCodeGuruProfilerAPI) DeleteProfilingGroupRequest(arg0 *codeguruprofiler.DeleteProfilingGroupInput) (*request.Request, *codeguruprofiler.DeleteProfilingGroupOutput) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "DeleteProfilingGroupRequest", arg0)
ret0, _ := ret[0].(*request.Request)
ret1, _ := ret[1].(*codeguruprofiler.DeleteProfilingGroupOutput)
return ret0, ret1
}
// DeleteProfilingGroupRequest indicates an expected call of DeleteProfilingGroupRequest.
func (mr *MockCodeGuruProfilerAPIMockRecorder) DeleteProfilingGroupRequest(arg0 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeleteProfilingGroupRequest", reflect.TypeOf((*MockCodeGuruProfilerAPI)(nil).DeleteProfilingGroupRequest), arg0)
}
// DeleteProfilingGroupWithContext mocks base method.
func (m *MockCodeGuruProfilerAPI) DeleteProfilingGroupWithContext(arg0 context.Context, arg1 *codeguruprofiler.DeleteProfilingGroupInput, arg2 ...request.Option) (*codeguruprofiler.DeleteProfilingGroupOutput, error) {
m.ctrl.T.Helper()
varargs := []interface{}{arg0, arg1}
for _, a := range arg2 {
varargs = append(varargs, a)
}
ret := m.ctrl.Call(m, "DeleteProfilingGroupWithContext", varargs...)
ret0, _ := ret[0].(*codeguruprofiler.DeleteProfilingGroupOutput)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// DeleteProfilingGroupWithContext indicates an expected call of DeleteProfilingGroupWithContext.
func (mr *MockCodeGuruProfilerAPIMockRecorder) DeleteProfilingGroupWithContext(arg0, arg1 interface{}, arg2 ...interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
varargs := append([]interface{}{arg0, arg1}, arg2...)
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeleteProfilingGroupWithContext", reflect.TypeOf((*MockCodeGuruProfilerAPI)(nil).DeleteProfilingGroupWithContext), varargs...)
}
// DescribeProfilingGroup mocks base method.
func (m *MockCodeGuruProfilerAPI) DescribeProfilingGroup(arg0 *codeguruprofiler.DescribeProfilingGroupInput) (*codeguruprofiler.DescribeProfilingGroupOutput, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "DescribeProfilingGroup", arg0)
ret0, _ := ret[0].(*codeguruprofiler.DescribeProfilingGroupOutput)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// DescribeProfilingGroup indicates an expected call of DescribeProfilingGroup.
func (mr *MockCodeGuruProfilerAPIMockRecorder) DescribeProfilingGroup(arg0 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DescribeProfilingGroup", reflect.TypeOf((*MockCodeGuruProfilerAPI)(nil).DescribeProfilingGroup), arg0)
}
// DescribeProfilingGroupRequest mocks base method.
func (m *MockCodeGuruProfilerAPI) DescribeProfilingGroupRequest(arg0 *codeguruprofiler.DescribeProfilingGroupInput) (*request.Request, *codeguruprofiler.DescribeProfilingGroupOutput) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "DescribeProfilingGroupRequest", arg0)
ret0, _ := ret[0].(*request.Request)
ret1, _ := ret[1].(*codeguruprofiler.DescribeProfilingGroupOutput)
return ret0, ret1
}
// DescribeProfilingGroupRequest indicates an expected call of DescribeProfilingGroupRequest.
func (mr *MockCodeGuruProfilerAPIMockRecorder) DescribeProfilingGroupRequest(arg0 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DescribeProfilingGroupRequest", reflect.TypeOf((*MockCodeGuruProfilerAPI)(nil).DescribeProfilingGroupRequest), arg0)
}
// DescribeProfilingGroupWithContext mocks base method.
func (m *MockCodeGuruProfilerAPI) DescribeProfilingGroupWithContext(arg0 context.Context, arg1 *codeguruprofiler.DescribeProfilingGroupInput, arg2 ...request.Option) (*codeguruprofiler.DescribeProfilingGroupOutput, error) {
m.ctrl.T.Helper()
varargs := []interface{}{arg0, arg1}
for _, a := range arg2 {
varargs = append(varargs, a)
}
ret := m.ctrl.Call(m, "DescribeProfilingGroupWithContext", varargs...)
ret0, _ := ret[0].(*codeguruprofiler.DescribeProfilingGroupOutput)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// DescribeProfilingGroupWithContext indicates an expected call of DescribeProfilingGroupWithContext.
func (mr *MockCodeGuruProfilerAPIMockRecorder) DescribeProfilingGroupWithContext(arg0, arg1 interface{}, arg2 ...interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
varargs := append([]interface{}{arg0, arg1}, arg2...)
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DescribeProfilingGroupWithContext", reflect.TypeOf((*MockCodeGuruProfilerAPI)(nil).DescribeProfilingGroupWithContext), varargs...)
}
// GetFindingsReportAccountSummary mocks base method.
func (m *MockCodeGuruProfilerAPI) GetFindingsReportAccountSummary(arg0 *codeguruprofiler.GetFindingsReportAccountSummaryInput) (*codeguruprofiler.GetFindingsReportAccountSummaryOutput, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "GetFindingsReportAccountSummary", arg0)
ret0, _ := ret[0].(*codeguruprofiler.GetFindingsReportAccountSummaryOutput)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// GetFindingsReportAccountSummary indicates an expected call of GetFindingsReportAccountSummary.
func (mr *MockCodeGuruProfilerAPIMockRecorder) GetFindingsReportAccountSummary(arg0 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetFindingsReportAccountSummary", reflect.TypeOf((*MockCodeGuruProfilerAPI)(nil).GetFindingsReportAccountSummary), arg0)
}
// GetFindingsReportAccountSummaryPages mocks base method.
func (m *MockCodeGuruProfilerAPI) GetFindingsReportAccountSummaryPages(arg0 *codeguruprofiler.GetFindingsReportAccountSummaryInput, arg1 func(*codeguruprofiler.GetFindingsReportAccountSummaryOutput, bool) bool) error {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "GetFindingsReportAccountSummaryPages", arg0, arg1)
ret0, _ := ret[0].(error)
return ret0
}
// GetFindingsReportAccountSummaryPages indicates an expected call of GetFindingsReportAccountSummaryPages.
func (mr *MockCodeGuruProfilerAPIMockRecorder) GetFindingsReportAccountSummaryPages(arg0, arg1 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetFindingsReportAccountSummaryPages", reflect.TypeOf((*MockCodeGuruProfilerAPI)(nil).GetFindingsReportAccountSummaryPages), arg0, arg1)
}
// GetFindingsReportAccountSummaryPagesWithContext mocks base method.
func (m *MockCodeGuruProfilerAPI) GetFindingsReportAccountSummaryPagesWithContext(arg0 context.Context, arg1 *codeguruprofiler.GetFindingsReportAccountSummaryInput, arg2 func(*codeguruprofiler.GetFindingsReportAccountSummaryOutput, bool) bool, arg3 ...request.Option) error {
m.ctrl.T.Helper()
varargs := []interface{}{arg0, arg1, arg2}
for _, a := range arg3 {
varargs = append(varargs, a)
}
ret := m.ctrl.Call(m, "GetFindingsReportAccountSummaryPagesWithContext", varargs...)
ret0, _ := ret[0].(error)
return ret0
}
// GetFindingsReportAccountSummaryPagesWithContext indicates an expected call of GetFindingsReportAccountSummaryPagesWithContext.
func (mr *MockCodeGuruProfilerAPIMockRecorder) GetFindingsReportAccountSummaryPagesWithContext(arg0, arg1, arg2 interface{}, arg3 ...interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
varargs := append([]interface{}{arg0, arg1, arg2}, arg3...)
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetFindingsReportAccountSummaryPagesWithContext", reflect.TypeOf((*MockCodeGuruProfilerAPI)(nil).GetFindingsReportAccountSummaryPagesWithContext), varargs...)
}
// GetFindingsReportAccountSummaryRequest mocks base method.
func (m *MockCodeGuruProfilerAPI) GetFindingsReportAccountSummaryRequest(arg0 *codeguruprofiler.GetFindingsReportAccountSummaryInput) (*request.Request, *codeguruprofiler.GetFindingsReportAccountSummaryOutput) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "GetFindingsReportAccountSummaryRequest", arg0)
ret0, _ := ret[0].(*request.Request)
ret1, _ := ret[1].(*codeguruprofiler.GetFindingsReportAccountSummaryOutput)
return ret0, ret1
}
// GetFindingsReportAccountSummaryRequest indicates an expected call of GetFindingsReportAccountSummaryRequest.
func (mr *MockCodeGuruProfilerAPIMockRecorder) GetFindingsReportAccountSummaryRequest(arg0 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetFindingsReportAccountSummaryRequest", reflect.TypeOf((*MockCodeGuruProfilerAPI)(nil).GetFindingsReportAccountSummaryRequest), arg0)
}
// GetFindingsReportAccountSummaryWithContext mocks base method.
func (m *MockCodeGuruProfilerAPI) GetFindingsReportAccountSummaryWithContext(arg0 context.Context, arg1 *codeguruprofiler.GetFindingsReportAccountSummaryInput, arg2 ...request.Option) (*codeguruprofiler.GetFindingsReportAccountSummaryOutput, error) {
m.ctrl.T.Helper()
varargs := []interface{}{arg0, arg1}
for _, a := range arg2 {
varargs = append(varargs, a)
}
ret := m.ctrl.Call(m, "GetFindingsReportAccountSummaryWithContext", varargs...)
ret0, _ := ret[0].(*codeguruprofiler.GetFindingsReportAccountSummaryOutput)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// GetFindingsReportAccountSummaryWithContext indicates an expected call of GetFindingsReportAccountSummaryWithContext.
func (mr *MockCodeGuruProfilerAPIMockRecorder) GetFindingsReportAccountSummaryWithContext(arg0, arg1 interface{}, arg2 ...interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
varargs := append([]interface{}{arg0, arg1}, arg2...)
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetFindingsReportAccountSummaryWithContext", reflect.TypeOf((*MockCodeGuruProfilerAPI)(nil).GetFindingsReportAccountSummaryWithContext), varargs...)
}
// GetNotificationConfiguration mocks base method.
func (m *MockCodeGuruProfilerAPI) GetNotificationConfiguration(arg0 *codeguruprofiler.GetNotificationConfigurationInput) (*codeguruprofiler.GetNotificationConfigurationOutput, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "GetNotificationConfiguration", arg0)
ret0, _ := ret[0].(*codeguruprofiler.GetNotificationConfigurationOutput)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// GetNotificationConfiguration indicates an expected call of GetNotificationConfiguration.
func (mr *MockCodeGuruProfilerAPIMockRecorder) GetNotificationConfiguration(arg0 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetNotificationConfiguration", reflect.TypeOf((*MockCodeGuruProfilerAPI)(nil).GetNotificationConfiguration), arg0)
}
// GetNotificationConfigurationRequest mocks base method.
func (m *MockCodeGuruProfilerAPI) GetNotificationConfigurationRequest(arg0 *codeguruprofiler.GetNotificationConfigurationInput) (*request.Request, *codeguruprofiler.GetNotificationConfigurationOutput) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "GetNotificationConfigurationRequest", arg0)
ret0, _ := ret[0].(*request.Request)
ret1, _ := ret[1].(*codeguruprofiler.GetNotificationConfigurationOutput)
return ret0, ret1
}
// GetNotificationConfigurationRequest indicates an expected call of GetNotificationConfigurationRequest.
func (mr *MockCodeGuruProfilerAPIMockRecorder) GetNotificationConfigurationRequest(arg0 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetNotificationConfigurationRequest", reflect.TypeOf((*MockCodeGuruProfilerAPI)(nil).GetNotificationConfigurationRequest), arg0)
}
// GetNotificationConfigurationWithContext mocks base method.
func (m *MockCodeGuruProfilerAPI) GetNotificationConfigurationWithContext(arg0 context.Context, arg1 *codeguruprofiler.GetNotificationConfigurationInput, arg2 ...request.Option) (*codeguruprofiler.GetNotificationConfigurationOutput, error) {
m.ctrl.T.Helper()
varargs := []interface{}{arg0, arg1}
for _, a := range arg2 {
varargs = append(varargs, a)
}
ret := m.ctrl.Call(m, "GetNotificationConfigurationWithContext", varargs...)
ret0, _ := ret[0].(*codeguruprofiler.GetNotificationConfigurationOutput)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// GetNotificationConfigurationWithContext indicates an expected call of GetNotificationConfigurationWithContext.
func (mr *MockCodeGuruProfilerAPIMockRecorder) GetNotificationConfigurationWithContext(arg0, arg1 interface{}, arg2 ...interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
varargs := append([]interface{}{arg0, arg1}, arg2...)
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetNotificationConfigurationWithContext", reflect.TypeOf((*MockCodeGuruProfilerAPI)(nil).GetNotificationConfigurationWithContext), varargs...)
}
// GetPolicy mocks base method.
func (m *MockCodeGuruProfilerAPI) GetPolicy(arg0 *codeguruprofiler.GetPolicyInput) (*codeguruprofiler.GetPolicyOutput, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "GetPolicy", arg0)
ret0, _ := ret[0].(*codeguruprofiler.GetPolicyOutput)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// GetPolicy indicates an expected call of GetPolicy.
func (mr *MockCodeGuruProfilerAPIMockRecorder) GetPolicy(arg0 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetPolicy", reflect.TypeOf((*MockCodeGuruProfilerAPI)(nil).GetPolicy), arg0)
}
// GetPolicyRequest mocks base method.
func (m *MockCodeGuruProfilerAPI) GetPolicyRequest(arg0 *codeguruprofiler.GetPolicyInput) (*request.Request, *codeguruprofiler.GetPolicyOutput) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "GetPolicyRequest", arg0)
ret0, _ := ret[0].(*request.Request)
ret1, _ := ret[1].(*codeguruprofiler.GetPolicyOutput)
return ret0, ret1
}
// GetPolicyRequest indicates an expected call of GetPolicyRequest.
func (mr *MockCodeGuruProfilerAPIMockRecorder) GetPolicyRequest(arg0 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetPolicyRequest", reflect.TypeOf((*MockCodeGuruProfilerAPI)(nil).GetPolicyRequest), arg0)
}
// GetPolicyWithContext mocks base method.
func (m *MockCodeGuruProfilerAPI) GetPolicyWithContext(arg0 context.Context, arg1 *codeguruprofiler.GetPolicyInput, arg2 ...request.Option) (*codeguruprofiler.GetPolicyOutput, error) {
m.ctrl.T.Helper()
varargs := []interface{}{arg0, arg1}
for _, a := range arg2 {
varargs = append(varargs, a)
}
ret := m.ctrl.Call(m, "GetPolicyWithContext", varargs...)
ret0, _ := ret[0].(*codeguruprofiler.GetPolicyOutput)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// GetPolicyWithContext indicates an expected call of GetPolicyWithContext.
func (mr *MockCodeGuruProfilerAPIMockRecorder) GetPolicyWithContext(arg0, arg1 interface{}, arg2 ...interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
varargs := append([]interface{}{arg0, arg1}, arg2...)
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetPolicyWithContext", reflect.TypeOf((*MockCodeGuruProfilerAPI)(nil).GetPolicyWithContext), varargs...)
}
// GetProfile mocks base method.
func (m *MockCodeGuruProfilerAPI) GetProfile(arg0 *codeguruprofiler.GetProfileInput) (*codeguruprofiler.GetProfileOutput, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "GetProfile", arg0)
ret0, _ := ret[0].(*codeguruprofiler.GetProfileOutput)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// GetProfile indicates an expected call of GetProfile.
func (mr *MockCodeGuruProfilerAPIMockRecorder) GetProfile(arg0 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetProfile", reflect.TypeOf((*MockCodeGuruProfilerAPI)(nil).GetProfile), arg0)
}
// GetProfileRequest mocks base method.
func (m *MockCodeGuruProfilerAPI) GetProfileRequest(arg0 *codeguruprofiler.GetProfileInput) (*request.Request, *codeguruprofiler.GetProfileOutput) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "GetProfileRequest", arg0)
ret0, _ := ret[0].(*request.Request)
ret1, _ := ret[1].(*codeguruprofiler.GetProfileOutput)
return ret0, ret1
}
// GetProfileRequest indicates an expected call of GetProfileRequest.
func (mr *MockCodeGuruProfilerAPIMockRecorder) GetProfileRequest(arg0 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetProfileRequest", reflect.TypeOf((*MockCodeGuruProfilerAPI)(nil).GetProfileRequest), arg0)
}
// GetProfileWithContext mocks base method.
func (m *MockCodeGuruProfilerAPI) GetProfileWithContext(arg0 context.Context, arg1 *codeguruprofiler.GetProfileInput, arg2 ...request.Option) (*codeguruprofiler.GetProfileOutput, error) {
m.ctrl.T.Helper()
varargs := []interface{}{arg0, arg1}
for _, a := range arg2 {
varargs = append(varargs, a)
}
ret := m.ctrl.Call(m, "GetProfileWithContext", varargs...)
ret0, _ := ret[0].(*codeguruprofiler.GetProfileOutput)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// GetProfileWithContext indicates an expected call of GetProfileWithContext.
func (mr *MockCodeGuruProfilerAPIMockRecorder) GetProfileWithContext(arg0, arg1 interface{}, arg2 ...interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
varargs := append([]interface{}{arg0, arg1}, arg2...)
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetProfileWithContext", reflect.TypeOf((*MockCodeGuruProfilerAPI)(nil).GetProfileWithContext), varargs...)
}
// GetRecommendations mocks base method.
func (m *MockCodeGuruProfilerAPI) GetRecommendations(arg0 *codeguruprofiler.GetRecommendationsInput) (*codeguruprofiler.GetRecommendationsOutput, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "GetRecommendations", arg0)
ret0, _ := ret[0].(*codeguruprofiler.GetRecommendationsOutput)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// GetRecommendations indicates an expected call of GetRecommendations.
func (mr *MockCodeGuruProfilerAPIMockRecorder) GetRecommendations(arg0 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetRecommendations", reflect.TypeOf((*MockCodeGuruProfilerAPI)(nil).GetRecommendations), arg0)
}
// GetRecommendationsRequest mocks base method.
func (m *MockCodeGuruProfilerAPI) GetRecommendationsRequest(arg0 *codeguruprofiler.GetRecommendationsInput) (*request.Request, *codeguruprofiler.GetRecommendationsOutput) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "GetRecommendationsRequest", arg0)
ret0, _ := ret[0].(*request.Request)
ret1, _ := ret[1].(*codeguruprofiler.GetRecommendationsOutput)
return ret0, ret1
}
// GetRecommendationsRequest indicates an expected call of GetRecommendationsRequest.
func (mr *MockCodeGuruProfilerAPIMockRecorder) GetRecommendationsRequest(arg0 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetRecommendationsRequest", reflect.TypeOf((*MockCodeGuruProfilerAPI)(nil).GetRecommendationsRequest), arg0)
}
// GetRecommendationsWithContext mocks base method.
func (m *MockCodeGuruProfilerAPI) GetRecommendationsWithContext(arg0 context.Context, arg1 *codeguruprofiler.GetRecommendationsInput, arg2 ...request.Option) (*codeguruprofiler.GetRecommendationsOutput, error) {
m.ctrl.T.Helper()
varargs := []interface{}{arg0, arg1}
for _, a := range arg2 {
varargs = append(varargs, a)
}
ret := m.ctrl.Call(m, "GetRecommendationsWithContext", varargs...)
ret0, _ := ret[0].(*codeguruprofiler.GetRecommendationsOutput)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// GetRecommendationsWithContext indicates an expected call of GetRecommendationsWithContext.
func (mr *MockCodeGuruProfilerAPIMockRecorder) GetRecommendationsWithContext(arg0, arg1 interface{}, arg2 ...interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
varargs := append([]interface{}{arg0, arg1}, arg2...)
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetRecommendationsWithContext", reflect.TypeOf((*MockCodeGuruProfilerAPI)(nil).GetRecommendationsWithContext), varargs...)
}
// ListFindingsReports mocks base method.
func (m *MockCodeGuruProfilerAPI) ListFindingsReports(arg0 *codeguruprofiler.ListFindingsReportsInput) (*codeguruprofiler.ListFindingsReportsOutput, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "ListFindingsReports", arg0)
ret0, _ := ret[0].(*codeguruprofiler.ListFindingsReportsOutput)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// ListFindingsReports indicates an expected call of ListFindingsReports.
func (mr *MockCodeGuruProfilerAPIMockRecorder) ListFindingsReports(arg0 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ListFindingsReports", reflect.TypeOf((*MockCodeGuruProfilerAPI)(nil).ListFindingsReports), arg0)
}
// ListFindingsReportsPages mocks base method.
func (m *MockCodeGuruProfilerAPI) ListFindingsReportsPages(arg0 *codeguruprofiler.ListFindingsReportsInput, arg1 func(*codeguruprofiler.ListFindingsReportsOutput, bool) bool) error {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "ListFindingsReportsPages", arg0, arg1)
ret0, _ := ret[0].(error)
return ret0
}
// ListFindingsReportsPages indicates an expected call of ListFindingsReportsPages.
func (mr *MockCodeGuruProfilerAPIMockRecorder) ListFindingsReportsPages(arg0, arg1 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ListFindingsReportsPages", reflect.TypeOf((*MockCodeGuruProfilerAPI)(nil).ListFindingsReportsPages), arg0, arg1)
}
// ListFindingsReportsPagesWithContext mocks base method.
func (m *MockCodeGuruProfilerAPI) ListFindingsReportsPagesWithContext(arg0 context.Context, arg1 *codeguruprofiler.ListFindingsReportsInput, arg2 func(*codeguruprofiler.ListFindingsReportsOutput, bool) bool, arg3 ...request.Option) error {
m.ctrl.T.Helper()
varargs := []interface{}{arg0, arg1, arg2}
for _, a := range arg3 {
varargs = append(varargs, a)
}
ret := m.ctrl.Call(m, "ListFindingsReportsPagesWithContext", varargs...)
ret0, _ := ret[0].(error)
return ret0
}
// ListFindingsReportsPagesWithContext indicates an expected call of ListFindingsReportsPagesWithContext.
func (mr *MockCodeGuruProfilerAPIMockRecorder) ListFindingsReportsPagesWithContext(arg0, arg1, arg2 interface{}, arg3 ...interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
varargs := append([]interface{}{arg0, arg1, arg2}, arg3...)
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ListFindingsReportsPagesWithContext", reflect.TypeOf((*MockCodeGuruProfilerAPI)(nil).ListFindingsReportsPagesWithContext), varargs...)
}
// ListFindingsReportsRequest mocks base method.
func (m *MockCodeGuruProfilerAPI) ListFindingsReportsRequest(arg0 *codeguruprofiler.ListFindingsReportsInput) (*request.Request, *codeguruprofiler.ListFindingsReportsOutput) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "ListFindingsReportsRequest", arg0)
ret0, _ := ret[0].(*request.Request)
ret1, _ := ret[1].(*codeguruprofiler.ListFindingsReportsOutput)
return ret0, ret1
}
// ListFindingsReportsRequest indicates an expected call of ListFindingsReportsRequest.
func (mr *MockCodeGuruProfilerAPIMockRecorder) ListFindingsReportsRequest(arg0 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ListFindingsReportsRequest", reflect.TypeOf((*MockCodeGuruProfilerAPI)(nil).ListFindingsReportsRequest), arg0)
}
// ListFindingsReportsWithContext mocks base method.
func (m *MockCodeGuruProfilerAPI) ListFindingsReportsWithContext(arg0 context.Context, arg1 *codeguruprofiler.ListFindingsReportsInput, arg2 ...request.Option) (*codeguruprofiler.ListFindingsReportsOutput, error) {
m.ctrl.T.Helper()
varargs := []interface{}{arg0, arg1}
for _, a := range arg2 {
varargs = append(varargs, a)
}
ret := m.ctrl.Call(m, "ListFindingsReportsWithContext", varargs...)
ret0, _ := ret[0].(*codeguruprofiler.ListFindingsReportsOutput)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// ListFindingsReportsWithContext indicates an expected call of ListFindingsReportsWithContext.
func (mr *MockCodeGuruProfilerAPIMockRecorder) ListFindingsReportsWithContext(arg0, arg1 interface{}, arg2 ...interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
varargs := append([]interface{}{arg0, arg1}, arg2...)
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ListFindingsReportsWithContext", reflect.TypeOf((*MockCodeGuruProfilerAPI)(nil).ListFindingsReportsWithContext), varargs...)
}
// ListProfileTimes mocks base method.
func (m *MockCodeGuruProfilerAPI) ListProfileTimes(arg0 *codeguruprofiler.ListProfileTimesInput) (*codeguruprofiler.ListProfileTimesOutput, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "ListProfileTimes", arg0)
ret0, _ := ret[0].(*codeguruprofiler.ListProfileTimesOutput)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// ListProfileTimes indicates an expected call of ListProfileTimes.
func (mr *MockCodeGuruProfilerAPIMockRecorder) ListProfileTimes(arg0 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ListProfileTimes", reflect.TypeOf((*MockCodeGuruProfilerAPI)(nil).ListProfileTimes), arg0)
}
// ListProfileTimesPages mocks base method.
func (m *MockCodeGuruProfilerAPI) ListProfileTimesPages(arg0 *codeguruprofiler.ListProfileTimesInput, arg1 func(*codeguruprofiler.ListProfileTimesOutput, bool) bool) error {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "ListProfileTimesPages", arg0, arg1)
ret0, _ := ret[0].(error)
return ret0
}
// ListProfileTimesPages indicates an expected call of ListProfileTimesPages.
func (mr *MockCodeGuruProfilerAPIMockRecorder) ListProfileTimesPages(arg0, arg1 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ListProfileTimesPages", reflect.TypeOf((*MockCodeGuruProfilerAPI)(nil).ListProfileTimesPages), arg0, arg1)
}
// ListProfileTimesPagesWithContext mocks base method.
func (m *MockCodeGuruProfilerAPI) ListProfileTimesPagesWithContext(arg0 context.Context, arg1 *codeguruprofiler.ListProfileTimesInput, arg2 func(*codeguruprofiler.ListProfileTimesOutput, bool) bool, arg3 ...request.Option) error {
m.ctrl.T.Helper()
varargs := []interface{}{arg0, arg1, arg2}
for _, a := range arg3 {
varargs = append(varargs, a)
}
ret := m.ctrl.Call(m, "ListProfileTimesPagesWithContext", varargs...)
ret0, _ := ret[0].(error)
return ret0
}
// ListProfileTimesPagesWithContext indicates an expected call of ListProfileTimesPagesWithContext.
func (mr *MockCodeGuruProfilerAPIMockRecorder) ListProfileTimesPagesWithContext(arg0, arg1, arg2 interface{}, arg3 ...interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
varargs := append([]interface{}{arg0, arg1, arg2}, arg3...)
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ListProfileTimesPagesWithContext", reflect.TypeOf((*MockCodeGuruProfilerAPI)(nil).ListProfileTimesPagesWithContext), varargs...)
}
// ListProfileTimesRequest mocks base method.
func (m *MockCodeGuruProfilerAPI) ListProfileTimesRequest(arg0 *codeguruprofiler.ListProfileTimesInput) (*request.Request, *codeguruprofiler.ListProfileTimesOutput) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "ListProfileTimesRequest", arg0)
ret0, _ := ret[0].(*request.Request)
ret1, _ := ret[1].(*codeguruprofiler.ListProfileTimesOutput)
return ret0, ret1
}
// ListProfileTimesRequest indicates an expected call of ListProfileTimesRequest.
func (mr *MockCodeGuruProfilerAPIMockRecorder) ListProfileTimesRequest(arg0 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ListProfileTimesRequest", reflect.TypeOf((*MockCodeGuruProfilerAPI)(nil).ListProfileTimesRequest), arg0)
}
// ListProfileTimesWithContext mocks base method.
func (m *MockCodeGuruProfilerAPI) ListProfileTimesWithContext(arg0 context.Context, arg1 *codeguruprofiler.ListProfileTimesInput, arg2 ...request.Option) (*codeguruprofiler.ListProfileTimesOutput, error) {
m.ctrl.T.Helper()
varargs := []interface{}{arg0, arg1}
for _, a := range arg2 {
varargs = append(varargs, a)
}
ret := m.ctrl.Call(m, "ListProfileTimesWithContext", varargs...)
ret0, _ := ret[0].(*codeguruprofiler.ListProfileTimesOutput)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// ListProfileTimesWithContext indicates an expected call of ListProfileTimesWithContext.
func (mr *MockCodeGuruProfilerAPIMockRecorder) ListProfileTimesWithContext(arg0, arg1 interface{}, arg2 ...interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
varargs := append([]interface{}{arg0, arg1}, arg2...)
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ListProfileTimesWithContext", reflect.TypeOf((*MockCodeGuruProfilerAPI)(nil).ListProfileTimesWithContext), varargs...)
}
// ListProfilingGroups mocks base method.
func (m *MockCodeGuruProfilerAPI) ListProfilingGroups(arg0 *codeguruprofiler.ListProfilingGroupsInput) (*codeguruprofiler.ListProfilingGroupsOutput, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "ListProfilingGroups", arg0)
ret0, _ := ret[0].(*codeguruprofiler.ListProfilingGroupsOutput)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// ListProfilingGroups indicates an expected call of ListProfilingGroups.
func (mr *MockCodeGuruProfilerAPIMockRecorder) ListProfilingGroups(arg0 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ListProfilingGroups", reflect.TypeOf((*MockCodeGuruProfilerAPI)(nil).ListProfilingGroups), arg0)
}
// ListProfilingGroupsPages mocks base method.
func (m *MockCodeGuruProfilerAPI) ListProfilingGroupsPages(arg0 *codeguruprofiler.ListProfilingGroupsInput, arg1 func(*codeguruprofiler.ListProfilingGroupsOutput, bool) bool) error {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "ListProfilingGroupsPages", arg0, arg1)
ret0, _ := ret[0].(error)
return ret0
}
// ListProfilingGroupsPages indicates an expected call of ListProfilingGroupsPages.
func (mr *MockCodeGuruProfilerAPIMockRecorder) ListProfilingGroupsPages(arg0, arg1 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ListProfilingGroupsPages", reflect.TypeOf((*MockCodeGuruProfilerAPI)(nil).ListProfilingGroupsPages), arg0, arg1)
}
// ListProfilingGroupsPagesWithContext mocks base method.
func (m *MockCodeGuruProfilerAPI) ListProfilingGroupsPagesWithContext(arg0 context.Context, arg1 *codeguruprofiler.ListProfilingGroupsInput, arg2 func(*codeguruprofiler.ListProfilingGroupsOutput, bool) bool, arg3 ...request.Option) error {
m.ctrl.T.Helper()
varargs := []interface{}{arg0, arg1, arg2}
for _, a := range arg3 {
varargs = append(varargs, a)
}
ret := m.ctrl.Call(m, "ListProfilingGroupsPagesWithContext", varargs...)
ret0, _ := ret[0].(error)
return ret0
}
// ListProfilingGroupsPagesWithContext indicates an expected call of ListProfilingGroupsPagesWithContext.
func (mr *MockCodeGuruProfilerAPIMockRecorder) ListProfilingGroupsPagesWithContext(arg0, arg1, arg2 interface{}, arg3 ...interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
varargs := append([]interface{}{arg0, arg1, arg2}, arg3...)
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ListProfilingGroupsPagesWithContext", reflect.TypeOf((*MockCodeGuruProfilerAPI)(nil).ListProfilingGroupsPagesWithContext), varargs...)
}
// ListProfilingGroupsRequest mocks base method.
func (m *MockCodeGuruProfilerAPI) ListProfilingGroupsRequest(arg0 *codeguruprofiler.ListProfilingGroupsInput) (*request.Request, *codeguruprofiler.ListProfilingGroupsOutput) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "ListProfilingGroupsRequest", arg0)
ret0, _ := ret[0].(*request.Request)
ret1, _ := ret[1].(*codeguruprofiler.ListProfilingGroupsOutput)
return ret0, ret1
}
// ListProfilingGroupsRequest indicates an expected call of ListProfilingGroupsRequest.
func (mr *MockCodeGuruProfilerAPIMockRecorder) ListProfilingGroupsRequest(arg0 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ListProfilingGroupsRequest", reflect.TypeOf((*MockCodeGuruProfilerAPI)(nil).ListProfilingGroupsRequest), arg0)
}
// ListProfilingGroupsWithContext mocks base method.
func (m *MockCodeGuruProfilerAPI) ListProfilingGroupsWithContext(arg0 context.Context, arg1 *codeguruprofiler.ListProfilingGroupsInput, arg2 ...request.Option) (*codeguruprofiler.ListProfilingGroupsOutput, error) {
m.ctrl.T.Helper()
varargs := []interface{}{arg0, arg1}
for _, a := range arg2 {
varargs = append(varargs, a)
}
ret := m.ctrl.Call(m, "ListProfilingGroupsWithContext", varargs...)
ret0, _ := ret[0].(*codeguruprofiler.ListProfilingGroupsOutput)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// ListProfilingGroupsWithContext indicates an expected call of ListProfilingGroupsWithContext.
func (mr *MockCodeGuruProfilerAPIMockRecorder) ListProfilingGroupsWithContext(arg0, arg1 interface{}, arg2 ...interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
varargs := append([]interface{}{arg0, arg1}, arg2...)
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ListProfilingGroupsWithContext", reflect.TypeOf((*MockCodeGuruProfilerAPI)(nil).ListProfilingGroupsWithContext), varargs...)
}
// ListTagsForResource mocks base method.
func (m *MockCodeGuruProfilerAPI) ListTagsForResource(arg0 *codeguruprofiler.ListTagsForResourceInput) (*codeguruprofiler.ListTagsForResourceOutput, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "ListTagsForResource", arg0)
ret0, _ := ret[0].(*codeguruprofiler.ListTagsForResourceOutput)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// ListTagsForResource indicates an expected call of ListTagsForResource.
func (mr *MockCodeGuruProfilerAPIMockRecorder) ListTagsForResource(arg0 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ListTagsForResource", reflect.TypeOf((*MockCodeGuruProfilerAPI)(nil).ListTagsForResource), arg0)
}
// ListTagsForResourceRequest mocks base method.
func (m *MockCodeGuruProfilerAPI) ListTagsForResourceRequest(arg0 *codeguruprofiler.ListTagsForResourceInput) (*request.Request, *codeguruprofiler.ListTagsForResourceOutput) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "ListTagsForResourceRequest", arg0)
ret0, _ := ret[0].(*request.Request)
ret1, _ := ret[1].(*codeguruprofiler.ListTagsForResourceOutput)
return ret0, ret1
}
// ListTagsForResourceRequest indicates an expected call of ListTagsForResourceRequest.
func (mr *MockCodeGuruProfilerAPIMockRecorder) ListTagsForResourceRequest(arg0 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ListTagsForResourceRequest", reflect.TypeOf((*MockCodeGuruProfilerAPI)(nil).ListTagsForResourceRequest), arg0)
}
// ListTagsForResourceWithContext mocks base method.
func (m *MockCodeGuruProfilerAPI) ListTagsForResourceWithContext(arg0 context.Context, arg1 *codeguruprofiler.ListTagsForResourceInput, arg2 ...request.Option) (*codeguruprofiler.ListTagsForResourceOutput, error) {
m.ctrl.T.Helper()
varargs := []interface{}{arg0, arg1}
for _, a := range arg2 {
varargs = append(varargs, a)
}
ret := m.ctrl.Call(m, "ListTagsForResourceWithContext", varargs...)
ret0, _ := ret[0].(*codeguruprofiler.ListTagsForResourceOutput)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// ListTagsForResourceWithContext indicates an expected call of ListTagsForResourceWithContext.
func (mr *MockCodeGuruProfilerAPIMockRecorder) ListTagsForResourceWithContext(arg0, arg1 interface{}, arg2 ...interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
varargs := append([]interface{}{arg0, arg1}, arg2...)
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ListTagsForResourceWithContext", reflect.TypeOf((*MockCodeGuruProfilerAPI)(nil).ListTagsForResourceWithContext), varargs...)
}
// PostAgentProfile mocks base method.
func (m *MockCodeGuruProfilerAPI) PostAgentProfile(arg0 *codeguruprofiler.PostAgentProfileInput) (*codeguruprofiler.PostAgentProfileOutput, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "PostAgentProfile", arg0)
ret0, _ := ret[0].(*codeguruprofiler.PostAgentProfileOutput)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// PostAgentProfile indicates an expected call of PostAgentProfile.
func (mr *MockCodeGuruProfilerAPIMockRecorder) PostAgentProfile(arg0 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "PostAgentProfile", reflect.TypeOf((*MockCodeGuruProfilerAPI)(nil).PostAgentProfile), arg0)
}
// PostAgentProfileRequest mocks base method.
func (m *MockCodeGuruProfilerAPI) PostAgentProfileRequest(arg0 *codeguruprofiler.PostAgentProfileInput) (*request.Request, *codeguruprofiler.PostAgentProfileOutput) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "PostAgentProfileRequest", arg0)
ret0, _ := ret[0].(*request.Request)
ret1, _ := ret[1].(*codeguruprofiler.PostAgentProfileOutput)
return ret0, ret1
}
// PostAgentProfileRequest indicates an expected call of PostAgentProfileRequest.
func (mr *MockCodeGuruProfilerAPIMockRecorder) PostAgentProfileRequest(arg0 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "PostAgentProfileRequest", reflect.TypeOf((*MockCodeGuruProfilerAPI)(nil).PostAgentProfileRequest), arg0)
}
// PostAgentProfileWithContext mocks base method.
func (m *MockCodeGuruProfilerAPI) PostAgentProfileWithContext(arg0 context.Context, arg1 *codeguruprofiler.PostAgentProfileInput, arg2 ...request.Option) (*codeguruprofiler.PostAgentProfileOutput, error) {
m.ctrl.T.Helper()
varargs := []interface{}{arg0, arg1}
for _, a := range arg2 {
varargs = append(varargs, a)
}
ret := m.ctrl.Call(m, "PostAgentProfileWithContext", varargs...)
ret0, _ := ret[0].(*codeguruprofiler.PostAgentProfileOutput)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// PostAgentProfileWithContext indicates an expected call of PostAgentProfileWithContext.
func (mr *MockCodeGuruProfilerAPIMockRecorder) PostAgentProfileWithContext(arg0, arg1 interface{}, arg2 ...interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
varargs := append([]interface{}{arg0, arg1}, arg2...)
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "PostAgentProfileWithContext", reflect.TypeOf((*MockCodeGuruProfilerAPI)(nil).PostAgentProfileWithContext), varargs...)
}
// PutPermission mocks base method.
func (m *MockCodeGuruProfilerAPI) PutPermission(arg0 *codeguruprofiler.PutPermissionInput) (*codeguruprofiler.PutPermissionOutput, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "PutPermission", arg0)
ret0, _ := ret[0].(*codeguruprofiler.PutPermissionOutput)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// PutPermission indicates an expected call of PutPermission.
func (mr *MockCodeGuruProfilerAPIMockRecorder) PutPermission(arg0 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "PutPermission", reflect.TypeOf((*MockCodeGuruProfilerAPI)(nil).PutPermission), arg0)
}
// PutPermissionRequest mocks base method.
func (m *MockCodeGuruProfilerAPI) PutPermissionRequest(arg0 *codeguruprofiler.PutPermissionInput) (*request.Request, *codeguruprofiler.PutPermissionOutput) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "PutPermissionRequest", arg0)
ret0, _ := ret[0].(*request.Request)
ret1, _ := ret[1].(*codeguruprofiler.PutPermissionOutput)
return ret0, ret1
}
// PutPermissionRequest indicates an expected call of PutPermissionRequest.
func (mr *MockCodeGuruProfilerAPIMockRecorder) PutPermissionRequest(arg0 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "PutPermissionRequest", reflect.TypeOf((*MockCodeGuruProfilerAPI)(nil).PutPermissionRequest), arg0)
}
// PutPermissionWithContext mocks base method.
func (m *MockCodeGuruProfilerAPI) PutPermissionWithContext(arg0 context.Context, arg1 *codeguruprofiler.PutPermissionInput, arg2 ...request.Option) (*codeguruprofiler.PutPermissionOutput, error) {
m.ctrl.T.Helper()
varargs := []interface{}{arg0, arg1}
for _, a := range arg2 {
varargs = append(varargs, a)
}
ret := m.ctrl.Call(m, "PutPermissionWithContext", varargs...)
ret0, _ := ret[0].(*codeguruprofiler.PutPermissionOutput)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// PutPermissionWithContext indicates an expected call of PutPermissionWithContext.
func (mr *MockCodeGuruProfilerAPIMockRecorder) PutPermissionWithContext(arg0, arg1 interface{}, arg2 ...interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
varargs := append([]interface{}{arg0, arg1}, arg2...)
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "PutPermissionWithContext", reflect.TypeOf((*MockCodeGuruProfilerAPI)(nil).PutPermissionWithContext), varargs...)
}
// RemoveNotificationChannel mocks base method.
func (m *MockCodeGuruProfilerAPI) RemoveNotificationChannel(arg0 *codeguruprofiler.RemoveNotificationChannelInput) (*codeguruprofiler.RemoveNotificationChannelOutput, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "RemoveNotificationChannel", arg0)
ret0, _ := ret[0].(*codeguruprofiler.RemoveNotificationChannelOutput)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// RemoveNotificationChannel indicates an expected call of RemoveNotificationChannel.
func (mr *MockCodeGuruProfilerAPIMockRecorder) RemoveNotificationChannel(arg0 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RemoveNotificationChannel", reflect.TypeOf((*MockCodeGuruProfilerAPI)(nil).RemoveNotificationChannel), arg0)
}
// RemoveNotificationChannelRequest mocks base method.
func (m *MockCodeGuruProfilerAPI) RemoveNotificationChannelRequest(arg0 *codeguruprofiler.RemoveNotificationChannelInput) (*request.Request, *codeguruprofiler.RemoveNotificationChannelOutput) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "RemoveNotificationChannelRequest", arg0)
ret0, _ := ret[0].(*request.Request)
ret1, _ := ret[1].(*codeguruprofiler.RemoveNotificationChannelOutput)
return ret0, ret1
}
// RemoveNotificationChannelRequest indicates an expected call of RemoveNotificationChannelRequest.
func (mr *MockCodeGuruProfilerAPIMockRecorder) RemoveNotificationChannelRequest(arg0 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RemoveNotificationChannelRequest", reflect.TypeOf((*MockCodeGuruProfilerAPI)(nil).RemoveNotificationChannelRequest), arg0)
}
// RemoveNotificationChannelWithContext mocks base method.
func (m *MockCodeGuruProfilerAPI) RemoveNotificationChannelWithContext(arg0 context.Context, arg1 *codeguruprofiler.RemoveNotificationChannelInput, arg2 ...request.Option) (*codeguruprofiler.RemoveNotificationChannelOutput, error) {
m.ctrl.T.Helper()
varargs := []interface{}{arg0, arg1}
for _, a := range arg2 {
varargs = append(varargs, a)
}
ret := m.ctrl.Call(m, "RemoveNotificationChannelWithContext", varargs...)
ret0, _ := ret[0].(*codeguruprofiler.RemoveNotificationChannelOutput)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// RemoveNotificationChannelWithContext indicates an expected call of RemoveNotificationChannelWithContext.
func (mr *MockCodeGuruProfilerAPIMockRecorder) RemoveNotificationChannelWithContext(arg0, arg1 interface{}, arg2 ...interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
varargs := append([]interface{}{arg0, arg1}, arg2...)
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RemoveNotificationChannelWithContext", reflect.TypeOf((*MockCodeGuruProfilerAPI)(nil).RemoveNotificationChannelWithContext), varargs...)
}
// RemovePermission mocks base method.
func (m *MockCodeGuruProfilerAPI) RemovePermission(arg0 *codeguruprofiler.RemovePermissionInput) (*codeguruprofiler.RemovePermissionOutput, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "RemovePermission", arg0)
ret0, _ := ret[0].(*codeguruprofiler.RemovePermissionOutput)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// RemovePermission indicates an expected call of RemovePermission.
func (mr *MockCodeGuruProfilerAPIMockRecorder) RemovePermission(arg0 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RemovePermission", reflect.TypeOf((*MockCodeGuruProfilerAPI)(nil).RemovePermission), arg0)
}
// RemovePermissionRequest mocks base method.
func (m *MockCodeGuruProfilerAPI) RemovePermissionRequest(arg0 *codeguruprofiler.RemovePermissionInput) (*request.Request, *codeguruprofiler.RemovePermissionOutput) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "RemovePermissionRequest", arg0)
ret0, _ := ret[0].(*request.Request)
ret1, _ := ret[1].(*codeguruprofiler.RemovePermissionOutput)
return ret0, ret1
}
// RemovePermissionRequest indicates an expected call of RemovePermissionRequest.
func (mr *MockCodeGuruProfilerAPIMockRecorder) RemovePermissionRequest(arg0 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RemovePermissionRequest", reflect.TypeOf((*MockCodeGuruProfilerAPI)(nil).RemovePermissionRequest), arg0)
}
// RemovePermissionWithContext mocks base method.
func (m *MockCodeGuruProfilerAPI) RemovePermissionWithContext(arg0 context.Context, arg1 *codeguruprofiler.RemovePermissionInput, arg2 ...request.Option) (*codeguruprofiler.RemovePermissionOutput, error) {
m.ctrl.T.Helper()
varargs := []interface{}{arg0, arg1}
for _, a := range arg2 {
varargs = append(varargs, a)
}
ret := m.ctrl.Call(m, "RemovePermissionWithContext", varargs...)
ret0, _ := ret[0].(*codeguruprofiler.RemovePermissionOutput)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// RemovePermissionWithContext indicates an expected call of RemovePermissionWithContext.
func (mr *MockCodeGuruProfilerAPIMockRecorder) RemovePermissionWithContext(arg0, arg1 interface{}, arg2 ...interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
varargs := append([]interface{}{arg0, arg1}, arg2...)
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RemovePermissionWithContext", reflect.TypeOf((*MockCodeGuruProfilerAPI)(nil).RemovePermissionWithContext), varargs...)
}
// SubmitFeedback mocks base method.
func (m *MockCodeGuruProfilerAPI) SubmitFeedback(arg0 *codeguruprofiler.SubmitFeedbackInput) (*codeguruprofiler.SubmitFeedbackOutput, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "SubmitFeedback", arg0)
ret0, _ := ret[0].(*codeguruprofiler.SubmitFeedbackOutput)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// SubmitFeedback indicates an expected call of SubmitFeedback.
func (mr *MockCodeGuruProfilerAPIMockRecorder) SubmitFeedback(arg0 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SubmitFeedback", reflect.TypeOf((*MockCodeGuruProfilerAPI)(nil).SubmitFeedback), arg0)
}
// SubmitFeedbackRequest mocks base method.
func (m *MockCodeGuruProfilerAPI) SubmitFeedbackRequest(arg0 *codeguruprofiler.SubmitFeedbackInput) (*request.Request, *codeguruprofiler.SubmitFeedbackOutput) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "SubmitFeedbackRequest", arg0)
ret0, _ := ret[0].(*request.Request)
ret1, _ := ret[1].(*codeguruprofiler.SubmitFeedbackOutput)
return ret0, ret1
}
// SubmitFeedbackRequest indicates an expected call of SubmitFeedbackRequest.
func (mr *MockCodeGuruProfilerAPIMockRecorder) SubmitFeedbackRequest(arg0 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SubmitFeedbackRequest", reflect.TypeOf((*MockCodeGuruProfilerAPI)(nil).SubmitFeedbackRequest), arg0)
}
// SubmitFeedbackWithContext mocks base method.
func (m *MockCodeGuruProfilerAPI) SubmitFeedbackWithContext(arg0 context.Context, arg1 *codeguruprofiler.SubmitFeedbackInput, arg2 ...request.Option) (*codeguruprofiler.SubmitFeedbackOutput, error) {
m.ctrl.T.Helper()
varargs := []interface{}{arg0, arg1}
for _, a := range arg2 {
varargs = append(varargs, a)
}
ret := m.ctrl.Call(m, "SubmitFeedbackWithContext", varargs...)
ret0, _ := ret[0].(*codeguruprofiler.SubmitFeedbackOutput)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// SubmitFeedbackWithContext indicates an expected call of SubmitFeedbackWithContext.
func (mr *MockCodeGuruProfilerAPIMockRecorder) SubmitFeedbackWithContext(arg0, arg1 interface{}, arg2 ...interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
varargs := append([]interface{}{arg0, arg1}, arg2...)
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SubmitFeedbackWithContext", reflect.TypeOf((*MockCodeGuruProfilerAPI)(nil).SubmitFeedbackWithContext), varargs...)
}
// TagResource mocks base method.
func (m *MockCodeGuruProfilerAPI) TagResource(arg0 *codeguruprofiler.TagResourceInput) (*codeguruprofiler.TagResourceOutput, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "TagResource", arg0)
ret0, _ := ret[0].(*codeguruprofiler.TagResourceOutput)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// TagResource indicates an expected call of TagResource.
func (mr *MockCodeGuruProfilerAPIMockRecorder) TagResource(arg0 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "TagResource", reflect.TypeOf((*MockCodeGuruProfilerAPI)(nil).TagResource), arg0)
}
// TagResourceRequest mocks base method.
func (m *MockCodeGuruProfilerAPI) TagResourceRequest(arg0 *codeguruprofiler.TagResourceInput) (*request.Request, *codeguruprofiler.TagResourceOutput) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "TagResourceRequest", arg0)
ret0, _ := ret[0].(*request.Request)
ret1, _ := ret[1].(*codeguruprofiler.TagResourceOutput)
return ret0, ret1
}
// TagResourceRequest indicates an expected call of TagResourceRequest.
func (mr *MockCodeGuruProfilerAPIMockRecorder) TagResourceRequest(arg0 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "TagResourceRequest", reflect.TypeOf((*MockCodeGuruProfilerAPI)(nil).TagResourceRequest), arg0)
}
// TagResourceWithContext mocks base method.
func (m *MockCodeGuruProfilerAPI) TagResourceWithContext(arg0 context.Context, arg1 *codeguruprofiler.TagResourceInput, arg2 ...request.Option) (*codeguruprofiler.TagResourceOutput, error) {
m.ctrl.T.Helper()
varargs := []interface{}{arg0, arg1}
for _, a := range arg2 {
varargs = append(varargs, a)
}
ret := m.ctrl.Call(m, "TagResourceWithContext", varargs...)
ret0, _ := ret[0].(*codeguruprofiler.TagResourceOutput)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// TagResourceWithContext indicates an expected call of TagResourceWithContext.
func (mr *MockCodeGuruProfilerAPIMockRecorder) TagResourceWithContext(arg0, arg1 interface{}, arg2 ...interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
varargs := append([]interface{}{arg0, arg1}, arg2...)
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "TagResourceWithContext", reflect.TypeOf((*MockCodeGuruProfilerAPI)(nil).TagResourceWithContext), varargs...)
}
// UntagResource mocks base method.
func (m *MockCodeGuruProfilerAPI) UntagResource(arg0 *codeguruprofiler.UntagResourceInput) (*codeguruprofiler.UntagResourceOutput, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "UntagResource", arg0)
ret0, _ := ret[0].(*codeguruprofiler.UntagResourceOutput)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// UntagResource indicates an expected call of UntagResource.
func (mr *MockCodeGuruProfilerAPIMockRecorder) UntagResource(arg0 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UntagResource", reflect.TypeOf((*MockCodeGuruProfilerAPI)(nil).UntagResource), arg0)
}
// UntagResourceRequest mocks base method.
func (m *MockCodeGuruProfilerAPI) UntagResourceRequest(arg0 *codeguruprofiler.UntagResourceInput) (*request.Request, *codeguruprofiler.UntagResourceOutput) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "UntagResourceRequest", arg0)
ret0, _ := ret[0].(*request.Request)
ret1, _ := ret[1].(*codeguruprofiler.UntagResourceOutput)
return ret0, ret1
}
// UntagResourceRequest indicates an expected call of UntagResourceRequest.
func (mr *MockCodeGuruProfilerAPIMockRecorder) UntagResourceRequest(arg0 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UntagResourceRequest", reflect.TypeOf((*MockCodeGuruProfilerAPI)(nil).UntagResourceRequest), arg0)
}
// UntagResourceWithContext mocks base method.
func (m *MockCodeGuruProfilerAPI) UntagResourceWithContext(arg0 context.Context, arg1 *codeguruprofiler.UntagResourceInput, arg2 ...request.Option) (*codeguruprofiler.UntagResourceOutput, error) {
m.ctrl.T.Helper()
varargs := []interface{}{arg0, arg1}
for _, a := range arg2 {
varargs = append(varargs, a)
}
ret := m.ctrl.Call(m, "UntagResourceWithContext", varargs...)
ret0, _ := ret[0].(*codeguruprofiler.UntagResourceOutput)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// UntagResourceWithContext indicates an expected call of UntagResourceWithContext.
func (mr *MockCodeGuruProfilerAPIMockRecorder) UntagResourceWithContext(arg0, arg1 interface{}, arg2 ...interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
varargs := append([]interface{}{arg0, arg1}, arg2...)
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UntagResourceWithContext", reflect.TypeOf((*MockCodeGuruProfilerAPI)(nil).UntagResourceWithContext), varargs...)
}
// UpdateProfilingGroup mocks base method.
func (m *MockCodeGuruProfilerAPI) UpdateProfilingGroup(arg0 *codeguruprofiler.UpdateProfilingGroupInput) (*codeguruprofiler.UpdateProfilingGroupOutput, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "UpdateProfilingGroup", arg0)
ret0, _ := ret[0].(*codeguruprofiler.UpdateProfilingGroupOutput)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// UpdateProfilingGroup indicates an expected call of UpdateProfilingGroup.
func (mr *MockCodeGuruProfilerAPIMockRecorder) UpdateProfilingGroup(arg0 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UpdateProfilingGroup", reflect.TypeOf((*MockCodeGuruProfilerAPI)(nil).UpdateProfilingGroup), arg0)
}
// UpdateProfilingGroupRequest mocks base method.
func (m *MockCodeGuruProfilerAPI) UpdateProfilingGroupRequest(arg0 *codeguruprofiler.UpdateProfilingGroupInput) (*request.Request, *codeguruprofiler.UpdateProfilingGroupOutput) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "UpdateProfilingGroupRequest", arg0)
ret0, _ := ret[0].(*request.Request)
ret1, _ := ret[1].(*codeguruprofiler.UpdateProfilingGroupOutput)
return ret0, ret1
}
// UpdateProfilingGroupRequest indicates an expected call of UpdateProfilingGroupRequest.
func (mr *MockCodeGuruProfilerAPIMockRecorder) UpdateProfilingGroupRequest(arg0 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UpdateProfilingGroupRequest", reflect.TypeOf((*MockCodeGuruProfilerAPI)(nil).UpdateProfilingGroupRequest), arg0)
}
// UpdateProfilingGroupWithContext mocks base method.
func (m *MockCodeGuruProfilerAPI) UpdateProfilingGroupWithContext(arg0 context.Context, arg1 *codeguruprofiler.UpdateProfilingGroupInput, arg2 ...request.Option) (*codeguruprofiler.UpdateProfilingGroupOutput, error) {
m.ctrl.T.Helper()
varargs := []interface{}{arg0, arg1}
for _, a := range arg2 {
varargs = append(varargs, a)
}
ret := m.ctrl.Call(m, "UpdateProfilingGroupWithContext", varargs...)
ret0, _ := ret[0].(*codeguruprofiler.UpdateProfilingGroupOutput)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// UpdateProfilingGroupWithContext indicates an expected call of UpdateProfilingGroupWithContext.
func (mr *MockCodeGuruProfilerAPIMockRecorder) UpdateProfilingGroupWithContext(arg0, arg1 interface{}, arg2 ...interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
varargs := append([]interface{}{arg0, arg1}, arg2...)
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UpdateProfilingGroupWithContext", reflect.TypeOf((*MockCodeGuruProfilerAPI)(nil).UpdateProfilingGroupWithContext), varargs...)
}
|
Kortemme-Lab/benchmark_set_construct | benchmark_constructor/__init__.py | from . import structure_collectors
from . import filters
from . import file_normalizers
from . import job_distributors
from . import flow_control
|
mengxy/swc | crates/swc_ecma_codegen/tests/test262/7be9be4918d25634.js | <reponame>mengxy/swc<gh_stars>1000+
--arguments;
|
xiaojie19852006/incubator-linkis | linkis-public-enhancements/linkis-publicservice/linkis-instance-label/linkis-instance-label-server/src/main/java/org/apache/linkis/instance/label/vo/InsPersistenceLabelSearchVo.java | <reponame>xiaojie19852006/incubator-linkis<gh_stars>100-1000
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.linkis.instance.label.vo;
import org.apache.linkis.instance.label.entity.InsPersistenceLabel;
public class InsPersistenceLabelSearchVo {
private Integer id;
private String labelKey;
private String stringValue;
public InsPersistenceLabelSearchVo() {}
public InsPersistenceLabelSearchVo(InsPersistenceLabel insLabel) {
this.id = insLabel.getId();
this.labelKey = insLabel.getLabelKey();
this.stringValue = insLabel.getStringValue();
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getLabelKey() {
return labelKey;
}
public void setLabelKey(String labelKey) {
this.labelKey = labelKey;
}
public String getStringValue() {
return stringValue;
}
public void setStringValue(String stringValue) {
this.stringValue = stringValue;
}
}
|
1stmateusz/motech | platform/mds/mds/src/test/java/org/motechproject/mds/it/reposistory/AllEntitiesContextIT.java | <reponame>1stmateusz/motech
package org.motechproject.mds.it.reposistory;
import org.junit.Before;
import org.junit.Test;
import org.motechproject.mds.it.BaseIT;
import org.motechproject.mds.domain.Entity;
import org.motechproject.mds.domain.Lookup;
import org.motechproject.mds.dto.EntityDto;
import org.motechproject.mds.exception.entity.EntityNotFoundException;
import org.motechproject.mds.repository.internal.AllEntities;
import org.motechproject.mds.util.Constants;
import org.springframework.beans.factory.annotation.Autowired;
import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class AllEntitiesContextIT extends BaseIT {
private static final String SAMPLE_CLASS = String.format("%s.Sample", Constants.PackagesGenerated.ENTITY);
private static final String EXAMPLE_CLASS = String.format("%s.Example", Constants.PackagesGenerated.ENTITY);
private static final String FOO_CLASS = String.format("%s.Foo", Constants.PackagesGenerated.ENTITY);
private static final String BAR_CLASS = String.format("%s.Bar", Constants.PackagesGenerated.ENTITY);
private static final String SAMPLE_LOOKUP = "SampleLookup";
private static final String EXAMPLE_CLASS_WITH_LOOKUPS = String.format("%s.ExampleWithLookups", Constants.PackagesGenerated.ENTITY);
private static final String EXAMPLE_LOOKUP_1 = "ExampleLookup1";
private static final String EXAMPLE_LOOKUP_2 = "ExampleLookup2";
@Autowired
private AllEntities allEntities;
@Before
public void setUp() throws Exception {
super.setUp();
PersistenceManager persistenceManager = getPersistenceManager();
persistenceManager.makePersistent(new Entity(SAMPLE_CLASS));
persistenceManager.makePersistent(new Entity(EXAMPLE_CLASS));
persistenceManager.makePersistent(new Entity(FOO_CLASS));
Entity entityWithLookups = new Entity(EXAMPLE_CLASS_WITH_LOOKUPS);
List<Lookup> lookups = new LinkedList<>();
lookups.add(new Lookup(EXAMPLE_LOOKUP_1, true, false, null, entityWithLookups));
lookups.add(new Lookup(EXAMPLE_LOOKUP_2, true, false, null, entityWithLookups));
entityWithLookups.setLookups(lookups);
persistenceManager.makePersistent(entityWithLookups);
}
@Test
public void shouldCreateEntity() throws Exception {
assertFalse(
String.format("Found %s in database", BAR_CLASS),
containsEntity(BAR_CLASS)
);
EntityDto entity = new EntityDto();
entity.setClassName(BAR_CLASS);
allEntities.create(entity);
assertTrue(
String.format("Not found %s in database", BAR_CLASS),
containsEntity(BAR_CLASS)
);
}
@Test
public void shouldFindExistingEntity() throws Exception {
for (String className : Arrays.asList(SAMPLE_CLASS, EXAMPLE_CLASS, FOO_CLASS)) {
assertTrue(
String.format("Not found %s in database", className),
allEntities.contains(className)
);
}
}
@Test
public void shouldNotFindNoExistingEntity() throws Exception {
assertFalse(
String.format("Found %s in database", BAR_CLASS),
allEntities.contains(BAR_CLASS)
);
}
@Test
public void shouldDeleteEntity() throws Exception {
EntityDto entity = new EntityDto();
entity.setClassName(BAR_CLASS);
allEntities.create(entity);
assertTrue(
String.format("Not found %s in database", BAR_CLASS),
allEntities.contains(BAR_CLASS)
);
Query query = getPersistenceManager().newQuery(Entity.class);
query.setFilter("className == name");
query.declareParameters("java.lang.String name");
query.setUnique(true);
Entity found = (Entity) query.execute(BAR_CLASS);
allEntities.delete(found.getId());
assertFalse(
String.format("Found %s in database", BAR_CLASS),
allEntities.contains(BAR_CLASS)
);
}
@Test(expected = EntityNotFoundException.class)
public void shouldThrowExceptionWhenDeletingNotExistingEntity() throws Exception {
allEntities.delete(1000L);
}
@Test
public void shouldCascadeSaveLookup() throws Exception {
Lookup lookup = new Lookup(SAMPLE_LOOKUP, true, false, null);
Entity entity = getEntities().get(0);
List<Lookup> lookupSet = new LinkedList<>();
lookupSet.add(lookup);
entity.setLookups(lookupSet);
int indexOfLookup = getLookups().indexOf(lookup);
assertTrue(String.format("'%s' not found in database", SAMPLE_LOOKUP), indexOfLookup >= 0);
assertEquals("Lookup was not associated with an entity",
entity,
getLookups().get(indexOfLookup).getEntity());
}
@Test
public void shouldCascadeDeleteLookups() {
Query query = getPersistenceManager().newQuery(Entity.class);
query.setFilter("className == name");
query.declareParameters("java.lang.String name");
query.setUnique(true);
Entity found = (Entity) query.execute(EXAMPLE_CLASS_WITH_LOOKUPS);
List<Lookup> lookups = new ArrayList<>(found.getLookups());
allEntities.delete(found.getId());
assertFalse("Lookup was not deleted", getLookups().contains(lookups.get(0)));
assertFalse("Lookup was not deleted", getLookups().contains(lookups.get(1)));
}
@Test
public void shouldUpdateLookup() throws Exception {
Query query = getPersistenceManager().newQuery(Entity.class);
query.setFilter("className == name");
query.declareParameters("java.lang.String name");
query.setUnique(true);
Entity entity = (Entity) query.execute(EXAMPLE_CLASS_WITH_LOOKUPS);
for (Lookup lookup : entity.getLookups()) {
if (EXAMPLE_LOOKUP_1.equals(lookup.getLookupName())) {
lookup.setSingleObjectReturn(false);
} else if (EXAMPLE_LOOKUP_2.equals(lookup.getLookupName())) {
lookup.setExposedViaRest(true);
}
}
for (Lookup lookup : getLookups()) {
if (EXAMPLE_LOOKUP_1.equals(lookup.getLookupName())) {
assertEquals("Lookup was not updated properly", false, lookup.isSingleObjectReturn());
assertEquals("Lookup was not updated properly", false, lookup.isExposedViaRest());
} else if (EXAMPLE_LOOKUP_2.equals(lookup.getLookupName())) {
assertEquals("Lookup was not updated properly", true, lookup.isSingleObjectReturn());
assertEquals("Lookup was not updated properly", true, lookup.isExposedViaRest());
}
}
}
}
|
jeske/csla | pysrc/message_db.py |
import os, sys, string, re, time
import marshal
import subprocess
from clearsilver import odb, hdfhelp, odb_sqlite3
from clearsilver.log import *
import neo_cgi, neo_util
import email_message
from mimelib import Message, Generator, Parser, date
import rfc822
import SwishE
import search_help
eNoMessage = "eNoMessage"
class Message(odb.Row):
def subclassinit(self):
self.snippet = None
def hdfExport(self, prefix, hdf, tz="US/Pacific", subj_prefix=None):
hdf.setValue(prefix, "1")
obj = hdf.getObj(prefix)
obj.setValue("doc_id", str(self.doc_id))
obj.setValue("thread_id", str(self.thread_id))
obj.setValue("parent_id", str(self.parent_id))
obj.setValue("next_id", str(self.next_id))
obj.setValue("child_id", str(self.child_id))
if self.date:
neo_cgi.exportDate(obj, "date", tz, self.date)
subject = self.subject
if subj_prefix:
subject = subject.replace(subj_prefix, '')
obj.setValue("subject", neo_cgi.htmlEscape(subject))
obj.setValue("subject_strip", neo_cgi.htmlEscape(strip_re(subject, subj_prefix=subj_prefix)))
obj.setValue("subject_reduced", reduce_subject(subject, subj_prefix=subj_prefix))
obj.setValue("author", neo_cgi.htmlEscape(self.author))
obj.setValue("email", neo_cgi.htmlEscape(self.email))
if self.summary is not None:
obj.setValue("summary", neo_cgi.text2html(self.summary))
if self.snippet is not None:
obj.setValue("snippet", self.snippet)
class MessageIndex(odb.Database):
# Maps message number to message meta information
def __init__ (self, conn):
odb.Database.__init__(self, conn)
self.addTable("messages", "ds_messages", MessageTable, rowClass=Message)
def defaultRowClass(self):
return hdfhelp.HdfRow
def defaultRowListClass(self):
return hdfhelp.HdfItemList
def add(self, doc_id, msg_data, parent_id, thread_id, date_t,
h_subj, author, email, summary):
parent_meta = None
if thread_id == 0:
parent_meta = self.get(parent_id)
if parent_meta:
thread_id = parent_meta.thread_id
row = self.messages.newRow()
row.doc_id = doc_id
row.thread_id = thread_id
row.parent_id = parent_id
row.next_id = 0
row.child_id = 0
row.date = date_t
row.subject = h_subj
row.summary = summary
row.author = author
row.email = email
row.msg_data = msg_data
row.save()
if parent_meta is not None:
if parent_meta.child_id == 0:
parent_meta.child_id = doc_id
parent_meta.save()
else:
child_meta = self.get(parent_meta.child_id)
while child_meta.next_id:
child_meta = self.get(child_meta.next_id)
child_meta.next_id = doc_id
child_meta.save()
return thread_id
def get(self, doc_id):
return self.messages.lookup(doc_id=doc_id)
class MessageTable(odb.Table):
def _defineRows(self):
self.d_addColumn("doc_id",odb.kInteger,None,primarykey = 1,
autoincrement = 1)
self.d_addColumn("thread_id",odb.kInteger)
self.d_addColumn("parent_id",odb.kInteger)
self.d_addColumn("child_id",odb.kInteger)
self.d_addColumn("next_id",odb.kInteger)
self.d_addColumn("date",odb.kInteger)
self.d_addColumn("subject",odb.kVarString)
self.d_addColumn("summary",odb.kVarString)
self.d_addColumn("author",odb.kVarString)
self.d_addColumn("email",odb.kVarString)
self.d_addColumn("msg_data",odb.kBigString,None, compress_ok=1)
class ByMonth:
def __init__ (self, path):
self._path = path
self._data = None
self._modified = 0
self.load()
def load(self):
# v1 = "year/month first_num count"
self._data = {}
path = "%s/archive/by_month" % self._path
if not os.path.exists(path): return
fp = open(path)
header = fp.readline()
if header != 'BY_MONTH_v1\n':
raise "Unknown ByMonth Version"
for line in fp.readlines():
parts = line.split(' ')
if len(parts) == 3:
self._data[parts[0]] = (int(parts[1]), int(parts[2]))
def get(self, month):
month = month.replace('-', '/')
(first_num, count) = self._data.get(month, (0, 0))
return (first_num, count)
def add(self, doc_id, date_t):
tup = time.localtime(date_t)
year = tup[0]
mon = tup[1]
date = '%s/%02d' % (year, mon)
(first_num, count) = self._data.get(date, (0, 0))
if first_num == 0 or doc_id < first_num:
first_num = doc_id
count = count + 1
self._data[date] = (first_num, count)
self._modified = 1
def __del__ (self):
self.save()
def save (self):
if self._modified:
path = "%s/archive/by_month" % self._path
fp = open(path + ".tmp", 'w')
fp.write('BY_MONTH_v1\n')
dates = self._data.keys()
dates.sort()
for date in dates:
(first_num, count) = self._data[date]
fp.write("%s %s %s\n" % (date, first_num, count))
fp.close()
os.rename(path + ".tmp", path)
self._modified = 0
def hdfExport(self, prefix, hdf, reverse=0):
dates = self._data.keys()
if not dates:
# if there is no data...
return
dates.sort()
first_date = dates[0]
(first_year, month) = first_date.split('/')
first_year = int(first_year)
last_date = dates[-1]
(last_year, month) = last_date.split('/')
last_year = int(last_year)
if reverse:
year = last_year
while year >= first_year:
for mon in range(1,13):
(first_num, count) = self._data.get("%d/%02d" % (year, mon), (0,0))
hdf.setValue("%s.%s.%s.num" % (prefix, year, mon), str(first_num))
hdf.setValue("%s.%s.%s.count" % (prefix, year, mon), str(count))
hdf.setValue("%s.%s.%s.year" % (prefix, year, mon), str(year))
hdf.setValue("%s.%s.%s.mon" % (prefix, year, mon), "%02d" % mon)
year -= 1
else:
year = first_year
while year <= last_year:
for mon in range(1,13):
(first_num, count) = self._data.get("%d/%02d" % (year, mon), (0,0))
hdf.setValue("%s.%s.%s.num" % (prefix, year, mon), str(first_num))
hdf.setValue("%s.%s.%s.count" % (prefix, year, mon), str(count))
hdf.setValue("%s.%s.%s.year" % (prefix, year, mon), str(year))
hdf.setValue("%s.%s.%s.mon" % (prefix, year, mon), "%02d" % mon)
year += 1
class ThreadIndexTable(odb.Table):
def _defineRows(self):
self.d_addColumn("thread_id",odb.kVarString,None,primarykey = 1)
self.d_addColumn("doc_list",odb.kVarString,None)
class ThreadRow(odb.Row):
def getDocList(self):
if self.doc_list is None: return []
return string.split(self.doc_list, ',')
def setDocList(self,dlist):
self.doc_list = string.join(dlist, ',')
class ThreadIndex(odb.Database):
# Maps thread ids to message numbers
def __init__ (self, conn):
odb.Database.__init__(self, conn)
self.addTable("threads", "ds_threads", ThreadIndexTable, rowClass=ThreadRow)
def add(self, thread_id, doc_id):
row = self.threads.lookupCreate(thread_id=thread_id)
dlist = row.getDocList()
dlist.append(str(doc_id))
row.setDocList(dlist)
row.save()
def get(self, thread_id):
row = self.threads.lookup(thread_id=thread_id)
return row
class MessageIDTable(odb.Table):
def _defineRows(self):
self.d_addColumn("msg_id",odb.kVarString,None,primarykey = 1)
self.d_addColumn("doc_id",odb.kInteger,None)
class MessageIDIndex(odb.Database):
# Maps message ids to message numbers
def __init__ (self, conn):
odb.Database.__init__(self, conn)
self.addTable("messageidx", "ds_messageidx", MessageIDTable)
def find(self, references):
for ref in references:
row = self.messageidx.lookup(msg_id=ref)
if row: return row.doc_id
return 0
def add(self, msg_id, doc_id):
row = self.messageidx.newRow(replace=1)
row.msg_id = msg_id
row.doc_id = doc_id
row.save()
class AuthorTable(odb.Table):
def _defineRows(self):
self.d_addColumn("email", odb.kVarString,None,primarykey = 1)
self.d_addColumn("name", odb.kVarString)
self.d_addColumn("bymonth", odb.kVarString)
class AuthorRow(odb.Row):
def getByMonth(self):
if self.bymonth is None: return {}
mon_data = self.bymonth.split(' ')
bymonth = {}
for part in mon_data:
(date, count) = part.split(':')
bymonth[date] = int(count)
return bymonth
def setByMonth(self, bymonthDict):
self.bymonth = string.join(map(lambda x: '%s:%d' % x, bymonthDict.items()))
class AuthorIndex(odb.Database):
# Maps email address to name and posts by month
def __init__ (self, conn, path):
odb.Database.__init__(self, conn)
self.addTable("authors", "ds_authors", AuthorTable, rowClass=AuthorRow)
self._path = path
def add(self, author, email, date_t):
if not email: return
email = email.strip()
lemail = email.lower()
tup = time.localtime(date_t)
year = tup[0]
mon = tup[1]
date = '%s-%02d' % (year, mon)
row = self.authors.lookupCreate(email=lemail)
name = row.name
bymonth = row.getByMonth()
#(junk, name, bymonth) = self.get(email)
if not author:
author = name
total = bymonth.get('total', 0)
total += 1
bymonth['total'] = total
count = bymonth.get(date, 0)
count += 1
bymonth[date] = count
row.setByMonth(bymonth)
if author is None: author = "no author"
row.name = author
row.save()
if 1:
# add to "totals" list
data = self.get_top('total')
if len(data) == 0:
data.append((total, email))
self.write_top('total', data)
else:
(min_total, junk) = data[-1]
if len(data) < 50 or min_total <= total:
data.append((total, email))
self.write_top('total', data)
# add to proper month
data = self.get_top(date)
if len(data) == 0:
data.append((count, email))
self.write_top(date, data)
else:
(min_count, junk) = data[-1]
if len(data) < 50 or min_count <= count:
data.append((count, email))
self.write_top(date, data)
def get(self, email):
lemail = email.lower()
row = self.authors.lookup(email=lemail)
return row
def get_top(self, date):
path = "%s/archive/authors_%s.top" % (self._path, date)
if not os.path.exists(path):
return []
fp = open(path)
header = fp.readline()
if header != 'TOP_AUTHOR_v1\n':
raise "Unknown Top Author Version"
data = []
for line in fp.readlines():
try:
(email, count) = line.strip().split('')
data.append((int(count), email))
except ValueError:
print "get_top: error parsing: %s" % line
continue
return data
def write_top(self, date, data):
path = "%s/archive/authors_%s.top" % (self._path, date)
fp = open(path + '.tmp', 'w')
fp.write('TOP_AUTHOR_v1\n')
data.sort()
data.reverse()
seen = {}
n = 0
for (count, email) in data:
email = email.lower()
if seen.has_key(email): continue
seen[email] = 1
fp.write("%s%s\n" % (email, count))
n += 1
if n >= 50: break
fp.close()
os.rename(path + '.tmp', path)
global flag
flag = 0
class SearchIndex:
# Full text index of the messages
def __init__ (self, path, mode):
self._rtv = None
self._path = path
self._search_path = os.path.join(self._path, "search")
if not os.path.exists(self._search_path):
os.mkdir(self._search_path, 0700)
self._configfn = os.path.join(self._search_path, "config")
self._indexfn = os.path.join(self._search_path, "index")
if not os.path.exists(self._configfn):
fp = open(self._configfn, "w")
fp.write("IndexFile %s\n" % self._indexfn)
fp.write("StoreDescription TXT* 10000\n")
fp.write("StoreDescription HTML* <body> 10000\n")
fp.write("MetaNames subject author\n")
fp.close()
self._stdin = None
if mode == 'w':
cmd = ["swish-e", "-c", self._configfn, "-S", "prog", "-i", "stdin"]
rtv = subprocess.Popen(cmd, stdin=subprocess.PIPE)
self._stdin = rtv.stdin
else:
rtv = SwishE.new(self._indexfn)
self._rtv = rtv
self._rtv_count = 0
def _write(self, s):
self._stdin.write(s)
self._stdin.write("\n")
def _writeln(self):
self._stdin.write("\n")
def __del__ (self):
self.close()
def close(self):
if self._rtv is not None:
if self._stdin:
self._rtv.stdin.close()
self._rtv.wait()
self._rtv = None
def add(self, msg_num, msgobj, email):
# Ok, time to index the actual message
rm = email_message.RenderMessage(mimemsg=msgobj)
self._write("Path-Name: %s" % (os.path.join(self._path, str(msg_num))))
extra = []
if 1:
for hdr in ["subject"]:
val = rm.decode_header(msgobj, hdr, "", as_utf8=1)
if val:
extra.append('<meta name="%s" content="%s">' % (hdr, neo_cgi.htmlEscape(val)))
extra.append('<meta name="author" content="%s">' % neo_cgi.htmlEscape(string.lower(email)))
extra = string.join(extra, "\n")
data = rm.as_text()
data = neo_cgi.htmlEscape(data)
data = data + extra
self._write("Document-Type: HTML*")
self._write("Content-Length: %s" % str(len(data)))
self._writeln()
self._rtv.stdin.write(data)
self._rtv_count = self._rtv_count + 1
def search(self, query, attrs=[]):
search = self._rtv.search(query)
results = search.execute(query)
ret = []
for result in results:
path = result.getproperty("swishdocpath")
base, num = os.path.split(path)
ret.append(int(num))
return ret
class MessageDB:
def __init__ (self, path):
self._path = path
if not os.path.exists(self._path + '/archive'):
os.makedirs(self._path + '/archive', 0777)
self._messageIndex = None
self._messageIndex_mode = None
self._byMonth = None
self._threadIndex = None
self._threadIndex_mode = None
self._messageIDIndex = None
self._messageIDIndex_mode = None
self._authorIndex = None
self._authorIndex_mode = None
self._searchIndex = None
self._searchIndex_mode = None
self.config = neo_util.HDF()
self._config_file = "%s/archive/mdb.hdf" % self._path
if os.path.exists(self._config_file):
self.config.readFile(self._config_file)
self._config_dirty = 0
self._parser = None
def createTables(self):
import which_read
which_read.createTables(self._path)
for openCmd in (self.openMessageIndex, self.openThreadIndex,
self.openMessageIDIndex, self.openAuthorIndex):
db = openCmd("rw")
db.createTables()
db.synchronizeSchema()
db.createIndices()
def __del__ (self):
self.flush()
def flush(self):
if self._config_dirty:
self.config.writeFile("%s/archive/mdb.hdf" % self._path)
self._config_dirty = 0
self._messageIndex = None
self._messageIndex_mode = None
self._byMonth = None
self._threadIndex = None
self._threadIndex_mode = None
self._messageIDIndex = None
self._messageIDIndex_mode = None
self._authorIndex = None
self._authorIndex_mode = None
self._searchIndex = None
self._searchIndex_mode = None
def openMessageIndex(self, mode):
if self._messageIndex is None or self._messageIndex_mode != mode:
apath = "%s/archive/msgidx.db3" % self._path
# conn = odb_sqlite3.Connection(apath, autocommit=0)
conn = odb_sqlite3.Connection(apath)
self._messageIndex = MessageIndex(conn)
self._messageIndex_mode = mode
return self._messageIndex
def openByMonth(self):
if self._byMonth is None:
self._byMonth = ByMonth(self._path)
return self._byMonth
def openThreadIndex(self, mode):
if self._threadIndex is None or self._threadIndex_mode != mode:
apath = "%s/archive/threadidx.db3" % self._path
# conn = odb_sqlite3.Connection(apath, autocommit=0)
conn = odb_sqlite3.Connection(apath)
self._threadIndex = ThreadIndex(conn)
self._threadIndex_mode = mode
return self._threadIndex
def openMessageIDIndex(self, mode):
if self._messageIDIndex is None or self._messageIDIndex_mode != mode:
apath = "%s/archive/msgids.db3" % self._path
# conn = odb_sqlite3.Connection(apath, autocommit=0)
conn = odb_sqlite3.Connection(apath)
self._messageIDIndex = MessageIDIndex(conn)
self._messageIDIndex_mode = mode
return self._messageIDIndex
def openAuthorIndex(self, mode):
if self._authorIndex is None or self._authorIndex_mode != mode:
apath = "%s/archive/authors.db3" % self._path
# conn = odb_sqlite3.Connection(apath, autocommit=0)
conn = odb_sqlite3.Connection(apath)
self._authorIndex = AuthorIndex(conn, self._path)
self._authorIndex_mode = mode
return self._authorIndex
def openSearchIndex(self, mode):
if self._searchIndex is None or self._searchIndex_mode != mode:
self._searchIndex = SearchIndex(self._path, mode)
self._searchIndex_mode = mode
return self._searchIndex
def setConfig(self, k, v):
self._config_dirty = 1
self.config.setValue(k, v)
################################################################
#### Message Helper Functions
def parser(self):
if self._parser is None:
self._parser = Parser.Parser()
return self._parser
def references(self, msg, h_subject):
refs = []
ref_line = msg.get("References")
if ref_line:
ref_line = string.replace(ref_line, '\r', ' ')
ref_line = string.replace(ref_line, '\n', ' ')
ref_line = string.replace(ref_line, '\t', ' ')
parts = string.split(ref_line)
for part in parts:
part = string.strip(part)
if not part: continue
m = re.search("<([^>]+)>", part)
if m:
ref = m.group(1)
if ref not in refs:
refs.append(ref)
h_inreply = msg.get("In-Reply-To")
if h_inreply:
h_inreply = string.strip(h_inreply)
if h_inreply:
m = re.search("<([^>]+)>", h_inreply)
if m:
ref = m.group(1)
if ref not in refs:
refs.insert(0, ref)
msg_id = None
h_msg_id = msg.get("Message-ID")
if h_msg_id:
m = re.search("<([^>]+)>", h_msg_id)
if m: msg_id = m.group(1)
h_subject = reduce_subject(h_subject)
if len(h_subject) > 9:
subj_id = "subj:%s" % (str(abs(hash(h_subject))))
refs.append(subj_id)
else:
subj_id = None
return msg_id, subj_id, refs
def summary(self, msgobj):
SUMMARY_LENGTH = 50
# We're looking for the first SUMMARY_LENGTH chars of original text
rm = email_message.RenderMessage(mimemsg=msgobj)
data = rm.as_text()
lines = data.split('\n')
quote_regexp = "([ \t]*[|>:}#])+"
header_regexp = "(From|Subject|Date): "
quote_re = re.compile(quote_regexp)
header_re = re.compile(header_regexp)
dash_re = re.compile('------')
summary = []
summary_length = 0
found_quoted = 0
for line in lines:
if quote_re.match(line):
found_quoted = 1
elif header_re.match(line):
found_quoted = 1
elif line.find('Original Message') != -1:
break
elif dash_re.search(line):
found_quoted = 1
else:
if found_quoted:
summary.append('...')
found_quoted = 0
summary.append(line)
summary_length += len(line)
if summary_length > SUMMARY_LENGTH:
break
return " ".join(summary) + '...'
def lock(self):
pass
def unlock(self):
pass
################################################################
#### Data Write
def insertMessage(self, msg_data):
# Ok, inserting a message is a bit of a mess... we have 7 data
# sets to maintain based on the message data (what I wouldn't do for a
# database...)
# 1) Parse the message, and get:
# - message id, subj_id, references
# - author, subject, date
# - summary
m = self.parser().parsestr(msg_data)
rm = email_message.RenderMessage(mimemsg=m)
h_subj = rm.decode_header(m, 'subject', as_utf8 = 1)
msg_id, subj_id, references = self.references(m, h_subj)
h_date = rm.decode_header(m, 'date', as_utf8 = 0)
date_t = 0
if h_date:
tup = date.parsedate_tz(h_date)
try:
date_t = date.mktime_tz(tup)
except (ValueError, OverflowError):
pass
h_from = rm.decode_header(m, 'from', as_utf8 = 1)
from_adr_obj = rfc822.AddressList(h_from)
if len(from_adr_obj):
from_name, from_addr = from_adr_obj.addresslist[0]
else:
from_name, from_addr = "", ""
summary = self.summary(m)
# 2) Lookup reference information to determine thread id and parent
# Let's see if this message refers to any message we've
# seen before...
msgid_idx = self.openMessageIDIndex('w')
parent_id = msgid_idx.find(references)
doc_id = self.config.getIntValue("MaxDocID", 0)
doc_id = doc_id + 1
self.setConfig("MaxDocID", str(doc_id))
if parent_id == 0:
thread_id = self.config.getIntValue("MaxThreadID", 0)
thread_id = thread_id + 1
self.setConfig("MaxThreadID", str(thread_id))
else:
thread_id = 0
# 3) Write message
# 4) Write message index entry
# 5) Update parent or sibling entry (ie, next or child)
msg_idx = self.openMessageIndex('w')
thread_id = msg_idx.add(doc_id, msg_data, parent_id, thread_id, date_t, h_subj, from_name, from_addr, summary)
# 6) Update thread index
thr_idx = self.openThreadIndex('w')
thr_idx.add(thread_id, doc_id)
# 7) Update Msgid Index
if msg_id:
msgid_idx.add(msg_id, doc_id)
if subj_id:
msgid_idx.add(subj_id, doc_id)
# 9) Update by month
bymonth = self.openByMonth()
bymonth.add(doc_id, date_t)
# 10) Update authors
author_idx = self.openAuthorIndex('w')
author_idx.add(from_name, from_addr, date_t)
# 11) Update search
if 0:
search_idx = self.openSearchIndex('w')
search_idx.add(doc_id, m, from_addr)
################################################################
#### Data Read Functions
def messageIndex(self, start, count):
max = self.config.getIntValue("MaxDocID", 0)
if start < 0:
start = start + max + 1
if start + count > max:
count = max - start + 1
msg_idx = self.openMessageIndex('r')
idxs = []
while count:
idxs.append(msg_idx.get(start))
start = start + 1
count = count - 1
return idxs
def message(self, num, full=0, summary=0, snippet_for=None):
max = self.config.getIntValue("MaxDocID", 0)
if num < 0:
num = num + max + 1
if num > max:
raise eNoMessage
if snippet_for:
# we need the full message
full=1
msg_idx = self.openMessageIndex('r')
msg = msg_idx.get(num)
if snippet_for:
snippet = search_help.Snippet()
m = self.parser().parsestr(msg.msg_data)
rm = email_message.RenderMessage(mimemsg=m)
msg.snippet = snippet.snippet(snippet_for, rm.as_text())
return msg
def thread_count(self, thread_id):
max = self.config.getIntValue("MaxThreadID", 0)
if thread_id < 0:
thread_id = thread_id + max + 1
if thread_id > max:
return 0
thr_idx = self.openThreadIndex('r')
return len(thr_idx.get(thread_id))
def thread(self, thread_id):
max = self.config.getIntValue("MaxThreadID", 0)
if thread_id < 0:
thread_id = thread_id + max + 1
if thread_id > max:
raise eNoMessage
thr_idx = self.openThreadIndex('r')
thr = thr_idx.get(thread_id)
dlist = thr.getDocList()
if len(dlist) == 0:
raise eNoMessage
msgs = []
for num in dlist:
msgs.append(self.message(int(num)))
return msgs
def search_author(self, email):
srch_idx = self.openSearchIndex('r')
log("search %s" % email)
results = srch_idx.search("author=(%s)" % email.lower())
log(str(results))
msgs = []
for num in results:
msgs.append(self.message(int(num), full=1))
return msgs
def search(self, query, start = None, count = None):
srch_idx = self.openSearchIndex('r')
results = srch_idx.search(query)
partial = results
msgs = []
if start is None:
partial = results
else:
partial = results[start:start+count]
for num in partial:
msgs.append(self.message(int(num), full=1,snippet_for=query))
return len(results), msgs
def counts(self):
max_thread = self.config.getIntValue("MaxThreadID", 0)
max_doc = self.config.getIntValue("MaxDocID", 0)
return max_doc, max_thread
def strip_re(subject_string, subj_prefix = None):
if subj_prefix:
subject_string = subject_string.replace(subj_prefix, '')
subject_string = re.sub("\s+", " ", subject_string)
subject_string = string.strip(subject_string)
re_re = re.compile("(re([\\[0-9\\]+])*|aw):[ \t]*(.*)", re.IGNORECASE)
match = re_re.match(subject_string)
while match:
subject_string = match.group(3)
match = re_re.match(subject_string)
return string.strip(subject_string)
def reduce_subject(subject_string, subj_prefix = None):
if subj_prefix:
subject_string = subject_string.replace(subj_prefix, '')
subject_string = re.sub("\s+", "", subject_string)
subject_string = string.strip(subject_string)
re_re = re.compile("(re([\\[0-9\\]+])*|aw):[ \t]*(.*)", re.IGNORECASE)
match = re_re.match(subject_string)
while match:
subject_string = match.group(3)
match = re_re.match(subject_string)
return string.strip(subject_string)
|
peterneely/launch | src/main/src/app/browser/types.js | export const SETTINGS_KEY = 'launchSettings';
|
delphi122/knowledge_planet | luogu/P1827.cpp | //
// Created by yangtao on 20-5-15.
//
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <map>
using namespace std;
string s1, s2;
map<char, int> mm;
void dfs(int p1, int p2, int q1, int q2) {
if(q1 > q2 || p1 > p2) return;
char c = s2[q1];
int p = mm[c];
int l1 = p - p1;
dfs(p1, p - 1, q1 + 1, q1 +l1 );
dfs(p + 1, p2, q1 + l1 + 1 , q2);
cout << c ;
}
int main() {
cin >> s1 >> s2;
for(int i = 0; i < s1.length(); i++) {
mm[s1[i]] = i;
}
dfs( 0, s1.length() - 1, 0, s2.length() - 1);
return 0;
} |
iiag/iiag-legacy | src/introspection.c | <filename>src/introspection.c<gh_stars>1-10
//
// introspection.c
//
#include <string.h>
#include <stdio.h>
#include "introspection.h"
#include "log.h"
#ifndef WITH_INTROSPECTION
void init_introspection(const char *prg_file)
{
info("Introspection not enabled; no symbol information will be shown.");
debug("Compile with WITH_INTROSPECTION defined to enable.");
}
#else
#include <sys/mman.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <elf.h>
#include <stdlib.h>
#include <errno.h>
#include "arch.h"
//Change this between 32/64-bit headers
//TODO: Is there a way to do this at compile-time?
#if defined(__i386__)
#define ElfN(tp) Elf32_##tp
#define GET_BASEPOINTER() asm("mov %ebp, __ebp")
#elif defined(__amd64__)
#define ElfN(tp) Elf64_##tp
#define GET_BASEPOINTER() asm("mov %rbp, __ebp")
#else
#error WITH_INTROSPECTION: Architecture does not support introspection
#endif
static void *exec_map=NULL;
static ElfN(Sym) *symtab=NULL;
static ElfN(Shdr) *symsec=NULL;
static ElfN(Shdr) *strsec=NULL;
static char *strtab=NULL;
static unsigned long *__ebp;
void init_introspection(const char *prg_file)
{
int exec_fd, i;
struct stat stat_buf;
ElfN(Ehdr) *header;
ElfN(Shdr) *sections;
ElfN(Shdr) *secstrsec;
char *secstrtbl;
info("Introspection initialization with program %s", prg_file);
//Create a memory map of our own executable (argv[0])
if(stat(prg_file, &stat_buf)) {
warning("Failed to stat program file; no symbol information will be available.");
debug("Error: %s", strerror(errno));
return;
}
exec_fd = open(prg_file, O_RDONLY);
if(exec_fd < 0) {
warning("Failed to open program file for debugging; no symbol information will be available.");
debug("Error: %s", strerror(errno));
return;
}
exec_map = mmap(NULL, stat_buf.st_size, PROT_READ, MAP_SHARED, exec_fd, 0);
close(exec_fd);
if(exec_map == MAP_FAILED) {
warning("Failed to map program file; no symbol information will be available.");
debug("Error: %s", strerror(errno));
return;
}
//Initialize the ELF headers
header = ((ElfN(Ehdr) *) exec_map);
sections = ((ElfN(Shdr) *) ((char *) exec_map + header->e_shoff));
//Search for a symbol string table--first find the section string table
secstrsec = (sections + header->e_shstrndx);
secstrtbl = ((char *) exec_map + secstrsec->sh_offset);
//Search for a the sections section
symtab=NULL;
for(i = 0; i < header->e_shnum; i++) {
if(sections[i].sh_type == SHT_SYMTAB) {
symsec = (sections + i);
symtab = ((ElfN(Sym) *) ((char *) exec_map + symsec->sh_offset));
}
if(sections[i].sh_type == SHT_STRTAB
&& !strncmp((secstrtbl + sections[i].sh_name), ".strtab", 7)) {
strsec = (sections + i);
strtab = ((char *) exec_map + strsec->sh_offset);
}
}
if(!symtab) {
warning("Could not locate a symbol table; no symbol information will be available.");
munmap(exec_map, stat_buf.st_size);
return;
}
info("Successfully loaded debugging symbol information.");
}
void get_location(void *loc, char *s, int sz) {
const char *symname="<unknown symbol>";
int i, offset=-1;
int entries;
ElfN(Sym) *entry;
if(!symtab) {
snprintf(s, sz, "<pre-init; location %p>", loc);
return;
}
entries = (symsec->sh_size / symsec->sh_entsize);
for(i = 0; i < entries; i++) {
entry = (symtab + i);
if(loc >= entry->st_value && loc < (entry->st_value + entry->st_size)) {
if(entry->st_name != 0) {
symname = resolve_string(entry->st_name);
} else {
symname = "<unnamed symbol>";
}
offset = ((long) loc - entry->st_value);
break;
}
}
if(offset < 0) {
snprintf(s, sz, "<unknown location %p>", loc);
} else {
snprintf(s, sz, "<%p> %s+%x", loc, symname, offset);
}
}
void *get_frame(int lev) {
int i;
GET_BASEPOINTER();
//Starting at level -1 because we're inside a function call already
//...or not
for(i = 0; i < lev; i++) {
__ebp = *((unsigned int **)__ebp);
}
return ((void *) __ebp[1]);
}
const char *resolve_string(int idx) {
return strtab + idx;
}
#endif
|
wiedi/rspamd | src/lmtp_proto.c | <reponame>wiedi/rspamd
/*
* Copyright (c) 2009-2012, <NAME>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY AUTHOR ''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 AUTHOR BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "main.h"
#include "cfg_file.h"
#include "util.h"
#include "lmtp.h"
#include "lmtp_proto.h"
/* Max line size as it is defined in rfc2822 */
#define OUTBUFSIZ 1000
/* LMTP commands */
static rspamd_fstring_t lhlo_command = {
.begin = "LHLO",
.len = sizeof ("LHLO") - 1
};
static rspamd_fstring_t mail_command = {
.begin = "MAIL FROM:",
.len = sizeof ("MAIL FROM:") - 1
};
static rspamd_fstring_t rcpt_command = {
.begin = "RCPT TO:",
.len = sizeof ("RCPT TO:") - 1
};
static rspamd_fstring_t data_command = {
.begin = "DATA",
.len = sizeof ("DATA") - 1
};
static rspamd_fstring_t data_dot = {
.begin = ".\r\n",
.len = sizeof (".\r\n") - 1
};
static const gchar *mail_regexp =
"[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?";
static GRegex *mail_re = NULL;
/*
* Extract e-mail from read line
* return <> if no valid address detected
*/
static gchar *
extract_mail (rspamd_mempool_t * pool, rspamd_fstring_t * line)
{
GError *err = NULL;
gchar *match;
GMatchInfo *info;
if (mail_re == NULL) {
/* Compile regexp */
mail_re = g_regex_new (mail_regexp, G_REGEX_RAW, 0, &err);
}
if (g_regex_match_full (mail_re, line->begin, line->len, 0, 0, &info,
NULL) == TRUE) {
match = rspamd_mempool_strdup (pool, g_match_info_fetch (info, 0));
g_match_info_free (info);
}
else {
match = "<>";
}
return match;
}
static gboolean
out_lmtp_reply (struct rspamd_task *task, gint code, gchar *rcode, gchar *msg)
{
gchar outbuf[OUTBUFSIZ];
gint r;
if (*rcode == '\0') {
r = rspamd_snprintf (outbuf, OUTBUFSIZ, "%d %s\r\n", code, msg);
}
else {
r =
rspamd_snprintf (outbuf, OUTBUFSIZ, "%d %s %s\r\n", code, rcode,
msg);
}
if (!rspamd_dispatcher_write (task->dispatcher, outbuf, r, FALSE, FALSE)) {
return FALSE;
}
return TRUE;
}
gint
read_lmtp_input_line (struct rspamd_lmtp_proto *lmtp, rspamd_fstring_t * line)
{
gchar *c, *rcpt;
rspamd_fstring_t fstr;
gint i = 0, l = 0, size;
switch (lmtp->state) {
case LMTP_READ_LHLO:
/* Search LHLO line */
if ((i = rspamd_fstrstri (line, &lhlo_command)) == -1) {
msg_info ("LHLO expected but not found");
(void)out_lmtp_reply (lmtp->task,
LMTP_BAD_CMD,
"5.0.0",
"Need LHLO here");
return -1;
}
else {
i += lhlo_command.len;
c = line->begin + i;
/* Skip spaces */
while (g_ascii_isspace (*c) && i < (gint)line->len) {
i++;
c++;
}
lmtp->task->helo = rspamd_mempool_alloc (lmtp->task->task_pool,
line->len - i + 1);
/* Strlcpy makes string null terminated by design */
rspamd_strlcpy (lmtp->task->helo, c, line->len - i + 1);
lmtp->state = LMTP_READ_FROM;
if (!out_lmtp_reply (lmtp->task, LMTP_OK, "", "Ok")) {
return -1;
}
return 0;
}
break;
case LMTP_READ_FROM:
/* Search MAIL FROM: line */
if ((i = rspamd_fstrstri (line, &mail_command)) == -1) {
msg_info ("MAIL expected but not found");
(void)out_lmtp_reply (lmtp->task,
LMTP_BAD_CMD,
"5.0.0",
"Need MAIL here");
return -1;
}
else {
i += mail_command.len;
c = line->begin + i;
fstr.begin = line->begin + i;
fstr.len = line->len - i;
lmtp->task->from = extract_mail (lmtp->task->task_pool, &fstr);
lmtp->state = LMTP_READ_RCPT;
if (!out_lmtp_reply (lmtp->task, LMTP_OK, "2.1.0", "Sender ok")) {
return -1;
}
return 0;
}
break;
case LMTP_READ_RCPT:
/* Search RCPT_TO: line */
if ((i = rspamd_fstrstri (line, &rcpt_command)) == -1) {
msg_info ("RCPT expected but not found");
(void)out_lmtp_reply (lmtp->task,
LMTP_NO_RCPT,
"5.5.4",
"Need RCPT here");
return -1;
}
else {
i += rcpt_command.len;
c = line->begin + i;
fstr.begin = line->begin + i;
fstr.len = line->len - i;
rcpt = extract_mail (lmtp->task->task_pool, &fstr);
if (*rcpt == '<' && *(rcpt + 1) == '>') {
/* Invalid or empty rcpt not allowed */
msg_info ("bad recipient");
(void)out_lmtp_reply (lmtp->task,
LMTP_NO_RCPT,
"5.5.4",
"Bad recipient");
return -1;
}
/* Strlcpy makes string null terminated by design */
lmtp->task->rcpt = g_list_prepend (lmtp->task->rcpt, rcpt);
lmtp->state = LMTP_READ_DATA;
if (!out_lmtp_reply (lmtp->task, LMTP_OK, "2.1.0",
"Recipient ok")) {
return -1;
}
return 0;
}
break;
case LMTP_READ_DATA:
/* Search DATA line */
if ((i = rspamd_fstrstri (line, &data_command)) == -1) {
msg_info ("DATA expected but not found");
(void)out_lmtp_reply (lmtp->task,
LMTP_BAD_CMD,
"5.0.0",
"Need DATA here");
return -1;
}
else {
i += data_command.len;
c = line->begin + i;
/* Skip spaces */
while (g_ascii_isspace (*c++)) {
i++;
}
rcpt = rspamd_mempool_alloc (lmtp->task->task_pool,
line->len - i + 1);
/* Strlcpy makes string null terminated by design */
rspamd_strlcpy (rcpt, c, line->len - i + 1);
lmtp->task->rcpt = g_list_prepend (lmtp->task->rcpt, rcpt);
lmtp->state = LMTP_READ_MESSAGE;
if (!out_lmtp_reply (lmtp->task, LMTP_DATA, "",
"Enter message, ending with \".\" on a line by itself")) {
return -1;
}
lmtp->task->msg = rspamd_fstralloc (lmtp->task->task_pool, BUFSIZ);
return 0;
}
break;
case LMTP_READ_MESSAGE:
if (strncmp (line->begin, data_dot.begin, line->len) == 0) {
lmtp->state = LMTP_READ_DOT;
lmtp->task->state = READ_MESSAGE;
return 0;
}
else {
l = lmtp->task->msg->len;
size = lmtp->task->msg->size;
if ((gint)(l + line->len) > size) {
/* Grow buffer */
if ((gint)line->len > size) {
size += line->len << 1;
}
else {
/* size *= 2 */
size <<= 1;
}
lmtp->task->msg = rspamd_fstrgrow (lmtp->task->task_pool,
lmtp->task->msg,
size);
}
rspamd_fstrcat (lmtp->task->msg, line);
return 0;
}
break;
case LMTP_READ_DOT:
/* We have some input after reading dot, close connection as we have no currently support of multiply
* messages per session
*/
if (!out_lmtp_reply (lmtp->task, LMTP_QUIT, "", "Bye")) {
return -1;
}
return 0;
break;
}
return 0;
}
struct mta_callback_data {
struct rspamd_task *task;
rspamd_io_dispatcher_t *dispatcher;
enum {
LMTP_WANT_GREETING,
LMTP_WANT_MAIL,
LMTP_WANT_RCPT,
LMTP_WANT_DATA,
LMTP_WANT_DOT,
LMTP_WANT_CLOSING,
} state;
};
static gboolean
parse_mta_str (rspamd_fstring_t * in, struct mta_callback_data *cd)
{
gint r;
static rspamd_fstring_t okres1 = {
.begin = "250 ",
.len = sizeof ("250 ") - 1,
}
, okres2 = {
.begin = "220 ",.len = sizeof ("220 ") - 1,
}
, datares = {
.begin = "354 ",.len = sizeof ("354 ") - 1,
};
switch (cd->state) {
case LMTP_WANT_GREETING:
case LMTP_WANT_MAIL:
case LMTP_WANT_RCPT:
case LMTP_WANT_DATA:
case LMTP_WANT_CLOSING:
r = rspamd_fstrstr (in, &okres1);
if (r == -1) {
r = rspamd_fstrstr (in, &okres2);
}
break;
case LMTP_WANT_DOT:
r = rspamd_fstrstr (in, &datares);
break;
}
return r != -1;
}
static void
close_mta_connection (struct mta_callback_data *cd, gboolean is_success)
{
cd->task->state = CLOSING_CONNECTION;
if (is_success) {
if (!out_lmtp_reply (cd->task, LMTP_OK, "", "Delivery completed")) {
return;
}
}
else {
if (!out_lmtp_reply (cd->task, LMTP_FAILURE, "", "Delivery failure")) {
return;
}
}
rspamd_remove_dispatcher (cd->dispatcher);
}
/*
* Callback that is called when there is data to read in buffer
*/
static gboolean
mta_read_socket (rspamd_fstring_t * in, void *arg)
{
struct mta_callback_data *cd = (struct mta_callback_data *)arg;
gchar outbuf[1024], *hostbuf, *c;
gint hostmax, r;
GList *cur;
static rspamd_fstring_t contres1 = {
.begin = "250-",
.len = sizeof ("250-") - 1,
}
, contres2 = {
.begin = "220-",.len = sizeof ("220-") - 1,
};
if (rspamd_fstrstr (in, &contres1) != -1 || rspamd_fstrstr (in, &contres2) != -1) {
/* Skip such lines */
return TRUE;
}
switch (cd->state) {
case LMTP_WANT_GREETING:
if (!parse_mta_str (in, cd)) {
msg_warn ("got bad greeting");
close_mta_connection (cd, FALSE);
return FALSE;
}
hostmax = sysconf (_SC_HOST_NAME_MAX) + 1;
hostbuf = alloca (hostmax);
gethostname (hostbuf, hostmax);
hostbuf[hostmax - 1] = '\0';
if (cd->task->cfg->deliver_lmtp) {
r = rspamd_snprintf (outbuf,
sizeof (outbuf),
"LHLO %s" CRLF,
hostbuf);
}
else {
r = rspamd_snprintf (outbuf,
sizeof (outbuf),
"HELO %s" CRLF,
hostbuf);
}
if (!rspamd_dispatcher_write (cd->task->dispatcher, outbuf, r, FALSE,
FALSE)) {
return FALSE;
}
cd->state = LMTP_WANT_MAIL;
break;
case LMTP_WANT_MAIL:
if (!parse_mta_str (in, cd)) {
msg_warn ("got bad helo");
close_mta_connection (cd, FALSE);
return FALSE;
}
r = rspamd_snprintf (outbuf,
sizeof (outbuf),
"MAIL FROM: <%s>" CRLF,
cd->task->from);
if (!rspamd_dispatcher_write (cd->task->dispatcher, outbuf, r, FALSE,
FALSE)) {
return FALSE;
}
cd->state = LMTP_WANT_RCPT;
break;
case LMTP_WANT_RCPT:
if (!parse_mta_str (in, cd)) {
msg_warn ("got bad mail from");
close_mta_connection (cd, FALSE);
return FALSE;
}
cur = g_list_first (cd->task->rcpt);
r = 0;
while (cur) {
r += rspamd_snprintf (outbuf + r,
sizeof (outbuf) - r,
"RCPT TO: <%s>" CRLF,
(gchar *)cur->data);
cur = g_list_next (cur);
}
if (!rspamd_dispatcher_write (cd->task->dispatcher, outbuf, r, FALSE,
FALSE)) {
return FALSE;
}
cd->state = LMTP_WANT_DATA;
break;
case LMTP_WANT_DATA:
if (!parse_mta_str (in, cd)) {
msg_warn ("got bad rcpt");
close_mta_connection (cd, FALSE);
return FALSE;
}
r = rspamd_snprintf (outbuf, sizeof (outbuf), "DATA" CRLF);
if (!rspamd_dispatcher_write (cd->task->dispatcher, outbuf, r, FALSE,
FALSE)) {
return FALSE;
}
cd->state = LMTP_WANT_DOT;
break;
case LMTP_WANT_DOT:
if (!parse_mta_str (in, cd)) {
msg_warn ("got bad data");
close_mta_connection (cd, FALSE);
return FALSE;
}
c = g_mime_object_to_string ((GMimeObject *) cd->task->message);
r = strlen (c);
if (!rspamd_dispatcher_write (cd->task->dispatcher, c, r, TRUE, TRUE)) {
return FALSE;
}
rspamd_mempool_add_destructor (cd->task->task_pool,
(rspamd_mempool_destruct_t) g_free, c);
r = rspamd_snprintf (outbuf, sizeof (outbuf), CRLF "." CRLF);
if (!rspamd_dispatcher_write (cd->task->dispatcher, outbuf, r, FALSE,
FALSE)) {
return FALSE;
}
cd->state = LMTP_WANT_CLOSING;
break;
case LMTP_WANT_CLOSING:
if (!parse_mta_str (in, cd)) {
msg_warn ("message not delivered");
close_mta_connection (cd, FALSE);
return FALSE;
}
close_mta_connection (cd, TRUE);
break;
}
return TRUE;
}
/*
* Called if something goes wrong
*/
static void
mta_err_socket (GError * err, void *arg)
{
struct mta_callback_data *cd = (struct mta_callback_data *)arg;
msg_info ("abnormaly terminating connection with MTA");
close_mta_connection (cd, FALSE);
}
/*
* Deliver mail via smtp or lmtp
*/
static gint
lmtp_deliver_mta (struct rspamd_task *task)
{
gint sock;
struct sockaddr_un *un;
struct mta_callback_data *cd;
if (task->cfg->deliver_family == AF_UNIX) {
un = alloca (sizeof (struct sockaddr_un));
sock = rspamd_socket_unix (task->cfg->deliver_host,
un,
SOCK_STREAM,
FALSE,
TRUE);
}
else {
sock = rspamd_socket (task->cfg->deliver_host,
task->cfg->deliver_port,
SOCK_STREAM,
TRUE,
FALSE,
TRUE);
}
if (sock == -1) {
msg_warn ("cannot create socket for %s, %s",
task->cfg->deliver_host,
strerror (errno));
}
cd = rspamd_mempool_alloc (task->task_pool,
sizeof (struct mta_callback_data));
cd->task = task;
cd->state = LMTP_WANT_GREETING;
cd->dispatcher = rspamd_create_dispatcher (task->ev_base,
sock,
BUFFER_LINE,
mta_read_socket,
NULL,
mta_err_socket,
NULL,
(void *)cd);
return 0;
}
static gchar *
format_lda_args (struct rspamd_task *task)
{
gchar *res, *c, *r;
size_t len;
GList *rcpt;
gboolean got_args = FALSE;
c = task->cfg->deliver_agent_path;
/* Find first arg */
if ((c = strchr (c, ' ')) == NULL) {
return task->cfg->deliver_agent_path;
}
/* Calculate length of result string */
len = strlen (task->cfg->deliver_agent_path);
while (*c) {
if (*c == '%') {
c++;
switch (*c) {
case 'f':
/* Insert from */
len += strlen (task->from) - 2;
break;
case 'r':
/* Insert list of recipients */
rcpt = g_list_first (task->rcpt);
len -= 2;
while (rcpt) {
len += strlen ((gchar *)rcpt->data) + 1;
rcpt = g_list_next (rcpt);
}
break;
}
}
c++;
len++;
}
res = rspamd_mempool_alloc (task->task_pool, len + 1);
r = res;
c = task->cfg->deliver_agent_path;
while (*c) {
if (*c == ' ') {
got_args = TRUE;
}
if (got_args && *c == '%') {
switch (*(c + 1)) {
case 'f':
/* Insert from */
c += 2;
len = strlen (task->from);
memcpy (r, task->from, len);
r += len;
break;
case 'r':
/* Insert list of recipients */
c += 2;
rcpt = g_list_first (task->rcpt);
while (rcpt) {
len = strlen ((gchar *)rcpt->data) + 1;
memcpy (r, rcpt->data, len);
r += len;
*r++ = ' ';
rcpt = g_list_next (rcpt);
}
break;
default:
*r = *c;
r++;
c++;
break;
}
}
else {
*r = *c;
r++;
c++;
}
}
return res;
}
static gint
lmtp_deliver_lda (struct rspamd_task *task)
{
gchar *args, **argv;
GMimeStream *stream;
gint rc, ecode, p[2], argc;
pid_t cpid, pid;
if ((args = format_lda_args (task)) == NULL) {
return -1;
}
/* Format arguments in shell style */
if (!g_shell_parse_argv (args, &argc, &argv, NULL)) {
msg_info ("cannot parse arguments");
return -1;
}
if (pipe (p) == -1) {
g_strfreev (argv);
msg_info ("cannot open pipe: %s", strerror (errno));
return -1;
}
/* Fork to exec LDA */
#ifdef HAVE_VFORK
if ((cpid = vfork ()) == -1) {
g_strfreev (argv);
msg_info ("cannot fork: %s", strerror (errno));
return -1;
}
#else
if ((cpid = fork ()) == -1) {
g_strfreev (argv);
msg_info ("cannot fork: %s", strerror (errno));
return -1;
}
#endif
if (cpid == 0) {
/* Child process, close write pipe and keep only read one */
close (p[1]);
/* Set standart IO descriptors */
if (p[0] != STDIN_FILENO) {
(void)dup2 (p[0], STDIN_FILENO);
(void)close (p[0]);
}
execv (argv[0], argv);
_exit (127);
}
close (p[0]);
stream = g_mime_stream_fs_new (p[1]);
if (g_mime_object_write_to_stream ((GMimeObject *) task->message,
stream) == -1) {
g_strfreev (argv);
msg_info ("cannot write stream to lda");
return -1;
}
g_object_unref (stream);
close (p[1]);
#if defined(HAVE_WAIT4)
do {
pid = wait4 (cpid, &rc, 0, NULL);
} while (pid == -1 && errno == EINTR);
#elif defined(HAVE_WAITPID)
do {
pid = waitpid (cpid, &rc, 0);
} while (pid == -1 && errno == EINTR);
#else
# error wait mechanisms are undefined
#endif
if (rc == -1) {
g_strfreev (argv);
msg_info ("lda returned error code");
return -1;
}
else if (WIFEXITED (rc)) {
ecode = WEXITSTATUS (rc);
if (ecode == 0) {
g_strfreev (argv);
return 0;
}
else {
g_strfreev (argv);
msg_info ("lda returned error code %d", ecode);
return -1;
}
}
g_strfreev (argv);
return -1;
}
gint
lmtp_deliver_message (struct rspamd_task *task)
{
if (task->cfg->deliver_agent_path != NULL) {
/* Do deliver to LDA */
return lmtp_deliver_lda (task);
}
else {
/* XXX: do lmtp/smtp client */
return -1;
}
}
gint
write_lmtp_reply (struct rspamd_lmtp_proto *lmtp)
{
gint r;
struct rspamd_task *task = lmtp->task;
debug_task ("writing reply to client");
if (lmtp->task->error_code != 0) {
if (!out_lmtp_reply (lmtp->task, lmtp->task->error_code, "",
lmtp->task->last_error)) {
return -1;
}
}
else {
/* Do delivery */
if ((r = lmtp_deliver_message (lmtp->task)) == -1) {
out_lmtp_reply (lmtp->task, LMTP_FAILURE, "", "Delivery failure");
return -1;
}
else if (r == 0) {
if (!out_lmtp_reply (lmtp->task, LMTP_OK, "",
"Delivery completed")) {
return -1;
}
}
else {
return 1;
}
}
return 0;
}
/*
* vi:ts=4
*/
|
crcrewso/qatrackplus | qatrack/reports/service_log/due_dates.py | <reponame>crcrewso/qatrackplus
from django.conf import settings
from django.utils import timezone
from django.utils.safestring import mark_safe
from django.utils.text import slugify
from django.utils.translation import gettext as _
from django.utils.translation import gettext_lazy as _l
from qatrack.qatrack_core.dates import end_of_day, format_as_date
from qatrack.reports import filters
from qatrack.reports.reports import BaseReport
from qatrack.service_log import models
from qatrack.units import models as umodels
class DueDatesReportMixin(filters.ServiceEventScheduleFilterDetailsMixin):
category = _l("Service Log")
def get_queryset(self):
return models.ServiceEventSchedule.objects.select_related(
"assigned_to",
"service_event_template",
"unit_service_area",
"unit_service_area__unit",
"unit_service_area__service_area",
"frequency",
).exclude(active=False)
def get_context(self):
context = super().get_context()
qs = self.filter_set.qs
sites = self.filter_set.qs.order_by(
"unit_service_area__unit__site__name"
).values_list("unit_service_area__unit__site", flat=True).distinct()
sites_data = []
for site in sites:
if site: # site can be None here since not all units may have a site
site = umodels.Site.objects.get(pk=site)
sites_data.append((site.name if site else "", []))
schedules = qs.filter(
unit_service_area__unit__site_id=(site if site else None),
due_date__isnull=False,
).order_by("due_date", "unit_service_area__unit__%s" % settings.ORDER_UNITS_BY)
for schedule in schedules:
window = schedule.window()
if window:
window = "%s - %s" % (format_as_date(window[0]), format_as_date(window[1]))
sites_data[-1][-1].append({
'schedule': schedule,
'unit_name': schedule.unit_service_area.unit.name,
'service_area_name': schedule.unit_service_area.service_area.name,
'service_event_template_name': schedule.service_event_template.name,
'window': window,
'frequency': schedule.frequency.name if schedule.frequency else _("Ad Hoc"),
'due_date': format_as_date(schedule.due_date),
'assigned_to': schedule.assigned_to.name,
'link': self.make_url(schedule.get_absolute_url(), plain=True),
})
context['sites_data'] = sites_data
return context
def to_table(self, context):
rows = super().to_table(context)
rows.append([])
for site, site_rows in context['sites_data']:
rows.extend([
[],
[],
[site if site else _("Other")],
[_("Unit"),
_("Service Area"),
_("Template Name"),
_("Frequency"),
_("Due Date"),
_("Window"),
_("Assigned To"),
_("Perform")],
])
for row in site_rows:
rows.append([
row['unit_name'],
row['service_area_name'],
row['service_event_template_name'],
row['frequency'],
format_as_date(row['schedule'].due_date),
row['window'],
row['assigned_to'],
])
return rows
class NextScheduledServiceEventsDueDatesReport(DueDatesReportMixin, BaseReport):
report_type = "service_event_next_due"
name = _l("Next Due Dates for Scheduled Service Events")
filter_class = filters.SchedulingFilter
description = mark_safe(
_l("This report shows scheduled service events whose next due date fall in the selected time period.")
)
category = _l("Service Event Scheduling")
template = "reports/service_log/next_due.html"
def get_filename(self, report_format):
return "%s.%s" % (slugify(self.name or _("next-due-dates-for-sl-report")), report_format)
class DueAndOverdueServiceEventScheduleReport(DueDatesReportMixin, BaseReport):
report_type = "service_event_due_and_overdue"
name = _l("Due and Overdue Scheduled Service Events")
filter_class = filters.ScheduledServiceEventFilter
description = mark_safe(_l("This report shows scheduled service events which are currently due or overdue"))
category = _l("Service Event Scheduling")
template = "reports/service_log/next_due.html"
def get_queryset(self):
return super().get_queryset().filter(
due_date__lte=end_of_day(timezone.now())
).exclude(due_date=None)
def get_filename(self, report_format):
return "%s.%s" % (slugify(self.name or _("due-and-overdue-sl-report")), report_format)
|
gaigeshen/wechat-mp | src/main/java/me/gaigeshen/wechat/mp/message/MusicReplyMessage.java | package me.gaigeshen.wechat.mp.message;
import com.thoughtworks.xstream.annotations.XStreamAlias;
import lombok.AllArgsConstructor;
/**
* @author gaigeshen
*/
@XStreamAlias("xml")
public class MusicReplyMessage extends AbstractReplyMessage {
@XStreamAlias(("Music"))
private Music music;
@AllArgsConstructor
public static class Music {
@XStreamAlias("Title") private String title;
@XStreamAlias("Description") private String description;
@XStreamAlias("MusicUrl") private String musicUrl;
@XStreamAlias("HQMusicUrl") private String hqMusicUrl;
@XStreamAlias("ThumbMediaId") private String thumbMediaId;
}
public MusicReplyMessage(String toUserName, String fromUserName, Music music) {
super(toUserName, fromUserName, "music");
this.music = music;
}
}
|
chaiwanlin/tp | src/main/java/seedu/edrecord/model/assignment/Weightage.java | <filename>src/main/java/seedu/edrecord/model/assignment/Weightage.java<gh_stars>0
package seedu.edrecord.model.assignment;
import static java.util.Objects.requireNonNull;
import static seedu.edrecord.commons.util.AppUtil.checkArgument;
/**
* Represents an Assignment's weightage in edrecord.
* Guarantees: immutable; is valid as declared in {@link #isValidWeightage(String)}
*/
public class Weightage implements Comparable<Weightage> {
public static final String MESSAGE_CONSTRAINTS =
"Assignment weightage should be a non-negative integer or float (max 2 decimal numbers) from 0 to 100";
public final Float weightage;
/**
* Constructs a {@code Weightage} object.
* @param weightage The weightage in percentage.
*/
public Weightage(String weightage) {
requireNonNull(weightage);
checkArgument(isValidWeightage(weightage), MESSAGE_CONSTRAINTS);
this.weightage = Float.valueOf(weightage);
}
/**
* Returns true if a given string is a valid weightage.
* @param test The string to test.
*/
public static boolean isValidWeightage(String test) {
try {
float f = Float.parseFloat(test);
return (f >= 0) && (f <= 100);
} catch (NumberFormatException e) {
return false;
}
}
@Override
public String toString() {
return String.format("%.2f%%", weightage);
}
@Override
public int compareTo(Weightage other) {
return this.weightage.compareTo(other.weightage);
}
@Override
public boolean equals(Object other) {
return other == this // short circuit if same object
|| (other instanceof Weightage // instanceof handles nulls
&& weightage.equals(((Weightage) other).weightage)); // state check
}
@Override
public int hashCode() {
return weightage.hashCode();
}
}
|
aduispace/Leetcode-1 | leetcode-algorithms/src/main/java/com/stevesun/solutions/LargestBSTSubtree.java | <reponame>aduispace/Leetcode-1
package com.stevesun.solutions;
import com.stevesun.common.classes.TreeNode;
public class LargestBSTSubtree {
public int largestBSTSubtree(TreeNode root) {
if(root == null) return 0;
if(isBST(root)) return getNodes(root);
return Math.max(find(root.left), find(root.right));
}
int find(TreeNode root){
if(isBST(root)) return getNodes(root);
return Math.max(find(root.left), find(root.right));
}
int getNodes(TreeNode root){
if(root == null) return 0;
return dfsCount(root);
}
int dfsCount(TreeNode root){
if(root == null) return 0;
return dfsCount(root.left) + dfsCount(root.right) + 1;
}
boolean isBST(TreeNode root){
if(root == null) return true;
return dfs(root, Long.MIN_VALUE, Long.MAX_VALUE);
}
boolean dfs(TreeNode root, long min, long max){
if(root == null) return true;
if(root.val <= min || root.val >= max) return false;
return dfs(root.left, min, root.val) && dfs(root.right, root.val, max);
}
}
|
DataCanvasIO/StreamTau2 | streamtau_expr/src/main/java/com/zetyun/streamtau/expr/op/AndOp.java | /*
* Copyright 2020 Zetyun
*
* 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.zetyun.streamtau.expr.op;
import com.zetyun.streamtau.expr.runtime.RtConst;
import com.zetyun.streamtau.expr.runtime.RtExpr;
import com.zetyun.streamtau.expr.runtime.op.RtAndOp;
import com.zetyun.streamtau.runtime.context.CompileContext;
import javax.annotation.Nonnull;
public class AndOp extends BinaryOp {
public AndOp() {
super(null);
}
@Nonnull
@Override
public RtExpr compileIn(CompileContext ctx) {
RtExpr rtExpr0 = expr0.compileIn(ctx);
RtExpr rtExpr1 = expr1.compileIn(ctx);
RtAndOp rt = new RtAndOp(rtExpr0, rtExpr1);
if (rtExpr0 instanceof RtConst && rtExpr1 instanceof RtConst) {
return new RtConst(rt.eval(null));
}
return rt;
}
@Nonnull
@Override
public Class<?> calcType(CompileContext ctx) {
return Boolean.class;
}
}
|
mactkg/CotEditor | CotEditor/Sources/CESyntaxDictionaryKeys.h | //
// CESyntaxDictionaryKeys.h
// CotEditor
//
// Created by imanishi on 3/21/16.
// Copyright © 2016 CotEditor Project. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface CESyntaxDictionaryKeys : NSString
@end
|
gprinc/RoundTwo | Kernel/buddyMemManager.c | //
// Created by juanfra on 12/11/16.
//
#include "include/buddyMemManager.h"
#include "include/videoDriver.h"
#include "include/lib.h"
#include "include/mutex.h"
#include "include/scheduler.h"
#define NULL ((void*)0)
/* Initializing heap*/
uint16_t recursiveMark(int index);
/* Modifying Heap */
void* addNblocks(uint8_t n);
void* recursiveAdd(int i , uint16_t n,uint64_t address,uint64_t innerSize);
void releaseUp(int i,uint16_t level);
int searchUp(int i,uint16_t level);
/* Moving and marking the Heap */
#define PARENT(i) ((i)>>1)
#define LCHILD(i) ((i)<<1)
#define RCHILD(i) (((i)<<1)+1)
#define AMILEFT(i) !((i)%2)
#define SIBLING(i) ((i)%2?((i)-1):((i)+1))
#define ISNAVAILABLE(i,n) ((i)&(myBit(n)))
static uint16_t heap[MAXHEAPSIZE];
static uint64_t heapSize;
static uint64_t block;
static void* beginning=(void*)MEMBEGIN;
static int mutex;
uint64_t roundUpPower2(uint64_t v){
v--;
v |= v >> 1;
v |= v >> 2;
v |= v >> 4;
v |= v >> 8;
v |= v >> 16;
v |= v >> 32;
v++;
return v;
}
uint64_t pow2(uint64_t n){
return (uint64_t)1 << n;
}
void* buddyAllocate(uint64_t amount){
if(amount<=0) return NULL;
lockMutex(mutex);
uint64_t pages = roundUpPower2( amount/block );
pages = pages == 0 ? 1 : pages;
void* ans = addNblocks(pages);
unlockMutex(mutex);
return ans;
}
void* buddyAllocatePages(uint64_t pages){
if (pages==0) return NULL;
lockMutex(mutex);
void* ans=addNblocks(pages);
unlockMutex(mutex);
return ans;
}
void* buddyReallocatePages(void* address,uint64_t pages){
if( buddyFree(address) != -1){
void* ans = buddyAllocatePages(pages);
if(ans!=NULL && ans!=address){
memcpy(ans,address,pages*MINPAGE);
}
return ans;
}else{
return NULL;
}
}
void* buddyReallocate(void* address,uint64_t amount){
if( buddyFree(address) != -1){
void* ans = buddyAllocate(amount);
if(ans!=NULL && ans!=address){
memcpy(ans,address,amount);
}
return ans;
}else{
return NULL;
}
}
int lowerBound2Pow(int n){
int i=0;
while(n){
n=n>>1;
i++;
}
return 1<<i;
}
uint16_t myBit(uint16_t n){
int i=0;
while(n){
n=n>>1;
i++;
}
return 1<<(i-1);
}
uint16_t myMask(uint16_t n){
uint16_t i=0;
while(n){
n--;
i=(i<<1) +1;
}
return i;
}
int isPowerOfTwo (uint64_t x){
return ((x != 0) && !(x & (x - 1)));
}
void initializeHeap(){
mutex=getMutex(PAGESMUTEX);
block=MINPAGE;
heapSize=MAXHEAPSIZE;
recursiveMark(1);
}
uint16_t recursiveMark(int index){
if(index>heapSize/2){
heap[index]=1;
return (1<<1) + 1;
}
recursiveMark(RCHILD(index));
uint16_t mark=recursiveMark(LCHILD(index));
heap[index]=mark;
return (mark<<1) + 1;
}
void* addNblocks(unsigned char n){
int a=((1+heapSize)/2);
if(n> ((1+heapSize)/2)) return NULL;
return recursiveAdd(1,n,(uint64_t)beginning,MAXMEMORY);
}
void* recursiveAdd(int i , uint16_t n,uint64_t address,uint64_t innerSize){
void*ans=NULL;
if(!ISNAVAILABLE(heap[i],n))
return NULL;
else{
if(i<=heapSize/2 && ISNAVAILABLE(heap[RCHILD(i)],n)){
ans= recursiveAdd(RCHILD(i),n,address+(innerSize/2),innerSize/2);
heap[i]=heap[RCHILD(i)] | heap[LCHILD(i)];
}else if(i<=heapSize/2 && ISNAVAILABLE(heap[LCHILD(i)],n)){
ans= recursiveAdd(LCHILD(i),n,address,innerSize/2);
heap[i]=heap[RCHILD(i)] | heap[LCHILD(i)];
}else{
heap[i]= 0;
return (void*)address;
}
}
return ans;
}
int isInt(float f){
return (f-(int)f == 0);
}
int buddyFree(void* address){
int ans;
lockMutex(mutex);
address= (void*)((char*)address - (char*)beginning);
if(!isInt((uint64_t)address/(block*1.0f))){
ans= -1;
} else{
int position=((uint64_t)address)/block;
ans= searchUp(heapSize/2 + 1 + position,1);
}
unlockMutex(mutex);
return ans;
}
int searchMemoryUp(int i, uint16_t level){
if(i<1) return 0;
if(heap[i]==0){
return pow2(level-1);
}else if(AMILEFT(i)){
return searchMemoryUp(PARENT(i),level+1);
}else{
return 0;
}
}
int getMemoryUsed(){
int acu=0;
for (int i = heapSize/2 + 1; i < MAXHEAPSIZE; ++i) {
acu+=searchMemoryUp(i,1);
}
return acu*MINPAGE;
}
int searchUp(int i, uint16_t level){
if(i<1) return -1;
if(heap[i]==0){
heap[i]=myMask(level);
releaseUp(PARENT(i),level+1);
return 0;
}else if(AMILEFT(i)){
return searchUp(PARENT(i),level+1);
}else{
return -1;
}
}
void releaseUp(int i,uint16_t level){
if(i<1) return;
if(heap[RCHILD(i)] == myMask(level-1) && heap[LCHILD(i)] == myMask(level-1)){
heap[i]=myMask(level);
}else{
heap[i]=heap[RCHILD(i)] | heap[LCHILD(i)];
}
releaseUp(PARENT(i),level+1);
}
|
tycho/arc | source/Interface/laser_zap.cpp | /*
* ARC++
*
* Copyright (c) 2007-2008 <NAME>.
*
* Licensed under the New BSD License.
*
*/
#include "universal_include.h"
#include "App/app.h"
#include "Game/game.h"
#include "Game/collide.h"
#include "Graphics/graphics.h"
#include "Interface/interface.h"
#include "Interface/laser_zap.h"
static const SDL_Rect rShipHit[7] =
{
{ 387, 157, 2, 2 },
{ 391, 157, 4, 4 },
{ 396, 157, 6, 6 },
{ 403, 157, 9, 9 },
{ 413, 157, 11, 11 },
{ 426, 157, 11, 11 },
{ 440, 157, 13, 13 }
};
LaserZap::LaserZap ( Sint32 _x, Sint32 _y )
: Widget(0, 0, 61, 61), m_damaged(true), m_zapFrame(0), m_x(_x), m_y(_y)
{
SetWidgetClass ( "LaserZap" );
Initialise();
}
LaserZap::~LaserZap()
{
}
int LaserZap::SendEnterKey ()
{
return 0;
}
int LaserZap::MouseDown ( bool _mouseDown, Sint32 _x, Sint32 _y )
{
return 0;
}
void LaserZap::Initialise()
{
g_graphics->DeleteSurface(m_cachedSurfaceID);
m_cachedSurfaceID = g_graphics->CreateSurface ( 13, 13, false );
Widget::Initialise();
}
void LaserZap::Update()
{
m_zapFrame += g_game->GetGameSpeed() * 0.5;
if ( (int)m_zapFrame > 6 )
m_expired = true;
}
void LaserZap::Render()
{
if ( m_expired ) return;
SDL_Rect const &rSource = rShipHit[(int)m_zapFrame];
short CenterSX = g_graphics->GetCenterX() - 16,
CenterSY = g_graphics->GetCenterY() - 16;
short MeX = (short)(g_game->m_me->GetX() - CenterSX),
MeY = (short)(g_game->m_me->GetY() - CenterSY);
m_position.x = m_x - MeX - rSource.w / 2;
m_position.y = m_y - MeY - rSource.h / 2;
g_graphics->FillRect ( m_cachedSurfaceID, NULL, g_graphics->GetColorKey() );
g_graphics->Blit ( g_interface->GetTuna1SurfaceID(), (SDL_Rect *)&rSource, m_cachedSurfaceID, NULL );
Widget::Render();
}
|
kazuyaujihara/rdkit | Code/GraphMol/MolStandardize/AcidBaseCatalog/AcidBaseCatalogUtils.cpp | <gh_stars>1000+
//
// Copyright (C) 2018-2021 <NAME> and other RDKit contributors
//
// @@ All Rights Reserved @@
// This file is part of the RDKit.
// The contents are covered by the terms of the BSD license
// which is included in the file license.txt, found at the root
// of the RDKit source tree.
//
#include "AcidBaseCatalogUtils.h"
#include <RDGeneral/BadFileException.h>
#include <GraphMol/SmilesParse/SmilesParse.h>
#include <boost/algorithm/string.hpp>
#include <boost/tokenizer.hpp>
typedef boost::tokenizer<boost::char_separator<char>> tokenizer;
#include <fstream>
#include <string>
namespace RDKit {
namespace {
std::pair<ROMol*, ROMol*>* getPair(const std::string& name,
const std::string& acid_smarts,
const std::string& base_smarts) {
ROMol* acid(SmartsToMol(acid_smarts));
if (!acid) {
throw ValueErrorException("Failed parsing acid SMARTS: " + acid_smarts);
}
ROMol* base(SmartsToMol(base_smarts));
if (!base) {
delete acid;
throw ValueErrorException("Failed parsing base SMARTS: " + base_smarts);
}
acid->setProp(common_properties::_Name, name);
base->setProp(common_properties::_Name, name);
return new std::pair<ROMol*, ROMol*>(acid, base);
}
std::pair<ROMol*, ROMol*>* getPair(std::string tmpStr) {
// Remove whitespace
boost::trim(tmpStr);
if (tmpStr.length() == 0 || tmpStr.substr(0, 2) == "//") {
// empty or comment line
return nullptr;
}
boost::char_separator<char> tabSep("\t");
tokenizer tokens(tmpStr, tabSep);
tokenizer::iterator token = tokens.begin();
// name of the functional groups
std::string name = *token;
boost::erase_all(name, " ");
++token;
// grab the acid:
std::string acid_smarts = *token;
boost::erase_all(acid_smarts, " ");
++token;
// grab the base:
std::string base_smarts = *token;
boost::erase_all(base_smarts, " ");
++token;
return getPair(name, acid_smarts, base_smarts);
}
} // namespace
namespace MolStandardize {
std::vector<std::pair<ROMOL_SPTR, ROMOL_SPTR>> readPairs(std::string fileName) {
std::ifstream inStream(fileName.c_str());
if ((!inStream) || (inStream.bad())) {
std::ostringstream errout;
errout << "Bad input file " << fileName;
throw BadFileException(errout.str());
}
std::vector<std::pair<ROMOL_SPTR, ROMOL_SPTR>> mol_pairs =
readPairs(inStream);
return mol_pairs;
}
std::vector<std::pair<ROMOL_SPTR, ROMOL_SPTR>> readPairs(std::istream& inStream,
int nToRead) {
std::vector<std::pair<ROMOL_SPTR, ROMOL_SPTR>> pairs;
pairs.clear();
if (inStream.bad()) {
throw BadFileException("Bad stream contents.");
}
const int MAX_LINE_LEN = 512;
char inLine[MAX_LINE_LEN];
std::string tmpstr;
int nRead = 0;
while (!inStream.eof() && !inStream.fail() &&
(nToRead < 0 || nRead < nToRead)) {
inStream.getline(inLine, MAX_LINE_LEN, '\n');
tmpstr = inLine;
// parse the molpair on this line (if there is one)
std::shared_ptr<std::pair<ROMol*, ROMol*>> mol_pair(getPair(tmpstr));
if (mol_pair != nullptr) {
pairs.emplace_back(ROMOL_SPTR(mol_pair->first),
ROMOL_SPTR(mol_pair->second));
nRead++;
}
}
return pairs;
}
std::vector<std::pair<ROMOL_SPTR, ROMOL_SPTR>> readPairs(
const std::vector<std::tuple<std::string, std::string, std::string>>&
data) {
std::vector<std::pair<ROMOL_SPTR, ROMOL_SPTR>> pairs;
for (const auto& tpl : data) {
std::shared_ptr<std::pair<ROMol*, ROMol*>> mol_pair(
getPair(std::get<0>(tpl), std::get<1>(tpl), std::get<2>(tpl)));
pairs.emplace_back(ROMOL_SPTR(mol_pair->first),
ROMOL_SPTR(mol_pair->second));
}
return pairs;
}
} // namespace MolStandardize
} // namespace RDKit
|
cjdb/NanoRange | include/nanorange/algorithm/partition_point.hpp | <reponame>cjdb/NanoRange
// nanorange/algorithm/partition_point.hpp
//
// Copyright (c) 2018 <NAME> (<EMAIL>le at gmail dot com)
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
// Uses code from CMCSTL2
// Copyright <NAME> 2014
// Copyright <NAME> 2015
//===-------------------------- algorithm ---------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
#ifndef NANORANGE_ALGORITHM_PARTITION_POINT_HPP_INCLUDED
#define NANORANGE_ALGORITHM_PARTITION_POINT_HPP_INCLUDED
#include <nanorange/ranges.hpp>
NANO_BEGIN_NAMESPACE
namespace detail {
struct partition_point_fn {
private:
friend struct lower_bound_fn;
friend struct upper_bound_fn;
template <typename I, typename Pred, typename Proj>
static constexpr I impl_n(I first, iter_difference_t<I> n, Pred& pred,
Proj& proj)
{
while (n != 0) {
const auto half = n/2;
auto middle = nano::next(first, half);
if (nano::invoke(pred, nano::invoke(proj, *middle))) {
first = std::move(++middle);
n -= half + 1;
} else {
n = half;
}
}
return first;
}
template <typename I, typename S, typename Pred, typename Proj>
static constexpr std::enable_if_t<sized_sentinel_for<S, I>, I>
impl(I first, S last, Pred& pred, Proj& proj)
{
const auto n = nano::distance(first, std::move(last));
return partition_point_fn::impl_n(std::move(first), n, pred, proj);
}
template <typename I, typename S, typename Pred, typename Proj>
static constexpr std::enable_if_t<!sized_sentinel_for<S, I>, I>
impl(I first, S last, Pred& pred, Proj& proj)
{
// Probe exponentially for either end-of-range or an iterator
// that is past the partition point (i.e., does not satisfy pred).
iter_difference_t<I> n{1};
while (true) {
auto m = first;
auto d = nano::advance(m, n, last);
if (m == last || !nano::invoke(pred, nano::invoke(proj, *m))) {
n -= d;
return partition_point_fn::impl_n(std::move(first), n,
pred, proj);
}
first = std::move(m);
n *= 2;
}
}
public:
template <typename I, typename S, typename Pred, typename Proj = identity>
std::enable_if_t<forward_iterator<I> && sentinel_for<S, I> &&
indirect_unary_predicate<Pred, projected<I, Proj>>, I>
constexpr operator()(I first, S last, Pred pred, Proj proj = Proj{}) const
{
return partition_point_fn::impl(std::move(first), std::move(last),
pred, proj);
}
template <typename Rng, typename Pred, typename Proj = identity>
std::enable_if_t<
forward_range<Rng> &&
indirect_unary_predicate<Pred, projected<iterator_t<Rng>, Proj>>,
borrowed_iterator_t<Rng>>
constexpr operator()(Rng&& rng, Pred pred, Proj proj = Proj{}) const
{
return partition_point_fn::impl(nano::begin(rng), nano::end(rng),
pred, proj);
}
};
}
NANO_INLINE_VAR(detail::partition_point_fn, partition_point)
NANO_END_NAMESPACE
#endif
|
uwplse/legato | test/edu/washington/instrumentation/analysis/test/TestSynchronizationHavoc.java | <reponame>uwplse/legato
package edu.washington.instrumentation.analysis.test;
import java.util.Set;
import org.testng.annotations.Test;
import edu.washington.cse.instrumentation.analysis.EverythingIsInconsistentException;
@Test(groups="legatoTests")
public class TestSynchronizationHavoc extends AbstractLegatoTest {
public TestSynchronizationHavoc() {
super("SynchronizationTest", "resolver:simple-get,pm:simple");
this.enableSyncHavoc = true;
}
public void testSimpleSynchronization() {
assertBottomReturn("testSimpleSynchronization");
}
public void testSameReadSync() {
assertIsomorphicTreeReturn("testSameReadSync", "{s2}{1}");
}
public void testSynchNarrowing() {
assertIsomorphicTreeReturn("testSynchNarrowing", "{s2}{1}");
assertIsomorphicTreeReturn("testInterProcNarrowing", "{s2}{1}");
assertIsomorphicTreeReturn("testInterProcNarrowingDD", "{s2}{1}");
}
public void testInterproceduralSynch() {
assertBottomReturn("testInterproceduralSynch");
}
public void testSyncPriming() {
assertBottomReturn("testSyncPriming");
}
public void testNestedSynchronization() {
assertBottomReturn("testNestedSync");
assertBottomReturn("testInterproceduralNestedSync");
assertIsomorphicTreeReturn("testInterproceduralNopSync", "{s1}{2}");
assertBottomReturn("testNestedSynchronizedMethod");
}
public void testSynchronizedMethod() {
assertIsomorphicTreeReturn("testSynchronizedMethod", "{2}{s3}{1}");
assertBottomReturn("testSynchronizedMethodPriming");
}
public void testVolatileReads() {
assertIsomorphicTreeReturn("testSimpleVolatileRead", "{s3}{1}");
assertBottomReturn("testUniqueVolatileReads");
assertBottomReturn("testNoMutexSync");
assertBottomReturn("testVolatilePriming");
assertIsomorphicTreeReturn("testVolatilePriming2", "{s3}'{1}");
}
public void testWaitHavoc() {
assertBottomReturn("testSimpleWaitHavoc");
assertIsomorphicTreeReturn("testWaitHavocPrev", "{s3}{1}");
}
public void testNestedWait() {
assertAnalysisThrows("testNestedSyncWait", EverythingIsInconsistentException.class);
assertAnalysisThrows("testRecursiveSync", EverythingIsInconsistentException.class);
}
@Override
protected Set<String> testMethods() {
final Set<String> toReturn = super.testMethods();
toReturn.add("recursiveSyncExecute");
return toReturn;
}
}
|
h0tbird/clusterawsadm | providers/terraform-provider-aws/aws/resource_aws_ec2_local_gateway_route.go | <gh_stars>0
package aws
import (
"fmt"
"log"
"strings"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/ec2"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
)
const (
ec2LocalGatewayRouteEventualConsistencyTimeout = 1 * time.Minute
)
func resourceAwsEc2LocalGatewayRoute() *schema.Resource {
return &schema.Resource{
Create: resourceAwsEc2LocalGatewayRouteCreate,
Read: resourceAwsEc2LocalGatewayRouteRead,
Delete: resourceAwsEc2LocalGatewayRouteDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"destination_cidr_block": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validateCIDRNetworkAddress,
},
"local_gateway_route_table_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"local_gateway_virtual_interface_group_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
},
}
}
func resourceAwsEc2LocalGatewayRouteCreate(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*AWSClient).ec2conn
destination := d.Get("destination_cidr_block").(string)
localGatewayRouteTableID := d.Get("local_gateway_route_table_id").(string)
input := &ec2.CreateLocalGatewayRouteInput{
DestinationCidrBlock: aws.String(destination),
LocalGatewayRouteTableId: aws.String(localGatewayRouteTableID),
LocalGatewayVirtualInterfaceGroupId: aws.String(d.Get("local_gateway_virtual_interface_group_id").(string)),
}
_, err := conn.CreateLocalGatewayRoute(input)
if err != nil {
return fmt.Errorf("error creating EC2 Local Gateway Route: %s", err)
}
d.SetId(fmt.Sprintf("%s_%s", localGatewayRouteTableID, destination))
return resourceAwsEc2LocalGatewayRouteRead(d, meta)
}
func resourceAwsEc2LocalGatewayRouteRead(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*AWSClient).ec2conn
localGatewayRouteTableID, destination, err := decodeEc2LocalGatewayRouteID(d.Id())
if err != nil {
return err
}
var localGatewayRoute *ec2.LocalGatewayRoute
err = resource.Retry(ec2LocalGatewayRouteEventualConsistencyTimeout, func() *resource.RetryError {
var err error
localGatewayRoute, err = getEc2LocalGatewayRoute(conn, localGatewayRouteTableID, destination)
if err != nil {
return resource.NonRetryableError(err)
}
if d.IsNewResource() && localGatewayRoute == nil {
return resource.RetryableError(&resource.NotFoundError{})
}
return nil
})
if isResourceTimeoutError(err) {
localGatewayRoute, err = getEc2LocalGatewayRoute(conn, localGatewayRouteTableID, destination)
}
if isAWSErr(err, "InvalidRouteTableID.NotFound", "") {
log.Printf("[WARN] EC2 Local Gateway Route Table (%s) not found, removing from state", localGatewayRouteTableID)
d.SetId("")
return nil
}
if !d.IsNewResource() && isResourceNotFoundError(err) {
log.Printf("[WARN] EC2 Local Gateway Route (%s) not found, removing from state", d.Id())
d.SetId("")
return nil
}
if err != nil {
return fmt.Errorf("error reading EC2 Local Gateway Route: %s", err)
}
if localGatewayRoute == nil {
log.Printf("[WARN] EC2 Local Gateway Route (%s) not found, removing from state", d.Id())
d.SetId("")
return nil
}
state := aws.StringValue(localGatewayRoute.State)
if state == ec2.LocalGatewayRouteStateDeleted || state == ec2.LocalGatewayRouteStateDeleting {
log.Printf("[WARN] EC2 Local Gateway Route (%s) deleted, removing from state", d.Id())
d.SetId("")
return nil
}
d.Set("destination_cidr_block", localGatewayRoute.DestinationCidrBlock)
d.Set("local_gateway_virtual_interface_group_id", localGatewayRoute.LocalGatewayVirtualInterfaceGroupId)
d.Set("local_gateway_route_table_id", localGatewayRoute.LocalGatewayRouteTableId)
return nil
}
func resourceAwsEc2LocalGatewayRouteDelete(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*AWSClient).ec2conn
localGatewayRouteTableID, destination, err := decodeEc2LocalGatewayRouteID(d.Id())
if err != nil {
return err
}
input := &ec2.DeleteLocalGatewayRouteInput{
DestinationCidrBlock: aws.String(destination),
LocalGatewayRouteTableId: aws.String(localGatewayRouteTableID),
}
log.Printf("[DEBUG] Deleting EC2 Local Gateway Route (%s): %s", d.Id(), input)
_, err = conn.DeleteLocalGatewayRoute(input)
if isAWSErr(err, "InvalidRoute.NotFound", "") || isAWSErr(err, "InvalidRouteTableID.NotFound", "") {
return nil
}
if err != nil {
return fmt.Errorf("error deleting EC2 Local Gateway Route: %s", err)
}
return nil
}
func decodeEc2LocalGatewayRouteID(id string) (string, string, error) {
parts := strings.Split(id, "_")
if len(parts) != 2 {
return "", "", fmt.Errorf("Unexpected format of ID (%q), expected tgw-rtb-ID_DESTINATION", id)
}
return parts[0], parts[1], nil
}
func getEc2LocalGatewayRoute(conn *ec2.EC2, localGatewayRouteTableID, destination string) (*ec2.LocalGatewayRoute, error) {
input := &ec2.SearchLocalGatewayRoutesInput{
Filters: []*ec2.Filter{
{
Name: aws.String("type"),
Values: aws.StringSlice([]string{"static"}),
},
},
LocalGatewayRouteTableId: aws.String(localGatewayRouteTableID),
}
output, err := conn.SearchLocalGatewayRoutes(input)
if err != nil {
return nil, err
}
if output == nil || len(output.Routes) == 0 {
return nil, nil
}
for _, route := range output.Routes {
if route == nil {
continue
}
if aws.StringValue(route.DestinationCidrBlock) == destination {
return route, nil
}
}
return nil, nil
}
|
5l1v3r1/0-orchestrator | api/ays-client/Event.go | package client
import (
"gopkg.in/validator.v2"
)
type Event struct {
Actions []string `json:"actions" validate:"nonzero"`
Channel string `json:"channel" validate:"nonzero"`
Command string `json:"command" validate:"nonzero"`
Tags []string `json:"tags" validate:"nonzero"`
}
func (s Event) Validate() error {
return validator.Validate(s)
}
|
lxqfirst/bi-platform | designer/src/main/java/com/baidu/rigel/biplatform/ma/report/query/QueryContext.java | /**
* Copyright (c) 2014 Baidu, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.baidu.rigel.biplatform.ma.report.query;
import java.io.Serializable;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import com.google.common.collect.Maps;
/**
* 请求上下文
*
* @author zhongyi
*
* 2014-8-5
*/
public class QueryContext implements Serializable {
/**
* QueryContext.java -- long
* description:
*/
private static final long serialVersionUID = -8916777353652443192L;
/**
* params
*/
private Map<String, Object> params;
/**
* extendAreaId
*/
private String extendAreaId;
/**
* get the params
*
* @return the params
*/
public Map<String, Object> getParams() {
if (this.params == null) {
this.params = Maps.newHashMap();
}
return params;
}
/**
* set the params
*
* @param params
* the params to set
*/
public void setParams(Map<String, Object> params) {
this.params = params;
}
/**
* get the extendAreaId
*
* @return the extendAreaId
*/
public String getExtendAreaId() {
return extendAreaId;
}
/**
* set the extendAreaId
*
* @param extendAreaId
* the extendAreaId to set
*/
public void setExtendAreaId(String extendAreaId) {
this.extendAreaId = extendAreaId;
}
/**
* 将全局变量放入上下文
*
* @param itemId
* @param value
*/
public void put(String id, Object value) {
if (this.params == null) {
this.params = new ConcurrentHashMap<String, Object>();
}
this.params.put(id, value);
}
/**
* 从上下文获取值
*
* @param id
* @return 存在返回值,否则返回null
*/
public Object get(String id) {
if (this.params == null) {
return null;
}
return this.params.get(id);
}
/**
*
*/
public void reset() {
if (this.params != null) {
this.params.clear();
}
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.