max_stars_count
int64 301
224k
| text
stringlengths 6
1.05M
| token_count
int64 3
727k
|
---|---|---|
3,084 | <reponame>ixjf/Windows-driver-samples
/*++
Copyright (c) 2005 Microsoft Corporation
All rights reserved.
THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
PARTICULAR PURPOSE.
File Name:
globals.cpp
Abstract:
Stores function definitions, variable declerations and pre-processor macros
global to the filter module. This is shared between all filters.
--*/
#pragma once
//
// Module's Instance handle from DLLEntry of process.
//
extern HINSTANCE g_hInstance;
//
// Server lock count
//
extern LONG g_cServerLocks;
//
// Global defines
//
#define CB_COPY_BUFFER 0x10000
#define MAX_UISTRING_LEN 256
#define OEM_SIGNATURE 'XDSM'
#define OEM_VERSION 0x00000001L
//
// Conversion functions for Microns to 1/100th of Inch (and visa versa)
//
#define HUNDREDTH_OFINCH_TO_MICRON(x) MulDiv(x, 25400, 100)
#define MICRON_TO_HUNDREDTH_OFINCH(x) MulDiv(x, 100, 25400)
//
// Macros for checking pointers and handles.
//
#define CHECK_POINTER(p, hr) ((p) == NULL ? hr : S_OK)
#define CHECK_HANDLE(h, hr) ((h) == NULL ? hr : S_OK)
static const FLOAT kMaxByteAsFloat = 255.0f;
static const FLOAT kMaxWordAsFloat = 65535.0f;
static const WORD kS2Dot13Neg = 0x8000;
static const WORD kS2Dot13One = 0x2000;
static const WORD kS2Dot13Min = 0xFFFF;
static const WORD kS2Dot13Max = 0x7FFF;
static const FLOAT k96thInchAsMicrons = 264.58f;
//
// countof macro
//
#ifndef countof
#define countof(ary) (sizeof(ary) / sizeof((ary)[0]))
#endif
//
// Converts the Win32 last error to an HRESULT
//
HRESULT
GetLastErrorAsHResult(
void
);
//
// Converts a GDI status error to an HRESULT
//
HRESULT
GetGDIStatusErrorAsHResult(
_In_ Status gdiPStatus
);
//
// Check if we are running under Vista
//
BOOL
IsVista(
VOID
);
//
// Returns a unique number
//
DWORD
GetUniqueNumber(
VOID
);
| 861 |
23,325 | /*
* Copyright (C) 2021 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.gson;
import java.io.IOException;
import java.io.StringReader;
import java.math.BigDecimal;
import com.google.gson.internal.LazilyParsedNumber;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.MalformedJsonException;
import junit.framework.TestCase;
public class ToNumberPolicyTest extends TestCase {
public void testDouble() throws IOException {
ToNumberStrategy strategy = ToNumberPolicy.DOUBLE;
assertEquals(10.1, strategy.readNumber(fromString("10.1")));
assertEquals(3.141592653589793D, strategy.readNumber(fromString("3.141592653589793238462643383279")));
try {
strategy.readNumber(fromString("1e400"));
fail();
} catch (MalformedJsonException expected) {
assertEquals("JSON forbids NaN and infinities: Infinity at line 1 column 6 path $", expected.getMessage());
}
try {
strategy.readNumber(fromString("\"not-a-number\""));
fail();
} catch (NumberFormatException expected) {
}
}
public void testLazilyParsedNumber() throws IOException {
ToNumberStrategy strategy = ToNumberPolicy.LAZILY_PARSED_NUMBER;
assertEquals(new LazilyParsedNumber("10.1"), strategy.readNumber(fromString("10.1")));
assertEquals(new LazilyParsedNumber("3.141592653589793238462643383279"), strategy.readNumber(fromString("3.141592653589793238462643383279")));
assertEquals(new LazilyParsedNumber("1e400"), strategy.readNumber(fromString("1e400")));
}
public void testLongOrDouble() throws IOException {
ToNumberStrategy strategy = ToNumberPolicy.LONG_OR_DOUBLE;
assertEquals(10L, strategy.readNumber(fromString("10")));
assertEquals(10.1, strategy.readNumber(fromString("10.1")));
assertEquals(3.141592653589793D, strategy.readNumber(fromString("3.141592653589793238462643383279")));
try {
strategy.readNumber(fromString("1e400"));
fail();
} catch (MalformedJsonException expected) {
assertEquals("JSON forbids NaN and infinities: Infinity; at path $", expected.getMessage());
}
try {
strategy.readNumber(fromString("\"not-a-number\""));
fail();
} catch (JsonParseException expected) {
assertEquals("Cannot parse not-a-number; at path $", expected.getMessage());
}
assertEquals(Double.NaN, strategy.readNumber(fromStringLenient("NaN")));
assertEquals(Double.POSITIVE_INFINITY, strategy.readNumber(fromStringLenient("Infinity")));
assertEquals(Double.NEGATIVE_INFINITY, strategy.readNumber(fromStringLenient("-Infinity")));
try {
strategy.readNumber(fromString("NaN"));
fail();
} catch (MalformedJsonException expected) {
assertEquals("Use JsonReader.setLenient(true) to accept malformed JSON at line 1 column 1 path $", expected.getMessage());
}
try {
strategy.readNumber(fromString("Infinity"));
fail();
} catch (MalformedJsonException expected) {
assertEquals("Use JsonReader.setLenient(true) to accept malformed JSON at line 1 column 1 path $", expected.getMessage());
}
try {
strategy.readNumber(fromString("-Infinity"));
fail();
} catch (MalformedJsonException expected) {
assertEquals("Use JsonReader.setLenient(true) to accept malformed JSON at line 1 column 1 path $", expected.getMessage());
}
}
public void testBigDecimal() throws IOException {
ToNumberStrategy strategy = ToNumberPolicy.BIG_DECIMAL;
assertEquals(new BigDecimal("10.1"), strategy.readNumber(fromString("10.1")));
assertEquals(new BigDecimal("3.141592653589793238462643383279"), strategy.readNumber(fromString("3.141592653589793238462643383279")));
assertEquals(new BigDecimal("1e400"), strategy.readNumber(fromString("1e400")));
try {
strategy.readNumber(fromString("\"not-a-number\""));
fail();
} catch (JsonParseException expected) {
assertEquals("Cannot parse not-a-number; at path $", expected.getMessage());
}
}
public void testNullsAreNeverExpected() throws IOException {
try {
ToNumberPolicy.DOUBLE.readNumber(fromString("null"));
fail();
} catch (IllegalStateException expected) {
}
try {
ToNumberPolicy.LAZILY_PARSED_NUMBER.readNumber(fromString("null"));
fail();
} catch (IllegalStateException expected) {
}
try {
ToNumberPolicy.LONG_OR_DOUBLE.readNumber(fromString("null"));
fail();
} catch (IllegalStateException expected) {
}
try {
ToNumberPolicy.BIG_DECIMAL.readNumber(fromString("null"));
fail();
} catch (IllegalStateException expected) {
}
}
private static JsonReader fromString(String json) {
return new JsonReader(new StringReader(json));
}
private static JsonReader fromStringLenient(String json) {
JsonReader jsonReader = fromString(json);
jsonReader.setLenient(true);
return jsonReader;
}
}
| 1,914 |
335 | <gh_stars>100-1000
{
"word": "Casualty",
"definitions": [
"A person killed or injured in a war or accident.",
"A person or thing badly affected by an event or situation.",
"The department of a hospital providing immediate treatment for emergency cases.",
"(chiefly in insurance) an accident or disaster."
],
"parts-of-speech": "Noun"
} | 134 |
1,127 | // Copyright (C) 2018-2022 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
#include "gtest/gtest.h"
#include "ngraph/ngraph.hpp"
#include "ngraph/op/util/attr_types.hpp"
#include "ngraph/opsets/opset7.hpp"
#include "util/visitor.hpp"
using namespace std;
using namespace ngraph;
using ngraph::test::NodeBuilder;
TEST(attributes, roll_op) {
NodeBuilder::get_ops().register_factory<opset7::Roll>();
const auto A = make_shared<op::Parameter>(element::f32, Shape{4, 3});
const auto B = make_shared<op::Constant>(element::i32, Shape{3});
const auto C = make_shared<op::Constant>(element::i32, Shape{3});
const auto roll = make_shared<opset7::Roll>(A, B, C);
NodeBuilder builder(roll);
const auto expected_attr_count = 0;
EXPECT_EQ(builder.get_value_map_size(), expected_attr_count);
}
| 315 |
12,711 | {"type":"tag","loc":{"start":{"line":1,"column":1},"filename":"/cases/attrs.unescaped.pug","end":{"line":1,"column":7}},"val":"script"}
{"type":"start-attributes","loc":{"start":{"line":1,"column":7},"filename":"/cases/attrs.unescaped.pug","end":{"line":1,"column":8}}}
{"type":"attribute","loc":{"start":{"line":1,"column":8},"filename":"/cases/attrs.unescaped.pug","end":{"line":1,"column":30}},"name":"type","mustEscape":true,"val":"'text/x-template'"}
{"type":"end-attributes","loc":{"start":{"line":1,"column":30},"filename":"/cases/attrs.unescaped.pug","end":{"line":1,"column":31}}}
{"type":"indent","loc":{"start":{"line":2,"column":1},"filename":"/cases/attrs.unescaped.pug","end":{"line":2,"column":3}},"val":2}
{"type":"tag","loc":{"start":{"line":2,"column":3},"filename":"/cases/attrs.unescaped.pug","end":{"line":2,"column":6}},"val":"div"}
{"type":"start-attributes","loc":{"start":{"line":2,"column":6},"filename":"/cases/attrs.unescaped.pug","end":{"line":2,"column":7}}}
{"type":"attribute","loc":{"start":{"line":2,"column":7},"filename":"/cases/attrs.unescaped.pug","end":{"line":2,"column":32}},"name":"id","mustEscape":false,"val":"'user-<%= user.id %>'"}
{"type":"end-attributes","loc":{"start":{"line":2,"column":32},"filename":"/cases/attrs.unescaped.pug","end":{"line":2,"column":33}}}
{"type":"indent","loc":{"start":{"line":3,"column":1},"filename":"/cases/attrs.unescaped.pug","end":{"line":3,"column":5}},"val":4}
{"type":"tag","loc":{"start":{"line":3,"column":5},"filename":"/cases/attrs.unescaped.pug","end":{"line":3,"column":7}},"val":"h1"}
{"type":"text","loc":{"start":{"line":3,"column":8},"filename":"/cases/attrs.unescaped.pug","end":{"line":3,"column":25}},"val":"<%= user.title %>"}
{"type":"outdent","loc":{"start":{"line":3,"column":25},"filename":"/cases/attrs.unescaped.pug","end":{"line":3,"column":25}}}
{"type":"outdent","loc":{"start":{"line":3,"column":25},"filename":"/cases/attrs.unescaped.pug","end":{"line":3,"column":25}}}
{"type":"eos","loc":{"start":{"line":3,"column":25},"filename":"/cases/attrs.unescaped.pug","end":{"line":3,"column":25}}} | 733 |
626 | <gh_stars>100-1000
package org.jsmart.zerocode.core.domain;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.JsonNode;
@JsonInclude(JsonInclude.Include.NON_NULL)
public class Validator {
private final String field;
private final JsonNode value;
public Validator(
@JsonProperty("field") String field,
@JsonProperty("value") JsonNode value) {
this.field = field;
this.value = value;
}
public String getField() {
return field;
}
public JsonNode getValue() {
return value;
}
@Override
public String toString() {
return "Validator{" +
"field='" + field + '\'' +
", value=" + value +
'}';
}
}
| 375 |
372 | /* Editor Settings: expandtabs and use 4 spaces for indentation
* ex: set softtabstop=4 tabstop=8 expandtab shiftwidth=4: *
* -*- mode: c, c-basic-offset: 4 -*- */
/*
* Copyright © BeyondTrust Software 2004 - 2019
* 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.
*
* BEYONDTRUST MAKES THIS SOFTWARE AVAILABLE UNDER OTHER LICENSING TERMS AS
* WELL. IF YOU HAVE ENTERED INTO A SEPARATE LICENSE AGREEMENT WITH
* BEYONDTRUST, THEN YOU MAY ELECT TO USE THE SOFTWARE UNDER THE TERMS OF THAT
* SOFTWARE LICENSE AGREEMENT INSTEAD OF THE TERMS OF THE APACHE LICENSE,
* NOTWITHSTANDING THE ABOVE NOTICE. IF YOU HAVE QUESTIONS, OR WISH TO REQUEST
* A COPY OF THE ALTERNATE LICENSING TERMS OFFERED BY BEYONDTRUST, PLEASE CONTACT
* BEYONDTRUST AT beyondtrust.com/contact
*/
/*
* Copyright (C) BeyondTrust Software. All rights reserved.
*
* Module Name:
*
* listener.c
*
* Abstract:
*
* Registry
*
* Authors: <NAME> (<EMAIL>)
* <NAME> (<EMAIL>)
* <NAME> (<EMAIL>)
* <NAME> (<EMAIL>)
*/
#include "registryd.h"
#define MAX_DISPATCH 8
#define MAX_CLIENTS 512
static LWMsgContext* gpContext = NULL;
static LWMsgProtocol* gpProtocol = NULL;
static LWMsgPeer* gpServer = NULL;
static
LWMsgBool
RegSrvLogIpc (
LWMsgLogLevel level,
const char* pszMessage,
const char* pszFunction,
const char* pszFilename,
unsigned int line,
void* pData
)
{
RegLogLevel regLevel = REG_LOG_LEVEL_DEBUG;
LWMsgBool result = LWMSG_FALSE;
switch (level)
{
case LWMSG_LOGLEVEL_ALWAYS:
regLevel = REG_LOG_LEVEL_ALWAYS;
break;
case LWMSG_LOGLEVEL_ERROR:
regLevel = REG_LOG_LEVEL_ERROR;
break;
case LWMSG_LOGLEVEL_WARNING:
regLevel = REG_LOG_LEVEL_WARNING;
break;
case LWMSG_LOGLEVEL_INFO:
regLevel = REG_LOG_LEVEL_INFO;
break;
case LWMSG_LOGLEVEL_VERBOSE:
regLevel = REG_LOG_LEVEL_VERBOSE;
break;
case LWMSG_LOGLEVEL_DEBUG:
regLevel = REG_LOG_LEVEL_DEBUG;
break;
case LWMSG_LOGLEVEL_TRACE:
default:
regLevel = REG_LOG_LEVEL_TRACE;
break;
}
result = (LwRtlLogGetLevel() >= regLevel);
if (pszMessage && result)
{
LW_RTL_LOG_RAW(regLevel, "lwreg-ipc", pszFunction, pszFilename, line, "%s", pszMessage);
}
return result;
}
DWORD
RegSrvStartListenThread(
void
)
{
PSTR pszCachePath = NULL;
PSTR pszCommPath = NULL;
BOOLEAN bDirExists = FALSE;
DWORD dwError = 0;
static LWMsgTime idleTimeout = {30, 0};
dwError = RegSrvGetCachePath(&pszCachePath);
BAIL_ON_REG_ERROR(dwError);
dwError = RegCheckDirectoryExists(pszCachePath, &bDirExists);
BAIL_ON_REG_ERROR(dwError);
if (!bDirExists)
{
// Directory should be RWX for root and accessible to all
// (so they can see the socket.
mode_t mode = S_IRWXU | S_IRGRP| S_IXGRP | S_IROTH | S_IXOTH;
dwError = RegCreateDirectory(pszCachePath, mode);
BAIL_ON_REG_ERROR(dwError);
}
dwError = LwRtlCStringAllocatePrintf(&pszCommPath, "%s/%s",
pszCachePath, REG_SERVER_FILENAME);
BAIL_ON_REG_ERROR(dwError);
dwError = MAP_LWMSG_ERROR(lwmsg_context_new(NULL, &gpContext));
BAIL_ON_REG_ERROR(dwError);
lwmsg_context_set_log_function(gpContext, RegSrvLogIpc, NULL);
/* Set up IPC protocol object */
dwError = MAP_LWMSG_ERROR(lwmsg_protocol_new(gpContext, &gpProtocol));
BAIL_ON_REG_ERROR(dwError);
dwError = MAP_LWMSG_ERROR(lwmsg_protocol_add_protocol_spec(
gpProtocol,
RegIPCGetProtocolSpec()));
BAIL_ON_REG_ERROR(dwError);
/* Set up IPC server object */
dwError = MAP_LWMSG_ERROR(lwmsg_peer_new(gpContext, gpProtocol, &gpServer));
BAIL_ON_REG_ERROR(dwError);
dwError = MAP_LWMSG_ERROR(lwmsg_peer_add_dispatch_spec(
gpServer,
RegSrvGetDispatchSpec()));
BAIL_ON_REG_ERROR(dwError);
dwError = MAP_LWMSG_ERROR(lwmsg_peer_add_listen_endpoint(
gpServer,
LWMSG_ENDPOINT_DIRECT,
"lwreg",
0));
BAIL_ON_REG_ERROR(dwError);
dwError = MAP_LWMSG_ERROR(lwmsg_peer_add_listen_endpoint(
gpServer,
LWMSG_ENDPOINT_LOCAL,
pszCommPath,
0666));
BAIL_ON_REG_ERROR(dwError);
dwError = MAP_LWMSG_ERROR(lwmsg_peer_set_max_listen_clients(
gpServer,
MAX_CLIENTS));
BAIL_ON_REG_ERROR(dwError);
dwError = MAP_LWMSG_ERROR(lwmsg_peer_set_max_listen_backlog(
gpServer,
REG_MAX(5, MAX_CLIENTS / 4)));
BAIL_ON_REG_ERROR(dwError);
dwError = MAP_LWMSG_ERROR(lwmsg_peer_set_timeout(
gpServer,
LWMSG_TIMEOUT_IDLE,
&idleTimeout));
BAIL_ON_REG_ERROR(dwError);
dwError = MAP_LWMSG_ERROR(lwmsg_peer_set_listen_session_functions(
gpServer,
RegSrvIpcConstructSession,
RegSrvIpcDestructSession,
NULL));
BAIL_ON_REG_ERROR(dwError);
dwError = MAP_LWMSG_ERROR(lwmsg_peer_start_listen(gpServer));
error:
LWREG_SAFE_FREE_STRING(pszCachePath);
LWREG_SAFE_FREE_STRING(pszCommPath);
if (dwError)
{
if (gpServer)
{
lwmsg_peer_stop_listen(gpServer);
lwmsg_peer_delete(gpServer);
gpServer = NULL;
}
}
return dwError;
}
DWORD
RegSrvStopListenThread(
void
)
{
DWORD dwError = 0;
if (gpServer)
{
dwError = MAP_LWMSG_ERROR(lwmsg_peer_stop_listen(gpServer));
BAIL_ON_REG_ERROR(dwError);
}
error:
if (gpServer)
{
lwmsg_peer_delete(gpServer);
gpServer = NULL;
}
if (gpProtocol)
{
lwmsg_protocol_delete(gpProtocol);
}
if (gpContext)
{
lwmsg_context_delete(gpContext);
}
return dwError;
}
| 3,458 |
629 | <gh_stars>100-1000
/*
* Copyright (c) 2017-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#include "buildorders/base.h"
#include "fivepool.h"
#include "gameutils/game.h"
#include "modules.h"
#include "player.h"
#include "registry.h"
#include "test.h"
#include <glog/logging.h>
DECLARE_string(build);
DECLARE_double(rtfactor);
using namespace cherrypi;
namespace {
auto constexpr kBuildOrderFirst = "test1";
auto constexpr kBuildOrderSecond = "test2";
auto constexpr kBuildOrderChangeAtFrame = 1000;
class ABBOTest1 : public ABBOBase {
public:
using ABBOBase::ABBOBase;
virtual void preBuild2(autobuild::BuildState& st) override {}
virtual void buildStep2(autobuild::BuildState& st) override {}
};
class ABBOTest2 : public ABBOBase {
public:
using ABBOBase::ABBOBase;
virtual void preBuild2(autobuild::BuildState& st) override {}
virtual void buildStep2(autobuild::BuildState& st) override {}
};
REGISTER_SUBCLASS_3(ABBOBase, ABBOTest1, UpcId, State*, Module*);
REGISTER_SUBCLASS_3(ABBOBase, ABBOTest2, UpcId, State*, Module*);
} // namespace
class GenericAutobuildTestUtils {
public:
static auto createMyPlayer(
GameMultiPlayer* scenario,
std::function<void(State*)> init_fn = nullptr) {
auto bot = std::make_shared<Player>(scenario->makeClient1());
if (init_fn) {
init_fn(bot->state());
}
bot->setRealtimeFactor(FLAGS_rtfactor);
bot->addModule(Module::make<CreateGatherAttackModule>());
bot->addModule(Module::make<StrategyModule>());
bot->addModule(Module::make<GenericAutoBuildModule>());
bot->addModule(Module::make<BuildingPlacerModule>());
bot->addModule(Module::make<BuilderModule>());
bot->addModule(Module::make<GathererModule>());
bot->addModule(Module::make<UPCToCommandModule>());
bot->init();
return bot;
}
static auto createEnemyPlayer(GameMultiPlayer* scenario) {
auto bot = std::make_shared<Player>(scenario->makeClient2());
bot->setRealtimeFactor(FLAGS_rtfactor);
bot->init();
return bot;
}
template <typename T>
static bool hasGenericAutoBuildSubtask(std::shared_ptr<BasePlayer> player) {
std::shared_ptr<GenericAutoBuildModule> module =
player->findModule<GenericAutoBuildModule>();
for (auto task : player->state()->board()->tasksOfModule(module.get())) {
if (std::dynamic_pointer_cast<T>(task)) {
return true;
}
}
return false;
}
};
SCENARIO("genericautobuild") {
GIVEN("build order initialized with kBuildOrderKey") {
auto scenario = GameMultiPlayer(
"maps/(4)Fighting Spirit.scx", tc::BW::Race::Zerg, tc::BW::Race::Zerg);
auto ourBot =
GenericAutobuildTestUtils::createMyPlayer(&scenario, [](State* s) {
s->board()->post(
Blackboard::kBuildOrderKey, std::string(kBuildOrderSecond));
});
auto theirBot = GenericAutobuildTestUtils::createEnemyPlayer(&scenario);
auto ourBoard = ourBot->state()->board();
ourBot->step();
theirBot->step();
EXPECT(ourBoard->hasKey(Blackboard::kBuildOrderKey));
EXPECT(
ourBoard->get<std::string>(Blackboard::kBuildOrderKey) ==
kBuildOrderSecond);
EXPECT(GenericAutobuildTestUtils::hasGenericAutoBuildSubtask<ABBOTest2>(
ourBot));
}
GIVEN("build order initialized with kOpeningBuildOrderKey") {
auto scenario = GameMultiPlayer(
"maps/(4)Fighting Spirit.scx", tc::BW::Race::Zerg, tc::BW::Race::Zerg);
auto ourBot =
GenericAutobuildTestUtils::createMyPlayer(&scenario, [](State* s) {
s->board()->post(
Blackboard::kOpeningBuildOrderKey,
std::string(kBuildOrderSecond));
});
auto theirBot = GenericAutobuildTestUtils::createEnemyPlayer(&scenario);
auto ourBoard = ourBot->state()->board();
ourBot->step();
theirBot->step();
EXPECT(ourBoard->hasKey(Blackboard::kBuildOrderKey));
EXPECT(
ourBoard->get<std::string>(Blackboard::kBuildOrderKey) ==
kBuildOrderSecond);
EXPECT(GenericAutobuildTestUtils::hasGenericAutoBuildSubtask<ABBOTest2>(
ourBot));
}
GIVEN("A blank state") {
auto scenario = GameMultiPlayer(
"maps/(4)Fighting Spirit.scx", tc::BW::Race::Zerg, tc::BW::Race::Zerg);
auto ourBot =
GenericAutobuildTestUtils::createMyPlayer(&scenario, [](State* s) {
s->board()->post(
Blackboard::kBuildOrderKey, std::string(kBuildOrderFirst));
});
auto theirBot = GenericAutobuildTestUtils::createEnemyPlayer(&scenario);
auto ourState = ourBot->state();
auto ourBoard = ourState->board();
while (!ourState->gameEnded() &&
ourState->currentFrame() < kBuildOrderChangeAtFrame) {
ourBot->step();
theirBot->step();
}
WHEN("the game has been initialized with a first build order") {
EXPECT(!ourState->gameEnded());
EXPECT(ourBoard->hasKey(Blackboard::kBuildOrderKey));
EXPECT(
ourBoard->get<std::string>(Blackboard::kBuildOrderKey) ==
kBuildOrderFirst);
EXPECT(GenericAutobuildTestUtils::hasGenericAutoBuildSubtask<ABBOTest1>(
ourBot));
}
WHEN("the build order has changed") {
ourBoard->post(
Blackboard::kBuildOrderKey, std::string(kBuildOrderSecond));
while (!ourState->gameEnded() &&
ourState->currentFrame() < (kBuildOrderChangeAtFrame * 2)) {
ourBot->step();
theirBot->step();
}
EXPECT(!ourState->gameEnded());
EXPECT(ourBoard->hasKey(Blackboard::kBuildOrderKey));
EXPECT(
ourBoard->get<std::string>(Blackboard::kBuildOrderKey) ==
kBuildOrderSecond);
EXPECT(GenericAutobuildTestUtils::hasGenericAutoBuildSubtask<ABBOTest2>(
ourBot));
EXPECT(!GenericAutobuildTestUtils::hasGenericAutoBuildSubtask<ABBOTest1>(
ourBot));
}
}
}
| 2,335 |
742 | /*------------------------------------
///\ Plywood C++ Framework
\\\/ https://plywood.arc80.com/
------------------------------------*/
#pragma once
#include <ply-math/Core.h>
#include <ply-math/Vector.h>
namespace ply {
// You are expected to pass in a value between -1 and 1
// It maps the value linearly from [-1, 1] to [0, 2 * Pi] and returns the sin of the mapped
// value The wrapper function fastSin() accepts any argument value in radians
inline float fastSinPart(float x) {
float val = 4 * x * (fabsf(x) - 1);
return val * (0.225f * fabsf(val) + 0.775f);
}
inline float fastSin(float rad) {
float frac = rad * (0.5f / Pi);
return fastSinPart((frac - floorf(frac)) * 2 - 1);
}
inline float fastCos(float rad) {
return fastSin(rad + (Pi * 0.5f));
}
inline Float2 fastCosSin(float rad) {
return {fastCos(rad), fastSin(rad)};
}
} // namespace ply
| 310 |
322 | ///////////////////////////////////////////////////////////////////////////////
// BSD 3-Clause License
//
// Copyright (C) 2021, LAAS-CNRS, University of Edinburgh
// Copyright note valid unless otherwise stated in individual files.
// All rights reserved.
///////////////////////////////////////////////////////////////////////////////
#include <pinocchio/algorithm/frames.hpp>
#include "crocoddyl/multibody/residuals/frame-placement.hpp"
namespace crocoddyl {
template <typename Scalar>
ResidualModelFramePlacementTpl<Scalar>::ResidualModelFramePlacementTpl(boost::shared_ptr<StateMultibody> state,
const pinocchio::FrameIndex id, const SE3& pref,
const std::size_t nu)
: Base(state, 6, nu, true, false, false),
id_(id),
pref_(pref),
oMf_inv_(pref.inverse()),
pin_model_(state->get_pinocchio()) {}
template <typename Scalar>
ResidualModelFramePlacementTpl<Scalar>::ResidualModelFramePlacementTpl(boost::shared_ptr<StateMultibody> state,
const pinocchio::FrameIndex id, const SE3& pref)
: Base(state, 6, true, false, false),
id_(id),
pref_(pref),
oMf_inv_(pref.inverse()),
pin_model_(state->get_pinocchio()) {}
template <typename Scalar>
ResidualModelFramePlacementTpl<Scalar>::~ResidualModelFramePlacementTpl() {}
template <typename Scalar>
void ResidualModelFramePlacementTpl<Scalar>::calc(const boost::shared_ptr<ResidualDataAbstract>& data,
const Eigen::Ref<const VectorXs>&,
const Eigen::Ref<const VectorXs>&) {
Data* d = static_cast<Data*>(data.get());
// Compute the frame placement w.r.t. the reference frame
pinocchio::updateFramePlacement(*pin_model_.get(), *d->pinocchio, id_);
d->rMf = oMf_inv_ * d->pinocchio->oMf[id_];
data->r = pinocchio::log6(d->rMf).toVector();
}
template <typename Scalar>
void ResidualModelFramePlacementTpl<Scalar>::calcDiff(const boost::shared_ptr<ResidualDataAbstract>& data,
const Eigen::Ref<const VectorXs>&,
const Eigen::Ref<const VectorXs>&) {
Data* d = static_cast<Data*>(data.get());
// Compute the derivatives of the frame placement
const std::size_t nv = state_->get_nv();
pinocchio::Jlog6(d->rMf, d->rJf);
pinocchio::getFrameJacobian(*pin_model_.get(), *d->pinocchio, id_, pinocchio::LOCAL, d->fJf);
data->Rx.leftCols(nv).noalias() = d->rJf * d->fJf;
}
template <typename Scalar>
boost::shared_ptr<ResidualDataAbstractTpl<Scalar> > ResidualModelFramePlacementTpl<Scalar>::createData(
DataCollectorAbstract* const data) {
return boost::allocate_shared<Data>(Eigen::aligned_allocator<Data>(), this, data);
}
template <typename Scalar>
void ResidualModelFramePlacementTpl<Scalar>::print(std::ostream& os) const {
const Eigen::IOFormat fmt(2, Eigen::DontAlignCols, ", ", ";\n", "", "", "[", "]");
typename SE3::Quaternion qref;
pinocchio::quaternion::assignQuaternion(qref, pref_.rotation());
os << "ResidualModelFramePlacement {frame=" << pin_model_->frames[id_].name
<< ", tref=" << pref_.translation().transpose().format(fmt) << ", qref=" << qref.coeffs().transpose().format(fmt)
<< "}";
}
template <typename Scalar>
pinocchio::FrameIndex ResidualModelFramePlacementTpl<Scalar>::get_id() const {
return id_;
}
template <typename Scalar>
const pinocchio::SE3Tpl<Scalar>& ResidualModelFramePlacementTpl<Scalar>::get_reference() const {
return pref_;
}
template <typename Scalar>
void ResidualModelFramePlacementTpl<Scalar>::set_id(const pinocchio::FrameIndex id) {
id_ = id;
}
template <typename Scalar>
void ResidualModelFramePlacementTpl<Scalar>::set_reference(const SE3& placement) {
pref_ = placement;
oMf_inv_ = placement.inverse();
}
} // namespace crocoddyl
| 1,765 |
587 | /*
* Copyright 2020 Crown Copyright
*
* 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 uk.gov.gchq.gaffer.rest.config;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.AbstractEnvironment;
import org.springframework.core.env.EnumerablePropertySource;
import org.springframework.core.env.Environment;
import uk.gov.gchq.gaffer.rest.SystemProperty;
import uk.gov.gchq.gaffer.rest.factory.DefaultExamplesFactory;
import uk.gov.gchq.gaffer.rest.factory.ExamplesFactory;
import uk.gov.gchq.gaffer.rest.factory.GraphFactory;
import uk.gov.gchq.gaffer.rest.factory.UserFactory;
import javax.annotation.PostConstruct;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
@Configuration
public class FactoryConfig {
private static final Logger LOGGER = LoggerFactory.getLogger(FactoryConfig.class);
private Environment environment;
@Autowired
public void setEnvironment(final Environment environment) {
this.environment = environment;
}
@PostConstruct
public void setToSystemProperties() {
if (environment instanceof AbstractEnvironment) {
Set<String> checkedProperties = new HashSet<>();
((AbstractEnvironment) environment).getPropertySources().iterator().forEachRemaining(propertySource -> {
if (propertySource instanceof EnumerablePropertySource) {
String[] propertyNames = ((EnumerablePropertySource) propertySource).getPropertyNames();
Arrays.stream(propertyNames)
.filter(s -> s.startsWith("gaffer") && checkedProperties.add(s)) // Skips expensive property lookup
.forEach(s -> System.setProperty(s, environment.getProperty(s)));
} else {
LOGGER.info("Skipping Property source " + propertySource);
LOGGER.info("Any gaffer property configured with this source will not be automatically added " +
"to system properties");
}
});
return;
}
LOGGER.warn("Environment was not instance of AbstractEnvironment. Property setting will be skipped.");
}
@Bean
public GraphFactory createGraphFactory() throws IllegalAccessException, InstantiationException {
return getDefaultGraphFactory().newInstance();
}
@Bean
public UserFactory createUserFactory() throws IllegalAccessException, InstantiationException {
return getDefaultUserFactory().newInstance();
}
@Bean
public ExamplesFactory createExamplesFactory() {
return new DefaultExamplesFactory();
}
private Class<? extends GraphFactory> getDefaultGraphFactory() {
final String graphFactoryClass = System.getProperty(SystemProperty.GRAPH_FACTORY_CLASS,
SystemProperty.GRAPH_FACTORY_CLASS_DEFAULT);
try {
return Class.forName(graphFactoryClass)
.asSubclass(GraphFactory.class);
} catch (final ClassNotFoundException e) {
throw new IllegalArgumentException("Unable to create graph factory from class: " + graphFactoryClass, e);
}
}
private Class<? extends UserFactory> getDefaultUserFactory() {
final String userFactoryClass = System.getProperty(SystemProperty.USER_FACTORY_CLASS,
SystemProperty.USER_FACTORY_CLASS_DEFAULT);
try {
return Class.forName(userFactoryClass)
.asSubclass(UserFactory.class);
} catch (final ClassNotFoundException e) {
throw new IllegalArgumentException("Unable to create user factory from class: " + userFactoryClass, e);
}
}
}
| 1,586 |
965 | <gh_stars>100-1000
#ifndef GTKMM_EXAMPLE_Window_H
#define GTKMM_EXAMPLE_Window_H
#include <gtkmm/button.h>
#include <gtkmm/window.h>
class Window : public Gtk::Window
{
public:
Window();
virtual ~Window();
protected:
//Signal handlers:
void on_button_clicked();
//Member widgets:
Gtk::Button m_button;
};
#endif // GTKMM_EXAMPLE_Window_H
| 145 |
515 | <reponame>luiz158/caelum-stella<filename>stella-faces/src/main/java/br/com/caelum/stella/faces/validation/StellaCPFValidatorTagHandler.java
package br.com.caelum.stella.faces.validation;
import javax.faces.validator.Validator;
import com.sun.facelets.FaceletContext;
import com.sun.facelets.tag.TagAttribute;
import com.sun.facelets.tag.TagConfig;
import com.sun.facelets.tag.jsf.ValidateHandler;
import com.sun.facelets.tag.jsf.ValidatorConfig;
public class StellaCPFValidatorTagHandler extends ValidateHandler {
private final TagAttribute formatted;
@SuppressWarnings("deprecation")
public StellaCPFValidatorTagHandler(TagConfig config) {
super(config);
formatted = getAttribute("formatted");
}
public StellaCPFValidatorTagHandler(ValidatorConfig validatorConfig) {
super(validatorConfig);
formatted = getAttribute("formatted");
}
protected Validator createValidator(FaceletContext context) {
StellaCPFValidator validator = new StellaCPFValidator();
if (formatted != null) {
validator.setFormatted(formatted.getBoolean(context));
} else {
validator.setFormatted(false);
}
return validator;
}
}
| 459 |
494 | <filename>astyanax-core/src/main/java/com/netflix/astyanax/util/BlockingConcurrentWindowCounter.java<gh_stars>100-1000
/*******************************************************************************
* Copyright 2011 Netflix
*
* 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.netflix.astyanax.util;
import java.util.concurrent.PriorityBlockingQueue;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
public class BlockingConcurrentWindowCounter {
private final PriorityBlockingQueue<Integer> queue;
private volatile int tail = 0;
private volatile int head = 0;
private final Semaphore semaphore;
public BlockingConcurrentWindowCounter(int size) {
this(size, 0);
}
public BlockingConcurrentWindowCounter(int size, int init) {
this.queue = new PriorityBlockingQueue<Integer>(size);
this.semaphore = new Semaphore(size);
this.head = this.tail = init;
}
public int incrementAndGet() throws Exception {
semaphore.acquire();
synchronized (this) {
return head++;
}
}
public int incrementAndGet(long timeout, TimeUnit unit) throws Exception {
semaphore.tryAcquire(timeout, unit);
synchronized (this) {
return head++;
}
}
public synchronized int release(int index) {
int count = 0;
this.queue.add(index);
while (!this.queue.isEmpty() && this.queue.peek() == tail) {
this.queue.remove();
tail++;
count++;
}
if (count > 0)
semaphore.release(count);
return count;
}
}
| 766 |
4,054 | <reponame>Anlon-Burke/vespa<gh_stars>1000+
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.config.application;
import org.w3c.dom.Document;
import javax.xml.transform.TransformerException;
import java.io.IOException;
/**
* Performs pre-processing of XML document and returns new document that has been processed.
*
* @author <NAME>
*/
public interface PreProcessor {
Document process(Document input) throws IOException, TransformerException;
}
| 154 |
2,606 | <filename>src/main/java/weixin/popular/bean/datacube/getcardmembercardinfo/package-info.java
/**
* 微信卡券-卡券管理-统计卡券数据-拉取会员卡概况数据接口
* @author Moyq5
*
*/
package weixin.popular.bean.datacube.getcardmembercardinfo; | 140 |
1,350 | <filename>sdk/resourcemanager/azure-resourcemanager-monitor/src/main/java/com/azure/resourcemanager/monitor/fluent/PrivateLinkScopesClient.java
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.resourcemanager.monitor.fluent;
import com.azure.core.annotation.ReturnType;
import com.azure.core.annotation.ServiceMethod;
import com.azure.core.http.rest.PagedFlux;
import com.azure.core.http.rest.PagedIterable;
import com.azure.core.http.rest.Response;
import com.azure.core.management.polling.PollResult;
import com.azure.core.util.Context;
import com.azure.core.util.polling.PollerFlux;
import com.azure.core.util.polling.SyncPoller;
import com.azure.resourcemanager.monitor.fluent.models.AzureMonitorPrivateLinkScopeInner;
import com.azure.resourcemanager.resources.fluentcore.collection.InnerSupportsDelete;
import com.azure.resourcemanager.resources.fluentcore.collection.InnerSupportsGet;
import com.azure.resourcemanager.resources.fluentcore.collection.InnerSupportsListing;
import java.nio.ByteBuffer;
import java.util.Map;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
/** An instance of this class provides access to all the operations defined in PrivateLinkScopesClient. */
public interface PrivateLinkScopesClient
extends InnerSupportsGet<AzureMonitorPrivateLinkScopeInner>,
InnerSupportsListing<AzureMonitorPrivateLinkScopeInner>,
InnerSupportsDelete<Void> {
/**
* Gets a list of all Azure Monitor PrivateLinkScopes within a subscription.
*
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return a list of all Azure Monitor PrivateLinkScopes within a subscription.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
PagedFlux<AzureMonitorPrivateLinkScopeInner> listAsync();
/**
* Gets a list of all Azure Monitor PrivateLinkScopes within a subscription.
*
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return a list of all Azure Monitor PrivateLinkScopes within a subscription.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
PagedIterable<AzureMonitorPrivateLinkScopeInner> list();
/**
* Gets a list of all Azure Monitor PrivateLinkScopes within a subscription.
*
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return a list of all Azure Monitor PrivateLinkScopes within a subscription.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
PagedIterable<AzureMonitorPrivateLinkScopeInner> list(Context context);
/**
* Gets a list of Azure Monitor PrivateLinkScopes within a resource group.
*
* @param resourceGroupName The name of the resource group.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return a list of Azure Monitor PrivateLinkScopes within a resource group.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
PagedFlux<AzureMonitorPrivateLinkScopeInner> listByResourceGroupAsync(String resourceGroupName);
/**
* Gets a list of Azure Monitor PrivateLinkScopes within a resource group.
*
* @param resourceGroupName The name of the resource group.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return a list of Azure Monitor PrivateLinkScopes within a resource group.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
PagedIterable<AzureMonitorPrivateLinkScopeInner> listByResourceGroup(String resourceGroupName);
/**
* Gets a list of Azure Monitor PrivateLinkScopes within a resource group.
*
* @param resourceGroupName The name of the resource group.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return a list of Azure Monitor PrivateLinkScopes within a resource group.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
PagedIterable<AzureMonitorPrivateLinkScopeInner> listByResourceGroup(String resourceGroupName, Context context);
/**
* Deletes a Azure Monitor PrivateLinkScope.
*
* @param resourceGroupName The name of the resource group.
* @param scopeName The name of the Azure Monitor PrivateLinkScope resource.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the completion.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
Mono<Response<Flux<ByteBuffer>>> deleteWithResponseAsync(String resourceGroupName, String scopeName);
/**
* Deletes a Azure Monitor PrivateLinkScope.
*
* @param resourceGroupName The name of the resource group.
* @param scopeName The name of the Azure Monitor PrivateLinkScope resource.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the completion.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
PollerFlux<PollResult<Void>, Void> beginDeleteAsync(String resourceGroupName, String scopeName);
/**
* Deletes a Azure Monitor PrivateLinkScope.
*
* @param resourceGroupName The name of the resource group.
* @param scopeName The name of the Azure Monitor PrivateLinkScope resource.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the completion.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
SyncPoller<PollResult<Void>, Void> beginDelete(String resourceGroupName, String scopeName);
/**
* Deletes a Azure Monitor PrivateLinkScope.
*
* @param resourceGroupName The name of the resource group.
* @param scopeName The name of the Azure Monitor PrivateLinkScope resource.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the completion.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
SyncPoller<PollResult<Void>, Void> beginDelete(String resourceGroupName, String scopeName, Context context);
/**
* Deletes a Azure Monitor PrivateLinkScope.
*
* @param resourceGroupName The name of the resource group.
* @param scopeName The name of the Azure Monitor PrivateLinkScope resource.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the completion.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
Mono<Void> deleteAsync(String resourceGroupName, String scopeName);
/**
* Deletes a Azure Monitor PrivateLinkScope.
*
* @param resourceGroupName The name of the resource group.
* @param scopeName The name of the Azure Monitor PrivateLinkScope resource.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
void delete(String resourceGroupName, String scopeName);
/**
* Deletes a Azure Monitor PrivateLinkScope.
*
* @param resourceGroupName The name of the resource group.
* @param scopeName The name of the Azure Monitor PrivateLinkScope resource.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
void delete(String resourceGroupName, String scopeName, Context context);
/**
* Returns a Azure Monitor PrivateLinkScope.
*
* @param resourceGroupName The name of the resource group.
* @param scopeName The name of the Azure Monitor PrivateLinkScope resource.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return an Azure Monitor PrivateLinkScope definition.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
Mono<Response<AzureMonitorPrivateLinkScopeInner>> getByResourceGroupWithResponseAsync(
String resourceGroupName, String scopeName);
/**
* Returns a Azure Monitor PrivateLinkScope.
*
* @param resourceGroupName The name of the resource group.
* @param scopeName The name of the Azure Monitor PrivateLinkScope resource.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return an Azure Monitor PrivateLinkScope definition.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
Mono<AzureMonitorPrivateLinkScopeInner> getByResourceGroupAsync(String resourceGroupName, String scopeName);
/**
* Returns a Azure Monitor PrivateLinkScope.
*
* @param resourceGroupName The name of the resource group.
* @param scopeName The name of the Azure Monitor PrivateLinkScope resource.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return an Azure Monitor PrivateLinkScope definition.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
AzureMonitorPrivateLinkScopeInner getByResourceGroup(String resourceGroupName, String scopeName);
/**
* Returns a Azure Monitor PrivateLinkScope.
*
* @param resourceGroupName The name of the resource group.
* @param scopeName The name of the Azure Monitor PrivateLinkScope resource.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return an Azure Monitor PrivateLinkScope definition.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
Response<AzureMonitorPrivateLinkScopeInner> getByResourceGroupWithResponse(
String resourceGroupName, String scopeName, Context context);
/**
* Creates (or updates) a Azure Monitor PrivateLinkScope. Note: You cannot specify a different value for
* InstrumentationKey nor AppId in the Put operation.
*
* @param resourceGroupName The name of the resource group.
* @param scopeName The name of the Azure Monitor PrivateLinkScope resource.
* @param azureMonitorPrivateLinkScopePayload Properties that need to be specified to create or update a Azure
* Monitor PrivateLinkScope.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return an Azure Monitor PrivateLinkScope definition.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
Mono<Response<AzureMonitorPrivateLinkScopeInner>> createOrUpdateWithResponseAsync(
String resourceGroupName,
String scopeName,
AzureMonitorPrivateLinkScopeInner azureMonitorPrivateLinkScopePayload);
/**
* Creates (or updates) a Azure Monitor PrivateLinkScope. Note: You cannot specify a different value for
* InstrumentationKey nor AppId in the Put operation.
*
* @param resourceGroupName The name of the resource group.
* @param scopeName The name of the Azure Monitor PrivateLinkScope resource.
* @param azureMonitorPrivateLinkScopePayload Properties that need to be specified to create or update a Azure
* Monitor PrivateLinkScope.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return an Azure Monitor PrivateLinkScope definition.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
Mono<AzureMonitorPrivateLinkScopeInner> createOrUpdateAsync(
String resourceGroupName,
String scopeName,
AzureMonitorPrivateLinkScopeInner azureMonitorPrivateLinkScopePayload);
/**
* Creates (or updates) a Azure Monitor PrivateLinkScope. Note: You cannot specify a different value for
* InstrumentationKey nor AppId in the Put operation.
*
* @param resourceGroupName The name of the resource group.
* @param scopeName The name of the Azure Monitor PrivateLinkScope resource.
* @param azureMonitorPrivateLinkScopePayload Properties that need to be specified to create or update a Azure
* Monitor PrivateLinkScope.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return an Azure Monitor PrivateLinkScope definition.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
AzureMonitorPrivateLinkScopeInner createOrUpdate(
String resourceGroupName,
String scopeName,
AzureMonitorPrivateLinkScopeInner azureMonitorPrivateLinkScopePayload);
/**
* Creates (or updates) a Azure Monitor PrivateLinkScope. Note: You cannot specify a different value for
* InstrumentationKey nor AppId in the Put operation.
*
* @param resourceGroupName The name of the resource group.
* @param scopeName The name of the Azure Monitor PrivateLinkScope resource.
* @param azureMonitorPrivateLinkScopePayload Properties that need to be specified to create or update a Azure
* Monitor PrivateLinkScope.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return an Azure Monitor PrivateLinkScope definition.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
Response<AzureMonitorPrivateLinkScopeInner> createOrUpdateWithResponse(
String resourceGroupName,
String scopeName,
AzureMonitorPrivateLinkScopeInner azureMonitorPrivateLinkScopePayload,
Context context);
/**
* Updates an existing PrivateLinkScope's tags. To update other fields use the CreateOrUpdate method.
*
* @param resourceGroupName The name of the resource group.
* @param scopeName The name of the Azure Monitor PrivateLinkScope resource.
* @param tags Resource tags.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return an Azure Monitor PrivateLinkScope definition.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
Mono<Response<AzureMonitorPrivateLinkScopeInner>> updateTagsWithResponseAsync(
String resourceGroupName, String scopeName, Map<String, String> tags);
/**
* Updates an existing PrivateLinkScope's tags. To update other fields use the CreateOrUpdate method.
*
* @param resourceGroupName The name of the resource group.
* @param scopeName The name of the Azure Monitor PrivateLinkScope resource.
* @param tags Resource tags.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return an Azure Monitor PrivateLinkScope definition.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
Mono<AzureMonitorPrivateLinkScopeInner> updateTagsAsync(
String resourceGroupName, String scopeName, Map<String, String> tags);
/**
* Updates an existing PrivateLinkScope's tags. To update other fields use the CreateOrUpdate method.
*
* @param resourceGroupName The name of the resource group.
* @param scopeName The name of the Azure Monitor PrivateLinkScope resource.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return an Azure Monitor PrivateLinkScope definition.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
Mono<AzureMonitorPrivateLinkScopeInner> updateTagsAsync(String resourceGroupName, String scopeName);
/**
* Updates an existing PrivateLinkScope's tags. To update other fields use the CreateOrUpdate method.
*
* @param resourceGroupName The name of the resource group.
* @param scopeName The name of the Azure Monitor PrivateLinkScope resource.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return an Azure Monitor PrivateLinkScope definition.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
AzureMonitorPrivateLinkScopeInner updateTags(String resourceGroupName, String scopeName);
/**
* Updates an existing PrivateLinkScope's tags. To update other fields use the CreateOrUpdate method.
*
* @param resourceGroupName The name of the resource group.
* @param scopeName The name of the Azure Monitor PrivateLinkScope resource.
* @param tags Resource tags.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return an Azure Monitor PrivateLinkScope definition.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
Response<AzureMonitorPrivateLinkScopeInner> updateTagsWithResponse(
String resourceGroupName, String scopeName, Map<String, String> tags, Context context);
}
| 6,418 |
450 | <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.
*/
/*
* Legal Notice
*
* This document and associated source code (the "Work") is a part of a
* benchmark specification maintained by the TPC.
*
* The TPC reserves all right, title, and interest to the Work as provided
* under U.S. and international laws, including without limitation all patent
* and trademark rights therein.
*
* No Warranty
*
* 1.1 TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW, THE INFORMATION
* CONTAINED HEREIN IS PROVIDED "AS IS" AND WITH ALL FAULTS, AND THE
* AUTHORS AND DEVELOPERS OF THE WORK HEREBY DISCLAIM ALL OTHER
* WARRANTIES AND CONDITIONS, EITHER EXPRESS, IMPLIED OR STATUTORY,
* INCLUDING, BUT NOT LIMITED TO, ANY (IF ANY) IMPLIED WARRANTIES,
* DUTIES OR CONDITIONS OF MERCHANTABILITY, OF FITNESS FOR A PARTICULAR
* PURPOSE, OF ACCURACY OR COMPLETENESS OF RESPONSES, OF RESULTS, OF
* WORKMANLIKE EFFORT, OF LACK OF VIRUSES, AND OF LACK OF NEGLIGENCE.
* ALSO, THERE IS NO WARRANTY OR CONDITION OF TITLE, QUIET ENJOYMENT,
* QUIET POSSESSION, CORRESPONDENCE TO DESCRIPTION OR NON-INFRINGEMENT
* WITH REGARD TO THE WORK.
* 1.2 IN NO EVENT WILL ANY AUTHOR OR DEVELOPER OF THE WORK BE LIABLE TO
* ANY OTHER PARTY FOR ANY DAMAGES, INCLUDING BUT NOT LIMITED TO THE
* COST OF PROCURING SUBSTITUTE GOODS OR SERVICES, LOST PROFITS, LOSS
* OF USE, LOSS OF DATA, OR ANY INCIDENTAL, CONSEQUENTIAL, DIRECT,
* INDIRECT, OR SPECIAL DAMAGES WHETHER UNDER CONTRACT, TORT, WARRANTY,
* OR OTHERWISE, ARISING IN ANY WAY OUT OF THIS OR ANY OTHER AGREEMENT
* RELATING TO THE WORK, WHETHER OR NOT SUCH AUTHOR OR DEVELOPER HAD
* ADVANCE NOTICE OF THE POSSIBILITY OF SUCH DAMAGES.
*
* Contributors:
* Gradient Systems
*/
/*** includes ***/
#include "config.h"
#include "porting.h"
#include <stdlib.h>
#ifndef USE_STDLIB_H
#include <malloc.h>
#endif
#include <stdio.h>
#include <math.h>
#include "date.h"
#include "mathops.h"
#include "dist.h"
#define D_CHARS "ymdYMD24" /* valid characters in a DBGDATE setting */
#define MIN_DATE_INT 18000101
static int m_days[2][13] =
{
{0, 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334},
{0, 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335}
};
static char *qtr_start[5] = {NULL, "01-01", "04-01", "07-01", "10-01"};
char *weekday_names[8] = {NULL, "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};
/*
* Routine: mk_date(void)
* Purpose: initialize a date_t
* Algorithm:
* Data Structures:
* Params:
* Returns: date_t *
* Called By:
* Calls:
* Assumptions:
* Side Effects:
* TODO: None
*/
date_t *
mk_date(void)
{
date_t *res;
res = (date_t *)malloc(sizeof(struct DATE_T));
MALLOC_CHECK(res);
res->flags = 0;
res->year = 0;
res->month = 0;
res->day = 0;
res->julian = 0;
return(res);
}
/*
* Routine: strtotime(char *str)
* Purpose: convert a string from the time to the number of seconds since midnight
* Algorithm:
* Data Structures:
* Params:
* Returns: int
* Called By:
* Calls:
* Assumptions:
* Side Effects:
* TODO: None
*/
int
strtotime(char *str)
{
int hour, min, sec, res;
if (sscanf(str, "%d:%d:%d", &hour, &min, &sec) != 3)
{
if (sscanf(str, "%d:%d", &hour, &min) != 2)
{
INTERNAL("Invalid time format");
}
sec = 0;
}
if (hour > 23 || hour < 0)
INTERNAL("Invalid time format");
if (min > 59 || min < 0)
INTERNAL("Invalid time format");
if (sec > 59 || sec < 0)
INTERNAL("Invalid time format");
res = hour * 3600 + min * 60 + sec;
return(res);
}
/*
* Routine: strtodate(char *str)
* Purpose: initialize a date_t
* Algorithm:
* Data Structures:
* Params:
* Returns: date_t *
* Called By:
* Calls:
* Assumptions:
* Side Effects:
* TODO: None
*/
date_t *
strtodate(char *str)
{
date_t *res;
res = (date_t *)malloc(sizeof(struct DATE_T));
MALLOC_CHECK(res);
if (sscanf(str, "%d-%d-%d", &res->year, &res->month, &res->day) != 3)
INTERNAL("Badly formed string in call to strtodate()");
res->flags = 0;
res->julian = dttoj(res);
return(res);
}
/*
* Routine: jtodt(int src, date_t *dest)
* Purpose: convert a number of julian days to a date_t
* Algorithm: Fleigel and <NAME> (CACM, vol 11, #10, Oct. 1968, p. 657)
* Data Structures:
*
* Params: source integer: days since big bang
* Returns: date_t *; NULL on failure
* Called By:
* Calls:
* Assumptions:
* Side Effects:
* TODO:
*/
int
jtodt(date_t *dest, int src)
{
long i,
j,
l,
n;
if (src < 0)
return(-1);
dest->julian = src;
l = src + 68569 ;
n = (int)floor((4*l)/146097) ;
l = l - (int)floor((146097 * n + 3)/4) ;
i = (int)floor((4000 *(l + 1)/1461001)) ;
l = l - (int)floor((1461*i)/4) + 31 ;
j = (int)floor((80*l)/2447) ;
dest->day = l - (int)floor((2447*j)/80) ;
l=(int)floor(j/11) ;
dest->month = j + 2 - 12*l ;
dest->year = 100*(n-49) + i + l ;
return(0);
}
/*
* Routine: dttoj(date_t *)
* Purpose: convert a date_t to a number of julian days
* Algorithm: http://quasar.as.utexas.edu/BillInfo/JulianDatesG.html
* Data Structures:
*
* Params:
* Returns:
* Called By:
* Calls:
* Assumptions:
* Side Effects:
* TODO: None
*/
int
dttoj(date_t *dt)
{
int y, m, res;
y = dt->year;
m = dt->month;
if (m <= 2)
{
m += 12;
y -= 1;
}
/*
* added 1 to get dttoj and jtodt to match
*/
res = dt->day + (153 * m - 457) / 5 + 365 * y + (int)floor(y / 4) - (int)floor(y / 100) + (int)floor(y / 400) + 1721118 + 1;
return(res);
}
/*
* Routine: strtodt()
* Purpose: Convert an ascii string to a date_t structure
* Algorithm:
* Data Structures:
*
* Params: char *s, date_t *dest
* Returns: int; 0 on success
* Called By:
* Calls:
* Assumptions:
* Side Effects:
* TODO: Need to allow for date formats other than Y4MD-
*/
int
strtodt(date_t *dest, char *s)
{
int nRetCode = 0;
if (s == NULL)
{
dest = NULL;
return(-1);
}
if (sscanf(s, "%4d-%d-%d", &dest->year, &dest->month, &dest->day) != 3)
{
fprintf(stderr, "ERROR: Invalid string to date conversion in strtodt\n");
nRetCode = -1;
}
dest->julian = dttoj(dest);
return(nRetCode);
}
/*
* Routine: dttostr(date_t *d)
* Purpose: convert a date_t structure to a string
* Algorithm:
* Data Structures:
*
* Params:
* Returns: char *; NULL on failure
* Called By:
* Calls:
* Assumptions:
* Side Effects:
* TODO: 20000110 Need to handle more than Y4MD-
*/
char *
dttostr(date_t *d)
{
static char *res;
static int init = 0;
if (!init)
{
res = (char *)malloc(sizeof(char) * 11);
MALLOC_CHECK(res);
init = 1;
}
if (d == NULL)
return(NULL);
sprintf(res, "%4d-%02d-%02d", d->year, d->month, d->day);
return(res);
}
/*
* Routine: date_init
* Purpose: set the date handling parameters
* Algorithm:
* Data Structures:
*
* Params: None
* Returns: int; 0 on success
* Called By:
* Calls:
* Assumptions:
* Side Effects:
* TODO: None
*/
int
date_init(void)
{
printf("date_init is not yet complete\n");
exit(1);
return(0);
}
/*
* Routine: date_t_op(int op, date_t *operand1, date_t *operand2)
* Purpose: execute arbitrary binary operations on date_t's
* Algorithm:
* Data Structures:
*
* Params:
* Returns:
* Called By:
* Calls:
* Assumptions:
* Side Effects:
* TODO:
* 20010806 jms Return code is meaningless
*/
int
date_t_op(date_t *dest, int op, date_t *d1, date_t *d2)
{
int tJulian;
char tString[11];
date_t tDate;
switch(op)
{
case OP_FIRST_DOM: /* set to first day of month */
tJulian = d1->julian - d1->day + 1;
jtodt(dest, tJulian);
break;
case OP_LAST_DOM: /* set to last day of month */
tJulian = d1->julian - d1->day + m_days[is_leap(d1->year)][d1->month];
jtodt(dest, tJulian);
break;
case OP_SAME_LY:
if (is_leap(d1->year) && (d1->month == 2) && (d1->day == 29))
sprintf(tString, "%d-02-28", d1->year - 1);
else
sprintf(tString, "%4d-%02d-%02d", d1->year - 1, d1->month, d1->day);
strtodt(dest, tString);
break;
case OP_SAME_LQ:
switch(d1->month) {
case 1:
case 2:
case 3:
sprintf(tString, "%4d-%s", d1->year, qtr_start[1]);
strtodt(&tDate, tString);
tJulian = d1->julian - tDate.julian;
sprintf(tString, "%4d-%s", d1->year - 1, qtr_start[4]);
strtodt(&tDate, tString);
tJulian += tDate.julian;
jtodt(dest, tJulian);
break;
case 4:
case 5:
case 6:
sprintf(tString, "%4d-%s", d1->year, qtr_start[2]);
strtodt(&tDate, tString);
tJulian = d1->julian - tDate.julian;
sprintf(tString, "%4d-%s", d1->year, qtr_start[1]);
strtodt(&tDate, tString);
tJulian += tDate.julian;
jtodt(dest, tJulian);
break;
case 7:
case 8:
case 9:
sprintf(tString, "%4d-%s", d1->year, qtr_start[3]);
strtodt(&tDate, tString);
tJulian = d1->julian - tDate.julian;
sprintf(tString, "%4d-%s", d1->year, qtr_start[2]);
strtodt(&tDate, tString);
tJulian += tDate.julian;
jtodt(dest, tJulian);
break;
case 10:
case 11:
case 12:
sprintf(tString, "%4d-%s", d1->year, qtr_start[4]);
strtodt(&tDate, tString);
tJulian = d1->julian - tDate.julian;
sprintf(tString, "%4d-%s", d1->year, qtr_start[3]);
strtodt(&tDate, tString);
tJulian += tDate.julian;
jtodt(dest, tJulian);
break;
}
break;
}
return(0);
}
/*
* Routine: itodt(date_t *d, int src)
* Purpose: convert a number of days to a date_t
* Algorithm: NOTE: sets only julian field
* Data Structures:
*
* Params:
* Returns:
* Called By:
* Calls:
* Assumptions:
* Side Effects:
* TODO: None
*/
int
itodt(date_t *dest, int src)
{
dest->julian = src;
return(0);
}
/*
* Routine: set_dow(date *d)
* Purpose: perpetual calendar stuff
* Algorithm:
* Data Structures:
*
* Params:
* Returns:
* Called By:
* Calls:
* Assumptions:
* Side Effects:
* TODO:
*/
static int doomsday[4] = {3, 2, 0, 5};
static int known[13] = { 0, 3, 0, 0, 4, 9, 6, 11, 8, 5, 10, 7, 12 };
int
set_dow(date_t *d)
{
static int last_year = -1,
dday;
int res,
q, r, s;
if (d->year != last_year)
{
if (is_leap(d->year))
{
/* adjust the known dates for january and february */
known[1] = 4;
known[2] = 1;
}
else
{
known[1] = 3;
known[2] = 0;
}
/* calculate the doomsday for the century */
dday = d->year / 100;
dday -= 15;
dday %= 4;
dday = doomsday[dday];
/* and then calculate the doomsday for the year */
q = d->year % 100;
r = q % 12;
q /= 12;
s = r / 4;
dday += q + r + s;
dday %= 7;
last_year = d->year;
}
res = d->day;
res -= known[d->month];
while (res < 0)
res += 7;
while (res > 6)
res -= 7;
res += dday;
res %= 7;
return(res);
}
/*
* Routine: is_leap(year)
* Purpose:
* Algorithm:
* Data Structures:
*
* Params:
* Returns:
* Called By:
* Calls:
* Assumptions:
* Side Effects:
* TODO: None
*/
int
is_leap(int year)
{
return (((year % 100) == 0)?((((year % 400) % 2) == 0)?1:0):((year % 4) == 0)?1:0);
}
/*
* Routine: day_number(date_t *)
* Purpose:
* Algorithm: NOTE: this is NOT the ordinal day in the year, but the ordinal reference into the
* calendar distribution for the day; in particular, this needs to skip over the leap day
* Data Structures:
*
* Params:
* Returns:
* Called By:
* Calls:
* Assumptions:
* Side Effects:
* TODO: None
*/
int
day_number(date_t *d)
{
return(m_days[is_leap(d->year)][d->month] + d->day);
}
/*
* Routine: getDateWeightFromJulian(jDay, nDistribution)
* Purpose: return the weight associated with a particular julian date and distribution
* Algorithm:
* Data Structures:
*
* Params:
* Returns:
* Called By:
* Calls:
* Assumptions:
* Side Effects:
* TODO: None
*/
int
getDateWeightFromJulian(jDay, nDistribution)
{
date_t dTemp;
int nDay;
jtodt(&dTemp, jDay);
nDay = day_number(&dTemp);
return(dist_weight(NULL, "calendar", nDay, nDistribution + is_leap(dTemp.year)));
}
/*
* Routine: date_part(date_t *, int part)
* Purpose:
* Algorithm:
* Data Structures:
*
* Params:
* Returns:
* Called By:
* Calls:
* Assumptions:
* Side Effects:
* TODO: None
*/
int
date_part(date_t *d, int part)
{
switch(part)
{
case 1: return(d->year);
case 2: return(d->month);
case 3: return(d->day);
default:
INTERNAL("Invalid call to date_part()");
return(-1);
}
}
#ifdef TEST
main()
{
date_t *d;
int ret;
d = mk_date();
strtodt(d, "1776-07-04");
ret = set_dow(d);
printf("set_dow(\"1776-07-04\"): wanted 4 got %d\n", ret);
if (ret != 4)
{
exit(1);
}
strtodt(d, "2000-01-01");
ret = set_dow(d);
printf("set_dow(\"2000-01-01\"): wanted 6 got %d\n", ret);
if (ret != 6)
{
exit(1);
}
strtodt(d, "1970-01-01");
if ((ret = dttoj(d)) != 2440588)
{
printf("dttoj returned %d\n", ret);
exit(1);
}
d->year = 1;
d->month = 11;
d->date = 11;
jtodt(d, 2440588);
if ((d->year != 1970) || (d->month != 1) || (d->date != 1))
{
printf("jtodt failed got: ");
printf("%4d-%02d-%02d", d->year, d->month, d->date);
exit(1);
}
return(0);
}
#endif /* TEST */
| 5,907 |
517 | <reponame>kant/gratipay.com
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
from gratipay.testing import BrowserHarness
class Tests(BrowserHarness):
def check(self, status, has_request_button, has_check_button):
self.make_participant('alice', claimed_time='now', status_of_1_0_payout=status)
self.sign_in('alice')
self.visit('/~alice/settings/')
self.css('.account-details a button')
assert self.has_text('Request 1.0 Payout') is has_request_button
self.css('.account-details a button')
assert self.has_text('Check 1.0 Payout') is has_check_button
def test_too_little_has_neither(self):
self.check('too-little', False, False)
def test_pending_application_has_request_button(self):
self.check('pending-application', True, False)
def test_pending_review_has_check_button(self):
self.check('pending-review', False, True)
def test_rejected_has_neither(self):
self.check('rejected', False, False)
def test_pending_payout_has_check_button(self):
self.check('pending-payout', False, True)
def test_pending_completed_has_neither(self):
self.check('completed', False, False)
| 501 |
345 | import unittest
from programy.clients.events.console.config import ConsoleConfiguration
from programy.config.brain.securities import BrainSecuritiesConfiguration
from programy.config.file.yaml_file import YamlConfigurationFile
from programytest.config.brain.test_security import BrainSecurityConfigurationTests
class BrainSecuritiesConfigurationTests(unittest.TestCase):
def test_with_data(self):
yaml = YamlConfigurationFile()
self.assertIsNotNone(yaml)
yaml.load_from_text("""
brain:
security:
authentication:
classname: programy.security.authenticate.passthrough.PassThroughAuthenticationService
denied_srai: AUTHENTICATION_FAILED
authorisation:
classname: programy.security.authorise.passthrough.PassThroughAuthorisationService
denied_srai: AUTHORISATION_FAILED
""", ConsoleConfiguration(), ".")
brain_config = yaml.get_section("brain")
securities_config = BrainSecuritiesConfiguration()
securities_config.load_config_section(yaml, brain_config, ".")
self.assertIsNotNone(securities_config.authorisation)
self.assertIsNotNone(securities_config.authentication)
def test_defaults(self):
securities_config = BrainSecuritiesConfiguration()
data = {}
securities_config.to_yaml(data, True)
@staticmethod
def assert_defaults(test, data):
BrainSecurityConfigurationTests.assert_authenticate_defaults(test, data['authentication'])
BrainSecurityConfigurationTests.assert_authorise_defaults(test, data['authorisation'])
BrainSecurityConfigurationTests.assert_accountlinker_defaults(test, data['account_linker'])
| 666 |
1,168 | <reponame>wcalandro/kythe<filename>kythe/cxx/common/file_vname_generator.h
/*
* Copyright 2014 The Kythe Authors. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef KYTHE_CXX_COMMON_FILE_VNAME_GENERATOR_H_
#define KYTHE_CXX_COMMON_FILE_VNAME_GENERATOR_H_
#include <memory>
#include <string>
#include <vector>
#include "absl/status/status.h"
#include "absl/status/statusor.h"
#include "absl/strings/string_view.h"
#include "kythe/proto/storage.pb.h"
#include "re2/re2.h"
namespace kythe {
/// \brief Generates file VNames based on user-configurable paths and templates.
class FileVNameGenerator {
public:
explicit FileVNameGenerator() = default;
/// \brief Adds configuration entries from the json-encoded `json_string`.
/// \param json_string The string containing the configuration to add.
/// \param error_text Non-null. Will be set to text describing any errors.
/// \return false if the string could not be parsed.
bool LoadJsonString(absl::string_view data, std::string* error_text);
absl::Status LoadJsonString(absl::string_view data);
/// \brief Returns a base VName for a given file path (or an empty VName if
/// no configuration rule matches the path).
kythe::proto::VName LookupBaseVName(absl::string_view path) const;
/// \brief Returns a VName for the given file path.
kythe::proto::VName LookupVName(absl::string_view path) const;
/// \brief Sets the default base VName to use when no rules match.
void set_default_base_vname(const kythe::proto::VName& default_vname) {
default_vname_ = default_vname;
}
private:
/// \brief A rule to apply to certain paths.
struct VNameRule {
/// The pattern used to match against a path.
std::shared_ptr<re2::RE2> pattern;
/// Substitution pattern used to construct the corpus.
std::string corpus;
/// Substitution pattern used to construct the root.
std::string root;
/// Substitution pattern used to construct the path.
std::string path;
};
/// The rules to apply to incoming paths. The first one to match is used.
std::vector<VNameRule> rules_;
/// The default base VName to use when no rules match.
kythe::proto::VName default_vname_;
};
} // namespace kythe
#endif
| 868 |
571 | <reponame>taellinglin/butano
/*
* Copyright (c) 2020-2021 <NAME> <EMAIL>
* zlib License, see LICENSE file.
*/
#ifndef BN_SPRITE_ACTIONS_H
#define BN_SPRITE_ACTIONS_H
/**
* @file
* bn::sprite_ptr actions header file.
*
* @ingroup sprite
* @ingroup action
*/
#include "bn_sprite_ptr.h"
#include "bn_fixed_point.h"
#include "bn_value_template_actions.h"
namespace bn
{
// visible
/**
* @brief Manages if a sprite_ptr must be committed to the GBA or not.
*
* @ingroup sprite
* @ingroup action
*/
class sprite_visible_manager
{
public:
/**
* @brief Indicates if the given sprite_ptr is committed to the GBA or not.
*/
[[nodiscard]] static bool get(const sprite_ptr& sprite)
{
return sprite.visible();
}
/**
* @brief Sets if the given sprite_ptr must be committed to the GBA or not.
*/
static void set(bool visible, sprite_ptr& sprite)
{
sprite.set_visible(visible);
}
};
/**
* @brief Toggles if a sprite_ptr must be committed to the GBA or not
* when the action is updated a given number of times.
*
* @ingroup sprite
* @ingroup action
*/
class sprite_visible_toggle_action : public bool_toggle_value_template_action<sprite_ptr, sprite_visible_manager>
{
public:
/**
* @brief Constructor.
* @param sprite sprite_ptr to copy.
* @param duration_updates How much times the action has to be updated to toggle
* if the given sprite_ptr must be committed to the GBA or not.
*/
sprite_visible_toggle_action(const sprite_ptr& sprite, int duration_updates) :
bool_toggle_value_template_action(sprite, duration_updates)
{
}
/**
* @brief Constructor.
* @param sprite sprite_ptr to move.
* @param duration_updates How much times the action has to be updated to toggle
* if the given sprite_ptr must be committed to the GBA or not.
*/
sprite_visible_toggle_action(sprite_ptr&& sprite, int duration_updates) :
bool_toggle_value_template_action(move(sprite), duration_updates)
{
}
/**
* @brief Returns the sprite_ptr to modify.
*/
[[nodiscard]] const sprite_ptr& sprite() const
{
return value();
}
};
// position
/**
* @brief Manages the position of a sprite_ptr.
*
* @ingroup sprite
* @ingroup action
*/
class sprite_position_manager
{
public:
/**
* @brief Returns the position of the given sprite_ptr.
*/
[[nodiscard]] static const fixed_point& get(const sprite_ptr& sprite)
{
return sprite.position();
}
/**
* @brief Sets the position of the given sprite_ptr.
*/
static void set(const fixed_point& position, sprite_ptr& sprite)
{
sprite.set_position(position);
}
};
/**
* @brief Modifies the position of a sprite_ptr by a given delta.
*
* @ingroup sprite
* @ingroup action
*/
class sprite_move_by_action : public by_value_template_action<sprite_ptr, fixed_point, sprite_position_manager>
{
public:
/**
* @brief Constructor.
* @param sprite sprite_ptr to copy.
* @param delta_x How much to add to the horizontal position of the given sprite_ptr when the action is updated.
* @param delta_y How much to add to the horizontal position of the given sprite_ptr when the action is updated.
*/
sprite_move_by_action(const sprite_ptr& sprite, fixed delta_x, fixed delta_y) :
by_value_template_action(sprite, fixed_point(delta_x, delta_y))
{
}
/**
* @brief Constructor.
* @param sprite sprite_ptr to move.
* @param delta_x How much to add to the horizontal position of the given sprite_ptr when the action is updated.
* @param delta_y How much to add to the horizontal position of the given sprite_ptr when the action is updated.
*/
sprite_move_by_action(sprite_ptr&& sprite, fixed delta_x, fixed delta_y) :
by_value_template_action(move(sprite), fixed_point(delta_x, delta_y))
{
}
/**
* @brief Constructor.
* @param sprite sprite_ptr to copy.
* @param delta_position How much to add to the position of the given sprite_ptr when the action is updated.
*/
sprite_move_by_action(const sprite_ptr& sprite, const fixed_point& delta_position) :
by_value_template_action(sprite, delta_position)
{
}
/**
* @brief Constructor.
* @param sprite sprite_ptr to move.
* @param delta_position How much to add to the position of the given sprite_ptr when the action is updated.
*/
sprite_move_by_action(sprite_ptr&& sprite, const fixed_point& delta_position) :
by_value_template_action(move(sprite), delta_position)
{
}
/**
* @brief Returns the sprite_ptr to modify.
*/
[[nodiscard]] const sprite_ptr& sprite() const
{
return value();
}
/**
* @brief Returns how much to add to the position of the given sprite_ptr when the action is updated.
*/
[[nodiscard]] const fixed_point& delta_position() const
{
return delta_property();
}
};
/**
* @brief Modifies the position of a sprite_ptr until it has a given state.
*
* @ingroup sprite
* @ingroup action
*/
class sprite_move_to_action : public to_value_template_action<sprite_ptr, fixed_point, sprite_position_manager>
{
public:
/**
* @brief Constructor.
* @param sprite sprite_ptr to copy.
* @param duration_updates Number of times that the action must be updated
* until the position of the given sprite_ptr is equal to (final_x, final_y).
* @param final_x Horizontal position of the given sprite_ptr when the action is updated duration_updates times.
* @param final_y Vertical position of the given sprite_ptr when the action is updated duration_updates times.
*/
sprite_move_to_action(const sprite_ptr& sprite, int duration_updates, fixed final_x, fixed final_y) :
to_value_template_action(sprite, duration_updates, fixed_point(final_x, final_y))
{
}
/**
* @brief Constructor.
* @param sprite sprite_ptr to move.
* @param duration_updates Number of times that the action must be updated
* until the position of the given sprite_ptr is equal to (final_x, final_y).
* @param final_x Horizontal position of the given sprite_ptr when the action is updated duration_updates times.
* @param final_y Vertical position of the given sprite_ptr when the action is updated duration_updates times.
*/
sprite_move_to_action(sprite_ptr&& sprite, int duration_updates, fixed final_x, fixed final_y) :
to_value_template_action(move(sprite), duration_updates, fixed_point(final_x, final_y))
{
}
/**
* @brief Constructor.
* @param sprite sprite_ptr to copy.
* @param duration_updates Number of times that the action must be updated
* until the position of the given sprite_ptr is equal to final_position.
* @param final_position Position of the given sprite_ptr when the action is updated duration_updates times.
*/
sprite_move_to_action(const sprite_ptr& sprite, int duration_updates, const fixed_point& final_position) :
to_value_template_action(sprite, duration_updates, final_position)
{
}
/**
* @brief Constructor.
* @param sprite sprite_ptr to move.
* @param duration_updates Number of times that the action must be updated
* until the position of the given sprite_ptr is equal to final_position.
* @param final_position Position of the given sprite_ptr when the action is updated duration_updates times.
*/
sprite_move_to_action(sprite_ptr&& sprite, int duration_updates, const fixed_point& final_position) :
to_value_template_action(move(sprite), duration_updates, final_position)
{
}
/**
* @brief Returns the sprite_ptr to modify.
*/
[[nodiscard]] const sprite_ptr& sprite() const
{
return value();
}
/**
* @brief Returns the position of the given sprite_ptr when the action is updated the given number of times.
*/
[[nodiscard]] const fixed_point& final_position() const
{
return final_property();
}
};
/**
* @brief Modifies the position of a sprite_ptr from a minimum to a maximum.
* When the position is equal to the given final state, it goes back to its initial state and vice versa.
*
* @ingroup sprite
* @ingroup action
*/
class sprite_move_loop_action : public loop_value_template_action<sprite_ptr, fixed_point, sprite_position_manager>
{
public:
/**
* @brief Constructor.
* @param sprite sprite_ptr to copy.
* @param duration_updates How much times the action has to be updated
* before changing the direction of the position delta.
* @param final_x When the horizontal position of the given sprite_ptr is equal to this parameter,
* it goes back to its initial state and vice versa.
* @param final_y When the vertical position of the given sprite_ptr is equal to this parameter,
* it goes back to its initial state and vice versa.
*/
sprite_move_loop_action(const sprite_ptr& sprite, int duration_updates, fixed final_x, fixed final_y) :
loop_value_template_action(sprite, duration_updates, fixed_point(final_x, final_y))
{
}
/**
* @brief Constructor.
* @param sprite sprite_ptr to move.
* @param duration_updates How much times the action has to be updated
* before changing the direction of the position delta.
* @param final_x When the horizontal position of the given sprite_ptr is equal to this parameter,
* it goes back to its initial state and vice versa.
* @param final_y When the vertical position of the given sprite_ptr is equal to this parameter,
* it goes back to its initial state and vice versa.
*/
sprite_move_loop_action(sprite_ptr&& sprite, int duration_updates, fixed final_x, fixed final_y) :
loop_value_template_action(move(sprite), duration_updates, fixed_point(final_x, final_y))
{
}
/**
* @brief Constructor.
* @param sprite sprite_ptr to copy.
* @param duration_updates How much times the action has to be updated
* before changing the direction of the position delta.
* @param final_position When the position of the given sprite_ptr is equal to this parameter,
* it goes back to its initial state and vice versa.
*/
sprite_move_loop_action(const sprite_ptr& sprite, int duration_updates, const fixed_point& final_position) :
loop_value_template_action(sprite, duration_updates, final_position)
{
}
/**
* @brief Constructor.
* @param sprite sprite_ptr to move.
* @param duration_updates How much times the action has to be updated
* before changing the direction of the position delta.
* @param final_position When the position of the given sprite_ptr is equal to this parameter,
* it goes back to its initial state and vice versa.
*/
sprite_move_loop_action(sprite_ptr&& sprite, int duration_updates, const fixed_point& final_position) :
loop_value_template_action(move(sprite), duration_updates, final_position)
{
}
/**
* @brief Returns the sprite_ptr to modify.
*/
[[nodiscard]] const sprite_ptr& sprite() const
{
return value();
}
/**
* @brief When the position of the given sprite_ptr is equal to this returned parameter,
* it goes back to its initial state and vice versa.
*/
[[nodiscard]] const fixed_point& final_position() const
{
return final_property();
}
};
/**
* @brief Changes the position of a sprite_ptr when the action is updated a given number of times.
*
* @ingroup sprite
* @ingroup action
*/
class sprite_move_toggle_action :
public toggle_value_template_action<sprite_ptr, fixed_point, sprite_position_manager>
{
public:
/**
* @brief Constructor.
* @param sprite sprite_ptr to copy.
* @param duration_updates How much times the action has to be updated
* to change the position of the given sprite_ptr.
* @param new_x New horizontal position when the action is updated duration_updates times.
* @param new_y New vertical position when the action is updated duration_updates times.
*/
sprite_move_toggle_action(const sprite_ptr& sprite, int duration_updates, fixed new_x, fixed new_y) :
toggle_value_template_action(sprite, duration_updates, fixed_point(new_x, new_y))
{
}
/**
* @brief Constructor.
* @param sprite sprite_ptr to move.
* @param duration_updates How much times the action has to be updated
* to change the position of the given sprite_ptr.
* @param new_x New horizontal position when the action is updated duration_updates times.
* @param new_y New vertical position when the action is updated duration_updates times.
*/
sprite_move_toggle_action(sprite_ptr&& sprite, int duration_updates, fixed new_x, fixed new_y) :
toggle_value_template_action(move(sprite), duration_updates, fixed_point(new_x, new_y))
{
}
/**
* @brief Constructor.
* @param sprite sprite_ptr to copy.
* @param duration_updates How much times the action has to be updated
* to change the position of the given sprite_ptr.
* @param new_position New position when the action is updated duration_updates times.
*/
sprite_move_toggle_action(const sprite_ptr& sprite, int duration_updates, const fixed_point& new_position) :
toggle_value_template_action(sprite, duration_updates, new_position)
{
}
/**
* @brief Constructor.
* @param sprite sprite_ptr to move.
* @param duration_updates How much times the action has to be updated
* to change the position of the given sprite_ptr.
* @param new_position New position when the action is updated duration_updates times.
*/
sprite_move_toggle_action(sprite_ptr&& sprite, int duration_updates, const fixed_point& new_position) :
toggle_value_template_action(move(sprite), duration_updates, new_position)
{
}
/**
* @brief Returns the sprite_ptr to modify.
*/
[[nodiscard]] const sprite_ptr& sprite() const
{
return value();
}
/**
* @brief Returns the position of the given sprite_ptr when the action is updated the given number of times.
*/
[[nodiscard]] const fixed_point& new_position() const
{
return new_property();
}
};
// rotation
/**
* @brief Manages the rotation angle of a sprite_ptr.
*
* @ingroup sprite
* @ingroup action
*/
class sprite_rotation_manager
{
public:
/**
* @brief Returns the rotation angle of the given sprite_ptr.
*/
[[nodiscard]] static fixed get(const sprite_ptr& sprite)
{
return sprite.rotation_angle();
}
/**
* @brief Sets the rotation angle of the given sprite_ptr.
* @param rotation_angle Rotation angle in degrees, in the range [0..360].
* @param sprite sprite_ptr to modify.
*/
static void set(fixed rotation_angle, sprite_ptr& sprite)
{
sprite.set_rotation_angle(rotation_angle);
}
};
/**
* @brief Modifies the rotation angle of a sprite_ptr by delta_rotation_angle.
* When the rotation angle is over 360, it goes back to 0 and vice versa.
*
* @ingroup sprite
* @ingroup action
*/
class sprite_rotate_by_action : public cyclic_by_value_template_action<sprite_ptr, fixed, sprite_rotation_manager>
{
public:
/**
* @brief Constructor.
* @param sprite sprite_ptr to copy.
* @param delta_rotation_angle How much degrees to add to the rotation angle of the given sprite_ptr
* when the action is updated.
*
* This rotation angle must be in the range [0..360].
*/
sprite_rotate_by_action(const sprite_ptr& sprite, fixed delta_rotation_angle) :
cyclic_by_value_template_action(sprite, delta_rotation_angle, 0, 360)
{
BN_ASSERT(delta_rotation_angle > -360 && delta_rotation_angle < 360,
"Invalid delta rotation angle: ", delta_rotation_angle);
}
/**
* @brief Constructor.
* @param sprite sprite_ptr to move.
* @param delta_rotation_angle How much degrees to add to the rotation angle of the given sprite_ptr
* when the action is updated.
*
* This rotation angle must be in the range [0..360].
*/
sprite_rotate_by_action(sprite_ptr&& sprite, fixed delta_rotation_angle) :
cyclic_by_value_template_action(move(sprite), delta_rotation_angle, 0, 360)
{
BN_ASSERT(delta_rotation_angle > -360 && delta_rotation_angle < 360,
"Invalid delta rotation angle: ", delta_rotation_angle);
}
/**
* @brief Returns the sprite_ptr to modify.
*/
[[nodiscard]] const sprite_ptr& sprite() const
{
return value();
}
/**
* @brief Returns how much degrees to add to the rotation angle of the given sprite_ptr
* when the action is updated.
*/
[[nodiscard]] fixed delta_rotation_angle() const
{
return delta_property();
}
};
/**
* @brief Modifies the rotation angle of a sprite_ptr until it has a given state.
*
* @ingroup sprite
* @ingroup action
*/
class sprite_rotate_to_action : public to_value_template_action<sprite_ptr, fixed, sprite_rotation_manager>
{
public:
/**
* @brief Constructor.
* @param sprite sprite_ptr to copy.
* @param duration_updates Number of times that the action must be updated
* until the rotation angle of the given sprite_ptr is equal to final_rotation_angle.
* @param final_rotation_angle Rotation angle when the action is updated duration_updates times.
*
* This rotation angle must be in the range [0..360].
*/
sprite_rotate_to_action(const sprite_ptr& sprite, int duration_updates, fixed final_rotation_angle) :
to_value_template_action(sprite, duration_updates, final_rotation_angle)
{
BN_ASSERT(final_rotation_angle >= 0 && final_rotation_angle <= 360,
"Invalid final rotation angle: ", final_rotation_angle);
}
/**
* @brief Constructor.
* @param sprite sprite_ptr to move.
* @param duration_updates Number of times that the action must be updated
* until the rotation angle of the given sprite_ptr is equal to final_rotation_angle.
* @param final_rotation_angle Rotation angle when the action is updated duration_updates times.
*
* This rotation angle must be in the range [0..360].
*/
sprite_rotate_to_action(sprite_ptr&& sprite, int duration_updates, fixed final_rotation_angle) :
to_value_template_action(move(sprite), duration_updates, final_rotation_angle)
{
BN_ASSERT(final_rotation_angle >= 0 && final_rotation_angle <= 360,
"Invalid final rotation angle: ", final_rotation_angle);
}
/**
* @brief Returns the sprite_ptr to modify.
*/
[[nodiscard]] const sprite_ptr& sprite() const
{
return value();
}
/**
* @brief Returns the rotation angle of the given sprite_ptr
* when the action is updated the given number of times.
*/
[[nodiscard]] fixed final_rotation_angle() const
{
return final_property();
}
};
/**
* @brief Modifies the rotation angle of a sprite_ptr from a minimum to a maximum.
* When the rotation angle is equal to the given final state, it goes back to its initial state and vice versa.
*
* @ingroup sprite
* @ingroup action
*/
class sprite_rotate_loop_action : public loop_value_template_action<sprite_ptr, fixed, sprite_rotation_manager>
{
public:
/**
* @brief Constructor.
* @param sprite sprite_ptr to copy.
* @param duration_updates How much times the action has to be updated
* before changing the direction of the rotation angle delta.
* @param final_rotation_angle When the rotation angle of the given sprite_ptr
* is equal to this parameter, it goes back to its initial state and vice versa.
*
* This rotation angle must be in the range [0..360].
*/
sprite_rotate_loop_action(const sprite_ptr& sprite, int duration_updates, fixed final_rotation_angle) :
loop_value_template_action(sprite, duration_updates, final_rotation_angle)
{
BN_ASSERT(final_rotation_angle >= 0 && final_rotation_angle <= 360,
"Invalid final rotation angle: ", final_rotation_angle);
}
/**
* @brief Constructor.
* @param sprite sprite_ptr to move.
* @param duration_updates How much times the action has to be updated
* before changing the direction of the rotation angle delta.
* @param final_rotation_angle When the rotation angle of the given sprite_ptr
* is equal to this parameter, it goes back to its initial state and vice versa.
*
* This rotation angle must be in the range [0..360].
*/
sprite_rotate_loop_action(sprite_ptr&& sprite, int duration_updates, fixed final_rotation_angle) :
loop_value_template_action(move(sprite), duration_updates, final_rotation_angle)
{
BN_ASSERT(final_rotation_angle >= 0 && final_rotation_angle <= 360,
"Invalid final rotation angle: ", final_rotation_angle);
}
/**
* @brief Returns the sprite_ptr to modify.
*/
[[nodiscard]] const sprite_ptr& sprite() const
{
return value();
}
/**
* @brief When the rotation angle of the given sprite_ptr
* is equal to this returned parameter, it goes back to its initial state and vice versa.
*/
[[nodiscard]] fixed final_rotation_angle() const
{
return final_property();
}
};
/**
* @brief Changes the rotation angle of a sprite_ptr when the action is updated a given number of times.
*
* @ingroup sprite
* @ingroup action
*/
class sprite_rotate_toggle_action : public toggle_value_template_action<sprite_ptr, fixed, sprite_rotation_manager>
{
public:
/**
* @brief Constructor.
* @param sprite sprite_ptr to copy.
* @param duration_updates How much times the action has to be updated to change the rotation angle
* of the given sprite_ptr.
* @param new_rotation_angle New rotation angle when the action is updated duration_updates times.
*
* This rotation angle must be in the range [0..360].
*/
sprite_rotate_toggle_action(const sprite_ptr& sprite, int duration_updates, fixed new_rotation_angle) :
toggle_value_template_action(sprite, duration_updates, new_rotation_angle)
{
BN_ASSERT(new_rotation_angle >= 0 && new_rotation_angle <= 360,
"Invalid new rotation angle: ", new_rotation_angle);
}
/**
* @brief Constructor.
* @param sprite sprite_ptr to move.
* @param duration_updates How much times the action has to be updated to change the rotation angle
* of the given sprite_ptr.
* @param new_rotation_angle New rotation angle when the action is updated duration_updates times.
*
* This rotation angle must be in the range [0..360].
*/
sprite_rotate_toggle_action(sprite_ptr&& sprite, int duration_updates, fixed new_rotation_angle) :
toggle_value_template_action(move(sprite), duration_updates, new_rotation_angle)
{
BN_ASSERT(new_rotation_angle >= 0 && new_rotation_angle <= 360,
"Invalid new rotation angle: ", new_rotation_angle);
}
/**
* @brief Returns the sprite_ptr to modify.
*/
[[nodiscard]] const sprite_ptr& sprite() const
{
return value();
}
/**
* @brief Returns the rotation angle of the given sprite_ptr
* when the action is updated the given number of times.
*/
[[nodiscard]] fixed new_rotation_angle() const
{
return new_property();
}
};
// horizontal_scale
/**
* @brief Manages the horizontal scale of a sprite_ptr.
*
* @ingroup sprite
* @ingroup action
*/
class sprite_horizontal_scale_manager
{
public:
/**
* @brief Returns the horizontal scale of the given sprite_ptr.
*/
[[nodiscard]] static fixed get(const sprite_ptr& sprite)
{
return sprite.horizontal_scale();
}
/**
* @brief Sets the horizontal scale of the given sprite_ptr.
*/
static void set(fixed horizontal_scale, sprite_ptr& sprite)
{
sprite.set_horizontal_scale(horizontal_scale);
}
};
/**
* @brief Modifies the horizontal scale of a sprite_ptr until it has a given state.
*
* @ingroup sprite
* @ingroup action
*/
class sprite_horizontal_scale_to_action :
public to_value_template_action<sprite_ptr, fixed, sprite_horizontal_scale_manager>
{
public:
/**
* @brief Constructor.
* @param sprite sprite_ptr to copy.
* @param duration_updates Number of times that the action must be updated
* until the horizontal scale of the given sprite_ptr is equal to final_horizontal_scale.
* @param final_horizontal_scale Horizontal scale when the action is updated duration_updates times.
*/
sprite_horizontal_scale_to_action(const sprite_ptr& sprite, int duration_updates,
fixed final_horizontal_scale) :
to_value_template_action(sprite, duration_updates, final_horizontal_scale)
{
BN_ASSERT(final_horizontal_scale > 0, "Invalid final horizontal scale: ", final_horizontal_scale);
}
/**
* @brief Constructor.
* @param sprite sprite_ptr to move.
* @param duration_updates Number of times that the action must be updated
* until the horizontal scale of the given sprite_ptr is equal to final_horizontal_scale.
* @param final_horizontal_scale Horizontal scale when the action is updated duration_updates times.
*/
sprite_horizontal_scale_to_action(sprite_ptr&& sprite, int duration_updates, fixed final_horizontal_scale) :
to_value_template_action(move(sprite), duration_updates, final_horizontal_scale)
{
BN_ASSERT(final_horizontal_scale > 0, "Invalid final horizontal scale: ", final_horizontal_scale);
}
/**
* @brief Returns the sprite_ptr to modify.
*/
[[nodiscard]] const sprite_ptr& sprite() const
{
return value();
}
/**
* @brief Returns the horizontal scale of the given sprite_ptr
* when the action is updated the given number of times.
*/
[[nodiscard]] fixed final_horizontal_scale() const
{
return final_property();
}
};
/**
* @brief Modifies the horizontal scale of a sprite_ptr from a minimum to a maximum.
* When the horizontal scale is equal to the given final state, it goes back to its initial state and vice versa.
*
* @ingroup sprite
* @ingroup action
*/
class sprite_horizontal_scale_loop_action :
public loop_value_template_action<sprite_ptr, fixed, sprite_horizontal_scale_manager>
{
public:
/**
* @brief Constructor.
* @param sprite sprite_ptr to copy.
* @param duration_updates How much times the action has to be updated
* before changing the direction of the horizontal scale delta.
* @param final_horizontal_scale When the horizontal scale of the given sprite_ptr
* is equal to this parameter, it goes back to its initial state and vice versa.
*/
sprite_horizontal_scale_loop_action(const sprite_ptr& sprite, int duration_updates,
fixed final_horizontal_scale) :
loop_value_template_action(sprite, duration_updates, final_horizontal_scale)
{
BN_ASSERT(final_horizontal_scale > 0, "Invalid final horizontal scale: ", final_horizontal_scale);
}
/**
* @brief Constructor.
* @param sprite sprite_ptr to move.
* @param duration_updates How much times the action has to be updated
* before changing the direction of the horizontal scale delta.
* @param final_horizontal_scale When the horizontal scale of the given sprite_ptr
* is equal to this parameter, it goes back to its initial state and vice versa.
*/
sprite_horizontal_scale_loop_action(sprite_ptr&& sprite, int duration_updates, fixed final_horizontal_scale) :
loop_value_template_action(move(sprite), duration_updates, final_horizontal_scale)
{
BN_ASSERT(final_horizontal_scale > 0, "Invalid final horizontal scale: ", final_horizontal_scale);
}
/**
* @brief Returns the sprite_ptr to modify.
*/
[[nodiscard]] const sprite_ptr& sprite() const
{
return value();
}
/**
* @brief When the horizontal scale of the given sprite_ptr
* is equal to this returned parameter, it goes back to its initial state and vice versa.
*/
[[nodiscard]] fixed final_horizontal_scale() const
{
return final_property();
}
};
/**
* @brief Changes the horizontal scale of a sprite_ptr
* when the action is updated a given number of times.
*
* @ingroup sprite
* @ingroup action
*/
class sprite_horizontal_scale_toggle_action :
public toggle_value_template_action<sprite_ptr, fixed, sprite_horizontal_scale_manager>
{
public:
/**
* @brief Constructor.
* @param sprite sprite_ptr to copy.
* @param duration_updates How much times the action has to be updated to change the horizontal scale
* of the given sprite_ptr.
* @param new_horizontal_scale New horizontal scale when the action is updated duration_updates times.
*/
sprite_horizontal_scale_toggle_action(const sprite_ptr& sprite, int duration_updates,
fixed new_horizontal_scale) :
toggle_value_template_action(sprite, duration_updates, new_horizontal_scale)
{
BN_ASSERT(new_horizontal_scale > 0, "Invalid new horizontal scale: ", new_horizontal_scale);
}
/**
* @brief Constructor.
* @param sprite sprite_ptr to move.
* @param duration_updates How much times the action has to be updated to change the horizontal scale
* of the given sprite_ptr.
* @param new_horizontal_scale New horizontal scale when the action is updated duration_updates times.
*/
sprite_horizontal_scale_toggle_action(sprite_ptr&& sprite, int duration_updates,
fixed new_horizontal_scale) :
toggle_value_template_action(move(sprite), duration_updates, new_horizontal_scale)
{
BN_ASSERT(new_horizontal_scale > 0, "Invalid new horizontal scale: ", new_horizontal_scale);
}
/**
* @brief Returns the sprite_ptr to modify.
*/
[[nodiscard]] const sprite_ptr& sprite() const
{
return value();
}
/**
* @brief Returns the horizontal scale of the given sprite_ptr
* when the action is updated the given number of times.
*/
[[nodiscard]] fixed new_horizontal_scale() const
{
return new_property();
}
};
// vertical_scale
/**
* @brief Manages the vertical scale of a sprite_ptr.
*
* @ingroup sprite
* @ingroup action
*/
class sprite_vertical_scale_manager
{
public:
/**
* @brief Returns the vertical scale of the given sprite_ptr.
*/
[[nodiscard]] static fixed get(const sprite_ptr& sprite)
{
return sprite.vertical_scale();
}
/**
* @brief Sets the vertical scale of the given sprite_ptr.
*/
static void set(fixed vertical_scale, sprite_ptr& sprite)
{
sprite.set_vertical_scale(vertical_scale);
}
};
/**
* @brief Modifies the vertical scale of a sprite_ptr until it has a given state.
*
* @ingroup sprite
* @ingroup action
*/
class sprite_vertical_scale_to_action :
public to_value_template_action<sprite_ptr, fixed, sprite_vertical_scale_manager>
{
public:
/**
* @brief Constructor.
* @param sprite sprite_ptr to copy.
* @param duration_updates Number of times that the action must be updated
* until the vertical scale of the given sprite_ptr is equal to final_vertical_scale.
* @param final_vertical_scale Vertical scale when the action is updated duration_updates times.
*/
sprite_vertical_scale_to_action(const sprite_ptr& sprite, int duration_updates, fixed final_vertical_scale) :
to_value_template_action(sprite, duration_updates, final_vertical_scale)
{
BN_ASSERT(final_vertical_scale > 0, "Invalid final vertical scale: ", final_vertical_scale);
}
/**
* @brief Constructor.
* @param sprite sprite_ptr to move.
* @param duration_updates Number of times that the action must be updated
* until the vertical scale of the given sprite_ptr is equal to final_vertical_scale.
* @param final_vertical_scale Vertical scale when the action is updated duration_updates times.
*/
sprite_vertical_scale_to_action(sprite_ptr&& sprite, int duration_updates, fixed final_vertical_scale) :
to_value_template_action(move(sprite), duration_updates, final_vertical_scale)
{
BN_ASSERT(final_vertical_scale > 0, "Invalid final vertical scale: ", final_vertical_scale);
}
/**
* @brief Returns the sprite_ptr to modify.
*/
[[nodiscard]] const sprite_ptr& sprite() const
{
return value();
}
/**
* @brief Returns the vertical scale of the given sprite_ptr
* when the action is updated the given number of times.
*/
[[nodiscard]] fixed final_vertical_scale() const
{
return final_property();
}
};
/**
* @brief Modifies the vertical scale of a sprite_ptr from a minimum to a maximum.
* When the vertical scale is equal to the given final state, it goes back to its initial state and vice versa.
*
* @ingroup sprite
* @ingroup action
*/
class sprite_vertical_scale_loop_action :
public loop_value_template_action<sprite_ptr, fixed, sprite_vertical_scale_manager>
{
public:
/**
* @brief Constructor.
* @param sprite sprite_ptr to copy.
* @param duration_updates How much times the action has to be updated
* before changing the direction of the vertical scale delta.
* @param final_vertical_scale When the vertical scale of the given sprite_ptr
* is equal to this parameter, it goes back to its initial state and vice versa.
*/
sprite_vertical_scale_loop_action(const sprite_ptr& sprite, int duration_updates, fixed final_vertical_scale) :
loop_value_template_action(sprite, duration_updates, final_vertical_scale)
{
BN_ASSERT(final_vertical_scale > 0, "Invalid final vertical scale: ", final_vertical_scale);
}
/**
* @brief Constructor.
* @param sprite sprite_ptr to move.
* @param duration_updates How much times the action has to be updated
* before changing the direction of the vertical scale delta.
* @param final_vertical_scale When the vertical scale of the given sprite_ptr
* is equal to this parameter, it goes back to its initial state and vice versa.
*/
sprite_vertical_scale_loop_action(sprite_ptr&& sprite, int duration_updates, fixed final_vertical_scale) :
loop_value_template_action(move(sprite), duration_updates, final_vertical_scale)
{
BN_ASSERT(final_vertical_scale > 0, "Invalid final vertical scale: ", final_vertical_scale);
}
/**
* @brief Returns the sprite_ptr to modify.
*/
[[nodiscard]] const sprite_ptr& sprite() const
{
return value();
}
/**
* @brief When the vertical scale of the given sprite_ptr
* is equal to this returned parameter, it goes back to its initial state and vice versa.
*/
[[nodiscard]] fixed final_vertical_scale() const
{
return final_property();
}
};
/**
* @brief Changes the vertical scale of a sprite_ptr
* when the action is updated a given number of times.
*
* @ingroup sprite
* @ingroup action
*/
class sprite_vertical_scale_toggle_action :
public toggle_value_template_action<sprite_ptr, fixed, sprite_vertical_scale_manager>
{
public:
/**
* @brief Constructor.
* @param sprite sprite_ptr to copy.
* @param duration_updates How much times the action has to be updated to change the vertical scale
* of the given sprite_ptr.
* @param new_vertical_scale New vertical scale when the action is updated duration_updates times.
*/
sprite_vertical_scale_toggle_action(const sprite_ptr& sprite, int duration_updates, fixed new_vertical_scale) :
toggle_value_template_action(sprite, duration_updates, new_vertical_scale)
{
BN_ASSERT(new_vertical_scale > 0, "Invalid new vertical scale: ", new_vertical_scale);
}
/**
* @brief Constructor.
* @param sprite sprite_ptr to move.
* @param duration_updates How much times the action has to be updated to change the vertical scale
* of the given sprite_ptr.
* @param new_vertical_scale New vertical scale when the action is updated duration_updates times.
*/
sprite_vertical_scale_toggle_action(sprite_ptr&& sprite, int duration_updates, fixed new_vertical_scale) :
toggle_value_template_action(move(sprite), duration_updates, new_vertical_scale)
{
BN_ASSERT(new_vertical_scale > 0, "Invalid new vertical scale: ", new_vertical_scale);
}
/**
* @brief Returns the sprite_ptr to modify.
*/
[[nodiscard]] const sprite_ptr& sprite() const
{
return value();
}
/**
* @brief Returns the vertical scale of the given sprite_ptr
* when the action is updated the given number of times.
*/
[[nodiscard]] fixed new_vertical_scale() const
{
return new_property();
}
};
// scale
/**
* @brief Manages the scale of a sprite_ptr.
*
* @ingroup sprite
* @ingroup action
*/
class sprite_scale_manager
{
public:
/**
* @brief Returns the horizontal scale of the given sprite_ptr.
*/
[[nodiscard]] static fixed get(const sprite_ptr& sprite)
{
return sprite.horizontal_scale();
}
/**
* @brief Sets the scale of the given sprite_ptr.
*/
static void set(fixed scale, sprite_ptr& sprite)
{
sprite.set_scale(scale);
}
};
/**
* @brief Modifies the scale of a sprite_ptr until it has a given state.
*
* @ingroup sprite
* @ingroup action
*/
class sprite_scale_to_action : public to_value_template_action<sprite_ptr, fixed, sprite_scale_manager>
{
public:
/**
* @brief Constructor.
* @param sprite sprite_ptr to copy.
* @param duration_updates Number of times that the action must be updated
* until the scale of the given sprite_ptr is equal to final_scale.
* @param final_scale Scale when the action is updated duration_updates times.
*/
sprite_scale_to_action(const sprite_ptr& sprite, int duration_updates, fixed final_scale) :
to_value_template_action(sprite, duration_updates, final_scale)
{
BN_ASSERT(final_scale > 0, "Invalid final scale: ", final_scale);
}
/**
* @brief Constructor.
* @param sprite sprite_ptr to move.
* @param duration_updates Number of times that the action must be updated
* until the scale of the given sprite_ptr is equal to final_scale.
* @param final_scale Scale when the action is updated duration_updates times.
*/
sprite_scale_to_action(sprite_ptr&& sprite, int duration_updates, fixed final_scale) :
to_value_template_action(move(sprite), duration_updates, final_scale)
{
BN_ASSERT(final_scale > 0, "Invalid final scale: ", final_scale);
}
/**
* @brief Returns the sprite_ptr to modify.
*/
[[nodiscard]] const sprite_ptr& sprite() const
{
return value();
}
/**
* @brief Returns the scale of the given sprite_ptr
* when the action is updated the given number of times.
*/
[[nodiscard]] fixed final_scale() const
{
return final_property();
}
};
/**
* @brief Modifies the scale of a sprite_ptr from a minimum to a maximum.
* When the scale is equal to the given final state, it goes back to its initial state and vice versa.
*
* @ingroup sprite
* @ingroup action
*/
class sprite_scale_loop_action : public loop_value_template_action<sprite_ptr, fixed, sprite_scale_manager>
{
public:
/**
* @brief Constructor.
* @param sprite sprite_ptr to copy.
* @param duration_updates How much times the action has to be updated
* before changing the direction of the scale delta.
* @param final_scale When the scale of the given sprite_ptr
* is equal to this parameter, it goes back to its initial state and vice versa.
*/
sprite_scale_loop_action(const sprite_ptr& sprite, int duration_updates, fixed final_scale) :
loop_value_template_action(sprite, duration_updates, final_scale)
{
BN_ASSERT(final_scale > 0, "Invalid final scale: ", final_scale);
}
/**
* @brief Constructor.
* @param sprite sprite_ptr to move.
* @param duration_updates How much times the action has to be updated
* before changing the direction of the scale delta.
* @param final_scale When the scale of the given sprite_ptr
* is equal to this parameter, it goes back to its initial state and vice versa.
*/
sprite_scale_loop_action(sprite_ptr&& sprite, int duration_updates, fixed final_scale) :
loop_value_template_action(move(sprite), duration_updates, final_scale)
{
BN_ASSERT(final_scale > 0, "Invalid final scale: ", final_scale);
}
/**
* @brief Returns the sprite_ptr to modify.
*/
[[nodiscard]] const sprite_ptr& sprite() const
{
return value();
}
/**
* @brief When the scale of the given sprite_ptr
* is equal to this returned parameter, it goes back to its initial state and vice versa.
*/
[[nodiscard]] fixed final_scale() const
{
return final_property();
}
};
/**
* @brief Changes the scale of a sprite_ptr
* when the action is updated a given number of times.
*
* @ingroup sprite
* @ingroup action
*/
class sprite_scale_toggle_action : public toggle_value_template_action<sprite_ptr, fixed, sprite_scale_manager>
{
public:
/**
* @brief Constructor.
* @param sprite sprite_ptr to copy.
* @param duration_updates How much times the action has to be updated to change the scale
* of the given sprite_ptr.
* @param new_scale New scale when the action is updated duration_updates times.
*/
sprite_scale_toggle_action(const sprite_ptr& sprite, int duration_updates, fixed new_scale) :
toggle_value_template_action(sprite, duration_updates, new_scale)
{
BN_ASSERT(new_scale > 0, "Invalid new scale: ", new_scale);
}
/**
* @brief Constructor.
* @param sprite sprite_ptr to move.
* @param duration_updates How much times the action has to be updated to change the scale
* of the given sprite_ptr.
* @param new_scale New scale when the action is updated duration_updates times.
*/
sprite_scale_toggle_action(sprite_ptr&& sprite, int duration_updates, fixed new_scale) :
toggle_value_template_action(move(sprite), duration_updates, new_scale)
{
BN_ASSERT(new_scale > 0, "Invalid new scale: ", new_scale);
}
/**
* @brief Returns the sprite_ptr to modify.
*/
[[nodiscard]] const sprite_ptr& sprite() const
{
return value();
}
/**
* @brief Returns the scale of the given sprite_ptr
* when the action is updated the given number of times.
*/
[[nodiscard]] fixed new_scale() const
{
return new_property();
}
};
// horizontal_shear
/**
* @brief Manages the horizontal shear of a sprite_ptr.
*
* @ingroup sprite
* @ingroup action
*/
class sprite_horizontal_shear_manager
{
public:
/**
* @brief Returns the horizontal shear of the given sprite_ptr.
*/
[[nodiscard]] static fixed get(const sprite_ptr& sprite)
{
return sprite.horizontal_shear();
}
/**
* @brief Sets the horizontal shear of the given sprite_ptr.
*/
static void set(fixed horizontal_shear, sprite_ptr& sprite)
{
sprite.set_horizontal_shear(horizontal_shear);
}
};
/**
* @brief Modifies the horizontal shear of a sprite_ptr until it has a given state.
*
* @ingroup sprite
* @ingroup action
*/
class sprite_horizontal_shear_to_action :
public to_value_template_action<sprite_ptr, fixed, sprite_horizontal_shear_manager>
{
public:
/**
* @brief Constructor.
* @param sprite sprite_ptr to copy.
* @param duration_updates Number of times that the action must be updated
* until the horizontal shear of the given sprite_ptr is equal to final_horizontal_shear.
* @param final_horizontal_shear Horizontal shear when the action is updated duration_updates times.
*/
sprite_horizontal_shear_to_action(const sprite_ptr& sprite, int duration_updates,
fixed final_horizontal_shear) :
to_value_template_action(sprite, duration_updates, final_horizontal_shear)
{
}
/**
* @brief Constructor.
* @param sprite sprite_ptr to move.
* @param duration_updates Number of times that the action must be updated
* until the horizontal shear of the given sprite_ptr is equal to final_horizontal_shear.
* @param final_horizontal_shear Horizontal shear when the action is updated duration_updates times.
*/
sprite_horizontal_shear_to_action(sprite_ptr&& sprite, int duration_updates, fixed final_horizontal_shear) :
to_value_template_action(move(sprite), duration_updates, final_horizontal_shear)
{
}
/**
* @brief Returns the sprite_ptr to modify.
*/
[[nodiscard]] const sprite_ptr& sprite() const
{
return value();
}
/**
* @brief Returns the horizontal shear of the given sprite_ptr
* when the action is updated the given number of times.
*/
[[nodiscard]] fixed final_horizontal_shear() const
{
return final_property();
}
};
/**
* @brief Modifies the horizontal shear of a sprite_ptr from a minimum to a maximum.
* When the horizontal shear is equal to the given final state, it goes back to its initial state and vice versa.
*
* @ingroup sprite
* @ingroup action
*/
class sprite_horizontal_shear_loop_action :
public loop_value_template_action<sprite_ptr, fixed, sprite_horizontal_shear_manager>
{
public:
/**
* @brief Constructor.
* @param sprite sprite_ptr to copy.
* @param duration_updates How much times the action has to be updated
* before changing the direction of the horizontal shear delta.
* @param final_horizontal_shear When the horizontal shear of the given sprite_ptr
* is equal to this parameter, it goes back to its initial state and vice versa.
*/
sprite_horizontal_shear_loop_action(const sprite_ptr& sprite, int duration_updates,
fixed final_horizontal_shear) :
loop_value_template_action(sprite, duration_updates, final_horizontal_shear)
{
}
/**
* @brief Constructor.
* @param sprite sprite_ptr to move.
* @param duration_updates How much times the action has to be updated
* before changing the direction of the horizontal shear delta.
* @param final_horizontal_shear When the horizontal shear of the given sprite_ptr
* is equal to this parameter, it goes back to its initial state and vice versa.
*/
sprite_horizontal_shear_loop_action(sprite_ptr&& sprite, int duration_updates, fixed final_horizontal_shear) :
loop_value_template_action(move(sprite), duration_updates, final_horizontal_shear)
{
}
/**
* @brief Returns the sprite_ptr to modify.
*/
[[nodiscard]] const sprite_ptr& sprite() const
{
return value();
}
/**
* @brief When the horizontal shear of the given sprite_ptr
* is equal to this returned parameter, it goes back to its initial state and vice versa.
*/
[[nodiscard]] fixed final_horizontal_shear() const
{
return final_property();
}
};
/**
* @brief Changes the horizontal shear of a sprite_ptr
* when the action is updated a given number of times.
*
* @ingroup sprite
* @ingroup action
*/
class sprite_horizontal_shear_toggle_action :
public toggle_value_template_action<sprite_ptr, fixed, sprite_horizontal_shear_manager>
{
public:
/**
* @brief Constructor.
* @param sprite sprite_ptr to copy.
* @param duration_updates How much times the action has to be updated to change the horizontal shear
* of the given sprite_ptr.
* @param new_horizontal_shear New horizontal shear when the action is updated duration_updates times.
*/
sprite_horizontal_shear_toggle_action(const sprite_ptr& sprite, int duration_updates,
fixed new_horizontal_shear) :
toggle_value_template_action(sprite, duration_updates, new_horizontal_shear)
{
}
/**
* @brief Constructor.
* @param sprite sprite_ptr to move.
* @param duration_updates How much times the action has to be updated to change the horizontal shear
* of the given sprite_ptr.
* @param new_horizontal_shear New horizontal shear when the action is updated duration_updates times.
*/
sprite_horizontal_shear_toggle_action(sprite_ptr&& sprite, int duration_updates,
fixed new_horizontal_shear) :
toggle_value_template_action(move(sprite), duration_updates, new_horizontal_shear)
{
}
/**
* @brief Returns the sprite_ptr to modify.
*/
[[nodiscard]] const sprite_ptr& sprite() const
{
return value();
}
/**
* @brief Returns the horizontal shear of the given sprite_ptr
* when the action is updated the given number of times.
*/
[[nodiscard]] fixed new_horizontal_shear() const
{
return new_property();
}
};
// vertical_shear
/**
* @brief Manages the vertical shear of a sprite_ptr.
*
* @ingroup sprite
* @ingroup action
*/
class sprite_vertical_shear_manager
{
public:
/**
* @brief Returns the vertical shear of the given sprite_ptr.
*/
[[nodiscard]] static fixed get(const sprite_ptr& sprite)
{
return sprite.vertical_shear();
}
/**
* @brief Sets the vertical shear of the given sprite_ptr.
*/
static void set(fixed vertical_shear, sprite_ptr& sprite)
{
sprite.set_vertical_shear(vertical_shear);
}
};
/**
* @brief Modifies the vertical shear of a sprite_ptr until it has a given state.
*
* @ingroup sprite
* @ingroup action
*/
class sprite_vertical_shear_to_action :
public to_value_template_action<sprite_ptr, fixed, sprite_vertical_shear_manager>
{
public:
/**
* @brief Constructor.
* @param sprite sprite_ptr to copy.
* @param duration_updates Number of times that the action must be updated
* until the vertical shear of the given sprite_ptr is equal to final_vertical_shear.
* @param final_vertical_shear Vertical shear when the action is updated duration_updates times.
*/
sprite_vertical_shear_to_action(const sprite_ptr& sprite, int duration_updates, fixed final_vertical_shear) :
to_value_template_action(sprite, duration_updates, final_vertical_shear)
{
}
/**
* @brief Constructor.
* @param sprite sprite_ptr to move.
* @param duration_updates Number of times that the action must be updated
* until the vertical shear of the given sprite_ptr is equal to final_vertical_shear.
* @param final_vertical_shear Vertical shear when the action is updated duration_updates times.
*/
sprite_vertical_shear_to_action(sprite_ptr&& sprite, int duration_updates, fixed final_vertical_shear) :
to_value_template_action(move(sprite), duration_updates, final_vertical_shear)
{
}
/**
* @brief Returns the sprite_ptr to modify.
*/
[[nodiscard]] const sprite_ptr& sprite() const
{
return value();
}
/**
* @brief Returns the vertical shear of the given sprite_ptr
* when the action is updated the given number of times.
*/
[[nodiscard]] fixed final_vertical_shear() const
{
return final_property();
}
};
/**
* @brief Modifies the vertical shear of a sprite_ptr from a minimum to a maximum.
* When the vertical shear is equal to the given final state, it goes back to its initial state and vice versa.
*
* @ingroup sprite
* @ingroup action
*/
class sprite_vertical_shear_loop_action :
public loop_value_template_action<sprite_ptr, fixed, sprite_vertical_shear_manager>
{
public:
/**
* @brief Constructor.
* @param sprite sprite_ptr to copy.
* @param duration_updates How much times the action has to be updated
* before changing the direction of the vertical shear delta.
* @param final_vertical_shear When the vertical shear of the given sprite_ptr
* is equal to this parameter, it goes back to its initial state and vice versa.
*/
sprite_vertical_shear_loop_action(const sprite_ptr& sprite, int duration_updates, fixed final_vertical_shear) :
loop_value_template_action(sprite, duration_updates, final_vertical_shear)
{
}
/**
* @brief Constructor.
* @param sprite sprite_ptr to move.
* @param duration_updates How much times the action has to be updated
* before changing the direction of the vertical shear delta.
* @param final_vertical_shear When the vertical shear of the given sprite_ptr
* is equal to this parameter, it goes back to its initial state and vice versa.
*/
sprite_vertical_shear_loop_action(sprite_ptr&& sprite, int duration_updates, fixed final_vertical_shear) :
loop_value_template_action(move(sprite), duration_updates, final_vertical_shear)
{
}
/**
* @brief Returns the sprite_ptr to modify.
*/
[[nodiscard]] const sprite_ptr& sprite() const
{
return value();
}
/**
* @brief When the vertical shear of the given sprite_ptr
* is equal to this returned parameter, it goes back to its initial state and vice versa.
*/
[[nodiscard]] fixed final_vertical_shear() const
{
return final_property();
}
};
/**
* @brief Changes the vertical shear of a sprite_ptr
* when the action is updated a given number of times.
*
* @ingroup sprite
* @ingroup action
*/
class sprite_vertical_shear_toggle_action :
public toggle_value_template_action<sprite_ptr, fixed, sprite_vertical_shear_manager>
{
public:
/**
* @brief Constructor.
* @param sprite sprite_ptr to copy.
* @param duration_updates How much times the action has to be updated to change the vertical shear
* of the given sprite_ptr.
* @param new_vertical_shear New vertical shear when the action is updated duration_updates times.
*/
sprite_vertical_shear_toggle_action(const sprite_ptr& sprite, int duration_updates, fixed new_vertical_shear) :
toggle_value_template_action(sprite, duration_updates, new_vertical_shear)
{
}
/**
* @brief Constructor.
* @param sprite sprite_ptr to move.
* @param duration_updates How much times the action has to be updated to change the vertical shear
* of the given sprite_ptr.
* @param new_vertical_shear New vertical shear when the action is updated duration_updates times.
*/
sprite_vertical_shear_toggle_action(sprite_ptr&& sprite, int duration_updates, fixed new_vertical_shear) :
toggle_value_template_action(move(sprite), duration_updates, new_vertical_shear)
{
}
/**
* @brief Returns the sprite_ptr to modify.
*/
[[nodiscard]] const sprite_ptr& sprite() const
{
return value();
}
/**
* @brief Returns the vertical shear of the given sprite_ptr
* when the action is updated the given number of times.
*/
[[nodiscard]] fixed new_vertical_shear() const
{
return new_property();
}
};
// shear
/**
* @brief Manages the shear of a sprite_ptr.
*
* @ingroup sprite
* @ingroup action
*/
class sprite_shear_manager
{
public:
/**
* @brief Returns the horizontal shear of the given sprite_ptr.
*/
[[nodiscard]] static fixed get(const sprite_ptr& sprite)
{
return sprite.horizontal_shear();
}
/**
* @brief Sets the shear of the given sprite_ptr.
*/
static void set(fixed shear, sprite_ptr& sprite)
{
sprite.set_shear(shear);
}
};
/**
* @brief Modifies the shear of a sprite_ptr until it has a given state.
*
* @ingroup sprite
* @ingroup action
*/
class sprite_shear_to_action : public to_value_template_action<sprite_ptr, fixed, sprite_shear_manager>
{
public:
/**
* @brief Constructor.
* @param sprite sprite_ptr to copy.
* @param duration_updates Number of times that the action must be updated
* until the shear of the given sprite_ptr is equal to final_shear.
* @param final_shear Shear when the action is updated duration_updates times.
*/
sprite_shear_to_action(const sprite_ptr& sprite, int duration_updates, fixed final_shear) :
to_value_template_action(sprite, duration_updates, final_shear)
{
}
/**
* @brief Constructor.
* @param sprite sprite_ptr to move.
* @param duration_updates Number of times that the action must be updated
* until the shear of the given sprite_ptr is equal to final_shear.
* @param final_shear Shear when the action is updated duration_updates times.
*/
sprite_shear_to_action(sprite_ptr&& sprite, int duration_updates, fixed final_shear) :
to_value_template_action(move(sprite), duration_updates, final_shear)
{
}
/**
* @brief Returns the sprite_ptr to modify.
*/
[[nodiscard]] const sprite_ptr& sprite() const
{
return value();
}
/**
* @brief Returns the shear of the given sprite_ptr
* when the action is updated the given number of times.
*/
[[nodiscard]] fixed final_shear() const
{
return final_property();
}
};
/**
* @brief Modifies the shear of a sprite_ptr from a minimum to a maximum.
* When the shear is equal to the given final state, it goes back to its initial state and vice versa.
*
* @ingroup sprite
* @ingroup action
*/
class sprite_shear_loop_action : public loop_value_template_action<sprite_ptr, fixed, sprite_shear_manager>
{
public:
/**
* @brief Constructor.
* @param sprite sprite_ptr to copy.
* @param duration_updates How much times the action has to be updated
* before changing the direction of the shear delta.
* @param final_shear When the shear of the given sprite_ptr
* is equal to this parameter, it goes back to its initial state and vice versa.
*/
sprite_shear_loop_action(const sprite_ptr& sprite, int duration_updates, fixed final_shear) :
loop_value_template_action(sprite, duration_updates, final_shear)
{
}
/**
* @brief Constructor.
* @param sprite sprite_ptr to move.
* @param duration_updates How much times the action has to be updated
* before changing the direction of the shear delta.
* @param final_shear When the shear of the given sprite_ptr
* is equal to this parameter, it goes back to its initial state and vice versa.
*/
sprite_shear_loop_action(sprite_ptr&& sprite, int duration_updates, fixed final_shear) :
loop_value_template_action(move(sprite), duration_updates, final_shear)
{
}
/**
* @brief Returns the sprite_ptr to modify.
*/
[[nodiscard]] const sprite_ptr& sprite() const
{
return value();
}
/**
* @brief When the shear of the given sprite_ptr
* is equal to this returned parameter, it goes back to its initial state and vice versa.
*/
[[nodiscard]] fixed final_shear() const
{
return final_property();
}
};
/**
* @brief Changes the shear of a sprite_ptr
* when the action is updated a given number of times.
*
* @ingroup sprite
* @ingroup action
*/
class sprite_shear_toggle_action : public toggle_value_template_action<sprite_ptr, fixed, sprite_shear_manager>
{
public:
/**
* @brief Constructor.
* @param sprite sprite_ptr to copy.
* @param duration_updates How much times the action has to be updated to change the shear
* of the given sprite_ptr.
* @param new_shear New shear when the action is updated duration_updates times.
*/
sprite_shear_toggle_action(const sprite_ptr& sprite, int duration_updates, fixed new_shear) :
toggle_value_template_action(sprite, duration_updates, new_shear)
{
}
/**
* @brief Constructor.
* @param sprite sprite_ptr to move.
* @param duration_updates How much times the action has to be updated to change the shear
* of the given sprite_ptr.
* @param new_shear New shear when the action is updated duration_updates times.
*/
sprite_shear_toggle_action(sprite_ptr&& sprite, int duration_updates, fixed new_shear) :
toggle_value_template_action(move(sprite), duration_updates, new_shear)
{
}
/**
* @brief Returns the sprite_ptr to modify.
*/
[[nodiscard]] const sprite_ptr& sprite() const
{
return value();
}
/**
* @brief Returns the shear of the given sprite_ptr
* when the action is updated the given number of times.
*/
[[nodiscard]] fixed new_shear() const
{
return new_property();
}
};
// horizontal_flip
/**
* @brief Manages if a sprite_ptr is flipped in its horizontal axis or not.
*
* @ingroup sprite
* @ingroup action
*/
class sprite_horizontal_flip_manager
{
public:
/**
* @brief Indicates if the given sprite_ptr is flipped in the horizontal axis or not.
*/
[[nodiscard]] static bool get(const sprite_ptr& sprite)
{
return sprite.horizontal_flip();
}
/**
* @brief Sets if the given sprite_ptr must be flipped in the horizontal axis or not.
*/
static void set(bool horizontal_flip, sprite_ptr& sprite)
{
sprite.set_horizontal_flip(horizontal_flip);
}
};
/**
* @brief Toggles if a sprite_ptr must be flipped in the horizontal axis or not
* when the action is updated a given number of times.
*
* @ingroup sprite
* @ingroup action
*/
class sprite_horizontal_flip_toggle_action :
public bool_toggle_value_template_action<sprite_ptr, sprite_horizontal_flip_manager>
{
public:
/**
* @brief Constructor.
* @param sprite sprite_ptr to copy.
* @param duration_updates How much times the action has to be updated to toggle
* if the given sprite_ptr must be flipped in the horizontal axis or not.
*/
sprite_horizontal_flip_toggle_action(const sprite_ptr& sprite, int duration_updates) :
bool_toggle_value_template_action(sprite, duration_updates)
{
}
/**
* @brief Constructor.
* @param sprite sprite_ptr to move.
* @param duration_updates How much times the action has to be updated to toggle
* if the given sprite_ptr must be flipped in the horizontal axis or not.
*/
sprite_horizontal_flip_toggle_action(sprite_ptr&& sprite, int duration_updates) :
bool_toggle_value_template_action(move(sprite), duration_updates)
{
}
/**
* @brief Returns the sprite_ptr to modify.
*/
[[nodiscard]] const sprite_ptr& sprite() const
{
return value();
}
};
// vertical_flip
/**
* @brief Manages if a sprite_ptr is flipped in its vertical axis or not.
*
* @ingroup sprite
* @ingroup action
*/
class sprite_vertical_flip_manager
{
public:
/**
* @brief Indicates if the given sprite_ptr is flipped in the vertical axis or not.
*/
[[nodiscard]] static bool get(const sprite_ptr& sprite)
{
return sprite.vertical_flip();
}
/**
* @brief Sets if the given sprite_ptr must be flipped in the vertical axis or not.
*/
static void set(bool vertical_flip, sprite_ptr& sprite)
{
sprite.set_vertical_flip(vertical_flip);
}
};
/**
* @brief Toggles if a sprite_ptr must be flipped in the vertical axis or not
* when the action is updated a given number of times.
*
* @ingroup sprite
* @ingroup action
*/
class sprite_vertical_flip_toggle_action :
public bool_toggle_value_template_action<sprite_ptr, sprite_vertical_flip_manager>
{
public:
/**
* @brief Constructor.
* @param sprite sprite_ptr to copy.
* @param duration_updates How much times the action has to be updated to toggle
* if the given sprite_ptr must be flipped in the vertical axis or not.
*/
sprite_vertical_flip_toggle_action(const sprite_ptr& sprite, int duration_updates) :
bool_toggle_value_template_action(sprite, duration_updates)
{
}
/**
* @brief Constructor.
* @param sprite sprite_ptr to move.
* @param duration_updates How much times the action has to be updated to toggle
* if the given sprite_ptr must be flipped in the vertical axis or not.
*/
sprite_vertical_flip_toggle_action(sprite_ptr&& sprite, int duration_updates) :
bool_toggle_value_template_action(move(sprite), duration_updates)
{
}
/**
* @brief Returns the sprite_ptr to modify.
*/
[[nodiscard]] const sprite_ptr& sprite() const
{
return value();
}
};
// mosaic
/**
* @brief Manages if the mosaic effect must be applied to a sprite_ptr or not.
*
* @ingroup sprite
* @ingroup action
*/
class sprite_mosaic_manager
{
public:
/**
* @brief Indicates if the mosaic effect is applied to the given sprite_ptr or not.
*/
[[nodiscard]] static bool get(const sprite_ptr& sprite)
{
return sprite.mosaic_enabled();
}
/**
* @brief Sets if the mosaic effect must be applied to the given sprite_ptr or not.
*/
static void set(bool mosaic_enabled, sprite_ptr& sprite)
{
sprite.set_mosaic_enabled(mosaic_enabled);
}
};
/**
* @brief Toggles if the mosaic effect must be applied to a sprite_ptr or not
* when the action is updated a given number of times.
*
* @ingroup sprite
* @ingroup action
*/
class sprite_mosaic_toggle_action : public bool_toggle_value_template_action<sprite_ptr, sprite_mosaic_manager>
{
public:
/**
* @brief Constructor.
* @param sprite sprite_ptr to copy.
* @param duration_updates How much times the action has to be updated to toggle
* if the mosaic effect must be applied or not.
*/
sprite_mosaic_toggle_action(const sprite_ptr& sprite, int duration_updates) :
bool_toggle_value_template_action(sprite, duration_updates)
{
}
/**
* @brief Constructor.
* @param sprite sprite_ptr to move.
* @param duration_updates How much times the action has to be updated to toggle
* if the mosaic effect must be applied or not.
*/
sprite_mosaic_toggle_action(sprite_ptr&& sprite, int duration_updates) :
bool_toggle_value_template_action(move(sprite), duration_updates)
{
}
/**
* @brief Returns the sprite_ptr to modify.
*/
[[nodiscard]] const sprite_ptr& sprite() const
{
return value();
}
};
// blending
/**
* @brief Manages if blending must be applied to a sprite_ptr or not.
*
* @ingroup sprite
* @ingroup action
*/
class sprite_blending_manager
{
public:
/**
* @brief Indicates if blending is applied to the given sprite_ptr or not.
*/
[[nodiscard]] static bool get(const sprite_ptr& sprite)
{
return sprite.blending_enabled();
}
/**
* @brief Sets if blending must be applied to the given sprite_ptr or not.
*
* Keep in mind that blending and window attributes can't be enabled on a sprite_ptr at the same time.
*/
static void set(bool blending_enabled, sprite_ptr& sprite)
{
sprite.set_blending_enabled(blending_enabled);
}
};
/**
* @brief Toggles if blending must be applied to a sprite_ptr or not
* when the action is updated a given number of times.
*
* @ingroup sprite
* @ingroup action
*/
class sprite_blending_toggle_action : public bool_toggle_value_template_action<sprite_ptr, sprite_blending_manager>
{
public:
/**
* @brief Constructor.
* @param sprite sprite_ptr to copy.
* @param duration_updates How much times the action has to be updated to toggle
* if blending must be applied or not.
*/
sprite_blending_toggle_action(const sprite_ptr& sprite, int duration_updates) :
bool_toggle_value_template_action(sprite, duration_updates)
{
}
/**
* @brief Constructor.
* @param sprite sprite_ptr to move.
* @param duration_updates How much times the action has to be updated to toggle
* if blending must be applied or not.
*/
sprite_blending_toggle_action(sprite_ptr&& sprite, int duration_updates) :
bool_toggle_value_template_action(move(sprite), duration_updates)
{
}
/**
* @brief Returns the sprite_ptr to modify.
*/
[[nodiscard]] const sprite_ptr& sprite() const
{
return value();
}
};
// window
/**
* @brief Manages if a sprite_ptr must be part of the silhouette of the sprite window or not.
*
* @ingroup sprite
* @ingroup action
*/
class sprite_window_manager
{
public:
/**
* @brief Indicates if the given sprite_ptr must be part of the silhouette of the sprite window or not.
*/
[[nodiscard]] static bool get(const sprite_ptr& sprite)
{
return sprite.window_enabled();
}
/**
* @brief Sets if the given sprite_ptr must be part of the silhouette of the sprite window or not.
*
* Keep in mind that blending and window attributes can't be enabled on a sprite_ptr at the same time.
*/
static void set(bool window_enabled, sprite_ptr& sprite)
{
sprite.set_window_enabled(window_enabled);
}
};
/**
* @brief Toggles if a sprite_ptr must be part of the silhouette of the sprite window or not
* when the action is updated a given number of times.
*
* @ingroup sprite
* @ingroup action
*/
class sprite_window_toggle_action : public bool_toggle_value_template_action<sprite_ptr, sprite_window_manager>
{
public:
/**
* @brief Constructor.
* @param sprite sprite_ptr to copy.
* @param duration_updates How much times the action has to be updated to toggle
* if the given sprite_ptr must be part of the silhouette of the sprite window or not.
*/
sprite_window_toggle_action(const sprite_ptr& sprite, int duration_updates) :
bool_toggle_value_template_action(sprite, duration_updates)
{
}
/**
* @brief Constructor.
* @param sprite sprite_ptr to move.
* @param duration_updates How much times the action has to be updated to toggle
* if the given sprite_ptr must be part of the silhouette of the sprite window or not.
*/
sprite_window_toggle_action(sprite_ptr&& sprite, int duration_updates) :
bool_toggle_value_template_action(move(sprite), duration_updates)
{
}
/**
* @brief Returns the sprite_ptr to modify.
*/
[[nodiscard]] const sprite_ptr& sprite() const
{
return value();
}
};
}
#endif
| 25,868 |
2,151 | <reponame>zipated/src
/*
* Copyright (C) 2011 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 com.android.settingslib.bluetooth;
import com.android.settingslib.R;
import android.bluetooth.BluetoothClass;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothProfile;
/**
* OppProfile handles Bluetooth OPP.
*/
final class OppProfile implements LocalBluetoothProfile {
static final String NAME = "OPP";
// Order of this profile in device profiles list
private static final int ORDINAL = 2;
public boolean isConnectable() {
return false;
}
public boolean isAutoConnectable() {
return false;
}
public boolean connect(BluetoothDevice device) {
return false;
}
public boolean disconnect(BluetoothDevice device) {
return false;
}
public int getConnectionStatus(BluetoothDevice device) {
return BluetoothProfile.STATE_DISCONNECTED; // Settings app doesn't handle OPP
}
public boolean isPreferred(BluetoothDevice device) {
return false;
}
public int getPreferred(BluetoothDevice device) {
return BluetoothProfile.PRIORITY_OFF; // Settings app doesn't handle OPP
}
public void setPreferred(BluetoothDevice device, boolean preferred) {
}
public boolean isProfileReady() {
return true;
}
public String toString() {
return NAME;
}
public int getOrdinal() {
return ORDINAL;
}
public int getNameResource(BluetoothDevice device) {
return R.string.bluetooth_profile_opp;
}
public int getSummaryResourceForDevice(BluetoothDevice device) {
return 0; // OPP profile not displayed in UI
}
public int getDrawableResource(BluetoothClass btClass) {
return 0; // no icon for OPP
}
}
| 776 |
407 | <reponame>iuskye/SREWorks
package com.alibaba.tesla.authproxy.service.impl;
import com.alibaba.tesla.authproxy.Constants;
import com.alibaba.tesla.authproxy.lib.exceptions.AuthProxyThirdPartyError;
import com.alibaba.tesla.authproxy.lib.exceptions.PrivateSmsSignatureForbidden;
import com.alibaba.tesla.authproxy.lib.exceptions.PrivateValidationError;
import com.alibaba.tesla.authproxy.model.mapper.ConfigMapper;
import com.alibaba.tesla.authproxy.model.ConfigDO;
import com.alibaba.tesla.authproxy.service.PrivateSmsService;
import com.alibaba.tesla.authproxy.util.LocaleUtil;
import com.alibaba.tesla.authproxy.util.StringUtil;
import com.alibaba.tesla.authproxy.web.output.PrivateSmsConfigResult;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.time.Instant;
import java.util.Arrays;
import java.util.Objects;
import java.util.concurrent.ThreadLocalRandom;
@Service
@Slf4j
public class PrivateSmsServiceImpl implements PrivateSmsService {
@Autowired
private LocaleUtil locale;
@Autowired
private ConfigMapper configMapper;
@Autowired
private OkHttpClient okHttpClient;
private Gson gson = new GsonBuilder().serializeNulls().create();
/**
* 短信网关注册
*
* @param endpoint Endpoint
* @param token Token
*/
@Override
public void register(String endpoint, String token) throws PrivateValidationError {
if (StringUtil.isEmpty(endpoint) && StringUtil.isEmpty(token)) {
ConfigDO endpointConfig = ConfigDO.builder().name(Constants.CONFIG_PRIVATE_SMS_ENDPOINT).value("").build();
ConfigDO tokenConfig = ConfigDO.builder().name(Constants.CONFIG_PRIVATE_SMS_TOKEN).value("").build();
configMapper.save(endpointConfig);
configMapper.save(tokenConfig);
return;
}
if (StringUtil.isEmpty(endpoint) || StringUtil.isEmpty(token)) {
throw new PrivateValidationError("token", locale.msg("private.sms.register_invalid_combination"));
}
ConfigDO endpointConfig = ConfigDO.builder()
.name(Constants.CONFIG_PRIVATE_SMS_ENDPOINT)
.value(endpoint)
.build();
ConfigDO tokenConfig = ConfigDO.builder()
.name(Constants.CONFIG_PRIVATE_SMS_TOKEN)
.value(token)
.build();
configMapper.save(endpointConfig);
configMapper.save(tokenConfig);
}
/**
* 获取当前的 endpoint / token 配置
*
* @return PrivateSmsConfigResult 对象
*/
@Override
public PrivateSmsConfigResult getConfig() {
ConfigDO endpointConfig = configMapper.getByName(Constants.CONFIG_PRIVATE_SMS_ENDPOINT);
ConfigDO tokenConfig = configMapper.getByName(Constants.CONFIG_PRIVATE_SMS_TOKEN);
if (endpointConfig == null || tokenConfig == null) {
return PrivateSmsConfigResult.builder().endpoint("").token("").build();
}
return PrivateSmsConfigResult.builder()
.endpoint(endpointConfig.getValue())
.token(tokenConfig.getValue())
.build();
}
/**
* 向指定 phone 发送指定 content
* @param phone 手机号码
* @param content 内容
*/
@Override
public void sendMessage(String phone, String aliyunId, String code, String content) throws
AuthProxyThirdPartyError {
ConfigDO endpointConfig = configMapper.getByName(Constants.CONFIG_PRIVATE_SMS_ENDPOINT);
ConfigDO tokenConfig = configMapper.getByName(Constants.CONFIG_PRIVATE_SMS_TOKEN);
if (endpointConfig == null || tokenConfig == null) {
log.info("No sms gateway configured, skip");
return;
}
String endpoint = endpointConfig.getValue();
String token = tokenConfig.getValue();
Long timestamp = getTimestamp();
Integer nonce = getNonce();
String signature = buildSignature(token, String.valueOf(timestamp), String.valueOf(nonce));
HttpUrl.Builder urlBuilder = Objects.requireNonNull(HttpUrl.parse(endpoint)).newBuilder();
String jsonBody = gson.toJson(SmsContent.builder()
.phone(phone)
.aliyunId(aliyunId)
.code(code)
.content(content)
.signature(signature)
.timestamp(timestamp)
.nonce(nonce)
.timestamp(timestamp)
.build());
try {
postRequest(urlBuilder.build(), jsonBody);
} catch (Exception e) {
throw new AuthProxyThirdPartyError(Constants.THIRD_PARTY_SMS, locale.msg("private.sms.check_failed",
e.getMessage()));
}
}
/**
* 检查 endpoint 和 token 是否合法
*
* @param endpoint Endpoint
* @param token Token
* @throws AuthProxyThirdPartyError 当第三方系统出错时抛出
* @throws PrivateSmsSignatureForbidden 当签名不合法时抛出
*/
public void checkEndpoint(String endpoint, String token) throws AuthProxyThirdPartyError,
PrivateSmsSignatureForbidden, PrivateValidationError {
String timestamp = String.valueOf(getTimestamp());
String nonce = String.valueOf(getNonce());
String signature = buildSignature(token, timestamp, nonce);
HttpUrl url = HttpUrl.parse(endpoint);
if (url == null) {
throw new PrivateValidationError("endpoint", locale.msg("private.sms.endpoint_not_url"));
}
// 进行正确签名检查
HttpUrl.Builder urlBuilder = url.newBuilder();
urlBuilder.addQueryParameter("timestamp", timestamp);
urlBuilder.addQueryParameter("nonce", nonce);
urlBuilder.addQueryParameter("signature", signature);
try {
getRequest(urlBuilder.build());
} catch (IOException e) {
throw new AuthProxyThirdPartyError(Constants.THIRD_PARTY_SMS, locale.msg("private.sms.check_failed",
e.getMessage()));
}
// 进行错误签名检查
urlBuilder = url.newBuilder();
urlBuilder.addQueryParameter("timestamp", String.valueOf(getTimestamp()));
urlBuilder.addQueryParameter("nonce", String.valueOf(getNonce()));
urlBuilder.addQueryParameter("signature", signature);
try {
getRequest(urlBuilder.build());
} catch (IOException e) {
throw new AuthProxyThirdPartyError(Constants.THIRD_PARTY_SMS, locale.msg("private.sms.check_failed",
e.getMessage()));
} catch (PrivateSmsSignatureForbidden e) {
return;
}
throw new PrivateValidationError("endpoint", locale.msg("private.sms.register_check_invalid_signature_failed"));
}
/**
* 根据 token / timestamp / nonce 来构造对应的签名
*
* @param token Token
* @param timestamp Timestamp UNIX 时间戳
* @param nonce Nonce
* @return 计算出来的签名
*/
private String buildSignature(String token, String timestamp, String nonce) {
String[] arr = new String[]{token, timestamp, nonce};
Arrays.sort(arr);
StringBuilder arrStr = new StringBuilder();
for (String item : arr) {
arrStr.append(item);
}
return DigestUtils.sha1Hex(arrStr.toString());
}
/**
* 获取当前系统时间的 UNIX Timestamp 形式
*
* @return long
*/
private long getTimestamp() {
return Instant.now().getEpochSecond();
}
/**
* 获取一个随机数 nonce
*
* @return 位于 10000 ~ 99999 之间的数字
*/
private Integer getNonce() {
return ThreadLocalRandom.current().nextInt(10000, 100000);
}
/**
* 向指定 URL 发送 POST 数据
*
* @param url URL 地址
* @param body 表单数据 JSON
* @return 响应内容
*/
private void postRequest(HttpUrl url, String body) throws IOException, PrivateSmsSignatureForbidden {
RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), body);
request(new Request.Builder().url(url).post(requestBody).build());
}
/**
* 向指定 URL 发送 GET 数据
*
* @param url URL 地址
* * @return 响应内容
*/
private void getRequest(HttpUrl url) throws IOException, PrivateSmsSignatureForbidden {
request(new Request.Builder().url(url).get().build());
}
/**
* 发送 request 请求
*/
private void request(Request request) throws IOException, PrivateSmsSignatureForbidden {
Response response;
response = okHttpClient.newCall(request).execute();
int responseCode = response.code();
log.debug("[SmsService] request={}", request.toString());
response.close();
// 检查返回结果并进行处理
if (responseCode == 403) {
throw new PrivateSmsSignatureForbidden();
} else if (responseCode != 200) {
throw new IOException(String.format("Illegal response from third-party sms service server (%d)",
responseCode));
}
}
}
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
class SmsContent {
private String phone;
private String aliyunId;
private String code;
private String content;
private String signature;
private Long timestamp;
private Integer nonce;
} | 4,285 |
892 | {
"schema_version": "1.2.0",
"id": "GHSA-rhm9-p9w5-fwm7",
"modified": "2022-04-22T18:32:23Z",
"published": "2021-02-10T01:32:27Z",
"aliases": [
"CVE-2020-36242"
],
"summary": "Symmetrically encrypting large values can lead to integer overflow",
"details": "cryptography is a package designed to expose cryptographic primitives and recipes to Python developers. When certain sequences of `update()` calls with large values (multiple GBs) for symetric encryption or decryption occur, it's possible for an integer overflow to happen, leading to mishandling of buffers. This is patched in version 3.3.2 and newer.\n",
"severity": [
{
"type": "CVSS_V3",
"score": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:N/A:H"
}
],
"affected": [
{
"package": {
"ecosystem": "PyPI",
"name": "cryptography"
},
"ecosystem_specific": {
"affected_functions": [
"cryptography.hazmat.backends.openssl.ciphers._CipherContext"
]
},
"ranges": [
{
"type": "ECOSYSTEM",
"events": [
{
"introduced": "3.1"
},
{
"fixed": "3.3.2"
}
]
}
]
}
],
"references": [
{
"type": "WEB",
"url": "https://github.com/pyca/cryptography/security/advisories/GHSA-rhm9-p9w5-fwm7"
},
{
"type": "ADVISORY",
"url": "https://nvd.nist.gov/vuln/detail/CVE-2020-36242"
},
{
"type": "WEB",
"url": "https://github.com/pyca/cryptography/issues/5615"
},
{
"type": "WEB",
"url": "https://github.com/pyca/cryptography/commit/82b6ce28389f0a317bc55ba2091a74b346db7cae"
},
{
"type": "WEB",
"url": "https://github.com/pyca/cryptography/blob/master/CHANGELOG.rst"
},
{
"type": "WEB",
"url": "https://github.com/pyca/cryptography/compare/3.3.1...3.3.2"
},
{
"type": "WEB",
"url": "https://lists.fedoraproject.org/archives/list/[email protected]/message/L7RGQLK4J5ZQFRLKCHVVG6BKZTUQMG7E/"
},
{
"type": "WEB",
"url": "https://www.oracle.com/security-alerts/cpuapr2022.html"
},
{
"type": "PACKAGE",
"url": "https://github.com/pyca/cryptography"
}
],
"database_specific": {
"cwe_ids": [
"CWE-190",
"CWE-787"
],
"severity": "CRITICAL",
"github_reviewed": true
}
} | 1,255 |
1,829 | <reponame>useaname/thinking-in-spring-boot-samples
/*
* 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 thinking.in.spring.boot.samples.spring5.bootstrap;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.core.type.StandardAnnotationMetadata;
import org.springframework.core.type.classreading.MetadataReader;
import org.springframework.core.type.classreading.SimpleMetadataReaderFactory;
import thinking.in.spring.boot.samples.spring5.annotation.TransactionalService;
import java.io.IOException;
/**
* {@link AnnotationMetadata} 实现性能比较引导类
*
* @author <a href="mailto:<EMAIL>">Mercy</a>
* @since 1.0.0
*/
public class AnnotationMetadataPerformanceBootstrap {
public static void main(String[] args) throws IOException {
// 反射实现
AnnotationMetadata standardAnnotationMetadata = new StandardAnnotationMetadata(TransactionalService.class);
SimpleMetadataReaderFactory factory = new SimpleMetadataReaderFactory();
MetadataReader metadataReader = factory.getMetadataReader(TransactionalService.class.getName());
// ASM 实现
AnnotationMetadata annotationMetadata = metadataReader.getAnnotationMetadata();
int times = 10 * 10000; // 10 万次
testAnnotationMetadataPerformance(standardAnnotationMetadata, times);
testAnnotationMetadataPerformance(annotationMetadata, times);
times = 100 * 10000; // 100 万次
testAnnotationMetadataPerformance(standardAnnotationMetadata, times);
testAnnotationMetadataPerformance(annotationMetadata, times);
times = 1000 * 10000; // 1000 万次
testAnnotationMetadataPerformance(standardAnnotationMetadata, times);
testAnnotationMetadataPerformance(annotationMetadata, times);
times = 10000 * 10000; // 1 亿次
testAnnotationMetadataPerformance(standardAnnotationMetadata, times);
testAnnotationMetadataPerformance(annotationMetadata, times);
}
private static void testAnnotationMetadataPerformance(AnnotationMetadata annotationMetadata, int times) {
long startTime = System.currentTimeMillis();
for (int i = 0; i < times; i++) {
annotationMetadata.getAnnotationTypes();
}
long costTime = System.currentTimeMillis() - startTime;
System.out.printf("%d 次 %s.getAnnotationTypes() 方法执行消耗 %s ms\n",
times, annotationMetadata.getClass().getSimpleName(), costTime);
}
}
| 1,066 |
1,337 | /*
* Copyright (c) 2008-2017 Haulmont.
*
* 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.haulmont.cuba.core;
import com.haulmont.cuba.core.global.*;
import com.haulmont.cuba.security.entity.User;
import com.haulmont.cuba.testmodel.checkview.UserRelatedNews;
import com.haulmont.cuba.testsupport.TestContainer;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.UUID;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class CheckLoadedStateTest {
@RegisterExtension
public static TestContainer cont = TestContainer.Common.INSTANCE;
private UUID userRelatedNewsId = null;
private List<UUID> recursiveUserRelatedIds = null;
@Test
public void checkLocalProperties() {
DataManager dataManager = AppBeans.get(DataManager.class);
EntityStates entityStates = AppBeans.get(EntityStates.class);
User user = dataManager.load(LoadContext.create(User.class)
.setId(UUID.fromString("60885987-1b61-4247-94c7-dff348347f93"))
.setView(View.LOCAL));
entityStates.checkLoaded(user, "login", "name", "active");
try {
entityStates.checkLoaded(user, "group");
Assertions.fail("user.group is not loaded");
} catch (IllegalArgumentException e) {
Assertions.assertTrue(e.getMessage().contains("group is not loaded"));
}
}
@Test
public void checkMinimalProperties() {
DataManager dataManager = AppBeans.get(DataManager.class);
EntityStates entityStates = AppBeans.get(EntityStates.class);
User user = dataManager.load(LoadContext.create(User.class)
.setId(UUID.fromString("60885987-1b61-4247-94c7-dff348347f93"))
.setView(View.MINIMAL));
entityStates.checkLoaded(user, "login", "name");
try {
entityStates.checkLoaded(user, "group");
Assertions.fail("user.group is not loaded");
} catch (IllegalArgumentException e) {
Assertions.assertTrue(e.getMessage().contains("group is not loaded"));
}
try {
entityStates.checkLoaded(user, "password");
Assertions.fail("user.password is not loaded");
} catch (IllegalArgumentException e) {
Assertions.assertTrue(e.getMessage().contains("password is not loaded"));
}
try {
entityStates.checkLoaded(user, "email");
Assertions.fail("user.email is not loaded");
} catch (IllegalArgumentException e) {
Assertions.assertTrue(e.getMessage().contains("email is not loaded"));
}
}
@Test
public void checkLocalView() {
DataManager dataManager = AppBeans.get(DataManager.class);
EntityStates entityStates = AppBeans.get(EntityStates.class);
User user = dataManager.load(LoadContext.create(User.class)
.setId(UUID.fromString("60885987-1b61-4247-94c7-dff348347f93"))
.setView(View.LOCAL));
assertTrue(entityStates.isLoadedWithView(user, View.LOCAL));
entityStates.checkLoadedWithView(user, View.LOCAL);
User userMinimal = dataManager.load(LoadContext.create(User.class)
.setId(UUID.fromString("60885987-1b61-4247-94c7-dff348347f93"))
.setView(View.MINIMAL));
try {
assertFalse(entityStates.isLoadedWithView(userMinimal, View.LOCAL));
entityStates.checkLoadedWithView(userMinimal, View.LOCAL);
Assertions.fail("user local attributes are not loaded");
} catch (IllegalArgumentException e) {
Assertions.assertTrue(e.getMessage().contains(" is not loaded"));
}
}
@Test
public void checkDeepView() {
DataManager dataManager = AppBeans.get(DataManager.class);
EntityStates entityStates = AppBeans.get(EntityStates.class);
User user = dataManager.load(LoadContext.create(User.class)
.setId(UUID.fromString("60885987-1b61-4247-94c7-dff348347f93"))
.setView("user.browse"));
try {
assertFalse(entityStates.isLoadedWithView(user, "user.edit"));
entityStates.checkLoadedWithView(user, "user.edit");
Assertions.fail("user edit attributes are not loaded");
} catch (IllegalArgumentException e) {
Assertions.assertTrue(e.getMessage().contains(" is not loaded"));
}
User userEdit = dataManager.load(LoadContext.create(User.class)
.setId(UUID.fromString("60885987-1b61-4247-94c7-dff348347f93"))
.setView("user.edit"));
assertTrue(entityStates.isLoadedWithView(userEdit, "user.edit"));
entityStates.checkLoadedWithView(userEdit, "user.edit");
}
@Test
public void checkRelatedView() {
DataManager dataManager = AppBeans.get(DataManager.class);
EntityStates entityStates = AppBeans.get(EntityStates.class);
User user = dataManager.load(LoadContext.create(User.class)
.setId(UUID.fromString("60885987-1b61-4247-94c7-dff348347f93"))
.setView(View.MINIMAL));
UserRelatedNews record = cont.metadata().create(UserRelatedNews.class);
userRelatedNewsId = record.getId();
record.setName("Test");
record.setUser(user);
UserRelatedNews testRecord = dataManager.commit(record);
View view = new View(UserRelatedNews.class, false);
view.addProperty("userLogin");
view.addProperty("name");
entityStates.checkLoadedWithView(testRecord, view);
assertTrue(entityStates.isLoadedWithView(testRecord, view));
UserRelatedNews minimalRecord = dataManager.load(LoadContext.create(UserRelatedNews.class)
.setId(userRelatedNewsId)
.setView(View.MINIMAL));
try {
assertFalse(entityStates.isLoadedWithView(minimalRecord, view));
entityStates.checkLoadedWithView(minimalRecord, view);
Assertions.fail("minimal record attributes are not loaded");
} catch (IllegalArgumentException e) {
Assertions.assertTrue(e.getMessage().contains("userLogin is not loaded"));
}
}
@Test
public void checkRecursiveView() {
DataManager dataManager = AppBeans.get(DataManager.class);
EntityStates entityStates = AppBeans.get(EntityStates.class);
User user = dataManager.load(LoadContext.create(User.class)
.setId(UUID.fromString("60885987-1b61-4247-94c7-dff348347f93"))
.setView(View.MINIMAL));
recursiveUserRelatedIds = new ArrayList<>();
UserRelatedNews parentRecord = cont.metadata().create(UserRelatedNews.class);
parentRecord.setName("Test");
parentRecord.setUser(user);
UserRelatedNews committedParentRecord = dataManager.commit(parentRecord);
recursiveUserRelatedIds.add(committedParentRecord.getId());
UserRelatedNews record = cont.metadata().create(UserRelatedNews.class);
record.setName("Test");
record.setUser(user);
record.setParent(committedParentRecord);
UserRelatedNews committedRecord = dataManager.commit(record);
recursiveUserRelatedIds.add(committedRecord.getId());
View view = new View(UserRelatedNews.class, false);
view.addProperty("parent");
view.addProperty("name");
assertTrue(entityStates.isLoadedWithView(committedRecord, view));
entityStates.checkLoadedWithView(committedRecord, view);
UserRelatedNews localRecord = dataManager.load(LoadContext.create(UserRelatedNews.class)
.setId(committedRecord.getId())
.setView(View.LOCAL));
try {
assertFalse(entityStates.isLoadedWithView(localRecord, view));
entityStates.checkLoadedWithView(localRecord, view);
Assertions.fail("local record attributes are not loaded");
} catch (IllegalArgumentException e) {
Assertions.assertTrue(e.getMessage().contains("parent is not loaded"));
}
}
@AfterEach
public void tearDown() {
if (userRelatedNewsId != null) {
cont.deleteRecord("TEST_USER_RELATED_NEWS", userRelatedNewsId);
userRelatedNewsId = null;
}
if (recursiveUserRelatedIds != null) {
Collections.reverse(recursiveUserRelatedIds);
for (UUID id : recursiveUserRelatedIds) {
cont.deleteRecord("TEST_USER_RELATED_NEWS", id);
}
}
}
} | 3,848 |
1,669 | package me.ele.lancet.plugin;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Jude on 4/4/17.
*/
public class ClassFileUtil {
public static final String MetaDir = (new File("").getAbsolutePath().contains("sample-test")?"":"sample-test/") +"build/lancet/";
public static final String ClassDir = (new File("").getAbsolutePath().contains("sample-test")?"":"sample-test/") +"build/classes/java/main";
public static final String TestDir = (new File("").getAbsolutePath().contains("sample-test")?"":"sample-test/") +"build/classes/java/test";
public static final String ProductDir = (new File("").getAbsolutePath().contains("sample-test")?"":"sample-test/") +"build/product/java/main";
public static File getTestFile(String className){
className = className.replace(".","/");
return new File(TestDir,className+".class");
}
public static File getClassFile(String className){
className = className.replace(".","/");
return new File(ClassDir,className+".class");
}
public static File getProductFile(String className){
className = className.replace(".","/");
return new File(ProductDir,className+".class");
}
public static void moveClassToProduce(Class clazz){
File source = getTestFile(clazz.getName());
File target = getProductFile(clazz.getName());
String path = clazz.getPackage().getName().replace(".","/");
File dir = new File(ProductDir,path);
if (!dir.exists()){
dir.mkdirs();
}
try {
com.google.common.io.Files.copy(source,target);
} catch (IOException e) {
e.printStackTrace();
}
}
public static List<File> getClassPackageFiles(String packageName){
packageName = packageName.replace(".","/");
ArrayList<File> files = new ArrayList<>();
travelFiles(files,new File(ClassDir,packageName));
return files;
}
private static void travelFiles(ArrayList<File> fileArrayList,File file){
for (File fileChild : file.listFiles()) {
if (fileChild.isDirectory()){
travelFiles(fileArrayList,fileChild);
}else {
fileArrayList.add(fileChild);
}
}
}
public static File clearFile(File file) throws IOException {
if (!file.exists()){
file.getParentFile().mkdirs();
file.createNewFile();
}
return file;
}
public static void resetProductDir(){
File product = new File(ProductDir);
travelDeleteFiles(product);
if (!product.exists()){
product.mkdir();
}
travelDeleteFiles(new File(MetaDir));
}
private static void travelDeleteFiles(File file){
if (file == null || !file.exists()){
return;
}
for (File fileChild : file.listFiles()) {
if (fileChild.isDirectory()){
travelDeleteFiles(fileChild);
}else {
fileChild.delete();
}
}
file.delete();
}
}
| 1,333 |
308 | import flask
from tests.utils import assert_span_http_status_code
from . import BaseFlaskTestCase
class FlaskErrorhandlerTestCase(BaseFlaskTestCase):
def test_default_404_handler(self):
"""
When making a 404 request
And no user defined error handler is defined
We create the expected spans
"""
# Make our 404 request
res = self.client.get("/unknown")
self.assertEqual(res.status_code, 404)
spans = self.get_spans()
req_span = self.find_span_by_name(spans, "flask.request")
dispatch_span = self.find_span_by_name(spans, "flask.dispatch_request")
user_ex_span = self.find_span_by_name(spans, "flask.handle_user_exception")
http_ex_span = self.find_span_by_name(spans, "flask.handle_http_exception")
# flask.request span
self.assertEqual(req_span.error, 0)
assert_span_http_status_code(req_span, 404)
self.assertIsNone(req_span.get_tag("flask.endpoint"))
self.assertIsNone(req_span.get_tag("flask.url_rule"))
# flask.dispatch_request span
self.assertEqual(dispatch_span.error, 0)
self.assertIsNone(dispatch_span.get_tag("error.msg"))
self.assertIsNone(dispatch_span.get_tag("error.stack"))
self.assertIsNone(dispatch_span.get_tag("error.type"))
# flask.handle_user_exception span
self.assertEqual(user_ex_span.meta, dict())
self.assertEqual(user_ex_span.error, 0)
# flask.handle_http_exception span
self.assertEqual(http_ex_span.meta, dict())
self.assertEqual(http_ex_span.error, 0)
def test_abort_500(self):
"""
When making a 500 request
And no user defined error handler is defined
We create the expected spans
"""
@self.app.route("/500")
def endpoint_500():
flask.abort(500)
# Make our 500 request
res = self.client.get("/500")
self.assertEqual(res.status_code, 500)
spans = self.get_spans()
req_span = self.find_span_by_name(spans, "flask.request")
dispatch_span = self.find_span_by_name(spans, "flask.dispatch_request")
endpoint_span = self.find_span_by_name(spans, "tests.contrib.flask.test_errorhandler.endpoint_500")
user_ex_span = self.find_span_by_name(spans, "flask.handle_user_exception")
http_ex_span = self.find_span_by_name(spans, "flask.handle_http_exception")
# flask.request span
self.assertEqual(req_span.error, 1)
assert_span_http_status_code(req_span, 500)
self.assertEqual(req_span.get_tag("flask.endpoint"), "endpoint_500")
self.assertEqual(req_span.get_tag("flask.url_rule"), "/500")
# flask.dispatch_request span
self.assertEqual(dispatch_span.error, 1)
error_msg = dispatch_span.get_tag("error.msg")
self.assertTrue(error_msg.startswith("500 Internal Server Error"))
error_stack = dispatch_span.get_tag("error.stack")
self.assertTrue(error_stack.startswith("Traceback (most recent call last):"))
error_type = dispatch_span.get_tag("error.type")
self.assertEqual(error_type, "werkzeug.exceptions.InternalServerError")
# tests.contrib.flask.test_errorhandler.endpoint_500 span
self.assertEqual(endpoint_span.error, 1)
error_msg = endpoint_span.get_tag("error.msg")
self.assertTrue(error_msg.startswith("500 Internal Server Error"))
error_stack = endpoint_span.get_tag("error.stack")
self.assertTrue(error_stack.startswith("Traceback (most recent call last):"))
error_type = endpoint_span.get_tag("error.type")
self.assertEqual(error_type, "werkzeug.exceptions.InternalServerError")
# flask.handle_user_exception span
self.assertEqual(user_ex_span.meta, dict())
self.assertEqual(user_ex_span.error, 0)
# flask.handle_http_exception span
self.assertEqual(http_ex_span.meta, dict())
self.assertEqual(http_ex_span.error, 0)
def test_abort_500_custom_handler(self):
"""
When making a 500 request
And a user defined error handler is defined
We create the expected spans
"""
@self.app.errorhandler(500)
def handle_500(e):
return "whoops", 200
@self.app.route("/500")
def endpoint_500():
flask.abort(500)
# Make our 500 request
res = self.client.get("/500")
self.assertEqual(res.status_code, 200)
self.assertEqual(res.data, b"whoops")
spans = self.get_spans()
req_span = self.find_span_by_name(spans, "flask.request")
dispatch_span = self.find_span_by_name(spans, "flask.dispatch_request")
endpoint_span = self.find_span_by_name(spans, "tests.contrib.flask.test_errorhandler.endpoint_500")
handler_span = self.find_span_by_name(spans, "tests.contrib.flask.test_errorhandler.handle_500")
user_ex_span = self.find_span_by_name(spans, "flask.handle_user_exception")
http_ex_span = self.find_span_by_name(spans, "flask.handle_http_exception")
# flask.request span
self.assertEqual(req_span.error, 0)
assert_span_http_status_code(req_span, 200)
self.assertEqual(req_span.get_tag("flask.endpoint"), "endpoint_500")
self.assertEqual(req_span.get_tag("flask.url_rule"), "/500")
# flask.dispatch_request span
self.assertEqual(dispatch_span.error, 1)
error_msg = dispatch_span.get_tag("error.msg")
self.assertTrue(error_msg.startswith("500 Internal Server Error"))
error_stack = dispatch_span.get_tag("error.stack")
self.assertTrue(error_stack.startswith("Traceback (most recent call last):"))
error_type = dispatch_span.get_tag("error.type")
self.assertEqual(error_type, "werkzeug.exceptions.InternalServerError")
# tests.contrib.flask.test_errorhandler.endpoint_500 span
self.assertEqual(endpoint_span.error, 1)
error_msg = endpoint_span.get_tag("error.msg")
self.assertTrue(error_msg.startswith("500 Internal Server Error"))
error_stack = endpoint_span.get_tag("error.stack")
self.assertTrue(error_stack.startswith("Traceback (most recent call last):"))
error_type = endpoint_span.get_tag("error.type")
self.assertEqual(error_type, "werkzeug.exceptions.InternalServerError")
# tests.contrib.flask.test_errorhandler.handle_500 span
self.assertEqual(handler_span.error, 0)
self.assertIsNone(handler_span.get_tag("error.msg"))
self.assertIsNone(handler_span.get_tag("error.stack"))
self.assertIsNone(handler_span.get_tag("error.type"))
# flask.handle_user_exception span
self.assertEqual(user_ex_span.meta, dict())
self.assertEqual(user_ex_span.error, 0)
# flask.handle_http_exception span
self.assertEqual(http_ex_span.meta, dict())
self.assertEqual(http_ex_span.error, 0)
def test_raise_user_exception(self):
"""
When raising a custom user exception
And no user defined error handler is defined
We create the expected spans
"""
class FlaskTestException(Exception):
pass
@self.app.route("/error")
def endpoint_error():
raise FlaskTestException("custom error message")
# Make our 500 request
res = self.client.get("/error")
self.assertEqual(res.status_code, 500)
spans = self.get_spans()
req_span = self.find_span_by_name(spans, "flask.request")
dispatch_span = self.find_span_by_name(spans, "flask.dispatch_request")
endpoint_span = self.find_span_by_name(spans, "tests.contrib.flask.test_errorhandler.endpoint_error")
user_ex_span = self.find_span_by_name(spans, "flask.handle_user_exception")
http_ex_span = self.find_span_by_name(spans, "flask.handle_http_exception", required=False)
# flask.request span
self.assertEqual(req_span.error, 1)
assert_span_http_status_code(req_span, 500)
self.assertEqual(req_span.get_tag("flask.endpoint"), "endpoint_error")
self.assertEqual(req_span.get_tag("flask.url_rule"), "/error")
# flask.dispatch_request span
self.assertEqual(dispatch_span.error, 1)
error_msg = dispatch_span.get_tag("error.msg")
self.assertTrue(error_msg.startswith("custom error message"))
error_stack = dispatch_span.get_tag("error.stack")
self.assertTrue(error_stack.startswith("Traceback (most recent call last):"))
error_type = dispatch_span.get_tag("error.type")
self.assertEqual(error_type, "tests.contrib.flask.test_errorhandler.FlaskTestException")
# tests.contrib.flask.test_errorhandler.endpoint_500 span
self.assertEqual(endpoint_span.error, 1)
error_msg = endpoint_span.get_tag("error.msg")
self.assertTrue(error_msg.startswith("custom error message"))
error_stack = endpoint_span.get_tag("error.stack")
self.assertTrue(error_stack.startswith("Traceback (most recent call last):"))
error_type = endpoint_span.get_tag("error.type")
self.assertEqual(error_type, "tests.contrib.flask.test_errorhandler.FlaskTestException")
# flask.handle_user_exception span
self.assertEqual(user_ex_span.error, 1)
error_msg = user_ex_span.get_tag("error.msg")
self.assertTrue(error_msg.startswith("custom error message"))
error_stack = user_ex_span.get_tag("error.stack")
self.assertTrue(error_stack.startswith("Traceback (most recent call last):"))
error_type = user_ex_span.get_tag("error.type")
self.assertEqual(error_type, "tests.contrib.flask.test_errorhandler.FlaskTestException")
# flask.handle_http_exception span
self.assertIsNone(http_ex_span)
def test_raise_user_exception_handler(self):
"""
When raising a custom user exception
And a user defined error handler is defined
We create the expected spans
"""
class FlaskTestException(Exception):
pass
@self.app.errorhandler(FlaskTestException)
def handle_error(e):
return "whoops", 200
@self.app.route("/error")
def endpoint_error():
raise FlaskTestException("custom error message")
# Make our 500 request
res = self.client.get("/error")
self.assertEqual(res.status_code, 200)
self.assertEqual(res.data, b"whoops")
spans = self.get_spans()
req_span = self.find_span_by_name(spans, "flask.request")
dispatch_span = self.find_span_by_name(spans, "flask.dispatch_request")
endpoint_span = self.find_span_by_name(spans, "tests.contrib.flask.test_errorhandler.endpoint_error")
handler_span = self.find_span_by_name(spans, "tests.contrib.flask.test_errorhandler.handle_error")
user_ex_span = self.find_span_by_name(spans, "flask.handle_user_exception")
http_ex_span = self.find_span_by_name(spans, "flask.handle_http_exception", required=False)
# flask.request span
self.assertEqual(req_span.error, 0)
assert_span_http_status_code(req_span, 200)
self.assertEqual(req_span.get_tag("flask.endpoint"), "endpoint_error")
self.assertEqual(req_span.get_tag("flask.url_rule"), "/error")
# flask.dispatch_request span
self.assertEqual(dispatch_span.error, 1)
error_msg = dispatch_span.get_tag("error.msg")
self.assertTrue(error_msg.startswith("custom error message"))
error_stack = dispatch_span.get_tag("error.stack")
self.assertTrue(error_stack.startswith("Traceback (most recent call last):"))
error_type = dispatch_span.get_tag("error.type")
self.assertEqual(error_type, "tests.contrib.flask.test_errorhandler.FlaskTestException")
# tests.contrib.flask.test_errorhandler.endpoint_500 span
self.assertEqual(endpoint_span.error, 1)
error_msg = endpoint_span.get_tag("error.msg")
self.assertTrue(error_msg.startswith("custom error message"))
error_stack = endpoint_span.get_tag("error.stack")
self.assertTrue(error_stack.startswith("Traceback (most recent call last):"))
error_type = endpoint_span.get_tag("error.type")
self.assertEqual(error_type, "tests.contrib.flask.test_errorhandler.FlaskTestException")
# tests.contrib.flask.test_errorhandler.handle_error span
self.assertEqual(handler_span.error, 0)
# flask.handle_user_exception span
self.assertEqual(user_ex_span.error, 0)
self.assertEqual(user_ex_span.meta, dict())
# flask.handle_http_exception span
self.assertIsNone(http_ex_span)
| 5,545 |
10,225 | package io.quarkus.vault.runtime;
import static io.quarkus.vault.runtime.StringHelper.bytesToString;
import static io.quarkus.vault.runtime.StringHelper.stringToBytes;
import static java.util.Base64.getDecoder;
import static java.util.Base64.getEncoder;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
@JsonSerialize(using = Base64StringSerializer.class)
@JsonDeserialize(using = Base64StringDeserializer.class)
public class Base64String {
private String value;
public static byte[] toBytes(String s) {
return getDecoder().decode(s);
}
public static Base64String from(String s) {
return s == null ? null : new Base64String(getEncoder().encodeToString(stringToBytes(s)));
}
public static Base64String from(byte[] bytes) {
return bytes == null ? null : new Base64String(getEncoder().encodeToString(bytes));
}
public Base64String(String value) {
this.value = value;
}
public String getValue() {
return value;
}
public byte[] decodeAsBytes() {
return toBytes(value);
}
public String decodeAsString() {
return bytesToString(decodeAsBytes());
}
@Override
public String toString() {
return value;
}
}
| 488 |
706 | # Copyright 2021 The TensorFlow Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# 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.
"ResNet50 backbone for similarity learning"
from typing import Tuple
import tensorflow as tf
from tensorflow.keras import layers
from tensorflow.keras.applications import imagenet_utils
from tensorflow_similarity.layers import MetricEmbedding
from tensorflow_similarity.layers import GeneralizedMeanPooling2D
from tensorflow_similarity.models import SimilarityModel
# Create an image augmentation pipeline.
def ResNet18Sim(
input_shape: Tuple[int, int, int],
embedding_size: int = 128,
l2_norm: bool = True,
include_top: bool = True,
pooling: str = "gem",
gem_p=1.0,
preproc_mode: str = "torch",
similarity_model: bool = True,
) -> SimilarityModel:
"""Build an ResNet18 Model backbone for similarity learning
Architecture from [Deep Residual Learning for Image Recognition](https://arxiv.org/abs/1512.03385)
Args:
input_shape: Expected to be betweeen 32 and 224 and in the (H, W, C)
data_format augmentation function.
embedding_size: Size of the output embedding. Usually between 64
and 512. Defaults to 128.
l2_norm: If True and include_top is also True, then
tfsim.layers.MetricEmbedding is used as the last layer, otherwise
keras.layers.Dense is used. This should be true when using cosine
distance. Defaults to True.
include_top: Whether to include a fully-connected layer of
embedding_size at the top of the network. Defaults to True.
pooling: Optional pooling mode for feature extraction when
include_top is False. Defaults to gem.
- None means that the output of the model will be the 4D tensor
output of the last convolutional layer.
- avg means that global average pooling will be applied to the
output of the last convolutional layer, and thus the output of the
model will be a 2D tensor.
- max means that global max pooling will be applied.
- gem means that global GeneralizedMeanPooling2D will be applied.
The gem_p param sets the contrast amount on the pooling.
gem_p: Sets the power in the GeneralizedMeanPooling2D layer. A value
of 1.0 is equivelent to GlobalMeanPooling2D, while larger values
will increase the contrast between activations within each feature
map, and a value of math.inf will be equivelent to MaxPool2d.
preproc_mode: One of "caffe", "tf" or "torch".
- caffe: will convert the images from RGB to BGR, then will zero-center
each color channel with respect to the ImageNet dataset, without
scaling.
- tf: will scale pixels between -1 and 1, sample-wise.
- torch: will scale pixels between 0 and 1 and then will normalize each
channel with respect to the ImageNet dataset.
"""
# input
inputs = layers.Input(shape=input_shape)
x = inputs
resnet = build_resnet(x, "channels_last", preproc_mode)
x = resnet(x)
if pooling == "gem":
x = GeneralizedMeanPooling2D(p=gem_p, name="gem_pool")(x)
elif pooling == "avg":
x = layers.GlobalAveragePooling2D(name="avg_pool")(x)
elif pooling == "max":
x = layers.GlobalMaxPooling2D(name="max_pool")(x)
if include_top and pooling is not None:
if l2_norm:
outputs = MetricEmbedding(embedding_size)(x)
else:
outputs = layers.Dense(embedding_size)(x)
else:
outputs = x
return SimilarityModel(inputs, outputs, name="resnet18sim")
def build_resnet(x: layers.Layer, data_format, preproc_mode) -> layers.Layer:
"""Build the requested ResNet.
Args:
x: The input layer to the ResNet.
data_format: Data format of the image tensor.
preproc_mode: One of "caffe", "tf" or "torch".
Returns:
The ouptut layer of the ResNet model
"""
# Handle the case where x.shape includes the placeholder for the batch dim.
if x.shape[0] is None:
inputs = layers.Input(shape=x.shape[1:])
else:
inputs = layers.Input(shape=x.shape)
x = imagenet_utils.preprocess_input(
x, data_format=data_format, mode=preproc_mode
)
x = tf.keras.layers.ZeroPadding2D(
padding=((1, 1), (1, 1)), name="conv1_pad"
)(inputs)
x = tf.keras.layers.Conv2D(
64,
kernel_size=3,
strides=1,
use_bias=False,
kernel_initializer=tf.keras.initializers.LecunUniform(),
name="conv1_conv",
)(x)
x = tf.keras.layers.BatchNormalization(epsilon=1.001e-5, name="conv1_bn")(x)
x = tf.keras.layers.Activation("relu", name="conv1_relu")(x)
outputs = stack_fn(x)
model = tf.keras.Model(inputs, outputs, name="resnet18")
return model
def block0(
x,
filters,
kernel_size=3,
stride=1,
conv_shortcut=True,
name=None,
):
if conv_shortcut:
shortcut = tf.keras.layers.Conv2D(
filters,
1,
strides=stride,
use_bias=False,
kernel_initializer=tf.keras.initializers.LecunUniform(),
name=name + "_0_conv",
)(x)
shortcut = tf.keras.layers.BatchNormalization(
epsilon=1.001e-5, name=name + "_0_bn"
)(shortcut)
else:
shortcut = x
x = tf.keras.layers.Conv2D(
filters,
kernel_size,
strides=stride,
padding="SAME",
use_bias=False,
kernel_initializer=tf.keras.initializers.LecunUniform(),
name=name + "_1_conv",
)(x)
x = tf.keras.layers.BatchNormalization(
epsilon=1.001e-5, name=name + "_1_bn"
)(x)
x = tf.keras.layers.Activation("relu", name=name + "_1_relu")(x)
x = tf.keras.layers.Conv2D(
filters,
kernel_size,
padding="SAME",
use_bias=False,
kernel_initializer=tf.keras.initializers.LecunUniform(),
name=name + "_2_conv",
)(x)
x = tf.keras.layers.BatchNormalization(
epsilon=1.001e-5, name=name + "_2_bn"
)(x)
x = tf.keras.layers.Add(name=name + "_add")([shortcut, x])
x = tf.keras.layers.Activation("relu", name=name + "_out")(x)
return x
def stack0(x, filters, blocks, stride1=2, name=None):
x = block0(x, filters, stride=stride1, name=name + "_block1")
for i in range(2, blocks + 1):
x = block0(
x,
filters,
conv_shortcut=False,
name=name + "_block" + str(i),
)
return x
def stack_fn(x):
x = stack0(x, 64, 2, stride1=1, name="conv2")
x = stack0(x, 128, 2, name="conv3")
x = stack0(x, 256, 2, name="conv4")
return stack0(x, 512, 2, name="conv5")
| 3,045 |
947 | /**********************************************************************
* Copyright (c) 2016 <NAME> *
* Distributed under the MIT software license, see the accompanying *
* file COPYING or http://www.opensource.org/licenses/mit-license.php.*
**********************************************************************/
#ifndef _SECP256K1_SURJECTION_H_
#define _SECP256K1_SURJECTION_H_
#include "group.h"
#include "scalar.h"
SECP256K1_INLINE static int secp256k1_surjection_genmessage(unsigned char *msg32, secp256k1_ge *ephemeral_input_tags, size_t n_input_tags, secp256k1_ge *ephemeral_output_tag);
SECP256K1_INLINE static int secp256k1_surjection_genrand(secp256k1_scalar *s, size_t ns, const secp256k1_scalar *blinding_key);
SECP256K1_INLINE static int secp256k1_surjection_compute_public_keys(secp256k1_gej *pubkeys, size_t n_pubkeys, const secp256k1_ge *input_tags, size_t n_input_tags, const unsigned char *used_tags, const secp256k1_ge *output_tag, size_t input_index, size_t *ring_input_index);
#endif
| 391 |
14,668 | // Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "components/site_isolation/pref_names.h"
namespace site_isolation {
namespace prefs {
// A list of origins that were heuristically determined to need process
// isolation due to an action triggered by the user. For example, an origin may
// be placed on this list in response to the user typing a password on it.
const char kUserTriggeredIsolatedOrigins[] =
"site_isolation.user_triggered_isolated_origins";
// A list of origins that were determined to need process isolation based on
// heuristics triggered directly by web sites. For example, an origin may be
// placed on this list in response to serving Cross-Origin-Opener-Policy
// headers. Unlike the user-triggered list above, web-triggered isolated
// origins are subject to stricter size and eviction policies, to guard against
// too many sites triggering isolation and to eventually stop isolation if web
// sites stop serving headers that triggered it.
const char kWebTriggeredIsolatedOrigins[] =
"site_isolation.web_triggered_isolated_origins";
} // namespace prefs
} // namespace site_isolation
| 329 |
452 | package pl.altkom.asc.lab.micronaut.poc.auth;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.UUID;
import io.micronaut.data.annotation.Id;
import io.micronaut.data.annotation.MappedEntity;
@MappedEntity
record InsuranceAgent(
@Id UUID id,
String login,
String password,
String avatar,
String availableProducts) {
InsuranceAgent(UUID id,String login, String password, String avatar, List<String> availableProducts) {
this(id,login,password,avatar,String.join(";",availableProducts));
}
boolean passwordMatches(String passwordToTest) {
return this.password.equals(passwordToTest);
}
public Collection<String> availableProductCodes() {
return Arrays.asList(availableProducts.split(";"));
}
}
| 292 |
615 | /**
* @file query_lm.cpp
* @author <NAME>
*/
#include <iostream>
#include "meta/analyzers/tokenizers/icu_tokenizer.h"
#include "meta/analyzers/tokenizers/whitespace_tokenizer.h"
#include "meta/lm/language_model.h"
#include "meta/lm/mph_language_model.h"
#include "meta/logging/logger.h"
#include "meta/util/algorithm.h"
template <class LanguageModel>
void query_lm(const LanguageModel& model, bool verbose = false)
{
using namespace meta;
// record similar statistics to KenLM
double total = 0.0;
double total_oov_only = 0.0;
uint64_t oov = 0;
uint64_t tokens = 0;
std::string line;
while (std::getline(std::cin, line))
{
lm::lm_state state{{model.index("<s>")}};
lm::lm_state state_next;
util::for_each_token(
line.begin(), line.end(), " ",
[&](std::string::iterator begin, std::string::iterator end) {
std::string tok{begin, end};
auto idx = model.index(tok);
auto score = model.score(state, idx, state_next);
if (verbose)
std::cout << tok << "=" << idx << " "
<< state_next.previous.size() << " " << score
<< " ";
if (idx == model.unk())
{
total_oov_only += score;
++oov;
}
total += score;
state = state_next;
++tokens;
});
auto idx = model.index("</s>");
auto score = model.score(state, idx, state_next);
if (verbose)
std::cout << "</s>=" << idx << " " << state_next.previous.size()
<< " " << score << "\n";
total += score;
++tokens;
}
std::cout << "Perplexity including OOVs:\t"
<< std::pow(10, -total / static_cast<double>(tokens))
<< "\nPerplexity excluding OOVs:\t"
<< std::pow(10, -(total - total_oov_only)
/ static_cast<double>(tokens - oov))
<< "\nOOVs:\t" << oov << "\nTokens:\t" << tokens << std::endl;
}
int main(int argc, char** argv)
{
using namespace meta;
if (argc < 3)
{
std::cerr << "Usage: " << argv[0] << " config.toml (lm|mph)" << std::endl;
std::cerr << "\tlm: query using probing language model" << std::endl;
std::cerr << "\tmph: query using mph language model" << std::endl;
return 1;
}
logging::set_cerr_logging();
bool verbose = argc > 3;
auto config = cpptoml::parse_file(argv[1]);
util::string_view type{argv[2]};
if (type == "lm")
{
lm::language_model model{*config};
query_lm(model, verbose);
}
else if (type == "mph")
{
lm::mph_language_model model{*config};
query_lm(model, verbose);
}
else
{
LOG(fatal) << "Unrecognized language model type" << ENDLG;
return 1;
}
return 0;
}
| 1,546 |
1,392 | <reponame>eanknd/saleor
import pytest
from django.utils import timezone
from freezegun import freeze_time
from .....page.models import Page
from .....tests.utils import dummy_editorjs
from ....tests.utils import get_graphql_content
QUERY_PAGE_WITH_SORT = """
query ($sort_by: PageSortingInput!) {
pages(first:5, sortBy: $sort_by) {
edges{
node{
title
}
}
}
}
"""
@pytest.mark.parametrize(
"page_sort, result_order",
[
({"field": "TITLE", "direction": "ASC"}, ["About", "Page1", "Page2"]),
({"field": "TITLE", "direction": "DESC"}, ["Page2", "Page1", "About"]),
({"field": "SLUG", "direction": "ASC"}, ["About", "Page2", "Page1"]),
({"field": "SLUG", "direction": "DESC"}, ["Page1", "Page2", "About"]),
({"field": "VISIBILITY", "direction": "ASC"}, ["Page2", "About", "Page1"]),
({"field": "VISIBILITY", "direction": "DESC"}, ["Page1", "About", "Page2"]),
({"field": "CREATION_DATE", "direction": "ASC"}, ["Page1", "About", "Page2"]),
({"field": "CREATION_DATE", "direction": "DESC"}, ["Page2", "About", "Page1"]),
(
{"field": "PUBLICATION_DATE", "direction": "ASC"},
["Page1", "Page2", "About"],
),
(
{"field": "PUBLICATION_DATE", "direction": "DESC"},
["About", "Page2", "Page1"],
),
],
)
def test_query_pages_with_sort(
page_sort, result_order, staff_api_client, permission_manage_pages, page_type
):
with freeze_time("2017-05-31 12:00:01"):
Page.objects.create(
title="Page1",
slug="slug_page_1",
content=dummy_editorjs("p1."),
is_published=True,
published_at=timezone.now().replace(year=2018, month=12, day=5),
page_type=page_type,
)
with freeze_time("2019-05-31 12:00:01"):
Page.objects.create(
title="Page2",
slug="page_2",
content=dummy_editorjs("p2."),
is_published=False,
published_at=timezone.now().replace(year=2019, month=12, day=5),
page_type=page_type,
)
with freeze_time("2018-05-31 12:00:01"):
Page.objects.create(
title="About",
slug="about",
content=dummy_editorjs("Ab."),
is_published=True,
page_type=page_type,
)
variables = {"sort_by": page_sort}
staff_api_client.user.user_permissions.add(permission_manage_pages)
response = staff_api_client.post_graphql(QUERY_PAGE_WITH_SORT, variables)
content = get_graphql_content(response)
pages = content["data"]["pages"]["edges"]
for order, page_name in enumerate(result_order):
assert pages[order]["node"]["title"] == page_name
| 1,369 |
2,151 | // Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef IOS_CHROME_BROWSER_UI_ACTIVITY_SERVICES_CHROME_ACTIVITY_ITEM_THUMBNAIL_GENERATOR_H_
#define IOS_CHROME_BROWSER_UI_ACTIVITY_SERVICES_CHROME_ACTIVITY_ITEM_THUMBNAIL_GENERATOR_H_
#import <CoreGraphics/CoreGraphics.h>
#import <UIKit/UIKit.h>
@class Tab;
// Block returning a thumbnail at the specified size. May return nil.
typedef UIImage* (^ThumbnailGeneratorBlock)(const CGSize&);
namespace activity_services {
// Returns a thumbnail generator for the tab |tab|. |tab| must not be nil.
ThumbnailGeneratorBlock ThumbnailGeneratorForTab(Tab* tab);
} // namespace activity_services
#endif // IOS_CHROME_BROWSER_UI_ACTIVITY_SERVICES_CHROME_ACTIVITY_ITEM_THUMBNAIL_GENERATOR_H_
| 303 |
7,886 | <filename>litho-it/src/test/resources/processor/sections/FullGroupSection.java
package com.facebook.litho.sections.processor.integration.resources;
import android.widget.TextView;
import androidx.annotation.AttrRes;
import androidx.annotation.Nullable;
import androidx.annotation.StringRes;
import androidx.annotation.VisibleForTesting;
import com.facebook.litho.ClickEvent;
import com.facebook.litho.CommonUtils;
import com.facebook.litho.Component;
import com.facebook.litho.Diff;
import com.facebook.litho.EventDispatcher;
import com.facebook.litho.EventHandler;
import com.facebook.litho.HasEventDispatcher;
import com.facebook.litho.StateContainer;
import com.facebook.litho.StateValue;
import com.facebook.litho.TreeProps;
import com.facebook.litho.annotations.Comparable;
import com.facebook.litho.annotations.Generated;
import com.facebook.litho.annotations.Prop;
import com.facebook.litho.annotations.PropSetter;
import com.facebook.litho.annotations.RequiredProp;
import com.facebook.litho.annotations.ResType;
import com.facebook.litho.annotations.State;
import com.facebook.litho.annotations.TreeProp;
import com.facebook.litho.sections.ChangesInfo;
import com.facebook.litho.sections.Children;
import com.facebook.litho.sections.LoadingEvent;
import com.facebook.litho.sections.Section;
import com.facebook.litho.sections.SectionContext;
import java.util.BitSet;
/**
* classJavadoc
*
* <p>
*
* @prop-required prop1 int
* @prop-optional prop2 java.lang.String
* @prop-required prop3 com.facebook.litho.Component
* @prop-required prop4 java.lang.String
* @prop-required prop5 com.facebook.litho.sections.Section
* @see com.facebook.litho.sections.processor.integration.resources.FullGroupSectionSpec
*/
@Generated
final class FullGroupSection<T> extends Section {
@Prop(resType = ResType.NONE, optional = false)
@Comparable(type = 3)
int prop1;
@Prop(resType = ResType.NONE, optional = true)
@Comparable(type = 13)
String prop2;
@Prop(resType = ResType.NONE, optional = false)
@Comparable(type = 10)
Component prop3;
@Prop(resType = ResType.STRING, optional = false)
@Comparable(type = 13)
String prop4;
@Prop(resType = ResType.NONE, optional = false)
@Comparable(type = 15)
Section prop5;
@TreeProp
@Comparable(type = 13)
FullGroupSectionSpec.TreePropWrapper treeProp;
String _service;
@Nullable EventHandler<TestEvent> testEventHandler;
private FullGroupSection() {
super("FullGroupSection");
}
private FullGroupSectionStateContainer getStateContainerImpl(SectionContext c) {
return (FullGroupSectionStateContainer) Section.getStateContainer(c, this);
}
@Override
protected FullGroupSectionStateContainer createStateContainer() {
return new FullGroupSectionStateContainer();
}
@Override
public boolean isEquivalentTo(Section other) {
if (this == other) {
return true;
}
if (other == null || getClass() != other.getClass()) {
return false;
}
FullGroupSection fullGroupSectionRef = (FullGroupSection) other;
if (prop1 != fullGroupSectionRef.prop1) {
return false;
}
if (prop2 != null
? !prop2.equals(fullGroupSectionRef.prop2)
: fullGroupSectionRef.prop2 != null) {
return false;
}
if (prop3 != null
? !prop3.isEquivalentTo(fullGroupSectionRef.prop3)
: fullGroupSectionRef.prop3 != null) {
return false;
}
if (prop4 != null
? !prop4.equals(fullGroupSectionRef.prop4)
: fullGroupSectionRef.prop4 != null) {
return false;
}
if (prop5 != null
? !prop5.isEquivalentTo(fullGroupSectionRef.prop5)
: fullGroupSectionRef.prop5 != null) {
return false;
}
if (!useTreePropsFromContext()) {
if (treeProp != null
? !treeProp.equals(fullGroupSectionRef.treeProp)
: fullGroupSectionRef.treeProp != null) {
return false;
}
}
return true;
}
@Override
public FullGroupSection makeShallowCopy(boolean deepCopy) {
FullGroupSection component = (FullGroupSection) super.makeShallowCopy(deepCopy);
component.prop3 = component.prop3 != null ? component.prop3.makeShallowCopy() : null;
component.prop5 = component.prop5 != null ? component.prop5.makeShallowCopy() : null;
if (!deepCopy) {
component.setStateContainer(new FullGroupSectionStateContainer());
}
return component;
}
public static <T> Builder<T> create(SectionContext context) {
FullGroupSection instance = new FullGroupSection();
return new Builder(context, instance);
}
@Override
protected void transferState(
StateContainer _prevStateContainer, StateContainer _nextStateContainer) {
FullGroupSectionStateContainer<T> prevStateContainer =
(FullGroupSectionStateContainer<T>) _prevStateContainer;
FullGroupSectionStateContainer<T> nextStateContainer =
(FullGroupSectionStateContainer<T>) _nextStateContainer;
nextStateContainer.state1 = prevStateContainer.state1;
nextStateContainer.state2 = prevStateContainer.state2;
}
private FullGroupSectionStateContainer getStateContainerWithLazyStateUpdatesApplied(
SectionContext c, FullGroupSection component) {
FullGroupSectionStateContainer _stateContainer = new FullGroupSectionStateContainer();
transferState(Section.getStateContainer(c, component), _stateContainer);
c.applyLazyStateUpdatesForContainer(_stateContainer);
return _stateContainer;
}
protected static void updateState(SectionContext c, Object param) {
Section _component = c.getSectionScope();
if (_component == null) {
return;
}
StateContainer.StateUpdate _stateUpdate = new StateContainer.StateUpdate(0, param);
c.updateStateAsync(_stateUpdate, "updateState:FullGroupSection.updateState");
}
protected static void updateStateAsync(SectionContext c, Object param) {
Section _component = c.getSectionScope();
if (_component == null) {
return;
}
StateContainer.StateUpdate _stateUpdate = new StateContainer.StateUpdate(0, param);
c.updateStateAsync(_stateUpdate, "updateState:FullGroupSection.updateState");
}
protected static void updateStateSync(SectionContext c, Object param) {
Section _component = c.getSectionScope();
if (_component == null) {
return;
}
StateContainer.StateUpdate _stateUpdate = new StateContainer.StateUpdate(0, param);
c.updateStateSync(_stateUpdate, "updateState:FullGroupSection.updateState");
}
protected static void lazyUpdateState2(SectionContext c, final Object lazyUpdateValue) {
Section _component = c.getSectionScope();
if (_component == null) {
return;
}
StateContainer.StateUpdate _stateUpdate =
new StateContainer.StateUpdate(-2147483648, lazyUpdateValue);
c.updateStateLazy(_stateUpdate);
}
@Nullable
public static EventHandler<TestEvent> getTestEventHandler(SectionContext context) {
if (context.getSectionScope() == null) {
return null;
}
return ((FullGroupSection) context.getSectionScope()).testEventHandler;
}
static void dispatchTestEvent(EventHandler _eventHandler) {
final TestEvent _eventState = new TestEvent();
EventDispatcher _dispatcher = _eventHandler.mHasEventDispatcher.getEventDispatcher();
_dispatcher.dispatchOnEvent(_eventHandler, _eventState);
}
private void testEvent(
HasEventDispatcher _abstract, SectionContext c, TextView view, int someParam) {
FullGroupSection _ref = (FullGroupSection) _abstract;
FullGroupSectionStateContainer stateContainer =
getStateContainerWithLazyStateUpdatesApplied(c, _ref);
FullGroupSectionSpec.testEvent(
c, view, someParam, (Object) stateContainer.state2, (String) _ref.prop2);
}
public static EventHandler<ClickEvent> testEvent(SectionContext c, int someParam) {
return newEventHandler(
FullGroupSection.class,
"FullGroupSection",
c,
-1204074200,
new Object[] {
c, someParam,
});
}
@Override
protected Object dispatchOnEventImpl(final EventHandler eventHandler, final Object eventState) {
int id = eventHandler.id;
switch (id) {
case -1204074200:
{
ClickEvent _event = (ClickEvent) eventState;
testEvent(
eventHandler.mHasEventDispatcher,
(SectionContext) eventHandler.params[0],
(TextView) _event.view,
(int) eventHandler.params[1]);
return null;
}
default:
return null;
}
}
@Override
protected void createInitialState(SectionContext c) {
StateValue<T> state1 = new StateValue<>();
StateValue<Object> state2 = new StateValue<>();
FullGroupSectionSpec.onCreateInitialState(
(SectionContext) c, (int) prop1, (StateValue<T>) state1, (StateValue<Object>) state2);
getStateContainerImpl(c).state1 = state1.get();
getStateContainerImpl(c).state2 = state2.get();
}
private String onCreateService(SectionContext c) {
String _result;
_result = (String) FullGroupSectionSpec.onCreateService((SectionContext) c, (String) prop2);
return _result;
}
@Override
public void createService(SectionContext context) {
_service = onCreateService(context);
}
@Override
protected void transferService(SectionContext c, Section previous, Section next) {
FullGroupSection previousSection = (FullGroupSection) previous;
FullGroupSection nextSection = (FullGroupSection) next;
nextSection._service = previousSection._service;
}
@Override
protected Object getService(Section section) {
return ((FullGroupSection) section)._service;
}
@Override
protected Children createChildren(SectionContext c) {
Children _result;
_result =
(Children)
FullGroupSectionSpec.onCreateChildren(
(SectionContext) c,
(Component) prop3,
(String) prop4,
(Section) prop5,
(T) getStateContainerImpl(c).state1);
return _result;
}
@Override
protected void bindService(SectionContext c) {
FullGroupSectionSpec.bindService(
(SectionContext) c,
(String) _service,
(int) prop1,
(Object) getStateContainerImpl(c).state2);
}
@Override
protected void unbindService(SectionContext c) {
FullGroupSectionSpec.unbindService(
(SectionContext) c,
(String) _service,
(int) prop1,
(Object) getStateContainerImpl(c).state2);
}
@Override
protected void refresh(SectionContext c) {
FullGroupSectionSpec.onRefresh((SectionContext) c, (String) _service, (String) prop2);
}
@Override
protected void dataBound(SectionContext c) {
FullGroupSectionSpec.onDataBound(
(SectionContext) c, (Component) prop3, (Object) getStateContainerImpl(c).state2);
}
@Override
protected boolean shouldUpdate(
SectionContext _prevScopedContext,
Section _prevAbstractImpl,
SectionContext _nextScopedContext,
Section _nextAbstractImpl) {
FullGroupSection _prevImpl = (FullGroupSection) _prevAbstractImpl;
FullGroupSection _nextImpl = (FullGroupSection) _nextAbstractImpl;
boolean _result;
Diff<Integer> prop1 =
new Diff<Integer>(
_prevImpl == null ? null : _prevImpl.prop1, _nextImpl == null ? null : _nextImpl.prop1);
_result = (boolean) FullGroupSectionSpec.shouldUpdate((Diff<Integer>) prop1);
return _result;
}
@Override
protected void viewportChanged(
SectionContext c,
int firstVisibleIndex,
int lastVisibleIndex,
int totalCount,
int firstFullyVisibleIndex,
int lastFullyVisibleIndex) {
FullGroupSectionSpec.onViewportChanged(
(SectionContext) c,
(int) firstVisibleIndex,
(int) lastVisibleIndex,
(int) totalCount,
(int) firstFullyVisibleIndex,
(int) lastFullyVisibleIndex,
(T) getStateContainerImpl(c).state1,
(Object) getStateContainerImpl(c).state2,
(int) prop1,
(String) prop2,
(Component) prop3);
}
@Override
protected void dataRendered(
SectionContext c,
boolean isDataChanged,
boolean isMounted,
long uptimeMillis,
int firstVisibleIndex,
int lastVisibleIndex,
ChangesInfo changesInfo,
int globalOffset) {
FullGroupSectionSpec.onDataRendered(
(SectionContext) c,
(boolean) isDataChanged,
(boolean) isMounted,
(long) uptimeMillis,
(int) firstVisibleIndex,
(int) lastVisibleIndex,
(ChangesInfo) changesInfo,
(int) globalOffset,
(int) prop1,
(Object) getStateContainerImpl(c).state2,
(int) getCached(c));
}
@Override
protected void populateTreeProps(TreeProps treeProps) {
if (treeProps == null) {
return;
}
treeProp =
treeProps.get(
com.facebook.litho.sections.processor.integration.resources.FullGroupSectionSpec
.TreePropWrapper.class);
}
@Override
protected TreeProps getTreePropsForChildren(SectionContext c, TreeProps parentTreeProps) {
final TreeProps childTreeProps = TreeProps.acquire(parentTreeProps);
childTreeProps.put(
com.facebook.litho.sections.processor.integration.resources.FullGroupSectionSpec
.TreePropWrapper.class,
FullGroupSectionSpec.onCreateTreeProp(
(SectionContext) c,
useTreePropsFromContext()
? ((FullGroupSectionSpec.TreePropWrapper)
Component.getTreePropFromParent(
parentTreeProps,
com.facebook.litho.sections.processor.integration.resources
.FullGroupSectionSpec.TreePropWrapper.class))
: treeProp));
return childTreeProps;
}
private int getCached(SectionContext c) {
String globalKey = c.getGlobalKey();
final CachedInputs inputs = new CachedInputs(globalKey, prop1);
Integer cached = (Integer) c.getCachedValue(inputs);
if (cached == null) {
cached = FullGroupSectionSpec.onCalculateCached(prop1);
c.putCachedValue(inputs, cached);
}
return cached;
}
@VisibleForTesting(otherwise = 2)
@Generated
static class FullGroupSectionStateContainer<T> extends StateContainer {
@State
@Comparable(type = 13)
T state1;
@State
@Comparable(type = 13)
Object state2;
@Override
public void applyStateUpdate(StateContainer.StateUpdate stateUpdate) {
StateValue<T> state1;
StateValue<Object> state2;
final Object[] params = stateUpdate.params;
switch (stateUpdate.type) {
case 0:
state2 = new StateValue<Object>();
state2.set(this.state2);
FullGroupSectionSpec.updateState(state2, params[0]);
this.state2 = state2.get();
break;
case -2147483648:
this.state2 = (Object) params[0];
break;
}
}
}
@Generated
public static final class Builder<T> extends Section.Builder<Builder<T>> {
FullGroupSection mFullGroupSection;
SectionContext mContext;
private final String[] REQUIRED_PROPS_NAMES = new String[] {"prop1", "prop3", "prop4", "prop5"};
private final int REQUIRED_PROPS_COUNT = 4;
private final BitSet mRequired = new BitSet(REQUIRED_PROPS_COUNT);
private Builder(SectionContext context, FullGroupSection fullGroupSectionRef) {
super(context, fullGroupSectionRef);
mFullGroupSection = fullGroupSectionRef;
mContext = context;
mRequired.clear();
}
@PropSetter(value = "prop1", required = true)
@RequiredProp("prop1")
public Builder<T> prop1(int prop1) {
this.mFullGroupSection.prop1 = prop1;
mRequired.set(0);
return this;
}
@PropSetter(value = "prop2", required = false)
public Builder<T> prop2(String prop2) {
this.mFullGroupSection.prop2 = prop2;
return this;
}
@PropSetter(value = "prop3", required = true)
@RequiredProp("prop3")
public Builder<T> prop3(Component prop3) {
this.mFullGroupSection.prop3 = prop3 == null ? null : prop3.makeShallowCopy();
mRequired.set(1);
return this;
}
@PropSetter(value = "prop3", required = true)
@RequiredProp("prop3")
public Builder<T> prop3(Component.Builder<?> prop3Builder) {
this.mFullGroupSection.prop3 = prop3Builder == null ? null : prop3Builder.build();
mRequired.set(1);
return this;
}
@PropSetter(value = "prop4", required = true)
@RequiredProp("prop4")
public Builder<T> prop4(String prop4) {
this.mFullGroupSection.prop4 = prop4;
mRequired.set(2);
return this;
}
@PropSetter(value = "prop4", required = true)
@RequiredProp("prop4")
public Builder<T> prop4Res(@StringRes int resId) {
this.mFullGroupSection.prop4 = mResourceResolver.resolveStringRes(resId);
mRequired.set(2);
return this;
}
@PropSetter(value = "prop4", required = true)
@RequiredProp("prop4")
public Builder<T> prop4Res(@StringRes int resId, Object... formatArgs) {
this.mFullGroupSection.prop4 = mResourceResolver.resolveStringRes(resId, formatArgs);
mRequired.set(2);
return this;
}
@PropSetter(value = "prop4", required = true)
@RequiredProp("prop4")
public Builder<T> prop4Attr(@AttrRes int attrResId, @StringRes int defResId) {
this.mFullGroupSection.prop4 = mResourceResolver.resolveStringAttr(attrResId, defResId);
mRequired.set(2);
return this;
}
@PropSetter(value = "prop4", required = true)
@RequiredProp("prop4")
public Builder<T> prop4Attr(@AttrRes int attrResId) {
this.mFullGroupSection.prop4 = mResourceResolver.resolveStringAttr(attrResId, 0);
mRequired.set(2);
return this;
}
@PropSetter(value = "prop5", required = true)
@RequiredProp("prop5")
public Builder<T> prop5(Section prop5) {
this.mFullGroupSection.prop5 = prop5;
mRequired.set(3);
return this;
}
@PropSetter(value = "prop5", required = true)
@RequiredProp("prop5")
public Builder<T> prop5(Section.Builder<?> prop5Builder) {
this.mFullGroupSection.prop5 = prop5Builder == null ? null : prop5Builder.build();
mRequired.set(3);
return this;
}
public Builder<T> testEventHandler(@Nullable EventHandler<TestEvent> testEventHandler) {
this.mFullGroupSection.testEventHandler = testEventHandler;
return this;
}
@Override
public Builder<T> key(String key) {
return super.key(key);
}
@Override
public Builder<T> loadingEventHandler(EventHandler<LoadingEvent> loadingEventHandler) {
return super.loadingEventHandler(loadingEventHandler);
}
@Override
public Builder<T> getThis() {
return this;
}
@Override
public FullGroupSection build() {
checkArgs(REQUIRED_PROPS_COUNT, mRequired, REQUIRED_PROPS_NAMES);
return mFullGroupSection;
}
}
@Generated
private static class CachedInputs {
private final String globalKey;
private final int prop1;
CachedInputs(String globalKey, int prop1) {
this.globalKey = globalKey;
this.prop1 = prop1;
}
@Override
public int hashCode() {
return CommonUtils.hash(globalKey, prop1, getClass());
}
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
}
if (other == null || !(other instanceof CachedInputs)) {
return false;
}
CachedInputs cachedValueInputs = (CachedInputs) other;
if (!com.facebook.litho.CommonUtils.equals(globalKey, cachedValueInputs.globalKey)) {
return false;
}
if (prop1 != cachedValueInputs.prop1) {
return false;
}
return true;
}
}
}
| 7,510 |
1,900 | /*
* Copyright Terracotta, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.ehcache.testing;
import org.junit.runner.Description;
import org.junit.runner.Request;
import org.junit.runner.manipulation.Filter;
import org.junit.runner.notification.RunNotifier;
import org.junit.runners.ParentRunner;
import org.junit.runners.model.InitializationError;
import org.junit.runners.model.TestClass;
import java.io.IOException;
import java.io.InputStream;
import java.lang.annotation.Annotation;
import java.lang.annotation.Repeatable;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.reflect.Modifier;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.jar.JarEntry;
import java.util.jar.JarInputStream;
import java.util.stream.Collectors;
import static java.util.Arrays.asList;
import static java.util.Collections.singletonList;
public class ExternalTests extends ParentRunner<Request> {
private final List<Request> children;
public ExternalTests(Class<?> testClass) throws InitializationError, IOException, ClassNotFoundException {
super(testClass);
this.children = singletonList(parseRequest(getTestClass(), parseFilter(getTestClass())));
}
@Override
protected List<Request> getChildren() {
return children;
}
@Override
protected Description describeChild(Request child) {
return child.getRunner().getDescription();
}
@Override
protected void runChild(Request child, RunNotifier notifier) {
child.getRunner().run(notifier);
}
private static Filter parseFilter(TestClass testClass) {
return groupAnnotations(testClass, Ignore.class, Ignores.class).stream().map(IgnoreFilter::ignore).reduce(Filter.ALL, Filter::intersect);
}
private static class IgnoreFilter extends Filter {
private final Ignore ignore;
public static Filter ignore(Ignore ignore) {
return new IgnoreFilter(ignore);
}
private IgnoreFilter(Ignore ignore) {
this.ignore = ignore;
}
@Override
public boolean shouldRun(Description description) {
if (ignore.value().equals(description.getTestClass())) {
if (ignore.method().isEmpty()) {
return false;
} else {
return !ignore.method().equals(description.getMethodName());
}
} else {
return true;
}
}
@Override
public String describe() {
if (ignore.method().isEmpty()) {
return "Ignore " + ignore.value();
} else {
return "Ignore " + ignore.value() + "#" + ignore.method();
}
}
}
private static Request parseRequest(TestClass testClass, Filter filter) throws IOException, ClassNotFoundException {
List<From> froms = groupAnnotations(testClass, From.class, Froms.class);
List<Test> tests = groupAnnotations(testClass, Test.class, Tests.class);
List<Class<?>> classes = new ArrayList<>();
for (From from : froms) {
URL location = from.value().getProtectionDomain().getCodeSource().getLocation();
try (InputStream is = location.openStream(); JarInputStream jis = new JarInputStream(is)) {
while (true) {
JarEntry entry = jis.getNextJarEntry();
if (entry == null) {
break;
} else if (entry.getName().endsWith("Test.class")) {
classes.add(Class.forName(entry.getName().replace(".class", "").replace('/', '.')));
}
}
}
}
for (Test test : tests) {
classes.add(test.value());
}
return Request.classes(classes.stream()
.filter(c -> Modifier.isPublic(c.getModifiers()) && !Modifier.isAbstract(c.getModifiers()))
.filter(c -> !c.getSimpleName().startsWith("Abstract")).toArray(Class[]::new))
.filterWith(filter);
}
@SuppressWarnings("unchecked")
private static <T extends Annotation, WT extends Annotation> List<T> groupAnnotations(TestClass testClass, Class<T> annoType, Class<WT> wrapperType) {
try {
List<T> annotations = new ArrayList<>();
WT testsAnn = testClass.getAnnotation(wrapperType);
if (testsAnn != null) {
annotations.addAll(asList((T[]) wrapperType.getMethod("value").invoke(testsAnn)));
}
T singularAnn = testClass.getAnnotation(annoType);
if (singularAnn != null) {
annotations.add(singularAnn);
}
return annotations;
} catch (ReflectiveOperationException e) {
throw new IllegalArgumentException(e);
}
}
@Retention(RetentionPolicy.RUNTIME)
@Repeatable(Tests.class)
public @interface Test {
Class<?> value();
}
@Retention(RetentionPolicy.RUNTIME)
public @interface Tests {
Test[] value();
}
@Retention(RetentionPolicy.RUNTIME)
@Repeatable(Froms.class)
public @interface From {
Class<?> value();
}
@Retention(RetentionPolicy.RUNTIME)
public @interface Froms {
From[] value();
}
@Retention(RetentionPolicy.RUNTIME)
@Repeatable(Ignores.class)
public @interface Ignore {
Class<?> value();
String method() default "";
}
@Retention(RetentionPolicy.RUNTIME)
public @interface Ignores {
Ignore[] value();
}
}
| 1,961 |
878 | <reponame>lfkdsk/JustWeEngine
package com.lfk.justweengine.utils.blueTooth;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;
import com.lfk.justweengine.R;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Set;
/**
* Created by liufengkai on 16/1/20.
*/
public class BlueToothServer {
// Debugging
private static final String TAG = "BluetoothChat";
private static final boolean D = true;
// Message types sent from the BluetoothChatService Handler
public static final int MESSAGE_STATE_CHANGE = 1;
public static final int MESSAGE_READ = 2;
public static final int MESSAGE_WRITE = 3;
public static final int MESSAGE_DEVICE_NAME = 4;
public static final int MESSAGE_TOAST = 5;
// Key names received from the BluetoothChatService Handler
public static final String DEVICE_NAME = "device_name";
public static final String TOAST = "toast";
// Intent request codes
private static final int REQUEST_CONNECT_DEVICE_SECURE = 1;
private static final int REQUEST_CONNECT_DEVICE_INSECURE = 2;
private static final int REQUEST_ENABLE_BT = 3;
// Name of the connected device
private String mConnectedDeviceName = null;
// Array adapter for the conversation thread
private BluetoothChatService mChatService = null;
private BluetoothAdapter mBluetoothAdapter = null;
private Activity context;
private CharSequence mBlueToothState = null;
// msg handler
private BlueToothMsgHandler mHandler;
private ArrayList<String> mNewDeviceList;
private OnMessageBack onMessageBack = null;
public BlueToothServer(Activity context, OnMessageBack messageBack) {
this.context = context;
this.onMessageBack = messageBack;
this.mHandler = new BlueToothMsgHandler();
// Get local Bluetooth adapter
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
// If the adapter is null, then Bluetooth is not supported
if (mBluetoothAdapter == null) {
Toast.makeText(context, "Bluetooth is not available", Toast.LENGTH_LONG).show();
}
}
public void init() {
if (!mBluetoothAdapter.isEnabled()) {
Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
context.startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
// Otherwise, setup the chat session
} else {
if (mChatService == null) setupChat();
}
// Register for broadcasts when a device is discovered
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
context.registerReceiver(mReceiver, filter);
// Register for broadcasts when discovery has finished
filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
context.registerReceiver(mReceiver, filter);
}
public void unBindService() {
if (mChatService != null) mChatService.stop();
if (mBluetoothAdapter != null) {
mBluetoothAdapter.cancelDiscovery();
}
// Unregister broadcast listeners
context.unregisterReceiver(mReceiver);
}
private void setupChat() {
Log.d(TAG, "setupChat()");
// Initialize the BluetoothChatService to perform bluetooth connections
mChatService = new BluetoothChatService(context, mHandler);
this.mNewDeviceList = new ArrayList<>();
}
/**
* handler for message
*/
@SuppressLint("HandlerLeak")
private class BlueToothMsgHandler extends Handler {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what) {
case MESSAGE_STATE_CHANGE:
if (D) Log.i(TAG, "MESSAGE_STATE_CHANGE: " + msg.arg1);
switch (msg.arg1) {
case BluetoothChatService.STATE_CONNECTED:
setStatus(context.getString(R.string.title_connected_to, mConnectedDeviceName));
break;
case BluetoothChatService.STATE_CONNECTING:
setStatus(R.string.title_connecting);
break;
case BluetoothChatService.STATE_LISTEN:
case BluetoothChatService.STATE_NONE:
setStatus(R.string.title_not_connected);
break;
}
break;
case MESSAGE_WRITE:
byte[] writeBuf = (byte[]) msg.obj;
// construct a string from the buffer
onMessageBack.sendMessage(Arrays.toString(writeBuf));
break;
case MESSAGE_READ:
byte[] readBuf = (byte[]) msg.obj;
// construct a string from the valid bytes in the buffer
onMessageBack.getMessage(Arrays.toString(readBuf));
break;
case MESSAGE_DEVICE_NAME:
// save the connected device's name
mConnectedDeviceName = msg.getData().getString(DEVICE_NAME);
Toast.makeText(context, "Connected to "
+ mConnectedDeviceName, Toast.LENGTH_SHORT).show();
break;
case MESSAGE_TOAST:
Toast.makeText(context, msg.getData().getString(TOAST),
Toast.LENGTH_SHORT).show();
break;
}
}
}
/**
* set BlueTooth state
*
* @param s
*/
private void setStatus(CharSequence s) {
this.mBlueToothState = s;
}
private void setStatus(int res) {
this.mBlueToothState = context.getString(res);
}
/**
* enable for discover by others' phone
*/
public void ensureDiscoverable() {
if (D) Log.d(TAG, "ensure discoverable");
if (mBluetoothAdapter.getScanMode() !=
BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE) {
Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
context.startActivity(discoverableIntent);
}
}
/**
* send message
*
* @param message
*/
public void sendMessage(String message) {
// Check that we're actually connected before trying anything
if (mChatService.getState() != BluetoothChatService.STATE_CONNECTED) {
Toast.makeText(context, R.string.not_connected, Toast.LENGTH_SHORT).show();
return;
}
// Check that there's actually something to send
if (message.length() > 0) {
// Get the message bytes and tell the BluetoothChatService to write
byte[] send = message.getBytes();
mChatService.write(send);
}
}
/**
* do discovery
*/
public void doDiscovery() {
if (D) Log.d(TAG, "doDiscovery()");
// If we're already discovering, stop it
if (mBluetoothAdapter.isDiscovering()) {
mBluetoothAdapter.cancelDiscovery();
}
// Request discover from BluetoothAdapter
mBluetoothAdapter.startDiscovery();
}
// The BroadcastReceiver that listens for discovered devices and
// changes the title when discovery is finished
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
// When discovery finds a device
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
// Get the BluetoothDevice object from the Intent
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
// If it's already paired, skip it, because it's been listed already
if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
mNewDeviceList.add(device.getName() + "\n" + device.getAddress());
}
// When discovery is finished, change the Activity title
} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
if (mNewDeviceList.size() == 0) {
mNewDeviceList.clear();
}
onMessageBack.getDevice(mNewDeviceList);
}
}
};
/**
* connect to a device
*
* @param address mac
* @param secure is secure?
*/
public void connectToDevice(String address, boolean secure) {
// Get the BluetoothDevice object
BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
// Attempt to connect to the device
mChatService.connect(device, secure);
}
public ArrayList<String> getPairedDevices() {
ArrayList<String> arrayList = new ArrayList<>();
Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
// If there are paired devices, add each one to the ArrayAdapter
if (pairedDevices.size() > 0) {
for (BluetoothDevice device : pairedDevices) {
arrayList.add(device.getName() + "\n" + device.getAddress());
}
} else {
arrayList.clear();
}
return arrayList;
}
}
| 4,238 |
421 | <gh_stars>100-1000
// System::Windows::Forms::DataGridTableStyle.ResetHeaderBackColor
/*
The following example demonstrates the 'ResetHeaderBackColor' method of 'DataGridTableStyle' class.
It adds a 'DataGrid' and two buttons to a form. Then it creates a 'DataGridTableStyle' and maps it to the table of
'DataGrid'. When the user clicks on 'Change the ResetHeaderBackColor' button it changes the Header Background
color to light pink. If the user clicks the 'ResetHeaderBackColor' button it changes the Header Background
Color to default color.
*/
#using <System.dll>
#using <System.Drawing.dll>
#using <System.Windows.Forms.dll>
#using <System.Data.dll>
#using <System.Xml.dll>
using namespace System;
using namespace System::ComponentModel;
using namespace System::Data;
using namespace System::Drawing;
using namespace System::Windows::Forms;
public ref class Form1: public Form
{
private:
Button^ myButton;
Button^ myButton1;
DataGrid^ myDataGrid;
DataSet^ myDataSet;
DataGridColumnStyle^ myDataGridColumnStyle;
DataGridTableStyle^ myDataTableStyle;
public:
Form1()
{
InitializeComponent();
MakeDataSet();
myDataGrid->SetDataBinding( myDataSet, "Customers" );
AddCustomDataTableStyle();
}
private:
void InitializeComponent()
{
// Create the form and its controls.
myButton = gcnew Button;
myButton1 = gcnew Button;
myDataGrid = gcnew DataGrid;
Text = "DataGridTableStyle Sample";
ClientSize = System::Drawing::Size( 450, 330 );
myButton->Location = Point(50,16);
myButton->Name = "button1";
myButton->Size = System::Drawing::Size( 176, 23 );
myButton->TabIndex = 2;
myButton->Text = "Change the HeaderBackColor";
myButton->Click += gcnew EventHandler( this, &Form1::Button_Click );
myButton1->Location = Point(230,16);
myButton1->Name = "myButton";
myButton1->Size = System::Drawing::Size( 140, 24 );
myButton1->TabIndex = 0;
myButton1->Text = "Reset HeaderBackColor";
myButton1->Click += gcnew EventHandler( this, &Form1::Button1_Click );
myDataGrid->Location = Point(24,50);
myDataGrid->Size = System::Drawing::Size( 240, 150 );
myDataGrid->CaptionText = "DataGridTableStyle";
Controls->Add( myButton );
Controls->Add( myDataGrid );
Controls->Add( myButton1 );
}
// <Snippet1>
private:
void Button_Click( Object^ /*sender*/, EventArgs^ /*e*/ )
{
// Change the color of 'HeaderBack'.
myDataTableStyle->HeaderBackColor = Color::LightPink;
}
void Button1_Click( Object^ /*sender*/, EventArgs^ /*e*/ )
{
// Reset the 'HeaderBack' to its origanal color.
myDataTableStyle->ResetHeaderBackColor();
}
// </Snippet1>
private:
void AddCustomDataTableStyle()
{
// Create a 'DataGridTableStyle'.
myDataTableStyle = gcnew DataGridTableStyle;
myDataTableStyle->MappingName = "Customers";
// Create a 'DataGridColumnStyle'.
myDataGridColumnStyle = gcnew DataGridTextBoxColumn;
myDataGridColumnStyle->MappingName = "CustName";
myDataGridColumnStyle->HeaderText = "Customer Name";
myDataGridColumnStyle->Width = 150;
// Add the 'DataGridColumnStyle' to 'DataGridTableStyle'.
myDataTableStyle->GridColumnStyles->Add( myDataGridColumnStyle );
// Add the 'DataGridTableStyle' to 'DataGrid'.
myDataGrid->TableStyles->Add( myDataTableStyle );
}
void MakeDataSet()
{
myDataSet = gcnew DataSet( "myDataSet" );
DataTable^ myTable = gcnew DataTable( "Customers" );
DataColumn^ myColumn = gcnew DataColumn( "CustName",String::typeid );
myTable->Columns->Add( myColumn );
myDataSet->Tables->Add( myTable );
DataRow^ newRow1;
for ( int i = 0; i < 5; i++ )
{
newRow1 = myTable->NewRow();
newRow1[ "CustName" ] = i;
// Add the row to the Customers table.
myTable->Rows->Add( newRow1 );
}
myTable->Rows[ 0 ][ "CustName" ] = "Jones";
myTable->Rows[ 1 ][ "CustName" ] = "James";
myTable->Rows[ 2 ][ "CustName" ] = "David";
myTable->Rows[ 3 ][ "CustName" ] = "Robert";
myTable->Rows[ 4 ][ "CustName" ] = "John";
}
};
int main()
{
Application::Run( gcnew Form1 );
}
| 1,792 |
372 | /*
* 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.
*/
/*
* This code was generated by https://github.com/googleapis/google-api-java-client-services/
* Modify at your own risk.
*/
package com.google.api.services.privateca.v1beta1.model;
/**
* A CertificateDescription describes an X.509 certificate or CSR that has been issued, as an
* alternative to using ASN.1 / X.509.
*
* <p> This is the Java data model class that specifies how to parse/serialize into the JSON that is
* transmitted over HTTP when working with the Certificate Authority API. For a detailed explanation
* see:
* <a href="https://developers.google.com/api-client-library/java/google-http-java-client/json">https://developers.google.com/api-client-library/java/google-http-java-client/json</a>
* </p>
*
* @author Google, Inc.
*/
@SuppressWarnings("javadoc")
public final class CertificateDescription extends com.google.api.client.json.GenericJson {
/**
* Describes lists of issuer CA certificate URLs that appear in the "Authority Information Access"
* extension in the certificate.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<java.lang.String> aiaIssuingCertificateUrls;
/**
* Identifies the subject_key_id of the parent certificate, per
* https://tools.ietf.org/html/rfc5280#section-4.2.1.1
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private KeyId authorityKeyId;
/**
* The hash of the x.509 certificate.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private CertificateFingerprint certFingerprint;
/**
* Describes some of the technical fields in a certificate.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private ReusableConfigValues configValues;
/**
* Describes a list of locations to obtain CRL information, i.e. the DistributionPoint.fullName
* described by https://tools.ietf.org/html/rfc5280#section-4.2.1.13
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<java.lang.String> crlDistributionPoints;
/**
* The public key that corresponds to an issued certificate.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private PublicKey publicKey;
/**
* Describes some of the values in a certificate that are related to the subject and lifetime.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private SubjectDescription subjectDescription;
/**
* Provides a means of identifiying certificates that contain a particular public key, per
* https://tools.ietf.org/html/rfc5280#section-4.2.1.2.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private KeyId subjectKeyId;
/**
* Describes lists of issuer CA certificate URLs that appear in the "Authority Information Access"
* extension in the certificate.
* @return value or {@code null} for none
*/
public java.util.List<java.lang.String> getAiaIssuingCertificateUrls() {
return aiaIssuingCertificateUrls;
}
/**
* Describes lists of issuer CA certificate URLs that appear in the "Authority Information Access"
* extension in the certificate.
* @param aiaIssuingCertificateUrls aiaIssuingCertificateUrls or {@code null} for none
*/
public CertificateDescription setAiaIssuingCertificateUrls(java.util.List<java.lang.String> aiaIssuingCertificateUrls) {
this.aiaIssuingCertificateUrls = aiaIssuingCertificateUrls;
return this;
}
/**
* Identifies the subject_key_id of the parent certificate, per
* https://tools.ietf.org/html/rfc5280#section-4.2.1.1
* @return value or {@code null} for none
*/
public KeyId getAuthorityKeyId() {
return authorityKeyId;
}
/**
* Identifies the subject_key_id of the parent certificate, per
* https://tools.ietf.org/html/rfc5280#section-4.2.1.1
* @param authorityKeyId authorityKeyId or {@code null} for none
*/
public CertificateDescription setAuthorityKeyId(KeyId authorityKeyId) {
this.authorityKeyId = authorityKeyId;
return this;
}
/**
* The hash of the x.509 certificate.
* @return value or {@code null} for none
*/
public CertificateFingerprint getCertFingerprint() {
return certFingerprint;
}
/**
* The hash of the x.509 certificate.
* @param certFingerprint certFingerprint or {@code null} for none
*/
public CertificateDescription setCertFingerprint(CertificateFingerprint certFingerprint) {
this.certFingerprint = certFingerprint;
return this;
}
/**
* Describes some of the technical fields in a certificate.
* @return value or {@code null} for none
*/
public ReusableConfigValues getConfigValues() {
return configValues;
}
/**
* Describes some of the technical fields in a certificate.
* @param configValues configValues or {@code null} for none
*/
public CertificateDescription setConfigValues(ReusableConfigValues configValues) {
this.configValues = configValues;
return this;
}
/**
* Describes a list of locations to obtain CRL information, i.e. the DistributionPoint.fullName
* described by https://tools.ietf.org/html/rfc5280#section-4.2.1.13
* @return value or {@code null} for none
*/
public java.util.List<java.lang.String> getCrlDistributionPoints() {
return crlDistributionPoints;
}
/**
* Describes a list of locations to obtain CRL information, i.e. the DistributionPoint.fullName
* described by https://tools.ietf.org/html/rfc5280#section-4.2.1.13
* @param crlDistributionPoints crlDistributionPoints or {@code null} for none
*/
public CertificateDescription setCrlDistributionPoints(java.util.List<java.lang.String> crlDistributionPoints) {
this.crlDistributionPoints = crlDistributionPoints;
return this;
}
/**
* The public key that corresponds to an issued certificate.
* @return value or {@code null} for none
*/
public PublicKey getPublicKey() {
return publicKey;
}
/**
* The public key that corresponds to an issued certificate.
* @param publicKey publicKey or {@code null} for none
*/
public CertificateDescription setPublicKey(PublicKey publicKey) {
this.publicKey = publicKey;
return this;
}
/**
* Describes some of the values in a certificate that are related to the subject and lifetime.
* @return value or {@code null} for none
*/
public SubjectDescription getSubjectDescription() {
return subjectDescription;
}
/**
* Describes some of the values in a certificate that are related to the subject and lifetime.
* @param subjectDescription subjectDescription or {@code null} for none
*/
public CertificateDescription setSubjectDescription(SubjectDescription subjectDescription) {
this.subjectDescription = subjectDescription;
return this;
}
/**
* Provides a means of identifiying certificates that contain a particular public key, per
* https://tools.ietf.org/html/rfc5280#section-4.2.1.2.
* @return value or {@code null} for none
*/
public KeyId getSubjectKeyId() {
return subjectKeyId;
}
/**
* Provides a means of identifiying certificates that contain a particular public key, per
* https://tools.ietf.org/html/rfc5280#section-4.2.1.2.
* @param subjectKeyId subjectKeyId or {@code null} for none
*/
public CertificateDescription setSubjectKeyId(KeyId subjectKeyId) {
this.subjectKeyId = subjectKeyId;
return this;
}
@Override
public CertificateDescription set(String fieldName, Object value) {
return (CertificateDescription) super.set(fieldName, value);
}
@Override
public CertificateDescription clone() {
return (CertificateDescription) super.clone();
}
}
| 2,585 |
4,170 | <filename>docs/codesnippets/194_top_x_of_user.py
from itertools import islice
from math import ceil
from instaloader import Instaloader, Profile
PROFILE = ... # profile to download from
X_percentage = 10 # percentage of posts that should be downloaded
L = Instaloader()
profile = Profile.from_username(L.context, PROFILE)
posts_sorted_by_likes = sorted(profile.get_posts(),
key=lambda p: p.likes + p.comments,
reverse=True)
for post in islice(posts_sorted_by_likes, ceil(profile.mediacount * X_percentage / 100)):
L.download_post(post, PROFILE)
| 263 |
546 | <reponame>you-ri/LiliumToonGraph<filename>Packages/jp.lilium.toongraph/package.json
{
"name": "jp.lilium.toongraph",
"version": "0.5.0-preview.5",
"unity": "2020.2",
"author": "You-Ri",
"displayName": "Lilium ToonGraph",
"dependencies": {
"com.unity.render-pipelines.universal": "10.3.1"
},
"description": "UniversalRP Toon Shader with ShaderGraph"
} | 157 |
1,840 | /**
* Copyright Pravega Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* 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 io.pravega.controller.store;
import io.pravega.client.tables.impl.TableSegmentEntry;
import io.pravega.client.tables.impl.TableSegmentKey;
import io.pravega.client.tables.impl.TableSegmentKeyVersion;
import io.pravega.controller.server.SegmentHelper;
import io.pravega.controller.server.security.auth.GrpcAuthHelper;
import io.pravega.controller.store.stream.OperationContext;
import io.pravega.test.common.ThreadPooledTestSuite;
import org.junit.Test;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import static java.util.Collections.singletonList;
import static org.junit.Assert.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
public class PravegaTablesScopeTest extends ThreadPooledTestSuite {
private final String scope = "scope";
private final String stream = "stream";
private final String indexTable = "table";
private final String tag = "tag";
private final byte[] tagBytes = tag.getBytes(StandardCharsets.UTF_8);
private final OperationContext context = new TestOperationContext();
private List<TableSegmentKey> keySnapshot;
@Test(timeout = 5000)
@SuppressWarnings("unchecked")
public void testRemoveTagsUnderScope() {
// Setup Mocks.
GrpcAuthHelper authHelper = mock(GrpcAuthHelper.class);
when(authHelper.retrieveMasterToken()).thenReturn("");
SegmentHelper segmentHelper = mock(SegmentHelper.class);
PravegaTablesStoreHelper storeHelper = new PravegaTablesStoreHelper(segmentHelper, authHelper, executorService());
PravegaTablesScope tablesScope = spy(new PravegaTablesScope(scope, storeHelper));
doReturn(CompletableFuture.completedFuture(indexTable)).when(tablesScope)
.getAllStreamTagsInScopeTableNames(stream, context);
// Simulate an empty value being returned.
TableSegmentEntry entry = TableSegmentEntry.versioned(tagBytes, new byte[0], 1L);
when(segmentHelper.readTable(eq(indexTable), any(), anyString(), anyLong()))
.thenReturn(CompletableFuture.completedFuture(singletonList(entry)));
when(segmentHelper.updateTableEntries(eq(indexTable), any(), anyString(), anyLong()))
.thenReturn(CompletableFuture.completedFuture(singletonList(TableSegmentKeyVersion.from(2L))));
when(segmentHelper.removeTableKeys(eq(indexTable), any(), anyString(), anyLong()))
.thenAnswer(invocation -> {
//Capture the key value sent during removeTableKeys.
keySnapshot = (List<TableSegmentKey>) invocation.getArguments()[1];
return CompletableFuture.completedFuture(null);
});
// Invoke the removeTags method.
tablesScope.removeTagsUnderScope(stream, Set.of(tag), context).join();
// Verify if correctly detect that the data is empty and the entry is cleaned up.
verify(segmentHelper, times(1)).removeTableKeys(eq(indexTable), eq(keySnapshot), anyString(), anyLong());
// Verify if the version number is as expected.
assertEquals(2L, keySnapshot.get(0).getVersion().getSegmentVersion());
}
} | 1,502 |
2,816 | <reponame>AldoMyrtaj/duckdb
//===----------------------------------------------------------------------===//
// DuckDB
//
// duckdb/parser/parsed_data/parse_info.hpp
//
//
//===----------------------------------------------------------------------===//
#pragma once
#include "duckdb/common/common.hpp"
namespace duckdb {
struct ParseInfo {
virtual ~ParseInfo() {
}
};
} // namespace duckdb
| 142 |
849 | package milkman.ui.plugin;
import java.util.List;
/**
* this is an interface that can be used in request- and response-aspect-editors.
* If any of those implement this interface, a list of registered contentTypePlugins will be
* injected before doing anything else with those editors.
*/
public interface ContentTypeAwareEditor {
void setContentTypePlugins(List<ContentTypePlugin> plugins);
}
| 104 |
980 | <reponame>HeeroYui/jcodec
package org.jcodec.containers.mp4.boxes;
import java.nio.ByteBuffer;
import org.jcodec.common.io.NIOUtils;
import org.jcodec.platform.Platform;
/**
* This class is part of JCodec ( www.jcodec.org ) This software is distributed
* under FreeBSD License
*
* @author The JCodec project
*
*/
public class TextConfigBox extends FullBox {
private String textConfig;
public TextConfigBox(Header atom) {
super(atom);
}
public static String fourcc() {
return "txtC";
}
public static TextConfigBox createTextConfigBox(String textConfig) {
TextConfigBox box = new TextConfigBox(new Header(fourcc()));
box.textConfig = textConfig;
return box;
}
@Override
public void parse(ByteBuffer input) {
super.parse(input);
textConfig = NIOUtils.readNullTermStringCharset(input, Platform.UTF_8);
}
@Override
protected void doWrite(ByteBuffer out) {
super.doWrite(out);
NIOUtils.writeNullTermString(out, textConfig);
}
@Override
public int estimateSize() {
return 13 + Platform.getBytesForCharset(textConfig, Platform.UTF_8).length;
}
public String getTextConfig() {
return textConfig;
}
}
| 488 |
687 | <filename>core/src/test/java/io/kestra/core/runners/WorkerTest.java<gh_stars>100-1000
package io.kestra.core.runners;
import com.google.common.collect.ImmutableMap;
import io.kestra.core.models.executions.LogEntry;
import io.micronaut.context.ApplicationContext;
import io.micronaut.test.extensions.junit5.annotation.MicronautTest;
import org.junit.jupiter.api.Test;
import io.kestra.core.models.executions.Execution;
import io.kestra.core.models.executions.ExecutionKilled;
import io.kestra.core.models.executions.TaskRun;
import io.kestra.core.models.flows.Flow;
import io.kestra.core.models.flows.State;
import io.kestra.core.models.tasks.ResolvedTask;
import io.kestra.core.queues.QueueFactoryInterface;
import io.kestra.core.queues.QueueInterface;
import io.kestra.core.tasks.scripts.Bash;
import io.kestra.core.utils.Await;
import io.kestra.core.utils.IdUtils;
import io.kestra.core.utils.TestsUtils;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicReference;
import javax.inject.Inject;
import javax.inject.Named;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
@MicronautTest
class WorkerTest {
@Inject
ApplicationContext applicationContext;
@Inject
@Named(QueueFactoryInterface.WORKERTASK_NAMED)
QueueInterface<WorkerTask> workerTaskQueue;
@Inject
@Named(QueueFactoryInterface.WORKERTASKRESULT_NAMED)
QueueInterface<WorkerTaskResult> workerTaskResultQueue;
@Inject
@Named(QueueFactoryInterface.KILL_NAMED)
QueueInterface<ExecutionKilled> executionKilledQueue;
@Inject
@Named(QueueFactoryInterface.WORKERTASKLOG_NAMED)
QueueInterface<LogEntry> workerTaskLogQueue;
@Inject
RunContextFactory runContextFactory;
@Test
void success() throws TimeoutException {
Worker worker = new Worker(applicationContext, 8);
worker.run();
AtomicReference<WorkerTaskResult> workerTaskResult = new AtomicReference<>(null);
workerTaskResultQueue.receive(workerTaskResult::set);
workerTaskQueue.emit(workerTask("1"));
Await.until(
() -> workerTaskResult.get() != null && workerTaskResult.get().getTaskRun().getState().isTerninated(),
Duration.ofMillis(100),
Duration.ofMinutes(1)
);
assertThat(workerTaskResult.get().getTaskRun().getState().getHistories().size(), is(3));
}
@Test
void killed() throws InterruptedException, TimeoutException {
List<LogEntry> logs = new ArrayList<>();
workerTaskLogQueue.receive(logs::add);
Worker worker = new Worker(applicationContext, 8);
worker.run();
List<WorkerTaskResult> workerTaskResult = new ArrayList<>();
workerTaskResultQueue.receive(workerTaskResult::add);
WorkerTask workerTask = workerTask("999");
workerTaskQueue.emit(workerTask);
workerTaskQueue.emit(workerTask);
workerTaskQueue.emit(workerTask);
workerTaskQueue.emit(workerTask);
WorkerTask notKilled = workerTask("2");
workerTaskQueue.emit(notKilled);
Thread.sleep(500);
executionKilledQueue.emit(ExecutionKilled.builder().executionId(workerTask.getTaskRun().getExecutionId()).build());
Await.until(
() -> workerTaskResult.stream().filter(r -> r.getTaskRun().getState().isTerninated()).count() == 5,
Duration.ofMillis(100),
Duration.ofMinutes(1)
);
WorkerTaskResult oneKilled = workerTaskResult.stream()
.filter(r -> r.getTaskRun().getState().getCurrent() == State.Type.KILLED)
.findFirst()
.orElseThrow();
assertThat(oneKilled.getTaskRun().getState().getHistories().size(), is(3));
assertThat(oneKilled.getTaskRun().getState().getCurrent(), is(State.Type.KILLED));
WorkerTaskResult oneNotKilled = workerTaskResult.stream()
.filter(r -> r.getTaskRun().getState().getCurrent() == State.Type.SUCCESS)
.findFirst()
.orElseThrow();
assertThat(oneNotKilled.getTaskRun().getState().getHistories().size(), is(3));
assertThat(oneNotKilled.getTaskRun().getState().getCurrent(), is(State.Type.SUCCESS));
// child process is stopped and we never received 3 logs
Thread.sleep(1000);
assertThat(logs.stream().filter(logEntry -> logEntry.getMessage().equals("3")).count(), is(0L));
}
private WorkerTask workerTask(String sleep) {
Bash bash = Bash.builder()
.type(Bash.class.getName())
.id("unit-test")
.commands(new String[]{"for i in $(seq 1 " + sleep + "); do echo $i; sleep 1; done"})
.build();
Flow flow = Flow.builder()
.id(IdUtils.create())
.namespace("io.kestra.unit-test")
.tasks(Collections.singletonList(bash))
.build();
Execution execution = TestsUtils.mockExecution(flow, ImmutableMap.of());
ResolvedTask resolvedTask = ResolvedTask.of(bash);
return WorkerTask.builder()
.runContext(runContextFactory.of(ImmutableMap.of("key", "value")))
.task(bash)
.taskRun(TaskRun.of(execution, resolvedTask))
.build();
}
}
| 2,170 |
854 | __________________________________________________________________________________________________
sample 120 ms submission
static const auto speedup = []()
{
std::ios::sync_with_stdio(false);
std::cin.tie(NULL);
return 0;
}();
class TrieNode
{
public:
int num;
vector<TrieNode*> next;
TrieNode(): num(-1), next(26, NULL){}
};
class Solution
{
private:
TrieNode* buildTrie(vector<string>& words)
{
TrieNode* root=new TrieNode();
for(int i=0; i<words.size(); ++i)
{
string tmp=words[i];
reverse(tmp.begin(), tmp.end());
TrieNode* curr=root;
for(int j=0; j<tmp.size(); ++j)
{
if(!curr->next[tmp[j]-'a'])
curr->next[tmp[j]-'a']=new TrieNode();
curr=curr->next[tmp[j]-'a'];
}
curr->num=i;
}
return root;
}
inline bool isPP(string& a, string& b)
{
string c=a+b;
int head=0;
int tail=c.size()-1;
while(head<tail)
{
if(c[head]!=c[tail])
return false;
head++;
tail--;
}
return true;
}
inline bool isPP(string c)
{
int head=0;
int tail=c.size()-1;
while(head<tail)
{
if(c[head]!=c[tail])
return false;
head++;
tail--;
}
return true;
}
void backtracking(TrieNode* root, vector<string>& words, int start, int index, vector<vector<int>>& result)
{
if(root->num >= 0 && index!=root->num)//we find it in TrieNode
{
if(isPP(words[index], words[root->num]))
{
vector<int> tmp={index, root->num};
result.emplace_back(tmp);
}
}
for(int i=0; i<26; ++i)
{
if(start<words[index].size() && root->next[i] && i==int(words[index][start]-'a'))
backtracking(root->next[i], words, start+1, index, result);
if(start==words[index].size() && root->next[i])
backtracking(root->next[i], words, start, index, result);
}
}
public:
vector<vector<int>> palindromePairs(vector<string>& words) //more concise
{
vector<vector<int>> result;
int wsize=words.size();
if(wsize<2)
return result;
unordered_map<string, int>dict;
for(int i=0; i<wsize; ++i)
dict[words[i]]=i;
for(int i=0; i<wsize; ++i)
{
for(int j=0; j<words[i].size(); ++j)
{
if(is_palindrome(words[i], j, words[i].size()-1))
{
string prefix=words[i].substr(0,j);//does not include the whole s, but include ""
reverse(prefix.begin(), prefix.end());
if(dict.find(prefix)!=dict.end() && dict[prefix]!=i)
result.push_back({i, dict[prefix]});
}
}
for(int j=0; j<=words[i].size(); ++j)
{
if(is_palindrome(words[i], 0, j-1))
{
string prefix=words[i].substr(j);//include the whole s and should also include ""
//when j=words.size(), substr=""
reverse(prefix.begin(), prefix.end());
if(dict.find(prefix)!=dict.end() && dict[prefix]!=i)
result.push_back({dict[prefix], i});
}
}
}
return result;
}
bool is_palindrome(string& s, int start, int end) {
while(start < end) {
if(s[start++] != s[end--]) {
return false;
}
}
return true;
}
};
__________________________________________________________________________________________________
sample 31020 kb submission
#include<vector>
#include<string>
#include<unordered_map>
#include<algorithm>
#include<iostream>
using namespace std;
class Solution {
public:
typedef unordered_map<string,int> mapt;
// index: 0 1 2 3 4
// a b c d e
// index2: 01234567
// p[i] = length of palindrome at index2 i
vector<int> p;
inline char mapStr(const string &s, int index){
return index % 2 ? 0 : s[index/2];
}
// find the matching word that can form a complete palindrome
void find(const mapt&m, vector<vector<int>>&ans, int index, int palinLen,const string &s,const string &sr, bool rev){
string prefix = rev ? s.substr(palinLen): sr.substr(0, sr.size()-palinLen);
mapt::const_iterator it = m.find(prefix);
if (it != m.end() && index != it->second){
if (rev){
ans.push_back({index, it->second});
}
else {
ans.push_back({it->second, index });
}
}
}
void check(const mapt&m, vector<vector<int>>&ans, int index,const string &s, const string &sr, bool rev ){
if (s.size()==0)
return;
int palinLenHalf = 0;
const int maxIndex2 = s.size()*2-2;
p.clear();
p.reserve(maxIndex2+1);
// manacher's algo
for (int i=0,j=0;i<= maxIndex2;){
// expand palindrome
while (i-1-palinLenHalf >= 0 &&
i+1+palinLenHalf <= maxIndex2 &&
mapStr(s, i-1-palinLenHalf) == mapStr(s,i+1+palinLenHalf)){
palinLenHalf++;
}
p[i]=1+palinLenHalf*2;
const int ir = min(maxIndex2, i+palinLenHalf);
palinLenHalf=0;
for ( j=i+1; j <= ir; j++){
const int jp = i-(j-i);
const int jpl = p[jp];
if (jpl/2 + j >= ir){
palinLenHalf = ir-j;
break;
}
p[j] = jpl;
}
i=j;
}
// find prefix that is a palindrome
for (int i=0;i <=maxIndex2;i++){
if (i-p[i]/2 == 0){
const int palinLen = (p[i]+1)/2;
// find the missing word needed
find(m,ans,index, palinLen,s, sr, rev);
}
}
}
vector<vector<int>> palindromePairs(vector<string>& words) {
mapt m;
m.reserve(words.size());
int i=0;
vector<vector<int>> ans;
for (const string & s : words){
m [s] = i++;
}
i=0;
for (const string & s : words){
string sr(s);
reverse(sr.begin(),sr.end());
// find prefixes that are palindrome
check(m,ans,i,s,sr,false);
// find suffixes that are palindrome
check(m,ans,i,sr,s,true);
// account for the zero-length prefix palindrome
find(m,ans,i, 0, s,sr, false);
i++;
}
return ans;
}
};
__________________________________________________________________________________________________
| 4,054 |
2,347 | <gh_stars>1000+
{
"$schema": "node_modules/ng-packagr/ng-package.schema.json",
"dest": "build",
"lib": {
"entryFile": "src/index.ts",
"umdModuleIds": {
"@sentry/browser": "Sentry",
"@sentry/utils": "Sentry.util"
}
},
"whitelistedNonPeerDependencies": ["@sentry/browser", "@sentry/utils", "@sentry/types", "tslib"],
"assets": ["README.md", "LICENSE"]
}
| 174 |
416 | /*
* xlibc/stdio/fflush.c
*/
#include <errno.h>
#include <stdio.h>
int fflush(FILE * f)
{
if (!f)
return EINVAL;
if(!f->write)
return EINVAL;
return __stdio_write_flush(f);
}
| 102 |
502 | <reponame>jackx22/fixflow
/**
* Copyright 1996-2013 Founder International Co.,Ltd.
*
* 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 kenshin
*/
package com.founder.fix.fixflow.core.variable;
import java.util.List;
import java.util.Map;
import com.founder.fix.fixflow.core.runtime.ExecutionContext;
public interface BizData {
/**
* getMasterValue(获取流程主表的指定字段的值)
* TODO(这里描述这个方法适用条件 – 可选)
* TODO(这里描述这个方法的执行流程 – 可选)
* TODO(这里描述这个方法的使用方法 – 可选)
* TODO(这里描述这个方法的注意事项 – 可选)
*
* @Title: getMasterValue
* @Description: TODO
* @param @param defkey
* @param @param bizkey
* @param @param field 字段名
* @param @return 设定文件
* @return Object 返回类型
* @throws
*/
public Object getMasterValue(String defkey, String bizkey,String field);
/**
* getMasterMap(获取主表的整条记录)
* TODO(这里描述这个方法适用条件 – 可选)
* TODO(这里描述这个方法的执行流程 – 可选)
* TODO(这里描述这个方法的使用方法 – 可选)
* TODO(这里描述这个方法的注意事项 – 可选)
*
* @Title: getMasterMap
* @Description: TODO
* @param @param defkey
* @param @param bizkey
* @param @return 设定文件
* @return Map<String,Object> 返回类型
* @throws
*/
public Map<String,Object> getMasterMap(String defkey, String bizkey);
//,"明细字段名称"
//
/**
* getDetailAll(获取明细关联的所有值)
* TODO(这里描述这个方法适用条件 – 可选)
* TODO(这里描述这个方法的执行流程 – 可选)
* TODO(这里描述这个方法的使用方法 – 可选)
* TODO(这里描述这个方法的注意事项 – 可选)
*
* @Title: getDetailAll
* @Description: TODO
* @param @param defkey
* @param @param bizkey
* @param @param detailName 明细表名
* @param @return 设定文件
* @return List<Map<String,Object>> 返回类型
* @throws
*/
public List<Map<String,Object>> getDetailAll(String defkey, String bizkey, String detailName);
//
/**
* getDetailRows(获取明细表关联的指定行数据)
* TODO(这里描述这个方法适用条件 – 可选)
* TODO(这里描述这个方法的执行流程 – 可选)
* TODO(这里描述这个方法的使用方法 – 可选)
* TODO(这里描述这个方法的注意事项 – 可选)
*
* @Title: getDetailRows
* @Description: TODO
* @param @param defkey
* @param @param bizkey
* @param @param detailName
* @param @param rowNum
* @param @return 设定文件
* @return Map<String,Object> 返回类型
* @throws
*/
public Map<String,Object> getDetailRows(String defkey, String bizkey, String detailName, int rowNum);
//获取明细表指定的行、列的数据
public Object getDetailValue(String defkey, String bizkey, String detailName, int rowNum, String field);
//获取一列所有行的数据
public List<Object> getDetailColumnValue(String defkey, String bizkey, String detailName, String field);
public List<Map<String, Object>> getDataValueAll(String dataBaseId, String bizkey, String field, ExecutionContext executionContext);
public Object getDataValue(String dataBaseId, String bizkey, String field, ExecutionContext executionContext);
}
| 1,919 |
6,199 | <reponame>eddiejames/GameNetworkingSockets
//========= Copyright Valve LLC, All rights reserved. ========================
#include "crypto.h"
#include "crypto_25519.h"
#include <tier0/dbg.h>
#ifdef STEAMNETWORKINGSOCKETS_CRYPTO_25519_OPENSSL
#include <openssl/evp.h>
#if OPENSSL_VERSION_NUMBER < 0x10101000
// https://www.openssl.org/docs/man1.1.1/man3/EVP_PKEY_get_raw_private_key.html
#error "Raw access to 25519 keys requires OpenSSL 1.1.1"
#endif
CEC25519KeyBase::~CEC25519KeyBase()
{
Wipe();
}
bool CEC25519KeyBase::IsValid() const
{
return m_evp_pkey != nullptr;
}
uint32 CEC25519KeyBase::GetRawData( void *pData ) const
{
EVP_PKEY *pkey = (EVP_PKEY*)m_evp_pkey;
if ( !pkey )
return 0;
// All 25519 keys are the same size
if ( !pData )
return 32;
// Using a switch here instead of overriding virtual functions
// seems kind of messy, but given the other crypto providers,
// it's probably the simplest, cleanest thing.
size_t len = 32;
switch ( m_eKeyType )
{
case k_ECryptoKeyTypeSigningPublic:
case k_ECryptoKeyTypeKeyExchangePublic:
if ( EVP_PKEY_get_raw_public_key( pkey, (unsigned char *)pData, &len ) != 1 )
{
AssertMsg( false, "EVP_PKEY_get_raw_public_key failed?" );
return 0;
}
break;
case k_ECryptoKeyTypeSigningPrivate:
case k_ECryptoKeyTypeKeyExchangePrivate:
if ( EVP_PKEY_get_raw_private_key( pkey, (unsigned char *)pData, &len ) != 1 )
{
AssertMsg( false, "EVP_PKEY_get_raw_private_key failed?" );
return 0;
}
break;
default:
AssertMsg( false, "Invalid 25519 key type" );
return 0;
}
if ( len != 32 )
{
AssertMsg1( false, "unexpected raw key size %d", (int)len );
return 0;
}
return 32;
}
void CEC25519KeyBase::Wipe()
{
// We should never be using the raw buffer
Assert( CCryptoKeyBase_RawBuffer::m_pData == nullptr );
Assert( CCryptoKeyBase_RawBuffer::m_cbData == 0 );
EVP_PKEY_free( (EVP_PKEY*)m_evp_pkey );
m_evp_pkey = nullptr;
}
bool CEC25519KeyBase::SetRawData( const void *pData, size_t cbData )
{
Wipe();
EVP_PKEY *pkey = nullptr;
switch ( m_eKeyType )
{
case k_ECryptoKeyTypeSigningPublic:
pkey = EVP_PKEY_new_raw_public_key( EVP_PKEY_ED25519, nullptr, (const unsigned char *)pData, cbData );
break;
case k_ECryptoKeyTypeSigningPrivate:
pkey = EVP_PKEY_new_raw_private_key( EVP_PKEY_ED25519, nullptr, (const unsigned char *)pData, cbData );
break;
case k_ECryptoKeyTypeKeyExchangePublic:
pkey = EVP_PKEY_new_raw_public_key( EVP_PKEY_X25519, nullptr, (const unsigned char *)pData, cbData );
break;
case k_ECryptoKeyTypeKeyExchangePrivate:
pkey = EVP_PKEY_new_raw_private_key( EVP_PKEY_X25519, nullptr, (const unsigned char *)pData, cbData );
break;
}
if ( pkey == nullptr )
{
AssertMsg1( false, "EVP_PKEY_new_raw_xxx_key failed for key type %d", (int)m_eKeyType );
return false;
}
// Success
m_evp_pkey = pkey;
return true;
}
bool CCrypto::PerformKeyExchange( const CECKeyExchangePrivateKey &localPrivateKey, const CECKeyExchangePublicKey &remotePublicKey, SHA256Digest_t *pSharedSecretOut )
{
// Check if caller didn't provide valid keys
EVP_PKEY *pkey = (EVP_PKEY*)localPrivateKey.evp_pkey();
EVP_PKEY *peerkey = (EVP_PKEY*)remotePublicKey.evp_pkey();
if ( !pkey || !peerkey )
{
AssertMsg( false, "Cannot perform key exchange, keys not valid" );
GenerateRandomBlock( pSharedSecretOut, sizeof(*pSharedSecretOut) ); // In case caller isn't checking return value
return false;
}
size_t skeylen = sizeof(*pSharedSecretOut);
uint8 bufSharedSecret[32];
EVP_PKEY_CTX *ctx = EVP_PKEY_CTX_new( pkey, nullptr );
// Unless we have a bug, all these errors "should never happen".
VerifyFatal( ctx );
VerifyFatal( EVP_PKEY_derive_init(ctx) == 1 );
VerifyFatal( EVP_PKEY_derive_set_peer(ctx, peerkey) == 1 );
VerifyFatal( EVP_PKEY_derive(ctx, bufSharedSecret, &skeylen ) == 1 );
VerifyFatal( skeylen == sizeof(*pSharedSecretOut) );
EVP_PKEY_CTX_free(ctx);
GenerateSHA256Digest( bufSharedSecret, sizeof(bufSharedSecret), pSharedSecretOut );
SecureZeroMemory( bufSharedSecret, 32 );
return true;
}
void CECSigningPrivateKey::GenerateSignature( const void *pData, size_t cbData, CryptoSignature_t *pSignatureOut ) const
{
EVP_PKEY *pkey = (EVP_PKEY*)m_evp_pkey;
if ( !pkey )
{
AssertMsg( false, "Key not initialized, cannot generate signature" );
memset( pSignatureOut, 0, sizeof( CryptoSignature_t ) );
return;
}
EVP_MD_CTX *ctx = EVP_MD_CTX_create();
VerifyFatal( ctx );
VerifyFatal( EVP_DigestSignInit( ctx, nullptr, nullptr, nullptr, pkey ) == 1 );
size_t siglen = sizeof(*pSignatureOut);
VerifyFatal( EVP_DigestSign( ctx, (unsigned char *)pSignatureOut, &siglen, (const unsigned char *)pData, cbData ) == 1 );
VerifyFatal( siglen == sizeof(*pSignatureOut) );
EVP_MD_CTX_free(ctx);
}
bool CECSigningPublicKey::VerifySignature( const void *pData, size_t cbData, const CryptoSignature_t &signature ) const
{
EVP_PKEY *pkey = (EVP_PKEY*)m_evp_pkey;
if ( !pkey )
{
AssertMsg( false, "Key not initialized, cannot verify signature" );
return false;
}
EVP_MD_CTX *ctx = EVP_MD_CTX_create();
VerifyFatal( ctx );
VerifyFatal( EVP_DigestVerifyInit( ctx, nullptr, nullptr, nullptr, pkey ) == 1 );
int r = EVP_DigestVerify( ctx, (const unsigned char *)signature, sizeof(signature), (const unsigned char *)pData, cbData );
EVP_MD_CTX_free(ctx);
return r == 1;
}
bool CEC25519PrivateKeyBase::CachePublicKey()
{
EVP_PKEY *pkey = (EVP_PKEY*)m_evp_pkey;
if ( !pkey )
return false;
size_t len = 32;
if ( !EVP_PKEY_get_raw_public_key( pkey, m_publicKey, &len ) )
{
AssertMsg( false, "EVP_PKEY_get_raw_public_key failed?!" );
return false;
}
Assert( len == 32 );
return true;
}
#endif // #ifdef GNS_CRYPTO_25519_OPENSSL
| 2,379 |
3,603 | <gh_stars>1000+
/*
* 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 io.trino.plugin.thrift.api;
import io.airlift.drift.annotations.ThriftConstructor;
import io.airlift.drift.annotations.ThriftField;
import io.airlift.drift.annotations.ThriftStruct;
import java.util.List;
import java.util.Objects;
import static com.google.common.base.MoreObjects.toStringHelper;
import static java.util.Objects.requireNonNull;
@ThriftStruct
public final class TrinoThriftSplit
{
private final TrinoThriftId splitId;
private final List<TrinoThriftHostAddress> hosts;
@ThriftConstructor
public TrinoThriftSplit(TrinoThriftId splitId, List<TrinoThriftHostAddress> hosts)
{
this.splitId = requireNonNull(splitId, "splitId is null");
this.hosts = requireNonNull(hosts, "hosts is null");
}
/**
* Encodes all the information needed to identify a batch of rows to return to Trino.
* For a basic scan, includes schema name, table name, and output constraint.
* For an index scan, includes schema name, table name, set of keys to lookup and output constraint.
*/
@ThriftField(1)
public TrinoThriftId getSplitId()
{
return splitId;
}
/**
* Identifies the set of hosts on which the rows are available. If empty, then the rows
* are expected to be available on any host. The hosts in this list may be independent
* from the hosts used to serve metadata requests.
*/
@ThriftField(2)
public List<TrinoThriftHostAddress> getHosts()
{
return hosts;
}
@Override
public boolean equals(Object obj)
{
if (this == obj) {
return true;
}
if (obj == null || getClass() != obj.getClass()) {
return false;
}
TrinoThriftSplit other = (TrinoThriftSplit) obj;
return Objects.equals(this.splitId, other.splitId) &&
Objects.equals(this.hosts, other.hosts);
}
@Override
public int hashCode()
{
return Objects.hash(splitId, hosts);
}
@Override
public String toString()
{
return toStringHelper(this)
.add("splitId", splitId)
.add("hosts", hosts)
.toString();
}
}
| 1,023 |
365 | <filename>dhash/dhblock_keyhash_srv.h
#include <dhblock_replicated_srv.h>
class dhblock_keyhash_srv : public dhblock_replicated_srv
{
void real_store (chordID key, str od, str nd, u_int32_t exp, cb_dhstat cb);
void real_repair (blockID key, ptr<location> me, u_int32_t *myaux, ptr<location> them, u_int32_t *theiraux);
void delete_cb (chordID k, str d, u_int32_t v, u_int32_t exp, cb_dhstat cb, adb_status stat);
public:
dhblock_keyhash_srv (ptr<vnode> node, ptr<dhashcli> cli,
str msock, str dbsock, str dbname,
ptr<chord_trigger_t> t);
};
| 253 |
318 | // __BEGIN_LICENSE__
// Copyright (c) 2006-2013, United States Government as represented by the
// Administrator of the National Aeronautics and Space Administration. All
// rights reserved.
//
// The NASA Vision Workbench is 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.
// __END_LICENSE__
#if 0
#include <vw/gui/TextureCache.h>
using namespace vw;
using namespace vw::gui;
// --------------------------------------------------------------
// TextureRequest
// --------------------------------------------------------------
struct vw::gui::TextureRequest {
virtual ~TextureRequest() {}
virtual void process_request() = 0;
};
// Allocate Texture Request
class AllocateTextureRequest : public TextureRequest {
boost::shared_ptr<TextureRecordBase> m_record;
boost::shared_ptr<SrcImageResource> m_tile;
CachedTextureRenderer* m_parent;
public:
AllocateTextureRequest( boost::shared_ptr<TextureRecordBase> texture_record,
boost::shared_ptr<SrcImageResource> tile,
CachedTextureRenderer* parent) :
m_record(texture_record), m_tile(tile), m_parent(parent) {}
virtual ~AllocateTextureRequest() {}
virtual void process_request() {
m_record->texture_id = m_parent->allocate_texture(m_tile);
}
};
// Deallocate Texture Request
class DeallocateTextureRequest : public TextureRequest {
boost::shared_ptr<TextureRecordBase> m_record;
CachedTextureRenderer* m_parent;
public:
DeallocateTextureRequest( boost::shared_ptr<TextureRecordBase> texture_record,
CachedTextureRenderer* parent) :
m_record(texture_record), m_parent(parent) {}
virtual ~DeallocateTextureRequest() {}
virtual void process_request() {
m_parent->deallocate_texture(m_record->texture_id);
m_record->texture_id = 0;
}
};
// --------------------------------------------------------------
// CachedTextureRenderer
// --------------------------------------------------------------
void CachedTextureRenderer::request_allocation(boost::shared_ptr<TextureRecordBase> texture_record,
boost::shared_ptr<SrcImageResource> tile) {
vw::Mutex::Lock lock(m_request_mutex);
m_requests.push_back( boost::shared_ptr<TextureRequest>(new AllocateTextureRequest(texture_record, tile, this)) );
}
void CachedTextureRenderer::request_deallocation(boost::shared_ptr<TextureRecordBase> texture_record) {
vw::Mutex::Lock lock(m_request_mutex);
m_requests.push_back( boost::shared_ptr<TextureRequest>(new DeallocateTextureRequest(texture_record, this)) );
}
void CachedTextureRenderer::process_allocation_requests() {
vw::Mutex::Lock lock(m_request_mutex);
boost::shared_ptr<TextureRequest> r;
while (!m_requests.empty()) {
r = m_requests.front();
m_requests.pop_front();
r->process_request();
}
}
// --------------------------------------------------------------
// TextureFetchTask
// --------------------------------------------------------------
class vw::gui::TextureFetchTask {
bool terminate;
vw::Mutex &m_request_mutex;
std::list<boost::shared_ptr<TextureRecord> > &m_requests;
public:
TextureFetchTask(vw::Mutex &request_queue_mutex,
std::list<boost::shared_ptr<TextureRecord> > &request_queue) :
terminate(false), m_request_mutex(request_queue_mutex), m_requests(request_queue) {}
void operator()() {
while (!terminate) {
// Drain the request queue
bool found = false;
boost::shared_ptr<TextureRecord> r;
{
vw::Mutex::Lock lock(m_request_mutex);
if (!m_requests.empty()) {
r = m_requests.front();
m_requests.pop_front();
found = true;
}
}
if (found) {
// Force the texture to regenerate. Doing so will cause the
// image tile to be loaded into memory, and then a texture
// allocation request to be generated to be handled later by
// the OpenGL thread. This may cause one or more texture
// deallocation requests to be produced as well if cache tile
// need to be deallocated to make room for the new tile.
(*(r->handle)).texture_id();
r->handle.release();
} else {
// If there were no requests, sleep for a short time.
vw::Thread::sleep_ms(100);
}
}
}
void kill() { terminate = true; }
};
// --------------------------------------------------------------
// GlTextureCache
// --------------------------------------------------------------
vw::gui::GlTextureCache::GlTextureCache(boost::shared_ptr<TileGenerator> tile_generator) :
m_tile_generator(tile_generator) {
// Create the texture cache
int gl_texture_cache_size = 256 * 1024 * 1024; // Use 128-MB of
// texture cache
m_gl_texture_cache_ptr = new vw::Cache( gl_texture_cache_size );
// Start the texture fetch thread
m_texture_fetch_task.reset(new TextureFetchTask(m_request_mutex, m_requests));
m_texture_fetch_thread = new vw::Thread( m_texture_fetch_task );
// Create the texture record tree for storing cache handles and
// other useful texture-related metadata.
m_texture_records.reset( new gui::TreeNode<boost::shared_ptr<TextureRecord> >() );
m_previous_level = 0;
}
vw::gui::GlTextureCache::~GlTextureCache() {
// Stop the Texture Fetch thread
m_texture_fetch_task->kill();
m_texture_fetch_thread->join();
delete m_texture_fetch_thread;
// Free up remaining texture handles, and then the cache itself.
m_requests.clear();
delete m_gl_texture_cache_ptr;
}
void vw::gui::GlTextureCache::clear() {
Mutex::Lock lock(m_request_mutex);
m_requests.clear();
// Delete all of the existing texture records
m_texture_records.reset( new gui::TreeNode<boost::shared_ptr<TextureRecord> >() );
m_previous_level = 0;
}
GLuint vw::gui::GlTextureCache::get_texture_id(vw::gui::TileLocator const& tile_info,
CachedTextureRenderer* requestor) {
// Bail early if the tile_info request is totally invalid.
if (!tile_info.is_valid())
return 0;
// We purge the outgoing request queue whenever there is a change
// in LOD so that we can immediately begin serving tiles at the
// new level of detail.
if (tile_info.level != m_previous_level) {
Mutex::Lock lock(m_request_mutex);
m_requests.clear();
m_previous_level = tile_info.level;
}
try {
// First, see if the texture record is already in the cache.
boost::shared_ptr<TextureRecord> rec = m_texture_records->search(tile_info.col,
tile_info.row,
tile_info.level,
tile_info.transaction_id,
false);
// If the shared pointer for this record is empty, then this node
// was generated as part of a branch that supports a leaf node,
// but this node does not itself contain any data yet. To
// populate it with data, we throw an exception to run the code
// below.
if ( !rec )
vw_throw(gui::TileNotFoundErr() << "invalid record. regenerating...");
// If the texture_id of this record is 0, then we need to send a
// request to regenerate the texture. It will get rendered in the
// future after it has been loaded.
if (rec->texture_id == 0) {
Mutex::Lock lock(m_request_mutex);
m_requests.push_back( rec );
return 0;
}
// If the texture_id is valid, then the tile must be good. Return
// the texture_id to satisfy the request.
return rec->texture_id;
} catch (const gui::TileNotFoundErr& e) {
// If the tile isn't found or hasn't been properly initialized
// yet, we need to add an entry to the cache and then cause the
// tile to be generated.
TextureRecord* new_record = new TextureRecord();
boost::shared_ptr<TextureRecord> new_record_ptr(new_record);
new_record->texture_id = 0;
new_record->requestor = requestor;
new_record->handle = m_gl_texture_cache_ptr->insert( GlTextureGenerator(m_tile_generator,
tile_info,
new_record_ptr) );
new_record->handle.release();
// Place this cache handle into the tree for later access.
m_texture_records->insert( new_record_ptr, tile_info.col, tile_info.row,
tile_info.level, tile_info.transaction_id );
Mutex::Lock lock(m_request_mutex);
m_requests.push_back( new_record_ptr );
return 0;
}
return 0; // never reached
}
#endif
| 3,586 |
14,668 | // Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/android/profile_key_util.h"
#include "chrome/browser/android/profile_key_startup_accessor.h"
#include "chrome/browser/profiles/profile_key.h"
#include "chrome/browser/profiles/profile_manager.h"
namespace android {
namespace {
Profile* GetProfile() {
Profile* profile = ProfileManager::GetLastUsedProfile();
DCHECK(profile);
return profile;
}
} // namespace
ProfileKey* GetLastUsedRegularProfileKey() {
ProfileKey* key = ProfileKeyStartupAccessor::GetInstance()->profile_key();
if (!key)
key = GetProfile()->GetProfileKey();
DCHECK(key && !key->IsOffTheRecord());
return key;
}
} // namespace android
| 253 |
1,236 | /***************************************************************************
*
* 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.
*
**************************************************************************/
// Author: <NAME>(BDG)<<EMAIL>>
// <NAME> <<EMAIL>>
#ifndef FLUME_PLANNER_TESTING_EDGE_DESC_H_
#define FLUME_PLANNER_TESTING_EDGE_DESC_H_
#include <algorithm>
#include <set>
#include <string>
#include <vector>
#include "boost/lexical_cast.hpp"
#include "boost/make_shared.hpp"
#include "boost/shared_ptr.hpp"
#include "glog/logging.h"
#include "flume/planner/pass.h"
#include "flume/planner/plan.h"
#include "flume/planner/unit.h"
namespace baidu {
namespace flume {
namespace planner {
class EdgeDesc {
public:
virtual ~EdgeDesc() {}
virtual void Set(Unit* from, Unit* to) = 0;
virtual bool Test(Unit* from, Unit* to) = 0;
};
typedef boost::shared_ptr<EdgeDesc> EdgeDescRef;
EdgeDescRef PreparedEdge();
EdgeDescRef PartialEdge();
} // namespace planner
} // namespace flume
} // namespace baidu
#endif // FLUME_PLANNER_TESTING_EDGE_DESC_H_
| 533 |
2,151 | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef NET_SOCKET_SSL_CLIENT_SOCKET_H_
#define NET_SOCKET_SSL_CLIENT_SOCKET_H_
#include <stdint.h>
#include <string>
#include <vector>
#include "base/gtest_prod_util.h"
#include "base/strings/string_piece.h"
#include "net/base/completion_callback.h"
#include "net/base/load_flags.h"
#include "net/base/net_errors.h"
#include "net/base/net_export.h"
#include "net/socket/ssl_socket.h"
#include "net/socket/stream_socket.h"
#include "net/ssl/token_binding.h"
namespace base {
class FilePath;
}
namespace net {
class CTPolicyEnforcer;
class CertVerifier;
class ChannelIDService;
class CTVerifier;
class TransportSecurityState;
// This struct groups together several fields which are used by various
// classes related to SSLClientSocket.
struct SSLClientSocketContext {
SSLClientSocketContext() = default;
SSLClientSocketContext(CertVerifier* cert_verifier_arg,
ChannelIDService* channel_id_service_arg,
TransportSecurityState* transport_security_state_arg,
CTVerifier* cert_transparency_verifier_arg,
CTPolicyEnforcer* ct_policy_enforcer_arg,
const std::string& ssl_session_cache_shard_arg)
: cert_verifier(cert_verifier_arg),
channel_id_service(channel_id_service_arg),
transport_security_state(transport_security_state_arg),
cert_transparency_verifier(cert_transparency_verifier_arg),
ct_policy_enforcer(ct_policy_enforcer_arg),
ssl_session_cache_shard(ssl_session_cache_shard_arg) {}
CertVerifier* cert_verifier = nullptr;
ChannelIDService* channel_id_service = nullptr;
TransportSecurityState* transport_security_state = nullptr;
CTVerifier* cert_transparency_verifier = nullptr;
CTPolicyEnforcer* ct_policy_enforcer = nullptr;
// ssl_session_cache_shard is an opaque string that identifies a shard of the
// SSL session cache. SSL sockets with the same ssl_session_cache_shard may
// resume each other's SSL sessions but we'll never sessions between shards.
std::string ssl_session_cache_shard;
};
// A client socket that uses SSL as the transport layer.
//
// NOTE: The SSL handshake occurs within the Connect method after a TCP
// connection is established. If a SSL error occurs during the handshake,
// Connect will fail.
//
class NET_EXPORT SSLClientSocket : public SSLSocket {
public:
SSLClientSocket();
// Log SSL key material to |path|. Must be called before any
// SSLClientSockets are created.
//
// TODO(davidben): Switch this to a parameter on the SSLClientSocketContext
// once https://crbug.com/458365 is resolved. To avoid a dependency from
// OS_NACL to file I/O logic, this will require splitting SSLKeyLogger into an
// interface, built with OS_NACL and a non-NaCl SSLKeyLoggerImpl.
static void SetSSLKeyLogFile(const base::FilePath& path);
// Returns true if |error| is OK or |load_flags| ignores certificate errors
// and |error| is a certificate error.
static bool IgnoreCertError(int error, int load_flags);
// ClearSessionCache clears the SSL session cache, used to resume SSL
// sessions.
static void ClearSessionCache();
protected:
void set_signed_cert_timestamps_received(
bool signed_cert_timestamps_received) {
signed_cert_timestamps_received_ = signed_cert_timestamps_received;
}
void set_stapled_ocsp_response_received(bool stapled_ocsp_response_received) {
stapled_ocsp_response_received_ = stapled_ocsp_response_received;
}
// Serialize |next_protos| in the wire format for ALPN and NPN: protocols are
// listed in order, each prefixed by a one-byte length.
static std::vector<uint8_t> SerializeNextProtos(
const NextProtoVector& next_protos);
private:
FRIEND_TEST_ALL_PREFIXES(SSLClientSocket, SerializeNextProtos);
// For signed_cert_timestamps_received_ and stapled_ocsp_response_received_.
FRIEND_TEST_ALL_PREFIXES(SSLClientSocketTest,
ConnectSignedCertTimestampsTLSExtension);
FRIEND_TEST_ALL_PREFIXES(SSLClientSocketTest,
ConnectSignedCertTimestampsEnablesOCSP);
FRIEND_TEST_ALL_PREFIXES(SSLClientSocketTest,
ConnectSignedCertTimestampsDisabled);
FRIEND_TEST_ALL_PREFIXES(SSLClientSocketTest,
VerifyServerChainProperlyOrdered);
// True if SCTs were received via a TLS extension.
bool signed_cert_timestamps_received_;
// True if a stapled OCSP response was received.
bool stapled_ocsp_response_received_;
};
} // namespace net
#endif // NET_SOCKET_SSL_CLIENT_SOCKET_H_
| 1,722 |
407 | <gh_stars>100-1000
package com.alibaba.tesla.appmanager.server.repository;
import com.alibaba.tesla.appmanager.server.repository.condition.ProductReleaseAppRelQueryCondition;
import com.alibaba.tesla.appmanager.server.repository.domain.ProductReleaseAppRelDO;
import java.util.List;
public interface ProductReleaseAppRelRepository {
long countByCondition(ProductReleaseAppRelQueryCondition condition);
int deleteByCondition(ProductReleaseAppRelQueryCondition condition);
int insert(ProductReleaseAppRelDO record);
List<ProductReleaseAppRelDO> selectByCondition(ProductReleaseAppRelQueryCondition condition);
ProductReleaseAppRelDO getByCondition(ProductReleaseAppRelQueryCondition condition);
int updateByCondition(ProductReleaseAppRelDO record, ProductReleaseAppRelQueryCondition condition);
} | 222 |
310 | {
"name": "rikaikun",
"description": "A Chrome extension for translating Japanese.",
"url": "https://chrome.google.com/webstore/detail/rikaikun/jipdnfibhldikgcjhfnomkfpcebammhp?hl=en"
} | 73 |
2,236 | #import <UIKit/UIKit.h>
#import "BaseCollectionCell.h"
NS_ASSUME_NONNULL_BEGIN
@interface ImageCollectionViewCell : BaseCollectionCell
@property (nonatomic, strong) UIImageView *imgV;
@end
NS_ASSUME_NONNULL_END
| 80 |
348 | <gh_stars>100-1000
{"nom":"Sainte-Agathe-d'Aliermont","dpt":"Seine-Maritime","inscrits":254,"abs":65,"votants":189,"blancs":11,"nuls":3,"exp":175,"res":[{"panneau":"2","voix":126},{"panneau":"1","voix":49}]} | 88 |
1,875 | /*
* Copyright 2017 <NAME>.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.teavm.classlib.java.util;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.util.DuplicateFormatFlagsException;
import java.util.FormatFlagsConversionMismatchException;
import java.util.Formattable;
import java.util.Formatter;
import java.util.IllegalFormatCodePointException;
import java.util.IllegalFormatConversionException;
import java.util.IllegalFormatFlagsException;
import java.util.IllegalFormatPrecisionException;
import java.util.Locale;
import java.util.MissingFormatWidthException;
import java.util.UnknownFormatConversionException;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.teavm.junit.TeaVMTestRunner;
import org.teavm.junit.WholeClassCompilation;
@RunWith(TeaVMTestRunner.class)
@WholeClassCompilation
public class FormatterTest {
@Test(expected = UnknownFormatConversionException.class)
public void unexpectedEndOfFormatString() {
new Formatter().format("%1", "foo");
}
@Test(expected = DuplicateFormatFlagsException.class)
public void duplicateFlag() {
new Formatter().format("%--s", "q");
}
@Test(expected = UnknownFormatConversionException.class)
public void noPrecisionAfterDot() {
new Formatter().format("%1.s", "q");
}
@Test
public void bothPreviousModifierAndArgumentIndexPresent() {
String result = new Formatter().format("%s %2$<s", "q", "w").toString();
assertEquals("q q", result);
}
@Test
public void formatsBoolean() {
assertEquals("true", new Formatter().format("%b", true).toString());
assertEquals("false", new Formatter().format("%b", false).toString());
assertEquals("true", new Formatter().format("%b", new Object()).toString());
assertEquals("false", new Formatter().format("%b", null).toString());
assertEquals(" true", new Formatter().format("%6b", true).toString());
assertEquals("true ", new Formatter().format("%-6b", true).toString());
assertEquals("true", new Formatter().format("%2b", true).toString());
assertEquals("tr", new Formatter().format("%2.2b", true).toString());
assertEquals(" tr", new Formatter().format("%4.2b", true).toString());
assertEquals("TRUE", new Formatter().format("%B", true).toString());
try {
new Formatter().format("%+b", true);
fail("Should have thrown exception");
} catch (FormatFlagsConversionMismatchException e) {
assertEquals("+", e.getFlags());
assertEquals('b', e.getConversion());
}
}
@Test
public void formatsString() {
assertEquals("23 foo", new Formatter().format("%s %s", 23, "foo").toString());
assertEquals("0:-1:-1", new Formatter().format("%s", new A()).toString());
assertEquals("0:2:-1", new Formatter().format("%2s", new A()).toString());
assertEquals("0:2:3", new Formatter().format("%2.3s", new A()).toString());
assertEquals("1:3:-1", new Formatter().format("%-3s", new A()).toString());
}
static class A implements Formattable {
@Override
public void formatTo(Formatter formatter, int flags, int width, int precision) {
formatter.format("%s", flags + ":" + width + ":" + precision);
}
}
@Test
public void formatsHashCode() {
assertEquals("18cc6 17C13", new Formatter().format("%h %H", "foo", "bar").toString());
}
@Test
public void respectsFormatArgumentOrder() {
String result = new Formatter().format("%s %s %<s %1$s %<s %s %1$s %s %<s", "a", "b", "c", "d").toString();
assertEquals("a b b a a c a d d", result);
}
@Test
public void formatsChar() {
assertEquals("x: Y:\uDBFF\uDFFF ", new Formatter().format("%c:%3C:%-3c", 'x', 'y', 0x10ffff).toString());
try {
new Formatter().format("%c", Integer.MAX_VALUE);
fail("IllegalFormatCodePointException expected");
} catch (IllegalFormatCodePointException e) {
assertEquals(Integer.MAX_VALUE, e.getCodePoint());
}
assertEquals("null", new Formatter().format("%c", new Object[] { null }).toString());
try {
new Formatter().format("%C", new A());
fail("IllegalFormatConversionException expected");
} catch (IllegalFormatConversionException e) {
assertEquals(A.class, e.getArgumentClass());
}
try {
new Formatter().format("%3.1c", 'X');
fail("IllegalFormatPrecisionException expected");
} catch (IllegalFormatPrecisionException e) {
assertEquals(1, e.getPrecision());
}
}
@Test
public void formatsDecimalInteger() {
assertEquals("1 2 3 4", new Formatter().format("%d %d %d %d", (byte) 1, (short) 2, 3, 4L).toString());
assertEquals("00023", new Formatter().format("%05d", 23).toString());
assertEquals("-0023", new Formatter().format("%05d", -23).toString());
assertEquals("00001,234", new Formatter(Locale.US).format("%0,9d", 1234).toString());
assertEquals("(001,234)", new Formatter(Locale.US).format("%0,(9d", -1234).toString());
assertEquals("1 12 123 1,234 12,345 123,456 1,234,567", new Formatter(Locale.US)
.format("%,d %,d %,d %,d %,d %,d %,d", 1, 12, 123, 1234, 12345, 123456, 1234567).toString());
assertEquals(" -123:-234 ", new Formatter().format("%6d:%-6d", -123, -234).toString());
assertEquals("+123 +0123 +0", new Formatter().format("%+d %+05d %+d", 123, 123, 0).toString());
assertEquals(": 123:-123:", new Formatter().format(":% d:% d:", 123, -123).toString());
try {
new Formatter().format("%#d", 23);
fail("Should have thrown exception 1");
} catch (FormatFlagsConversionMismatchException e) {
assertEquals("#", e.getFlags());
}
try {
new Formatter().format("% +d", 23);
fail("Should have thrown exception 2");
} catch (IllegalFormatFlagsException e) {
assertTrue(e.getFlags().contains("+"));
assertTrue(e.getFlags().contains(" "));
}
try {
new Formatter().format("%-01d", 23);
fail("Should have thrown exception 3");
} catch (IllegalFormatFlagsException e) {
assertTrue(e.getFlags().contains("-"));
assertTrue(e.getFlags().contains("0"));
}
try {
new Formatter().format("%-d", 23);
fail("Should have thrown exception 4");
} catch (MissingFormatWidthException e) {
assertTrue(e.getFormatSpecifier().contains("d"));
}
try {
new Formatter().format("%1.2d", 23);
fail("Should have thrown exception 5");
} catch (IllegalFormatPrecisionException e) {
assertEquals(2, e.getPrecision());
}
}
@Test
public void formatsOctalInteger() {
assertEquals("1 2 3 4", new Formatter().format("%o %o %o %o", (byte) 1, (short) 2, 3, 4L).toString());
assertEquals("00027", new Formatter().format("%05o", 23).toString());
assertEquals("0173", new Formatter().format("%#o", 123).toString());
try {
new Formatter().format("%-01o", 23);
fail("Should have thrown exception 1");
} catch (IllegalFormatFlagsException e) {
assertTrue(e.getFlags().contains("-"));
assertTrue(e.getFlags().contains("0"));
}
try {
new Formatter().format("%-o", 23);
fail("Should have thrown exception 2");
} catch (MissingFormatWidthException e) {
assertTrue(e.getFormatSpecifier().contains("o"));
}
try {
new Formatter().format("%1.2o", 23);
fail("Should have thrown exception 3");
} catch (IllegalFormatPrecisionException e) {
assertEquals(2, e.getPrecision());
}
}
@Test
public void formatsHexInteger() {
assertEquals("1 2 3 4", new Formatter().format("%x %x %x %x", (byte) 1, (short) 2, 3, 4L).toString());
assertEquals("00017", new Formatter().format("%05x", 23).toString());
assertEquals("0x7b", new Formatter().format("%#x", 123).toString());
try {
new Formatter().format("%-01x", 23);
fail("Should have thrown exception 1");
} catch (IllegalFormatFlagsException e) {
assertTrue(e.getFlags().contains("-"));
assertTrue(e.getFlags().contains("0"));
}
try {
new Formatter().format("%-x", 23);
fail("Should have thrown exception 2");
} catch (MissingFormatWidthException e) {
assertTrue(e.getFormatSpecifier().contains("x"));
}
try {
new Formatter().format("%1.2x", 23);
fail("Should have thrown exception 3");
} catch (IllegalFormatPrecisionException e) {
assertEquals(2, e.getPrecision());
}
}
}
| 4,049 |
14,668 | // Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <list>
#include "chrome/browser/ui/views/payments/payment_request_browsertest_base.h"
#include "chrome/browser/ui/views/payments/payment_request_dialog_view_ids.h"
#include "components/autofill/core/browser/autofill_test_utils.h"
#include "content/public/test/browser_test.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace payments {
class PaymentRequestEmptyUpdateTest : public PaymentRequestBrowserTestBase {
public:
PaymentRequestEmptyUpdateTest(const PaymentRequestEmptyUpdateTest&) = delete;
PaymentRequestEmptyUpdateTest& operator=(
const PaymentRequestEmptyUpdateTest&) = delete;
protected:
PaymentRequestEmptyUpdateTest() {}
};
IN_PROC_BROWSER_TEST_F(PaymentRequestEmptyUpdateTest, NoCrash) {
NavigateTo("/payment_request_empty_update_test.html");
AddAutofillProfile(autofill::test::GetFullProfile());
InvokePaymentRequestUI();
OpenShippingAddressSectionScreen();
ResetEventWaiterForSequence({DialogEvent::PROCESSING_SPINNER_SHOWN,
DialogEvent::PROCESSING_SPINNER_HIDDEN,
DialogEvent::SPEC_DONE_UPDATING});
ClickOnChildInListViewAndWait(
/* child_index=*/0, /*total_num_children=*/1,
DialogViewID::SHIPPING_ADDRESS_SHEET_LIST_VIEW,
/*wait_for_animation=*/false);
// No crash indicates a successful test.
}
} // namespace payments
| 546 |
654 | {
"manifest_version": 2,
"name": "Show me the React!",
"short_name": "See React!",
"description": "Highlight React components on the page.",
"version": "1.1",
"icons": {
"600": "images/react.png",
"128": "images/react-128.png",
"112": "images/react-112.png",
"48": "images/react-48.png",
"16": "images/react-16.png"
},
"page_action": {
"default_icon": {
"38": "images/react-38.png",
"19": "images/react-19.png"
},
"default_title": "Highlight React components!"
},
"background": {
"scripts": ["js/background.js"],
"persistent": false
},
"permissions": [
"activeTab",
"declarativeContent"
]
}
| 284 |
335 | {
"word": "Sociology",
"definitions": [
"The study of the development, structure, and functioning of human society."
],
"parts-of-speech": "Noun"
} | 67 |
17,104 | <reponame>jonetomtom/mars
#include "boost/utility/result_of.hpp"
#include "comm\platform_comm.h"
#include "runtime2cs.h"
#include "comm\xlogger\xlogger.h"
#include "runtime_utils.h"
namespace mars {
using namespace Platform;
using namespace std;
//static Runtime2Cs_Comm^ Singleton();
Runtime2Cs_Comm^ Runtime2Cs_Comm::Singleton()
{
if (nullptr == instance)
{
instance = ref new Runtime2Cs_Comm();
}
return instance;
}
ICallback_Comm ^ Runtime2Cs_Comm::GetCallBack()
{
return m_callback;
}
Runtime2Cs_Comm::Runtime2Cs_Comm() :
m_callback(nullptr)
{
}
void Runtime2Cs_Comm::SetCallback(ICallback_Comm^ _callback)
{
m_callback = _callback;
}
Runtime2Cs_Comm^ Runtime2Cs_Comm::instance = nullptr;
} | 374 |
449 | #ifndef GEEF_OID_H
#define GEEF_OID_H
#include "erl_nif.h"
#include <git2.h>
ERL_NIF_TERM geef_oid_fmt(ErlNifEnv *env, int argc, const ERL_NIF_TERM argv[]);
ERL_NIF_TERM geef_oid_parse(ErlNifEnv *env, int argc, const ERL_NIF_TERM argv[]);
int geef_oid_bin(ErlNifBinary *bin, const git_oid *id);
#endif
| 161 |
45,293 | package test;
public @interface AnnotationWithField {
String text();
int ANSWER = 42;
}
| 35 |
5,954 | import javax.swing.JFrame;
import org.bytedeco.javacpp.*;
import org.bytedeco.javacv.*;
import org.bytedeco.opencv.opencv_core.*;
import org.bytedeco.opencv.opencv_imgproc.*;
import static org.bytedeco.opencv.global.opencv_core.*;
import static org.bytedeco.opencv.global.opencv_imgproc.*;
import static org.bytedeco.opencv.global.opencv_imgcodecs.*;
/**
* C to Java translation of the houghlines.c sample provided in the c sample directory of OpenCV 2.1,
* using the JavaCV Java wrapper of OpenCV 2.2 developped by Samuel Audet.
*
* @author <NAME>
* <EMAIL>
*/
public class HoughLines {
/**
* usage: java HoughLines imageDir\imageName TransformType
*/
public static void main(String[] args) {
String fileName = args.length >= 1 ? args[0] : "pic1.png"; // if no params provided, compute the defaut image
IplImage src = cvLoadImage(fileName, 0);
IplImage dst;
IplImage colorDst;
CvMemStorage storage = cvCreateMemStorage(0);
CvSeq lines = new CvSeq();
CanvasFrame source = new CanvasFrame("Source");
CanvasFrame hough = new CanvasFrame("Hough");
OpenCVFrameConverter.ToIplImage sourceConverter = new OpenCVFrameConverter.ToIplImage();
OpenCVFrameConverter.ToIplImage houghConverter = new OpenCVFrameConverter.ToIplImage();
if (src == null) {
System.out.println("Couldn't load source image.");
return;
}
dst = cvCreateImage(cvGetSize(src), src.depth(), 1);
colorDst = cvCreateImage(cvGetSize(src), src.depth(), 3);
cvCanny(src, dst, 50, 200, 3);
cvCvtColor(dst, colorDst, CV_GRAY2BGR);
/*
* apply the probabilistic hough transform
* which returns for each line deteced two points ((x1, y1); (x2,y2))
* defining the detected segment
*/
if (args.length == 2 && args[1].contentEquals("probabilistic")) {
System.out.println("Using the Probabilistic Hough Transform");
lines = cvHoughLines2(dst, storage, CV_HOUGH_PROBABILISTIC, 1, Math.PI / 180, 40, 50, 10, 0, CV_PI);
for (int i = 0; i < lines.total(); i++) {
// Based on JavaCPP, the equivalent of the C code:
// CvPoint* line = (CvPoint*)cvGetSeqElem(lines,i);
// CvPoint first=line[0], second=line[1]
// is:
Pointer line = cvGetSeqElem(lines, i);
CvPoint pt1 = new CvPoint(line).position(0);
CvPoint pt2 = new CvPoint(line).position(1);
System.out.println("Line spotted: ");
System.out.println("\t pt1: " + pt1);
System.out.println("\t pt2: " + pt2);
cvLine(colorDst, pt1, pt2, CV_RGB(255, 0, 0), 3, CV_AA, 0); // draw the segment on the image
}
}
/*
* Apply the multiscale hough transform which returns for each line two float parameters (rho, theta)
* rho: distance from the origin of the image to the line
* theta: angle between the x-axis and the normal line of the detected line
*/
else if(args.length==2 && args[1].contentEquals("multiscale")){
System.out.println("Using the multiscale Hough Transform"); //
lines = cvHoughLines2(dst, storage, CV_HOUGH_MULTI_SCALE, 1, Math.PI / 180, 40, 1, 1, 0, CV_PI);
for (int i = 0; i < lines.total(); i++) {
CvPoint2D32f point = new CvPoint2D32f(cvGetSeqElem(lines, i));
float rho=point.x();
float theta=point.y();
double a = Math.cos((double) theta), b = Math.sin((double) theta);
double x0 = a * rho, y0 = b * rho;
CvPoint pt1 = cvPoint((int) Math.round(x0 + 1000 * (-b)), (int) Math.round(y0 + 1000 * (a))), pt2 = cvPoint((int) Math.round(x0 - 1000 * (-b)), (int) Math.round(y0 - 1000 * (a)));
System.out.println("Line spoted: ");
System.out.println("\t rho= " + rho);
System.out.println("\t theta= " + theta);
cvLine(colorDst, pt1, pt2, CV_RGB(255, 0, 0), 3, CV_AA, 0);
}
}
/*
* Default: apply the standard hough transform. Outputs: same as the multiscale output.
*/
else {
System.out.println("Using the Standard Hough Transform");
lines = cvHoughLines2(dst, storage, CV_HOUGH_STANDARD, 1, Math.PI / 180, 90, 0, 0, 0, CV_PI);
for (int i = 0; i < lines.total(); i++) {
CvPoint2D32f point = new CvPoint2D32f(cvGetSeqElem(lines, i));
float rho=point.x();
float theta=point.y();
double a = Math.cos((double) theta), b = Math.sin((double) theta);
double x0 = a * rho, y0 = b * rho;
CvPoint pt1 = cvPoint((int) Math.round(x0 + 1000 * (-b)), (int) Math.round(y0 + 1000 * (a))), pt2 = cvPoint((int) Math.round(x0 - 1000 * (-b)), (int) Math.round(y0 - 1000 * (a)));
System.out.println("Line spotted: ");
System.out.println("\t rho= " + rho);
System.out.println("\t theta= " + theta);
cvLine(colorDst, pt1, pt2, CV_RGB(255, 0, 0), 3, CV_AA, 0);
}
}
source.showImage(sourceConverter.convert(src));
hough.showImage(houghConverter.convert(colorDst));
source.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
hough.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
| 2,674 |
348 | <reponame>chamberone/Leaflet.PixiOverlay
{"nom":"Mélecey","circ":"2ème circonscription","dpt":"Haute-Saône","inscrits":120,"abs":45,"votants":75,"blancs":16,"nuls":4,"exp":55,"res":[{"nuance":"FN","nom":"M. <NAME>","voix":36},{"nuance":"REM","nom":"M. <NAME>","voix":19}]} | 117 |
2,017 | package com.dream.service.impl;
import com.dream.mapper.BrowseMapper;
import com.dream.po.Browse;
import com.dream.po.BrowseExample;
import com.dream.service.BrowseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class BrowseServiceImpl implements BrowseService {
@Autowired
private BrowseMapper browseMapper;
@Override
public Browse getBrowseByUserId(Integer userid) {
BrowseExample example = new BrowseExample();
BrowseExample.Criteria criteria = example.createCriteria();
criteria.andUseridEqualTo(userid);
List<Browse> browseList = browseMapper.selectByExample(example);
if(browseList.size()!=0)
return browseList.get(0);
else
return null;
}
}
| 311 |
852 | #ifndef ALL_LMF
#define ALL_LMF
#include "OnlineDB/EcalCondDB/interface/LMFColor.h"
#include "OnlineDB/EcalCondDB/interface/LMFColoredTable.h"
#include "OnlineDB/EcalCondDB/interface/LMFCorrCoefDat.h"
#include "OnlineDB/EcalCondDB/interface/LMFCorrVers.h"
#include "OnlineDB/EcalCondDB/interface/LMFDat.h"
#include "OnlineDB/EcalCondDB/interface/LMFDefFabric.h"
#include "OnlineDB/EcalCondDB/interface/LMFIOV.h"
#include "OnlineDB/EcalCondDB/interface/LMFLaserPulseDat.h"
#include "OnlineDB/EcalCondDB/interface/LMFLmrSubIOV.h"
#include "OnlineDB/EcalCondDB/interface/LMFPnPrimDat.h"
#include "OnlineDB/EcalCondDB/interface/LMFPrimDat.h"
#include "OnlineDB/EcalCondDB/interface/LMFPrimVers.h"
#include "OnlineDB/EcalCondDB/interface/LMFRunDat.h"
#include "OnlineDB/EcalCondDB/interface/LMFRunIOV.h"
#include "OnlineDB/EcalCondDB/interface/LMFRunTag.h"
#include "OnlineDB/EcalCondDB/interface/LMFSeqDat.h"
#include "OnlineDB/EcalCondDB/interface/LMFSeqVers.h"
#include "OnlineDB/EcalCondDB/interface/LMFTrigType.h"
#include "OnlineDB/EcalCondDB/interface/LMFUnique.h"
#include "OnlineDB/EcalCondDB/interface/LMFTestPulseConfigDat.h"
#include "OnlineDB/EcalCondDB/interface/LMFLaserConfigDat.h"
#include "OnlineDB/EcalCondDB/interface/LMFClsDat.h"
#endif
| 497 |
3,508 | package com.fishercoder.solutions;
public class _1750 {
public static class Solution1 {
public int minimumLength(String s) {
int i = 0;
int j = s.length() - 1;
if (s.charAt(i) == s.charAt(j)) {
while (i < j && s.charAt(i) == s.charAt(j)) {
char c = s.charAt(i);
i++;
while (c == s.charAt(i) && i < j) {
i++;
}
j--;
while (c == s.charAt(j) && i < j) {
j--;
}
}
}
return i <= j ? s.substring(i, j).length() + 1 : 0;
}
}
}
| 477 |
2,350 | #if defined(__ARM_ARCH_5TE__)
#include "pyconfig_armeabi.h"
#elif defined(__ARM_ARCH_7A__) && !defined(__ARM_PCS_VFP)
#include "pyconfig_armeabi_v7a.h"
#elif defined(__ARM_ARCH_7A__) && defined(__ARM_PCS_VFP)
#include "pyconfig_armeabi_v7a_hard.h"
#elif defined(__aarch64__)
#include "pyconfig_arm64_v8a.h"
#elif defined(__i386__)
#include "pyconfig_x86.h"
#elif defined(__x86_64__)
#include "pyconfig_x86_64.h"
#elif defined(__mips__) && !defined(__mips64)
#include "pyconfig_mips.h"
#elif defined(__mips__) && defined(__mips64)
#include "pyconfig_mips64.h"
#else
#error "Unsupported ABI"
#endif
| 275 |
460 | <reponame>jacklovejia/shop
package com.tasly.user.db.reposity;
import com.tasly.user.db.domain.User;
import org.springframework.data.jpa.repository.JpaRepository;
/**
* Created by dulei on 18/1/8.
*/
public interface UserReposity extends JpaRepository<User,Long> {
}
| 106 |
320 | # -*- coding: UTF-8 -*-
from basic import BasicCtrl
class ScoreCtrl(BasicCtrl):
def post(self):
try:
self.datum('posts').submit(
'update posts set post_rank = post_rank + 1, post_plus = post_plus + 1 where post_id = ? limit 1', (self.input('poid'),))
self.flash(1)
except:
self.flash(0)
| 176 |
839 | <filename>systests/ws-rm/src/test/java/org/apache/cxf/systest/ws/rm/CachedOutMessageTest.java
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.cxf.systest.ws.rm;
import java.util.logging.Logger;
import javax.xml.ws.Endpoint;
import org.apache.cxf.Bus;
import org.apache.cxf.BusFactory;
import org.apache.cxf.bus.spring.SpringBusFactory;
import org.apache.cxf.common.logging.LogUtils;
import org.apache.cxf.ext.logging.LoggingInInterceptor;
import org.apache.cxf.ext.logging.LoggingOutInterceptor;
import org.apache.cxf.greeter_control.Greeter;
import org.apache.cxf.greeter_control.GreeterService;
import org.apache.cxf.io.CachedOutputStream;
import org.apache.cxf.systest.ws.util.ConnectionHelper;
import org.apache.cxf.testutil.common.AbstractBusClientServerTestBase;
import org.apache.cxf.testutil.common.AbstractBusTestServerBase;
import org.apache.cxf.ws.rm.RMManager;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.assertTrue;
/**
* Tests the WS-RM processing with the cached out message (using temporary files).
*/
public class CachedOutMessageTest extends AbstractBusClientServerTestBase {
public static final String PORT = allocatePort(Server.class);
public static final String DECOUPLE_PORT = allocatePort("decoupled.port");
private static final Logger LOG = LogUtils.getLogger(RetransmissionQueueTest.class);
private Bus bus;
public static class Server extends AbstractBusTestServerBase {
Endpoint ep;
protected void run() {
SpringBusFactory bf = new SpringBusFactory();
Bus bus = bf.createBus("/org/apache/cxf/systest/ws/rm/message-loss.xml");
BusFactory.setDefaultBus(bus);
setBus(bus);
LoggingInInterceptor in = new LoggingInInterceptor();
bus.getInInterceptors().add(in);
bus.getInFaultInterceptors().add(in);
LoggingOutInterceptor out = new LoggingOutInterceptor();
bus.getOutInterceptors().add(out);
bus.getOutFaultInterceptors().add(out);
GreeterImpl implementor = new GreeterImpl();
String address = "http://localhost:" + PORT + "/SoapContext/GreeterPort";
ep = Endpoint.create(implementor);
ep.publish(address);
LOG.info("Published greeter endpoint.");
}
public void tearDown() {
ep.stop();
ep = null;
}
}
@BeforeClass
public static void startServers() throws Exception {
CachedOutputStream.setDefaultThreshold(16);
assertTrue("server did not launch correctly",
launchServer(Server.class, true));
}
@AfterClass
public static void cleanup() throws Exception {
CachedOutputStream.setDefaultThreshold(-1);
}
@Test
public void testCachedOutMessage() throws Exception {
SpringBusFactory bf = new SpringBusFactory();
bus = bf.createBus("/org/apache/cxf/systest/ws/rm/message-loss.xml");
BusFactory.setDefaultBus(bus);
LoggingInInterceptor in = new LoggingInInterceptor();
bus.getInInterceptors().add(in);
bus.getInFaultInterceptors().add(in);
LoggingOutInterceptor out = new LoggingOutInterceptor();
bus.getOutInterceptors().add(out);
// an interceptor to simulate a message loss
MessageLossSimulator mls = new MessageLossSimulator();
bus.getOutInterceptors().add(mls);
RMManager manager = bus.getExtension(RMManager.class);
manager.getConfiguration().setBaseRetransmissionInterval(Long.valueOf(2000));
bus.getOutFaultInterceptors().add(out);
GreeterService gs = new GreeterService();
final Greeter greeter = gs.getGreeterPort();
updateAddressPort(greeter, PORT);
LOG.fine("Created greeter client.");
ConnectionHelper.setKeepAliveConnection(greeter, true);
greeter.greetMeOneWay("one");
greeter.greetMeOneWay("two");
greeter.greetMeOneWay("three");
long wait = 4000;
while (wait > 0) {
long start = System.currentTimeMillis();
try {
Thread.sleep(wait);
} catch (InterruptedException ex) {
// ignore
}
wait -= System.currentTimeMillis() - start;
}
boolean empty = manager.getRetransmissionQueue().isEmpty();
assertTrue("Some messages are not acknowledged", empty);
}
}
| 1,995 |
314 | <filename>Multiplex/IDEHeaders/IDEHeaders/IDEFoundation/IDEArchivePackagerEntitlementsMerger.h
//
// Generated by class-dump 3.5 (64 bit).
//
// class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2013 by <NAME>.
//
#import "CDStructures.h"
@interface IDEArchivePackagerEntitlementsMerger : NSObject
{
}
+ (id)genericallyDefinedProfileKeysToSkipWhenCopyingFromProfile;
+ (id)sharedMerger;
- (id)entitlementsByMergingProfileEntitlements:(id)arg1 appEntitlements:(id)arg2 bundleIdentifier:(id)arg3 warnings:(id)arg4 error:(id *)arg5;
@end
| 200 |
388 | <filename>libraries/botframework-connector/botframework/connector/auth/user_token_client.py
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
from abc import ABC, abstractmethod
from base64 import b64encode
from json import dumps
from typing import Dict, List
from botbuilder.schema import Activity, TokenResponse, TokenExchangeState
from botframework.connector.token_api.models import (
SignInUrlResponse,
TokenExchangeRequest,
TokenStatus,
)
class UserTokenClient(ABC):
@abstractmethod
async def get_user_token(
self, user_id: str, connection_name: str, channel_id: str, magic_code: str
) -> TokenResponse:
"""
Attempts to retrieve the token for a user that's in a login flow.
:param user_id: The user id that will be associated with the token.
:param connection_name: Name of the auth connection to use.
:param channel_id: The channel Id that will be associated with the token.
:param magic_code: (Optional) Optional user entered code to validate.
:return: A TokenResponse object.
"""
raise NotImplementedError()
@abstractmethod
async def get_sign_in_resource(
self, connection_name: str, activity: Activity, final_redirect: str
) -> SignInUrlResponse:
"""
Get the raw signin link to be sent to the user for signin for a connection name.
:param connection_name: Name of the auth connection to use.
:param activity: The Activity from which to derive the token exchange state.
:param final_redirect: The final URL that the OAuth flow will redirect to.
:return: A SignInUrlResponse.
"""
raise NotImplementedError()
@abstractmethod
async def sign_out_user(self, user_id: str, connection_name: str, channel_id: str):
"""
Signs the user out with the token server.
:param user_id: The user id that will be associated with the token.
:param connection_name: Name of the auth connection to use.
:param channel_id: The channel Id that will be associated with the token.
"""
raise NotImplementedError()
@abstractmethod
async def get_token_status(
self, user_id: str, channel_id: str, include_filter: str
) -> List[TokenStatus]:
"""
Retrieves the token status for each configured connection for the given user.
:param user_id: The user id that will be associated with the token.
:param channel_id: The channel Id that will be associated with the token.
:param include_filter: The include filter.
:return: A list of TokenStatus objects.
"""
raise NotImplementedError()
@abstractmethod
async def get_aad_tokens(
self,
user_id: str,
connection_name: str,
resource_urls: List[str],
channel_id: str,
) -> Dict[str, TokenResponse]:
"""
Retrieves Azure Active Directory tokens for particular resources on a configured connection.
:param user_id: The user id that will be associated with the token.
:param connection_name: Name of the auth connection to use.
:param resource_urls: The list of resource URLs to retrieve tokens for.
:param channel_id: The channel Id that will be associated with the token.
:return: A Dictionary of resource_urls to the corresponding TokenResponse.
"""
raise NotImplementedError()
@abstractmethod
async def exchange_token(
self,
user_id: str,
connection_name: str,
channel_id: str,
exchange_request: TokenExchangeRequest,
) -> TokenResponse:
"""
Performs a token exchange operation such as for single sign-on.
:param user_id The user id that will be associated with the token.
:param connection_name Name of the auth connection to use.
:param channel_id The channel Id that will be associated with the token.
:param exchange_request The exchange request details, either a token to exchange or a uri to exchange.
:return: A TokenResponse object.
"""
raise NotImplementedError()
@staticmethod
def create_token_exchange_state(
app_id: str, connection_name: str, activity: Activity
) -> str:
"""
Helper function to create the Base64 encoded token exchange state used in getSignInResource calls.
:param app_id The app_id to include in the token exchange state.
:param connection_name The connection_name to include in the token exchange state.
:param activity The [Activity](xref:botframework-schema.Activity) from which to derive the token exchange state.
:return: Base64 encoded token exchange state.
"""
if app_id is None or not isinstance(app_id, str):
raise TypeError("app_id")
if connection_name is None or not isinstance(connection_name, str):
raise TypeError("connection_name")
if activity is None or not isinstance(activity, Activity):
raise TypeError("activity")
token_exchange_state = TokenExchangeState(
connection_name=connection_name,
conversation=Activity.get_conversation_reference(activity),
relates_to=activity.relates_to,
ms_app_id=app_id,
)
tes_string = b64encode(
dumps(token_exchange_state.serialize()).encode(
encoding="UTF-8", errors="strict"
)
).decode()
return tes_string
| 2,063 |
313 | /*
* Copyright (c) 2020, the mcl_3dl authors
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef MCL_3DL_POINT_CLOUD_RANDOM_SAMPLERS_POINT_CLOUD_SAMPLER_WITH_NORMAL_H
#define MCL_3DL_POINT_CLOUD_RANDOM_SAMPLERS_POINT_CLOUD_SAMPLER_WITH_NORMAL_H
#include <memory>
#include <random>
#include <unordered_set>
#include <vector>
#include <Eigen/Core>
#include <Eigen/Eigenvalues>
#include <pcl/features/normal_3d.h>
#include <pcl/kdtree/kdtree_flann.h>
#include <pcl/point_cloud.h>
#include <pcl/point_types.h>
#include <ros/ros.h>
#include <mcl_3dl/point_cloud_random_sampler.h>
#include <mcl_3dl/state_6dof.h>
namespace mcl_3dl
{
template <class POINT_TYPE>
class PointCloudSamplerWithNormal : public PointCloudRandomSampler<POINT_TYPE>
{
private:
using Matrix = Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic>;
using Vector = Eigen::Matrix<double, Eigen::Dynamic, 1>;
std::shared_ptr<std::default_random_engine> engine_;
State6DOF mean_;
Matrix eigen_vectors_;
Vector eigen_values_;
double perform_weighting_ratio_;
double max_weight_ratio_;
double max_weight_;
double normal_search_range_;
public:
explicit PointCloudSamplerWithNormal(const unsigned int random_seed = std::random_device()())
: engine_(std::make_shared<std::default_random_engine>(random_seed))
, perform_weighting_ratio_(2.0)
, max_weight_ratio_(5.0)
, max_weight_(10.0)
, normal_search_range_(0.4)
{
}
void loadConfig(const ros::NodeHandle& nh)
{
ros::NodeHandle pnh(nh, "random_sampler_with_normal");
pnh.param("perform_weighting_ratio", perform_weighting_ratio_, 2.0);
pnh.param("max_weight_ratio", max_weight_ratio_, 5.0);
pnh.param("max_weight", max_weight_, 5.0);
pnh.param("normal_search_range", normal_search_range_, 0.4);
}
void setParameters(const double perform_weighting_ratio, const double max_weight_ratio,
const double max_weight, const double normal_search_range)
{
perform_weighting_ratio_ = perform_weighting_ratio;
max_weight_ratio_ = max_weight_ratio;
max_weight_ = max_weight;
normal_search_range_ = normal_search_range;
}
void setParticleStatistics(const State6DOF& mean, const std::vector<State6DOF>& covariances)
{
mean_ = mean;
Matrix pos_cov(3, 3);
for (size_t i = 0; i < 3; ++i)
{
for (size_t j = 0; j < 3; ++j)
{
pos_cov(i, j) = std::abs(covariances[i][j]);
}
}
const Eigen::SelfAdjointEigenSolver<Matrix> eigen_solver(pos_cov);
eigen_vectors_ = eigen_solver.eigenvectors();
eigen_values_ = eigen_solver.eigenvalues();
}
typename pcl::PointCloud<POINT_TYPE>::Ptr sample(
const typename pcl::PointCloud<POINT_TYPE>::ConstPtr& pc,
const size_t num) const final
{
const ros::WallTime start_timestamp = ros::WallTime::now();
typename pcl::PointCloud<POINT_TYPE>::Ptr output(new pcl::PointCloud<POINT_TYPE>);
output->header = pc->header;
if ((pc->points.size() == 0) || (num == 0))
{
return output;
}
if (pc->size() <= num)
{
*output = *pc;
return output;
}
const double eigen_value_ratio = std::sqrt(eigen_values_[2] / eigen_values_[1]);
double max_weight = 1.0;
if (eigen_value_ratio < perform_weighting_ratio_)
{
max_weight = 1.0;
}
else if (eigen_value_ratio > max_weight_ratio_)
{
max_weight = max_weight_;
}
else
{
const double weight_ratio =
(eigen_value_ratio - perform_weighting_ratio_) / (max_weight_ratio_ - perform_weighting_ratio_);
max_weight = 1.0 + (max_weight_ - 1.0) * weight_ratio;
}
const mcl_3dl::Vec3 fpc_global(eigen_vectors_(0, 2), eigen_vectors_(1, 2), eigen_vectors_(2, 2));
const mcl_3dl::Vec3 fpc_local = mean_.rot_.inv() * fpc_global;
pcl::NormalEstimation<POINT_TYPE, pcl::Normal> ne;
pcl::PointCloud<pcl::Normal>::Ptr cloud_normals(new pcl::PointCloud<pcl::Normal>);
typename pcl::search::KdTree<POINT_TYPE>::Ptr tree(new pcl::search::KdTree<POINT_TYPE>());
ne.setInputCloud(pc);
ne.setSearchMethod(tree);
ne.setRadiusSearch(normal_search_range_);
ne.compute(*cloud_normals);
const ros::WallTime compute_normal_timestamp = ros::WallTime::now();
std::vector<double> cumulative_weight(cloud_normals->points.size(), 0.0);
for (size_t i = 0; i < cloud_normals->points.size(); i++)
{
double weight = 1.0;
const auto& normal = cloud_normals->points[i];
if (!std::isnan(normal.normal_x) && !std::isnan(normal.normal_y) && !std::isnan(normal.normal_z))
{
double acos_angle = std::abs(normal.normal_x * fpc_local.x_ +
normal.normal_y * fpc_local.y_ +
normal.normal_z * fpc_local.z_);
// Avoid that std::acos() returns nan because of calculation errors
if (acos_angle > 1.0)
{
acos_angle = 1.0;
}
const double angle = std::acos(acos_angle);
weight = 1.0 + (max_weight - 1.0) * ((M_PI / 2 - angle) / (M_PI / 2));
}
cumulative_weight[i] = weight + ((i == 0) ? 0.0 : cumulative_weight[i - 1]);
}
std::uniform_real_distribution<double> ud(0, cumulative_weight.back());
// Use unordered_set to avoid duplication
std::unordered_set<size_t> selected_ids;
while (true)
{
const double random_value = ud(*engine_);
auto it = std::lower_bound(cumulative_weight.begin(), cumulative_weight.end(), random_value);
const size_t n = it - cumulative_weight.begin();
selected_ids.insert(n);
if (selected_ids.size() >= num)
{
break;
}
}
output->points.reserve(num);
for (const auto& index : selected_ids)
{
output->push_back(pc->points[index]);
}
const ros::WallTime final_timestamp = ros::WallTime::now();
ROS_DEBUG("PointCloudSamplerWithNormal::sample() computation time: %f[s] (Normal calculation: %f[s])",
(final_timestamp - start_timestamp).toSec(), (compute_normal_timestamp - start_timestamp).toSec());
ROS_DEBUG("Chosen eigen vector: (%f, %f, %f), max weight: %f",
eigen_vectors_(0, 2), eigen_vectors_(1, 2), eigen_vectors_(2, 2), max_weight);
return output;
}
};
} // namespace mcl_3dl
#endif // MCL_3DL_POINT_CLOUD_RANDOM_SAMPLERS_POINT_CLOUD_SAMPLER_WITH_NORMAL_H
| 3,226 |
782 | package com.octo.android.sample.model;
public interface Computer {
int getResult();
}
| 30 |
852 | <filename>GeneratorInterface/Pythia8Interface/test/pythia8test/chi.c
#include <stdio.h>
#include <math.h>
int main(void)
{
double y, dy, y0, dy0;
double chi;
scanf("%lE%lE%lE%lE", &y, &dy, &y0, &dy0);
if (dy == 0. && dy0 == 0.)
chi = -1.;
else
chi = (y - y0) / sqrt(dy*dy + dy0*dy0);
printf("%lE %lE %lE %lE %lf ", y, dy, y0, dy0, chi);
if ( (fabs(y0) < 5*dy0 || fabs(y) <= 4*dy) && fabs(chi) <= 3.)
printf("[BADSTAT]\n");
else
if (fabs(chi) > 3. || fabs(chi) <= 3.) { // this if is to deal with NaN
if (fabs(chi) > 3.) printf("[DEVIATION]\n");
if (fabs(chi) <= 3.) printf("[OK]\n");
}
else
printf("[DEVIATION]\n");
return 0;
}
| 370 |
311 | <gh_stars>100-1000
import logging
from decimal import Decimal
from django.utils.translation import ugettext as _
from django.contrib.auth import get_user_model
from rest_framework import serializers
from oscar.core.loading import get_model
from oscarapi.basket import operations
from oscarapi.utils.settings import overridable
from oscarapi.serializers.fields import (
DrillDownHyperlinkedIdentityField,
DrillDownHyperlinkedRelatedField,
)
from oscarapi.serializers.utils import (
OscarModelSerializer,
OscarHyperlinkedModelSerializer,
)
from oscarapi.serializers.fields import TaxIncludedDecimalField
logger = logging.getLogger(__name__)
User = get_user_model()
Basket = get_model("basket", "Basket")
Line = get_model("basket", "Line")
LineAttribute = get_model("basket", "LineAttribute")
StockRecord = get_model("partner", "StockRecord")
Voucher = get_model("voucher", "Voucher")
Product = get_model("catalogue", "Product")
class VoucherSerializer(OscarModelSerializer):
class Meta:
model = Voucher
fields = overridable(
"OSCARAPI_VOUCHER_FIELDS",
default=("name", "code", "start_datetime", "end_datetime"),
)
class OfferDiscountSerializer(
serializers.Serializer
): # pylint: disable=abstract-method
description = serializers.CharField()
name = serializers.CharField()
amount = serializers.DecimalField(
decimal_places=2, max_digits=12, source="discount"
)
class VoucherDiscountSerializer(OfferDiscountSerializer):
voucher = VoucherSerializer(required=False)
class BasketSerializer(serializers.HyperlinkedModelSerializer):
lines = serializers.HyperlinkedIdentityField(view_name="basket-lines-list")
offer_discounts = OfferDiscountSerializer(many=True, required=False)
total_excl_tax = serializers.DecimalField(
decimal_places=2, max_digits=12, required=False
)
total_excl_tax_excl_discounts = serializers.DecimalField(
decimal_places=2, max_digits=12, required=False
)
total_incl_tax = TaxIncludedDecimalField(
excl_tax_field="total_excl_tax", decimal_places=2, max_digits=12, required=False
)
total_incl_tax_excl_discounts = TaxIncludedDecimalField(
excl_tax_field="total_excl_tax_excl_discounts",
decimal_places=2,
max_digits=12,
required=False,
)
total_tax = TaxIncludedDecimalField(
excl_tax_value=Decimal("0.00"), decimal_places=2, max_digits=12, required=False
)
currency = serializers.CharField(required=False)
voucher_discounts = VoucherDiscountSerializer(many=True, required=False)
owner = serializers.HyperlinkedRelatedField(
view_name="user-detail",
required=False,
allow_null=True,
queryset=User.objects.all(),
)
class Meta:
model = Basket
fields = overridable(
"OSCARAPI_BASKET_FIELDS",
default=(
"id",
"owner",
"status",
"lines",
"url",
"total_excl_tax",
"total_excl_tax_excl_discounts",
"total_incl_tax",
"total_incl_tax_excl_discounts",
"total_tax",
"currency",
"voucher_discounts",
"offer_discounts",
"is_tax_known",
),
)
class LineAttributeSerializer(OscarHyperlinkedModelSerializer):
url = DrillDownHyperlinkedIdentityField(
view_name="lineattribute-detail",
extra_url_kwargs={"basket_pk": "line.basket.id", "line_pk": "line.id"},
)
line = DrillDownHyperlinkedIdentityField(
view_name="basket-line-detail", extra_url_kwargs={"basket_pk": "line.basket.id"}
)
class Meta:
model = LineAttribute
fields = "__all__"
class BasketLineSerializer(OscarHyperlinkedModelSerializer):
"""
This serializer computes the prices of this line by using the basket
strategy.
"""
url = DrillDownHyperlinkedIdentityField(
view_name="basket-line-detail", extra_url_kwargs={"basket_pk": "basket.id"}
)
attributes = LineAttributeSerializer(
many=True, fields=("url", "option", "value"), required=False, read_only=True
)
price_excl_tax = serializers.DecimalField(
decimal_places=2,
max_digits=12,
source="line_price_excl_tax_incl_discounts",
read_only=True,
)
price_incl_tax = TaxIncludedDecimalField(
decimal_places=2,
max_digits=12,
excl_tax_field="line_price_excl_tax_incl_discounts",
source="line_price_incl_tax_incl_discounts",
read_only=True,
)
price_incl_tax_excl_discounts = TaxIncludedDecimalField(
decimal_places=2,
max_digits=12,
excl_tax_field="line_price_excl_tax",
source="line_price_incl_tax",
read_only=True,
)
price_excl_tax_excl_discounts = serializers.DecimalField(
decimal_places=2, max_digits=12, source="line_price_excl_tax", read_only=True
)
warning = serializers.CharField(
read_only=True, required=False, source="get_warning"
)
stockrecord = DrillDownHyperlinkedRelatedField(
view_name="product-stockrecord-detail",
extra_url_kwargs={"product_pk": "product_id"},
queryset=StockRecord.objects.all(),
)
class Meta:
model = Line
fields = overridable(
"OSCARAPI_BASKETLINE_FIELDS",
default=(
"url",
"product",
"quantity",
"attributes",
"price_currency",
"price_excl_tax",
"price_incl_tax",
"price_incl_tax_excl_discounts",
"price_excl_tax_excl_discounts",
"is_tax_known",
"warning",
"basket",
"stockrecord",
"date_created",
"date_updated",
),
)
def to_representation(self, obj):
# This override is needed to reflect offer discounts or strategy
# related prices immediately in the response
operations.assign_basket_strategy(obj.basket, self.context["request"])
# Oscar stores the calculated discount in line._discount_incl_tax or
# line._discount_excl_tax when offers are applied. So by just
# retrieving the line from the db you will loose this values, that's
# why we need to get the line from the in-memory resultset here
lines = (x for x in obj.basket.all_lines() if x.id == obj.id)
line = next(lines, None)
return super(BasketLineSerializer, self).to_representation(line)
class VoucherAddSerializer(serializers.Serializer):
vouchercode = serializers.CharField(max_length=128, required=True)
def validate(self, attrs):
# oscar expects this always to be uppercase.
attrs["vouchercode"] = attrs["vouchercode"].upper()
request = self.context.get("request")
try:
voucher = Voucher.objects.get(code=attrs.get("vouchercode"))
# check expiry date
if not voucher.is_active():
message = _("The '%(code)s' voucher has expired") % {
"code": voucher.code
}
raise serializers.ValidationError(message)
# check voucher rules
is_available, message = voucher.is_available_to_user(request.user)
if not is_available:
raise serializers.ValidationError(message)
except Voucher.DoesNotExist:
raise serializers.ValidationError(_("Voucher code unknown"))
# set instance to the voucher so we can use this in the view
self.instance = voucher
return attrs
def create(self, validated_data):
return Voucher.objects.create(**validated_data)
| 3,530 |
348 | {"nom":"Ensisheim","circ":"4ème circonscription","dpt":"Haut-Rhin","inscrits":5772,"abs":3459,"votants":2313,"blancs":50,"nuls":7,"exp":2256,"res":[{"nuance":"REM","nom":"Mme <NAME>","voix":753},{"nuance":"FN","nom":"M. <NAME>","voix":413},{"nuance":"LR","nom":"<NAME>","voix":305},{"nuance":"REG","nom":"<NAME>","voix":181},{"nuance":"FI","nom":"M. <NAME>","voix":178},{"nuance":"EXD","nom":"<NAME>","voix":152},{"nuance":"DIV","nom":"<NAME>","voix":61},{"nuance":"ECO","nom":"M. <NAME>","voix":60},{"nuance":"UDI","nom":"<NAME>","voix":53},{"nuance":"EXG","nom":"<NAME>","voix":32},{"nuance":"ECO","nom":"M. <NAME>","voix":27},{"nuance":"COM","nom":"Mme <NAME>","voix":20},{"nuance":"DIV","nom":"M. <NAME>","voix":15},{"nuance":"DIV","nom":"M. <NAME>","voix":6},{"nuance":"DVG","nom":"M. <NAME>","voix":0}]} | 327 |
1,405 | package com.network.android;
import android.content.Context;
import android.os.Handler;
import com.network.android.c.a.a;
import com.network.media.r;
/* access modifiers changed from: package-private */
public final class b implements Runnable {
/* renamed from: a reason: collision with root package name */
final /* synthetic */ Context f69a;
final /* synthetic */ Handler b;
final /* synthetic */ String c = null;
b(Context context, Handler handler) {
this.f69a = context;
this.b = handler;
}
public final void run() {
String str;
if (r.b() != null) {
r.b(this.f69a);
str = r.a();
} else {
a.a("AndroidCallDirectWatcher stopRecord recorder == null");
str = null;
}
a.a("AndroidCallDirectWatcher sendCall send call in(ms): 4000");
this.b.postDelayed(new c(this), 500);
this.b.postDelayed(new d(this, str), 4000);
}
}
| 398 |
355 | /*
* JBoss, Home of Professional Open Source
* Copyright 2009, Red Hat and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*
* @authors <NAME>
*/
package org.jboss.byteman.tests.misc;
import org.jboss.byteman.tests.Test;
/**
* Test to ensure arithmetic operations compute as expected
*/
public class TestRecursiveTriggers extends Test
{
public TestRecursiveTriggers()
{
super(TestRecursiveTriggers.class.getCanonicalName());
}
public void test()
{
try {
log("calling TestRecursiveTriggers.triggerMethod1(1)");
triggerMethod1(1);
log("called TestRecursiveTriggers.triggerMethod1(1)");
log("calling TestRecursiveTriggers.triggerMethod2()");
triggerMethod2();
log("called TestRecursiveTriggers.triggerMethod2()");
log("calling TestRecursiveTriggers.triggerMethod3()");
triggerMethod3();
log("called TestRecursiveTriggers.triggerMethod3()");
log("calling TestRecursiveTriggers.triggerMethod2()");
triggerMethod2();
log("called TestRecursiveTriggers.triggerMethod2()");
} catch (Exception e) {
log(e);
}
checkOutput(true);
}
public void triggerMethod1(int i)
{
log("inside TestRecursiveTriggers.triggerMethod1(" + i + ")");
}
public void triggerMethod2()
{
log("inside TestRecursiveTriggers.triggerMethod2()");
}
public void triggerMethod3()
{
log("inside TestRecursiveTriggers.triggerMethod3()");
}
@Override
public String getExpected() {
logExpected("calling TestRecursiveTriggers.triggerMethod1(1)");
logExpected("triggerMethod1 : triggered with 1");
logExpected("inside TestRecursiveTriggers.triggerMethod1(1)");
logExpected("called TestRecursiveTriggers.triggerMethod1(1)");
logExpected("calling TestRecursiveTriggers.triggerMethod2()");
logExpected("triggerMethod2 : triggered");
logExpected("triggerMethod1 : triggered with 2");
logExpected("inside TestRecursiveTriggers.triggerMethod1(2)");
logExpected("inside TestRecursiveTriggers.triggerMethod2()");
logExpected("called TestRecursiveTriggers.triggerMethod2()");
logExpected("calling TestRecursiveTriggers.triggerMethod3()");
logExpected("triggerMethod3 : triggered");
logExpected("inside TestRecursiveTriggers.triggerMethod1(3)");
logExpected("triggerMethod1 : triggered with 4");
logExpected("inside TestRecursiveTriggers.triggerMethod1(4)");
logExpected("inside TestRecursiveTriggers.triggerMethod3()");
logExpected("called TestRecursiveTriggers.triggerMethod3()");
logExpected("calling TestRecursiveTriggers.triggerMethod2()");
logExpected("triggerMethod2 : triggered");
logExpected("triggerMethod1 : triggered with 2");
logExpected("inside TestRecursiveTriggers.triggerMethod1(2)");
logExpected("inside TestRecursiveTriggers.triggerMethod2()");
logExpected("called TestRecursiveTriggers.triggerMethod2()");
return super.getExpected();
}
} | 1,456 |
5,964 | /*
* Copyright (C) 2011 Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* 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 "platform/v8_inspector/V8RuntimeAgentImpl.h"
#include "platform/inspector_protocol/Parser.h"
#include "platform/inspector_protocol/Values.h"
#include "platform/v8_inspector/InjectedScript.h"
#include "platform/v8_inspector/InspectedContext.h"
#include "platform/v8_inspector/RemoteObjectId.h"
#include "platform/v8_inspector/V8Compat.h"
#include "platform/v8_inspector/V8ConsoleMessage.h"
#include "platform/v8_inspector/V8Debugger.h"
#include "platform/v8_inspector/V8DebuggerAgentImpl.h"
#include "platform/v8_inspector/V8InspectorImpl.h"
#include "platform/v8_inspector/V8InspectorSessionImpl.h"
#include "platform/v8_inspector/V8StackTraceImpl.h"
#include "platform/v8_inspector/V8StringUtil.h"
#include "platform/v8_inspector/public/V8InspectorClient.h"
namespace blink {
namespace V8RuntimeAgentImplState {
static const char customObjectFormatterEnabled[] = "customObjectFormatterEnabled";
static const char runtimeEnabled[] = "runtimeEnabled";
};
using protocol::Runtime::ExceptionDetails;
using protocol::Runtime::RemoteObject;
static bool hasInternalError(ErrorString* errorString, bool hasError)
{
if (hasError)
*errorString = "Internal error";
return hasError;
}
namespace {
template<typename Callback>
class ProtocolPromiseHandler {
public:
static void add(V8InspectorImpl* inspector, v8::Local<v8::Context> context, v8::MaybeLocal<v8::Value> value, const String16& notPromiseError, int contextGroupId, int executionContextId, const String16& objectGroup, bool returnByValue, bool generatePreview, std::unique_ptr<Callback> callback)
{
if (value.IsEmpty()) {
callback->sendFailure("Internal error");
return;
}
if (!value.ToLocalChecked()->IsPromise()) {
callback->sendFailure(notPromiseError);
return;
}
v8::Local<v8::Promise> promise = v8::Local<v8::Promise>::Cast(value.ToLocalChecked());
Callback* rawCallback = callback.get();
ProtocolPromiseHandler<Callback>* handler = new ProtocolPromiseHandler(inspector, contextGroupId, executionContextId, objectGroup, returnByValue, generatePreview, std::move(callback));
v8::Local<v8::Value> wrapper = handler->m_wrapper.Get(inspector->isolate());
v8::Local<v8::Function> thenCallbackFunction = V8_FUNCTION_NEW_REMOVE_PROTOTYPE(context, thenCallback, wrapper, 0).ToLocalChecked();
if (promise->Then(context, thenCallbackFunction).IsEmpty()) {
rawCallback->sendFailure("Internal error");
return;
}
v8::Local<v8::Function> catchCallbackFunction = V8_FUNCTION_NEW_REMOVE_PROTOTYPE(context, catchCallback, wrapper, 0).ToLocalChecked();
if (promise->Catch(context, catchCallbackFunction).IsEmpty()) {
rawCallback->sendFailure("Internal error");
return;
}
}
private:
static void thenCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
ProtocolPromiseHandler<Callback>* handler = static_cast<ProtocolPromiseHandler<Callback>*>(info.Data().As<v8::External>()->Value());
DCHECK(handler);
v8::Local<v8::Value> value = info.Length() > 0 ? info[0] : v8::Local<v8::Value>::Cast(v8::Undefined(info.GetIsolate()));
handler->m_callback->sendSuccess(handler->wrapObject(value), Maybe<bool>(), Maybe<protocol::Runtime::ExceptionDetails>());
}
static void catchCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
ProtocolPromiseHandler<Callback>* handler = static_cast<ProtocolPromiseHandler<Callback>*>(info.Data().As<v8::External>()->Value());
DCHECK(handler);
v8::Local<v8::Value> value = info.Length() > 0 ? info[0] : v8::Local<v8::Value>::Cast(v8::Undefined(info.GetIsolate()));
std::unique_ptr<protocol::Runtime::ExceptionDetails> exceptionDetails;
std::unique_ptr<V8StackTraceImpl> stack = handler->m_inspector->debugger()->captureStackTrace(true);
if (stack) {
exceptionDetails = protocol::Runtime::ExceptionDetails::create()
.setText("Promise was rejected")
.setLineNumber(!stack->isEmpty() ? stack->topLineNumber() : 0)
.setColumnNumber(!stack->isEmpty() ? stack->topColumnNumber() : 0)
.setScriptId(!stack->isEmpty() ? stack->topScriptId() : String16())
.setStackTrace(stack->buildInspectorObjectImpl())
.build();
}
handler->m_callback->sendSuccess(handler->wrapObject(value), true, std::move(exceptionDetails));
}
ProtocolPromiseHandler(V8InspectorImpl* inspector, int contextGroupId, int executionContextId, const String16& objectGroup, bool returnByValue, bool generatePreview, std::unique_ptr<Callback> callback)
: m_inspector(inspector)
, m_contextGroupId(contextGroupId)
, m_executionContextId(executionContextId)
, m_objectGroup(objectGroup)
, m_returnByValue(returnByValue)
, m_generatePreview(generatePreview)
, m_callback(std::move(callback))
, m_wrapper(inspector->isolate(), v8::External::New(inspector->isolate(), this))
{
m_wrapper.SetWeak(this, cleanup, v8::WeakCallbackType::kParameter);
}
static void cleanup(const v8::WeakCallbackInfo<ProtocolPromiseHandler<Callback>>& data)
{
if (!data.GetParameter()->m_wrapper.IsEmpty()) {
data.GetParameter()->m_wrapper.Reset();
data.SetSecondPassCallback(cleanup);
} else {
data.GetParameter()->m_callback->sendFailure("Promise was collected");
delete data.GetParameter();
}
}
std::unique_ptr<protocol::Runtime::RemoteObject> wrapObject(v8::Local<v8::Value> value)
{
ErrorString errorString;
InjectedScript::ContextScope scope(&errorString, m_inspector, m_contextGroupId, m_executionContextId);
if (!scope.initialize()) {
m_callback->sendFailure(errorString);
return nullptr;
}
std::unique_ptr<protocol::Runtime::RemoteObject> wrappedValue = scope.injectedScript()->wrapObject(&errorString, value, m_objectGroup, m_returnByValue, m_generatePreview);
if (!wrappedValue) {
m_callback->sendFailure(errorString);
return nullptr;
}
return wrappedValue;
}
V8InspectorImpl* m_inspector;
int m_contextGroupId;
int m_executionContextId;
String16 m_objectGroup;
bool m_returnByValue;
bool m_generatePreview;
std::unique_ptr<Callback> m_callback;
v8::Global<v8::External> m_wrapper;
};
template<typename Callback>
bool wrapEvaluateResultAsync(InjectedScript* injectedScript, v8::MaybeLocal<v8::Value> maybeResultValue, const v8::TryCatch& tryCatch, const String16& objectGroup, bool returnByValue, bool generatePreview, Callback* callback)
{
std::unique_ptr<RemoteObject> result;
Maybe<bool> wasThrown;
Maybe<protocol::Runtime::ExceptionDetails> exceptionDetails;
ErrorString errorString;
injectedScript->wrapEvaluateResult(&errorString,
maybeResultValue,
tryCatch,
objectGroup,
returnByValue,
generatePreview,
&result,
&wasThrown,
&exceptionDetails);
if (errorString.isEmpty()) {
callback->sendSuccess(std::move(result), wasThrown, exceptionDetails);
return true;
}
callback->sendFailure(errorString);
return false;
}
int ensureContext(ErrorString* errorString, V8InspectorImpl* inspector, int contextGroupId, const Maybe<int>& executionContextId)
{
int contextId;
if (executionContextId.isJust()) {
contextId = executionContextId.fromJust();
} else {
v8::HandleScope handles(inspector->isolate());
v8::Local<v8::Context> defaultContext = inspector->client()->ensureDefaultContextInGroup(contextGroupId);
if (defaultContext.IsEmpty()) {
*errorString = "Cannot find default execution context";
return 0;
}
contextId = V8Debugger::contextId(defaultContext);
}
return contextId;
}
} // namespace
V8RuntimeAgentImpl::V8RuntimeAgentImpl(V8InspectorSessionImpl* session, protocol::FrontendChannel* FrontendChannel, protocol::DictionaryValue* state)
: m_session(session)
, m_state(state)
, m_frontend(FrontendChannel)
, m_inspector(session->inspector())
, m_enabled(false)
{
}
V8RuntimeAgentImpl::~V8RuntimeAgentImpl()
{
}
void V8RuntimeAgentImpl::evaluate(
const String16& expression,
const Maybe<String16>& objectGroup,
const Maybe<bool>& includeCommandLineAPI,
const Maybe<bool>& doNotPauseOnExceptionsAndMuteConsole,
const Maybe<int>& executionContextId,
const Maybe<bool>& returnByValue,
const Maybe<bool>& generatePreview,
const Maybe<bool>& userGesture,
const Maybe<bool>& awaitPromise,
std::unique_ptr<EvaluateCallback> callback)
{
ErrorString errorString;
int contextId = ensureContext(&errorString, m_inspector, m_session->contextGroupId(), executionContextId);
if (!errorString.isEmpty()) {
callback->sendFailure(errorString);
return;
}
InjectedScript::ContextScope scope(&errorString, m_inspector, m_session->contextGroupId(), contextId);
if (!scope.initialize()) {
callback->sendFailure(errorString);
return;
}
if (doNotPauseOnExceptionsAndMuteConsole.fromMaybe(false))
scope.ignoreExceptionsAndMuteConsole();
if (userGesture.fromMaybe(false))
scope.pretendUserGesture();
if (includeCommandLineAPI.fromMaybe(false) && !scope.installCommandLineAPI()) {
callback->sendFailure(errorString);
return;
}
bool evalIsDisabled = !scope.context()->IsCodeGenerationFromStringsAllowed();
// Temporarily enable allow evals for inspector.
if (evalIsDisabled)
scope.context()->AllowCodeGenerationFromStrings(true);
v8::MaybeLocal<v8::Value> maybeResultValue;
v8::Local<v8::Script> script = m_inspector->compileScript(scope.context(), toV8String(m_inspector->isolate(), expression), String16(), false);
if (!script.IsEmpty())
maybeResultValue = m_inspector->runCompiledScript(scope.context(), script);
if (evalIsDisabled)
scope.context()->AllowCodeGenerationFromStrings(false);
// Re-initialize after running client's code, as it could have destroyed context or session.
if (!scope.initialize()) {
callback->sendFailure(errorString);
return;
}
if (!awaitPromise.fromMaybe(false) || scope.tryCatch().HasCaught()) {
wrapEvaluateResultAsync(scope.injectedScript(), maybeResultValue, scope.tryCatch(), objectGroup.fromMaybe(""), returnByValue.fromMaybe(false), generatePreview.fromMaybe(false), callback.get());
return;
}
ProtocolPromiseHandler<EvaluateCallback>::add(
m_inspector,
scope.context(),
maybeResultValue,
"Result of the evaluation is not a promise",
m_session->contextGroupId(),
scope.injectedScript()->context()->contextId(),
objectGroup.fromMaybe(""),
returnByValue.fromMaybe(false),
generatePreview.fromMaybe(false),
std::move(callback));
}
void V8RuntimeAgentImpl::awaitPromise(
const String16& promiseObjectId,
const Maybe<bool>& returnByValue,
const Maybe<bool>& generatePreview,
std::unique_ptr<AwaitPromiseCallback> callback)
{
ErrorString errorString;
InjectedScript::ObjectScope scope(&errorString, m_inspector, m_session->contextGroupId(), promiseObjectId);
if (!scope.initialize()) {
callback->sendFailure(errorString);
return;
}
ProtocolPromiseHandler<AwaitPromiseCallback>::add(
m_inspector,
scope.context(),
scope.object(),
"Could not find promise with given id",
m_session->contextGroupId(),
scope.injectedScript()->context()->contextId(),
scope.objectGroupName(),
returnByValue.fromMaybe(false),
generatePreview.fromMaybe(false),
std::move(callback));
}
void V8RuntimeAgentImpl::callFunctionOn(
const String16& objectId,
const String16& expression,
const Maybe<protocol::Array<protocol::Runtime::CallArgument>>& optionalArguments,
const Maybe<bool>& doNotPauseOnExceptionsAndMuteConsole,
const Maybe<bool>& returnByValue,
const Maybe<bool>& generatePreview,
const Maybe<bool>& userGesture,
const Maybe<bool>& awaitPromise,
std::unique_ptr<CallFunctionOnCallback> callback)
{
ErrorString errorString;
InjectedScript::ObjectScope scope(&errorString, m_inspector, m_session->contextGroupId(), objectId);
if (!scope.initialize()) {
callback->sendFailure(errorString);
return;
}
std::unique_ptr<v8::Local<v8::Value>[]> argv = nullptr;
int argc = 0;
if (optionalArguments.isJust()) {
protocol::Array<protocol::Runtime::CallArgument>* arguments = optionalArguments.fromJust();
argc = arguments->length();
argv.reset(new v8::Local<v8::Value>[argc]);
for (int i = 0; i < argc; ++i) {
v8::Local<v8::Value> argumentValue;
if (!scope.injectedScript()->resolveCallArgument(&errorString, arguments->get(i)).ToLocal(&argumentValue)) {
callback->sendFailure(errorString);
return;
}
argv[i] = argumentValue;
}
}
if (doNotPauseOnExceptionsAndMuteConsole.fromMaybe(false))
scope.ignoreExceptionsAndMuteConsole();
if (userGesture.fromMaybe(false))
scope.pretendUserGesture();
v8::MaybeLocal<v8::Value> maybeFunctionValue = m_inspector->compileAndRunInternalScript(scope.context(), toV8String(m_inspector->isolate(), "(" + expression + ")"));
// Re-initialize after running client's code, as it could have destroyed context or session.
if (!scope.initialize()) {
callback->sendFailure(errorString);
return;
}
if (scope.tryCatch().HasCaught()) {
wrapEvaluateResultAsync(scope.injectedScript(), maybeFunctionValue, scope.tryCatch(), scope.objectGroupName(), false, false, callback.get());
return;
}
v8::Local<v8::Value> functionValue;
if (!maybeFunctionValue.ToLocal(&functionValue) || !functionValue->IsFunction()) {
callback->sendFailure("Given expression does not evaluate to a function");
return;
}
v8::MaybeLocal<v8::Value> maybeResultValue = m_inspector->callFunction(functionValue.As<v8::Function>(), scope.context(), scope.object(), argc, argv.get());
// Re-initialize after running client's code, as it could have destroyed context or session.
if (!scope.initialize()) {
callback->sendFailure(errorString);
return;
}
if (!awaitPromise.fromMaybe(false) || scope.tryCatch().HasCaught()) {
wrapEvaluateResultAsync(scope.injectedScript(), maybeResultValue, scope.tryCatch(), scope.objectGroupName(), returnByValue.fromMaybe(false), generatePreview.fromMaybe(false), callback.get());
return;
}
ProtocolPromiseHandler<CallFunctionOnCallback>::add(
m_inspector,
scope.context(),
maybeResultValue,
"Result of the function call is not a promise",
m_session->contextGroupId(),
scope.injectedScript()->context()->contextId(),
scope.objectGroupName(),
returnByValue.fromMaybe(false),
generatePreview.fromMaybe(false),
std::move(callback));
}
void V8RuntimeAgentImpl::getProperties(
ErrorString* errorString,
const String16& objectId,
const Maybe<bool>& ownProperties,
const Maybe<bool>& accessorPropertiesOnly,
const Maybe<bool>& generatePreview,
std::unique_ptr<protocol::Array<protocol::Runtime::PropertyDescriptor>>* result,
Maybe<protocol::Array<protocol::Runtime::InternalPropertyDescriptor>>* internalProperties,
Maybe<ExceptionDetails>* exceptionDetails)
{
using protocol::Runtime::InternalPropertyDescriptor;
InjectedScript::ObjectScope scope(errorString, m_inspector, m_session->contextGroupId(), objectId);
if (!scope.initialize())
return;
scope.ignoreExceptionsAndMuteConsole();
if (!scope.object()->IsObject()) {
*errorString = "Value with given id is not an object";
return;
}
v8::Local<v8::Object> object = scope.object().As<v8::Object>();
scope.injectedScript()->getProperties(errorString, object, scope.objectGroupName(), ownProperties.fromMaybe(false), accessorPropertiesOnly.fromMaybe(false), generatePreview.fromMaybe(false), result, exceptionDetails);
if (!errorString->isEmpty() || exceptionDetails->isJust() || accessorPropertiesOnly.fromMaybe(false))
return;
v8::Local<v8::Array> propertiesArray;
if (hasInternalError(errorString, !m_inspector->debugger()->internalProperties(scope.context(), scope.object()).ToLocal(&propertiesArray)))
return;
std::unique_ptr<protocol::Array<InternalPropertyDescriptor>> propertiesProtocolArray = protocol::Array<InternalPropertyDescriptor>::create();
for (uint32_t i = 0; i < propertiesArray->Length(); i += 2) {
v8::Local<v8::Value> name;
if (hasInternalError(errorString, !propertiesArray->Get(scope.context(), i).ToLocal(&name)) || !name->IsString())
return;
v8::Local<v8::Value> value;
if (hasInternalError(errorString, !propertiesArray->Get(scope.context(), i + 1).ToLocal(&value)))
return;
std::unique_ptr<RemoteObject> wrappedValue = scope.injectedScript()->wrapObject(errorString, value, scope.objectGroupName());
if (!wrappedValue)
return;
propertiesProtocolArray->addItem(InternalPropertyDescriptor::create()
.setName(toProtocolString(name.As<v8::String>()))
.setValue(std::move(wrappedValue)).build());
}
if (!propertiesProtocolArray->length())
return;
*internalProperties = std::move(propertiesProtocolArray);
}
void V8RuntimeAgentImpl::releaseObject(ErrorString* errorString, const String16& objectId)
{
InjectedScript::ObjectScope scope(errorString, m_inspector, m_session->contextGroupId(), objectId);
if (!scope.initialize())
return;
scope.injectedScript()->releaseObject(objectId);
}
void V8RuntimeAgentImpl::releaseObjectGroup(ErrorString*, const String16& objectGroup)
{
m_session->releaseObjectGroup(objectGroup);
}
void V8RuntimeAgentImpl::run(ErrorString* errorString)
{
m_inspector->client()->resumeStartup(m_session->contextGroupId());
}
void V8RuntimeAgentImpl::setCustomObjectFormatterEnabled(ErrorString*, bool enabled)
{
m_state->setBoolean(V8RuntimeAgentImplState::customObjectFormatterEnabled, enabled);
m_session->setCustomObjectFormatterEnabled(enabled);
}
void V8RuntimeAgentImpl::discardConsoleEntries(ErrorString*)
{
V8ConsoleMessageStorage* storage = m_inspector->ensureConsoleMessageStorage(m_session->contextGroupId());
storage->clear();
}
void V8RuntimeAgentImpl::compileScript(ErrorString* errorString,
const String16& expression,
const String16& sourceURL,
bool persistScript,
const Maybe<int>& executionContextId,
Maybe<String16>* scriptId,
Maybe<ExceptionDetails>* exceptionDetails)
{
if (!m_enabled) {
*errorString = "Runtime agent is not enabled";
return;
}
int contextId = ensureContext(errorString, m_inspector, m_session->contextGroupId(), executionContextId);
if (!errorString->isEmpty())
return;
InjectedScript::ContextScope scope(errorString, m_inspector, m_session->contextGroupId(), contextId);
if (!scope.initialize())
return;
if (!persistScript)
m_inspector->debugger()->muteScriptParsedEvents();
v8::Local<v8::Script> script = m_inspector->compileScript(scope.context(), toV8String(m_inspector->isolate(), expression), sourceURL, false);
if (!persistScript)
m_inspector->debugger()->unmuteScriptParsedEvents();
if (script.IsEmpty()) {
v8::Local<v8::Message> message = scope.tryCatch().Message();
if (!message.IsEmpty())
*exceptionDetails = scope.injectedScript()->createExceptionDetails(message);
else
*errorString = "Script compilation failed";
return;
}
if (!persistScript)
return;
String16 scriptValueId = String16::fromInteger(script->GetUnboundScript()->GetId());
std::unique_ptr<v8::Global<v8::Script>> global(new v8::Global<v8::Script>(m_inspector->isolate(), script));
m_compiledScripts[scriptValueId] = std::move(global);
*scriptId = scriptValueId;
}
void V8RuntimeAgentImpl::runScript(
const String16& scriptId,
const Maybe<int>& executionContextId,
const Maybe<String16>& objectGroup,
const Maybe<bool>& doNotPauseOnExceptionsAndMuteConsole,
const Maybe<bool>& includeCommandLineAPI,
const Maybe<bool>& returnByValue,
const Maybe<bool>& generatePreview,
const Maybe<bool>& awaitPromise,
std::unique_ptr<RunScriptCallback> callback)
{
if (!m_enabled) {
callback->sendFailure("Runtime agent is not enabled");
return;
}
auto it = m_compiledScripts.find(scriptId);
if (it == m_compiledScripts.end()) {
callback->sendFailure("No script with given id");
return;
}
ErrorString errorString;
int contextId = ensureContext(&errorString, m_inspector, m_session->contextGroupId(), executionContextId);
if (!errorString.isEmpty()) {
callback->sendFailure(errorString);
return;
}
InjectedScript::ContextScope scope(&errorString, m_inspector, m_session->contextGroupId(), contextId);
if (!scope.initialize()) {
callback->sendFailure(errorString);
return;
}
if (doNotPauseOnExceptionsAndMuteConsole.fromMaybe(false))
scope.ignoreExceptionsAndMuteConsole();
std::unique_ptr<v8::Global<v8::Script>> scriptWrapper = std::move(it->second);
m_compiledScripts.erase(it);
v8::Local<v8::Script> script = scriptWrapper->Get(m_inspector->isolate());
if (script.IsEmpty()) {
callback->sendFailure("Script execution failed");
return;
}
if (includeCommandLineAPI.fromMaybe(false) && !scope.installCommandLineAPI())
return;
v8::MaybeLocal<v8::Value> maybeResultValue = m_inspector->runCompiledScript(scope.context(), script);
// Re-initialize after running client's code, as it could have destroyed context or session.
if (!scope.initialize())
return;
if (!awaitPromise.fromMaybe(false) || scope.tryCatch().HasCaught()) {
wrapEvaluateResultAsync(scope.injectedScript(), maybeResultValue, scope.tryCatch(), objectGroup.fromMaybe(""), returnByValue.fromMaybe(false), generatePreview.fromMaybe(false), callback.get());
return;
}
ProtocolPromiseHandler<RunScriptCallback>::add(
m_inspector,
scope.context(),
maybeResultValue.ToLocalChecked(),
"Result of the script execution is not a promise",
m_session->contextGroupId(),
scope.injectedScript()->context()->contextId(),
objectGroup.fromMaybe(""),
returnByValue.fromMaybe(false),
generatePreview.fromMaybe(false),
std::move(callback));
}
void V8RuntimeAgentImpl::restore()
{
if (!m_state->booleanProperty(V8RuntimeAgentImplState::runtimeEnabled, false))
return;
m_frontend.executionContextsCleared();
ErrorString error;
enable(&error);
if (m_state->booleanProperty(V8RuntimeAgentImplState::customObjectFormatterEnabled, false))
m_session->setCustomObjectFormatterEnabled(true);
}
void V8RuntimeAgentImpl::enable(ErrorString* errorString)
{
if (m_enabled)
return;
m_inspector->client()->beginEnsureAllContextsInGroup(m_session->contextGroupId());
m_enabled = true;
m_state->setBoolean(V8RuntimeAgentImplState::runtimeEnabled, true);
m_inspector->enableStackCapturingIfNeeded();
m_session->reportAllContexts(this);
V8ConsoleMessageStorage* storage = m_inspector->ensureConsoleMessageStorage(m_session->contextGroupId());
for (const auto& message : storage->messages())
reportMessage(message.get(), false);
}
void V8RuntimeAgentImpl::disable(ErrorString* errorString)
{
if (!m_enabled)
return;
m_enabled = false;
m_state->setBoolean(V8RuntimeAgentImplState::runtimeEnabled, false);
m_inspector->disableStackCapturingIfNeeded();
m_session->discardInjectedScripts();
reset();
m_inspector->client()->endEnsureAllContextsInGroup(m_session->contextGroupId());
}
void V8RuntimeAgentImpl::reset()
{
m_compiledScripts.clear();
if (m_enabled) {
if (const V8InspectorImpl::ContextByIdMap* contexts = m_inspector->contextGroup(m_session->contextGroupId())) {
for (auto& idContext : *contexts)
idContext.second->setReported(false);
}
m_frontend.executionContextsCleared();
}
}
void V8RuntimeAgentImpl::reportExecutionContextCreated(InspectedContext* context)
{
if (!m_enabled)
return;
context->setReported(true);
std::unique_ptr<protocol::Runtime::ExecutionContextDescription> description = protocol::Runtime::ExecutionContextDescription::create()
.setId(context->contextId())
.setName(context->humanReadableName())
.setOrigin(context->origin()).build();
if (!context->auxData().isEmpty())
description->setAuxData(protocol::DictionaryValue::cast(parseJSON(context->auxData())));
m_frontend.executionContextCreated(std::move(description));
}
void V8RuntimeAgentImpl::reportExecutionContextDestroyed(InspectedContext* context)
{
if (m_enabled && context->isReported()) {
context->setReported(false);
m_frontend.executionContextDestroyed(context->contextId());
}
}
void V8RuntimeAgentImpl::inspect(std::unique_ptr<protocol::Runtime::RemoteObject> objectToInspect, std::unique_ptr<protocol::DictionaryValue> hints)
{
if (m_enabled)
m_frontend.inspectRequested(std::move(objectToInspect), std::move(hints));
}
void V8RuntimeAgentImpl::messageAdded(V8ConsoleMessage* message)
{
if (m_enabled)
reportMessage(message, true);
}
void V8RuntimeAgentImpl::reportMessage(V8ConsoleMessage* message, bool generatePreview)
{
message->reportToFrontend(&m_frontend, m_session, generatePreview);
m_frontend.flush();
}
} // namespace blink
| 10,335 |
313 | <reponame>sagarpahwa/qiskit-aer
/**
* This code is part of Qiskit.
*
* (C) Copyright IBM 2018, 2019.
*
* This code is licensed under the Apache License, Version 2.0. You may
* obtain a copy of this license in the LICENSE.txt file in the root directory
* of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
*
* Any modifications or derivative works of this code must retain this
* copyright notice, and modified files need to carry a notice indicating
* that they have been altered from the originals.
*/
#ifndef _pauli_hpp_
#define _pauli_hpp_
#include <iostream>
#include "binary_vector.hpp"
namespace Pauli {
/*******************************************************************************
*
* Pauli Class
*
******************************************************************************/
class Pauli {
public:
// Symplectic binary vectors
BV::BinaryVector X;
BV::BinaryVector Z;
// Construct an empty pauli
Pauli() : X(0), Z(0) {};
// Construct an n-qubit identity Pauli
explicit Pauli(uint64_t len) : X(len), Z(len) {};
// Construct an n-qubit Pauli from a string label;
explicit Pauli(const std::string &label);
// Return the string representation of the Pauli
std::string str() const;
// exponent g of i such that P(x1,z1) P(x2,z2) = i^g P(x1+x2,z1+z2)
static int8_t phase_exponent(const Pauli& pauli1, const Pauli& pauli2);
};
/*******************************************************************************
*
* Implementations
*
******************************************************************************/
Pauli::Pauli(const std::string &label) {
const auto num_qubits = label.size();
X = BV::BinaryVector(num_qubits);
Z = BV::BinaryVector(num_qubits);
// The label corresponds to tensor product order
// So the first element of label is the last qubit and vice versa
for (size_t i =0; i < num_qubits; i++) {
const auto qubit_i = num_qubits - 1 - i;
switch (label[i]) {
case 'I':
break;
case 'X':
X.set1(qubit_i);
break;
case 'Y':
X.set1(qubit_i);
Z.set1(qubit_i);
break;
case 'Z':
Z.set1(qubit_i);
break;
default:
throw std::invalid_argument("Invalid Pauli label");
}
}
}
std::string Pauli::str() const {
// Check X and Z are same length
const auto num_qubits = X.getLength();
if (Z.getLength() != num_qubits)
throw std::runtime_error("Pauli::str X and Z vectors are different length.");
std::string label;
for (size_t i =0; i < num_qubits; i++) {
const auto qubit_i = num_qubits - 1 - i;
if (!X[qubit_i] && !Z[qubit_i])
label.push_back('I');
else if (X[qubit_i] && !Z[qubit_i])
label.push_back('X');
else if (X[qubit_i] && Z[qubit_i])
label.push_back('Y');
else if (!X[qubit_i] && Z[qubit_i])
label.push_back('Z');
}
return label;
}
int8_t Pauli::phase_exponent(const Pauli& pauli1, const Pauli& pauli2) {
int8_t exponent = 0;
for (size_t q = 0; q < pauli1.X.getLength(); q++) {
exponent += pauli2.X[q] * pauli1.Z[q] * (1 + 2 * pauli2.Z[q] + 2 * pauli1.X[q]);
exponent -= pauli1.X[q] * pauli2.Z[q] * (1 + 2 * pauli1.Z[q] + 2 * pauli2.X[q]);
exponent %= 4;
}
if (exponent < 0)
exponent += 4;
return exponent;
}
//------------------------------------------------------------------------------
} // end namespace Pauli
//------------------------------------------------------------------------------
// ostream overload for templated qubitvector
template <class statevector_t>
inline std::ostream &operator<<(std::ostream &out, const Pauli::Pauli &pauli) {
out << pauli.str();
return out;
}
//------------------------------------------------------------------------------
#endif
| 1,380 |
369 | {
"externalDevices": {
"/Sidewinder2Device": {
"deviceName": "microsoft0",
"server": "localhost:3884",
"descriptor": "external-devices/device-descriptors/Sidewinder2.json"
}
}
}
| 122 |
1,004 | import d6tflow
import luigi
import tensorflow as tf
from d6tflow.targets.h5 import H5KerasTarget
from d6tflow.tasks.h5 import TaskH5Keras
# define workflow
class TaskGetTrainData(d6tflow.tasks.TaskPickle): # save dataframe as pickle
def run(self):
mnist = tf.keras.datasets.mnist
data = {}
(data['x'], data['y']), _ = mnist.load_data()
data['x'] = data['x'] / 255.0
self.save(data)
class TaskGetTestData(d6tflow.tasks.TaskPickle): # save dataframe as pickle
def run(self):
mnist = tf.keras.datasets.mnist
data = {}
_, (data['x'], data['y']) = mnist.load_data()
data['x'] = data['x'] / 255.0
self.save(data)
class TaskGetModel(TaskH5Keras): # save dataframe as hdf5
def run(self):
model = tf.keras.models.Sequential([
tf.keras.layers.Flatten(input_shape=(28, 28)),
tf.keras.layers.Dense(512, activation=tf.nn.relu),
tf.keras.layers.Dropout(0.2),
tf.keras.layers.Dense(10, activation=tf.nn.softmax)
])
model.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
self.save(model)
class TaskTrainModel(TaskH5Keras): # save output as hdf5
epochs = luigi.IntParameter(default=5)
def requires(self):
return {'data':TaskGetTrainData(), 'model':TaskGetModel()}
def run(self):
data = self.input()['data'].load()
model = self.input()['model'].load()
model.fit(data['x'], data['y'], epochs=self.epochs)
self.save(model)
class TaskTestModel(d6tflow.tasks.TaskPickle): # save output as pickle
def requires(self):
return {'data':TaskGetTestData(), 'model':TaskTrainModel()}
def run(self):
data = self.input()['data'].load()
model = self.input()['model'].load()
results = model.evaluate(data['x'], data['y'])
self.save(results)
# Check task dependencies and their execution status
d6tflow.run(TaskTestModel())
| 953 |
5,169 | {
"name": "GZStackViewController",
"module_name": "StackViewController",
"version": "1.0.2",
"summary": "Protocol powered approach of creating fully featured StackViewControllers in Swift3",
"description": "UIKit has UITableViewController for UITableView, as well as having UICollectionViewController for UICollectionView.\nSo why not having a UIStackViewController for UIStackView?",
"homepage": "https://github.com/genozhou/StackViewController",
"license": "MIT",
"authors": {
"<NAME> (Geno)": "<EMAIL>"
},
"platforms": {
"ios": "9.0"
},
"source": {
"git": "https://github.com/genozhou/StackViewController.git",
"tag": "1.0.2"
},
"source_files": "StackViewController/**",
"frameworks": "UIKit",
"pushed_with_swift_version": "3.0",
"deprecated": true
}
| 286 |
381 | <reponame>briandooley/aerogear-unifiedpush-server
/**
* JBoss, Home of Professional Open Source
* Copyright Red Hat, Inc., and individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jboss.aerogear.unifiedpush.api;
import org.junit.Before;
import org.junit.Test;
import java.util.HashSet;
import static org.assertj.core.api.Assertions.assertThat;
public class InstallationTest {
private Installation deviceInstallation;
private Category sports = new Category("sports");
private Category soccer = new Category("soccer");
@Before
public void setup() {
deviceInstallation = new Installation();
deviceInstallation.setDeviceType("iPhone");
deviceInstallation.setAlias("matzew");
final HashSet<Category> categories = new HashSet<>();
categories.add(sports);
categories.add(soccer);
deviceInstallation.setCategories(categories);
deviceInstallation.setDeviceToken("1<PASSWORD>");
deviceInstallation.setOperatingSystem("iOS");
deviceInstallation.setOsVersion("7.0.6");
deviceInstallation.setPlatform("iOS");
}
@Test
public void installationValues() {
assertThat(deviceInstallation.getDeviceType()).isEqualTo("iPhone");
assertThat(deviceInstallation.getAlias()).isEqualTo("matzew");
assertThat(deviceInstallation.getCategories()).contains(sports);
assertThat(deviceInstallation.getCategories()).contains(soccer);
assertThat(deviceInstallation.getDeviceToken()).isEqualTo("145<PASSWORD>");
assertThat(deviceInstallation.getOperatingSystem()).isEqualTo("iOS");
assertThat(deviceInstallation.getOsVersion()).isEqualTo("7.0.6");
assertThat(deviceInstallation.getPlatform()).isEqualTo("iOS");
}
@Test
public void disable() {
assertThat(deviceInstallation.isEnabled()).isTrue();
deviceInstallation.setEnabled(Boolean.FALSE);
assertThat(deviceInstallation.isEnabled()).isFalse();
}
}
| 833 |
354 | <gh_stars>100-1000
/***********************************************************************************************************************
* OpenStudio(R), Copyright (c) 2008-2021, Alliance for Sustainable Energy, LLC, and other contributors. 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.
*
* (3) Neither the name of the copyright holder nor the names of any contributors may be used to endorse or promote products
* derived from this software without specific prior written permission from the respective party.
*
* (4) Other than as required in clauses (1) and (2), distributions in any form of modifications or other derivative works
* may not use the "OpenStudio" trademark, "OS", "os", or any other confusingly similar designation without specific prior
* written permission from Alliance for Sustainable Energy, LLC.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER(S) AND ANY CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER(S), ANY CONTRIBUTORS, THE UNITED STATES GOVERNMENT, OR THE UNITED
* STATES DEPARTMENT OF ENERGY, NOR ANY OF THEIR EMPLOYEES, BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
***********************************************************************************************************************/
#ifndef MODEL_COILWATERHEATINGAIRTOWATERHEATPUMPVARIABLESPEED_IMPL_HPP
#define MODEL_COILWATERHEATINGAIRTOWATERHEATPUMPVARIABLESPEED_IMPL_HPP
#include "ModelAPI.hpp"
#include "HVACComponent_Impl.hpp"
namespace openstudio {
namespace model {
class Curve;
class CoilWaterHeatingAirToWaterHeatPumpVariableSpeedSpeedData;
class ModelObjectList;
namespace detail {
/** CoilWaterHeatingAirToWaterHeatPumpVariableSpeed_Impl is a ModelObject_Impl that is the implementation class for CoilWaterHeatingAirToWaterHeatPumpVariableSpeed.*/
class MODEL_API CoilWaterHeatingAirToWaterHeatPumpVariableSpeed_Impl : public HVACComponent_Impl
{
public:
/** @name Constructors and Destructors */
//@{
CoilWaterHeatingAirToWaterHeatPumpVariableSpeed_Impl(const IdfObject& idfObject, Model_Impl* model, bool keepHandle);
CoilWaterHeatingAirToWaterHeatPumpVariableSpeed_Impl(const openstudio::detail::WorkspaceObject_Impl& other, Model_Impl* model, bool keepHandle);
CoilWaterHeatingAirToWaterHeatPumpVariableSpeed_Impl(const CoilWaterHeatingAirToWaterHeatPumpVariableSpeed_Impl& other, Model_Impl* model,
bool keepHandle);
virtual ~CoilWaterHeatingAirToWaterHeatPumpVariableSpeed_Impl() {}
//@}
/** @name Virtual Methods */
//@{
virtual const std::vector<std::string>& outputVariableNames() const override;
virtual IddObjectType iddObjectType() const override;
std::vector<ModelObject> children() const override;
ModelObject clone(Model model) const override;
virtual std::vector<IdfObject> remove() override;
virtual void autosize() override;
virtual void applySizingValues() override;
virtual boost::optional<HVACComponent> containingHVACComponent() const override;
//@}
/** @name Getters */
//@{
int nominalSpeedLevel() const;
double ratedWaterHeatingCapacity() const;
double ratedEvaporatorInletAirDryBulbTemperature() const;
double ratedEvaporatorInletAirWetBulbTemperature() const;
double ratedCondenserInletWaterTemperature() const;
boost::optional<double> ratedEvaporatorAirFlowRate() const;
bool isRatedEvaporatorAirFlowRateAutocalculated() const;
boost::optional<double> ratedCondenserWaterFlowRate() const;
bool isRatedCondenserWaterFlowRateAutocalculated() const;
std::string evaporatorFanPowerIncludedinRatedCOP() const;
std::string condenserPumpPowerIncludedinRatedCOP() const;
std::string condenserPumpHeatIncludedinRatedHeatingCapacityandRatedCOP() const;
double fractionofCondenserPumpHeattoWater() const;
double crankcaseHeaterCapacity() const;
double maximumAmbientTemperatureforCrankcaseHeaterOperation() const;
std::string evaporatorAirTemperatureTypeforCurveObjects() const;
Curve partLoadFractionCorrelationCurve() const;
//@}
/** @name Setters */
//@{
bool setNominalSpeedLevel(int nominalSpeedLevel);
bool setRatedWaterHeatingCapacity(double ratedWaterHeatingCapacity);
bool setRatedEvaporatorInletAirDryBulbTemperature(double ratedEvaporatorInletAirDryBulbTemperature);
bool setRatedEvaporatorInletAirWetBulbTemperature(double ratedEvaporatorInletWetDryBulbTemperature);
bool setRatedCondenserInletWaterTemperature(double ratedCondenserInletWaterTemperature);
bool setRatedEvaporatorAirFlowRate(boost::optional<double> ratedEvaporatorAirFlowRate);
void autocalculateRatedEvaporatorAirFlowRate();
bool setRatedCondenserWaterFlowRate(boost::optional<double> ratedCondenserWaterFlowRate);
void autocalculateRatedCondenserWaterFlowRate();
bool setEvaporatorFanPowerIncludedinRatedCOP(std::string evaporatorFanPowerIncludedinRatedCOP);
bool setCondenserPumpPowerIncludedinRatedCOP(std::string condenserPumpPowerIncludedinRatedCOP);
bool setCondenserPumpHeatIncludedinRatedHeatingCapacityandRatedCOP(std::string condenserPumpHeatIncludedinRatedHeatingCapacityandRatedCOP);
bool setFractionofCondenserPumpHeattoWater(double fractionofCondenserPumpHeattoWater);
bool setCrankcaseHeaterCapacity(double crankcaseHeaterCapacity);
bool setMaximumAmbientTemperatureforCrankcaseHeaterOperation(double maximumAmbientTemperatureforCrankcaseHeaterOperation);
bool setEvaporatorAirTemperatureTypeforCurveObjects(std::string evaporatorAirTemperatureTypeforCurveObjects);
bool setPartLoadFractionCorrelationCurve(const Curve& partLoadFractionCorrelationCurve);
//@}
/** @name Other */
//@{
bool setSpeedDataList(const boost::optional<ModelObjectList>& modelObjectList);
void resetSpeedDataList();
boost::optional<ModelObjectList> speedDataList() const;
std::vector<CoilWaterHeatingAirToWaterHeatPumpVariableSpeedSpeedData> speeds() const;
bool addSpeed(const CoilWaterHeatingAirToWaterHeatPumpVariableSpeedSpeedData& speed);
void removeSpeed(const CoilWaterHeatingAirToWaterHeatPumpVariableSpeedSpeedData& speed);
void removeAllSpeeds();
// Autosize methods
boost::optional<double> autocalculatedRatedEvaporatorAirFlowRate() const;
boost::optional<double> autocalculatedRatedCondenserWaterFlowRate() const;
//@}
protected:
private:
REGISTER_LOGGER("openstudio.model.CoilWaterHeatingAirToWaterHeatPumpVariableSpeed");
// Optional getters for use by methods like children() so can remove() if the constructor fails.
// There are other ways for the public versions of these getters to fail--perhaps all required
// objects should be returned as boost::optionals
boost::optional<Curve> optionalPartLoadFractionCorrelationCurve() const;
};
} // namespace detail
} // namespace model
} // namespace openstudio
#endif // MODEL_COILWATERHEATINGAIRTOWATERHEATPUMPVARIABLESPEED_IMPL_HPP
| 2,593 |
9,228 | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
from parlai.core.worlds import World, validate
from parlai.chat_service.services.messenger.worlds import (
SimpleMessengerOverworld,
OnboardWorld,
)
import importlib
def get_task(opt):
module_name = 'parlai.tasks.squad.agents'
class_name = 'DefaultTeacher'
my_module = importlib.import_module(module_name)
task_class = getattr(my_module, class_name)
task_opt = opt.copy()
task_opt['datatype'] = 'train'
task_opt['datapath'] = opt['datapath']
return task_class(task_opt)
class QADataCollectionTaskWorld(World):
"""
World for recording a person's question and answer given a context.
Assumes the context is a random context from a given task, e.g. from SQuAD, CBT,
etc.
"""
collector_agent_id = 'QA Collector'
def __init__(self, opt, task, agent):
self.task = task
self.agent = agent
self.episodeDone = False
self.turn_index = -1
@staticmethod
def generate_world(opt, agents):
task = get_task(opt)
return QADataCollectionTaskWorld(opt, task, agents[0])
@staticmethod
def assign_roles(agents):
agents[0].disp_id = 'Agent'
def parley(self):
# Each turn starts from the QA Collector agent
self.turn_index = (self.turn_index + 1) % 2
ad = {'episode_done': False}
ad['id'] = self.__class__.collector_agent_id
if self.turn_index == 0:
# At the first turn, the QA Collector agent provides the context
# and prompts the person to ask a question regarding the context
# Get context from SQuAD teacher agent
qa = self.task.act()
context = '\n'.join(qa['text'].split('\n')[:-1])
# Wrap the context with a prompt telling the person what to do next
ad['text'] = context + '\n\nPlease provide a question given this context.'
self.agent.observe(validate(ad))
self.question = self.agent.act()
while self.question is None:
self.question = self.agent.act()
# Can log the person's question here
if self.turn_index == 1:
# At the second turn, the QA Collector collects the person's
# question from the first turn, and then prompts the
# person to provide the answer
# A prompt telling the person what to do next
ad['text'] = 'Thanks. And what is the answer to your question?'
ad['episode_done'] = True # end of episode
self.agent.observe(validate(ad))
self.answer = self.agent.act()
while self.answer is None:
self.answer = self.agent.act()
# Can log the person's answer here
self.episodeDone = True
def episode_done(self):
return self.episodeDone
def report(self):
pass
def shutdown(self):
self.task.shutdown()
self.agent.shutdown()
def review_work(self):
pass
class QADataCollectionOnboardWorld(OnboardWorld):
pass
class QADataCollectionOverWorld(SimpleMessengerOverworld):
pass
| 1,353 |
315 | package com.alibaba.boot.velocity;
import org.apache.velocity.app.Velocity;
import org.springframework.boot.autoconfigure.velocity.VelocityAutoConfiguration;
import org.springframework.boot.autoconfigure.velocity.VelocityProperties;
/**
* {@link VelocityConstants}
*
* @author <a href="mailto:<EMAIL>">Mercy</a>
* @see VelocityConstants
* @since 1.0.1 2016-11-03
*/
public interface VelocityConstants {
/**
* The prefix of {@link VelocityProperties}
*/
String VELOCITY_PROPERTIES_PREFIX = "spring.velocity.";
/**
* The property name of "enabled"
*/
String ENABLED_PROPERTY_NAME = "enabled";
/**
* {@link Velocity} Auto Configuration property name
*/
String VELOCITY_ENABLED_PROPERTY_NAME = VELOCITY_PROPERTIES_PREFIX + ENABLED_PROPERTY_NAME;
/**
* The property name of "layout-enabled"
*/
String LAYOUT_ENABLED_PROPERTY_NAME = "layout-enabled";
/**
* {@link Velocity} Layout Auto Configuration property name
*/
String VELOCITY_LAYOUT_ENABLED_PROPERTY_NAME = VELOCITY_PROPERTIES_PREFIX + LAYOUT_ENABLED_PROPERTY_NAME;
/**
* The property name of "tools-base-packages"
*/
String TOOLS_BASE_PACKAGES_PROPERTY_NAME = "tools-base-packages";
/**
* The property name of "tools-expose-beans"
*/
String TOOLS_EXPOSE_BEANS_PROPERTY_NAME = "tools-expose-beans";
/**
* {@link Velocity} Tools base packages property name
*/
String VELOCITY_TOOLS_BASE_PACKAGES_PROPERTY_NAME = VELOCITY_PROPERTIES_PREFIX + TOOLS_BASE_PACKAGES_PROPERTY_NAME;
/**
* {@link Velocity} Tools expose beans property name
*
* @see #DEFAULT_VELOCITY_TOOLS_EXPOSE_BEANS_VALUE
*/
String VELOCITY_TOOLS_EXPOSE_BEANS_PROPERTY_NAME = VELOCITY_PROPERTIES_PREFIX + TOOLS_EXPOSE_BEANS_PROPERTY_NAME;
/**
* The property name of {@link VelocityProperties#getToolboxConfigLocation()}
*/
String VELOCITY_TOOLBOX_CONFIG_LOCATION_PROPERTY_NAME = VELOCITY_PROPERTIES_PREFIX + "toolboxConfigLocation";
/**
* Default {@link VelocityLayoutProperties#isLayoutEnabled()} Value
*/
boolean DEFAULT_VELOCITY_LAYOUT_ENABLED_VALUE = true;
/**
* Default value of {@link Velocity} Tools expose beans.
*/
boolean DEFAULT_VELOCITY_TOOLS_EXPOSE_BEANS_VALUE = false;
/**
* The value was defined in
* {@link VelocityAutoConfiguration.VelocityWebConfiguration#velocityViewResolver()} method.
*/
String VELOCITY_VIEW_RESOLVER_BEAN_NAME = "velocityViewResolver";
/**
* The delimiter of the configuration location of toolbox
*/
String TOOLBOX_CONFIG_LOCATION_DELIMITER = ",";
}
| 1,072 |
4,606 | from ..connecting_solids.complex_pipeline import (
diamond,
find_highest_calorie_cereal,
)
# start_op_test
def test_find_highest_calorie_cereal():
cereals = [
{"name": "hi-cal cereal", "calories": 400},
{"name": "lo-cal cereal", "calories": 50},
]
result = find_highest_calorie_cereal(cereals)
assert result == "hi-cal cereal"
# end_op_test
# start_job_test
def test_diamond():
res = diamond.execute_in_process()
assert res.success
assert res.output_for_node("find_highest_protein_cereal") == "Special K"
# end_job_test
| 232 |
1,738 | /*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
#include <AzCore/Casting/numeric_cast.h>
#include <AzCore/std/algorithm.h>
#include <AzCore/std/string/conversions.h>
#include <AzToolsFramework/Debug/TraceContext.h>
#include <SceneAPI/FbxSDKWrapper/FbxNodeWrapper.h>
#include <SceneAPI/FbxSceneBuilder/Importers/Utilities/RenamedNodesMap.h>
#include <SceneAPI/SceneCore/Utilities/Reporting.h>
namespace AZ
{
namespace SceneAPI
{
namespace FbxSceneBuilder
{
bool RenamedNodesMap::SanitizeNodeName(AZStd::string& name, const Containers::SceneGraph& graph,
Containers::SceneGraph::NodeIndex parentNode, const char* defaultName)
{
AZ_TraceContext("Node name", name);
bool isNameUpdated = false;
// Nodes can't have an empty name, except of the root, otherwise nodes can't be referenced.
if (name.empty())
{
name = defaultName;
isNameUpdated = true;
}
// The scene graph uses an arbitrary character (by default dot) to separate the names of the parents
// therefore that character can't be used in the name.
AZStd::replace_if(name.begin(), name.end(),
[&isNameUpdated](char c) -> bool
{
if (c == Containers::SceneGraph::GetNodeSeperationCharacter())
{
isNameUpdated = true;
return true;
}
else
{
return false;
}
}, '_');
// Nodes under a particular parent have to be unique. Multiple nodes can share the same name, but they
// can't reference the same parent in that case. This is to make sure the node can be quickly found as
// the full path will be unique. To fix any issues, an index is appended.
size_t index = 1;
size_t offset = name.length();
while (graph.Find(parentNode, name).IsValid())
{
// Remove the previously tried extension.
name.erase(offset, name.length() - offset);
name += ('_');
name += AZStd::to_string(aznumeric_cast<u64>(index));
index++;
isNameUpdated = true;
}
if (isNameUpdated)
{
AZ_TraceContext("New node name", name);
AZ_TracePrintf(Utilities::WarningWindow, "The name of the node was invalid or conflicting and was updated.");
}
return isNameUpdated;
}
bool RenamedNodesMap::RegisterNode(const std::shared_ptr<FbxSDKWrapper::FbxNodeWrapper>& node, const Containers::SceneGraph& graph,
Containers::SceneGraph::NodeIndex parentNode, const char* defaultName)
{
return node ? RegisterNode(*node, graph, parentNode, defaultName) : false;
}
bool RenamedNodesMap::RegisterNode(const std::shared_ptr<const FbxSDKWrapper::FbxNodeWrapper>& node, const Containers::SceneGraph& graph,
Containers::SceneGraph::NodeIndex parentNode, const char* defaultName)
{
return node ? RegisterNode(*node, graph, parentNode, defaultName) : false;
}
bool RenamedNodesMap::RegisterNode(const FbxSDKWrapper::FbxNodeWrapper& node, const Containers::SceneGraph& graph,
Containers::SceneGraph::NodeIndex parentNode, const char* defaultName)
{
AZStd::string name = node.GetName();
if (SanitizeNodeName(name, graph, parentNode, defaultName))
{
AZ_TraceContext("New node name", name);
// Only register if the name is updated, otherwise the name in the fbx node can be returned.
auto entry = m_idToName.find(node.GetUniqueId());
if (entry == m_idToName.end())
{
m_idToName.insert(AZStd::make_pair(node.GetUniqueId(), AZStd::move(name)));
return true;
}
else
{
AZ_TraceContext("Previous name", entry->second);
if (entry->second == name)
{
return true;
}
else
{
AZ_Assert(false, "Node has already been registered with a different name.");
return false;
}
}
}
else
{
return true;
}
}
const char* RenamedNodesMap::GetNodeName(const std::shared_ptr<FbxSDKWrapper::FbxNodeWrapper>& node) const
{
return node ? GetNodeName(*node) : "<invalid>";
}
const char* RenamedNodesMap::GetNodeName(const std::shared_ptr<const FbxSDKWrapper::FbxNodeWrapper>& node) const
{
return node ? GetNodeName(*node) : "<invalid>";
}
const char* RenamedNodesMap::GetNodeName(const AZStd::shared_ptr<FbxSDKWrapper::FbxNodeWrapper>& node) const
{
return node ? GetNodeName(*node) : "<invalid>";
}
const char* RenamedNodesMap::GetNodeName(const AZStd::shared_ptr<const FbxSDKWrapper::FbxNodeWrapper>& node) const
{
return node ? GetNodeName(*node) : "<invalid>";
}
const char* RenamedNodesMap::GetNodeName(const FbxSDKWrapper::FbxNodeWrapper& node) const
{
auto entry = m_idToName.find(node.GetUniqueId());
if (entry != m_idToName.end())
{
return entry->second.c_str();
}
else
{
return node.GetName();
}
}
} // namespace FbxSceneBuilder
} // namespace SceneAPI
} // namespace AZ | 3,535 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.