max_stars_count
int64 301
224k
| text
stringlengths 6
1.05M
| token_count
int64 3
727k
|
---|---|---|
607 | package dev.cheerfun.pixivic.basic.auth.domain;
import java.util.Map;
/**
* @author OysterQAQ
* @version 1.0
* @date 2019/09/08 22:24
* @description 权限约定
*/
public interface Authable {
String getIssuer();
Map<String, Object> getClaims();
boolean isEnabled();
}
| 114 |
504 | <reponame>steakknife/pcgeos<gh_stars>100-1000
extern void _cdecl MapHeapEnter(MemHandle phyMemInfoBlk);
extern void _cdecl MapHeapLeave(void);
extern Boolean _cdecl MapHeapCreate(char permName[GEODE_NAME_SIZE],
MemHandle *phyMemInfoBlk);
extern void _cdecl MapHeapDestroy(MemHandle phyMemInfoBlk);
extern Boolean _cdecl MapHeapMaybeInHeap(void *blockPtr);
extern void *_cdecl MapHeapMalloc(word blockSize);
extern void _cdecl MapHeapFree(void *blockPtr);
extern void *_cdecl MapHeapRealloc(void *blockPtr, word newSize);
extern ChunkHandle _cdecl LMemLockAllocAndReturnError(MemHandle block,
word chunkSize);
extern ChunkHandle _cdecl LMemLockReAllocAndReturnError(optr chunkOptr,
word chunkSize);
| 268 |
3,705 | <filename>tests/chainer_tests/functions_tests/activation_tests/test_swish.py
import numpy
from chainer import functions
from chainer import testing
def _sigmoid(x):
half = x.dtype.type(0.5)
return numpy.tanh(x * half) * half + half
def _broadcast_to(array, shape):
if hasattr(numpy, 'broadcast_to'):
return numpy.broadcast_to(array, shape)
dummy = numpy.empty(shape, array.dtype)
return numpy.broadcast_arrays(array, dummy)[0]
@testing.parameterize(*testing.product_dict(
[
{'x_shape': (4, 3, 2), 'beta_shape': (3,),
'extended_beta_shape': (1, 3, 1)},
{'x_shape': (4, 3, 2), 'beta_shape': (3, 2),
'extended_beta_shape': (1, 3, 2)},
], [
{'dtype': numpy.float16},
{'dtype': numpy.float32},
{'dtype': numpy.float64},
]
))
@testing.inject_backend_tests(
None,
# CPU tests
[
{},
]
# GPU tests
+ testing.product({
'use_cuda': [True],
'cuda_device': [0, 1],
})
+ [
{'use_chainerx': True, 'chainerx_device': 'native:0'},
{'use_chainerx': True, 'chainerx_device': 'cuda:0'},
{'use_chainerx': True, 'chainerx_device': 'cuda:1'},
]
)
class TestSwish(testing.FunctionTestCase):
def setUp(self):
if self.dtype == numpy.float16:
self.check_forward_options = {'atol': 5e-4, 'rtol': 5e-3}
self.check_backward_options.update({'atol': 5e-4, 'rtol': 5e-3})
self.check_double_backward_options.update(
{'atol': 5e-3, 'rtol': 5e-2})
def generate_inputs(self):
x = numpy.random.uniform(-1, 1, self.x_shape).astype(self.dtype)
beta = numpy.random.uniform(
-1, 1, self.beta_shape).astype(self.dtype)
return x, beta
def forward_expected(self, inputs):
x, beta = inputs
beta = _broadcast_to(beta.reshape(self.extended_beta_shape),
x.shape)
y = x * _sigmoid(beta * x)
return y,
def forward(self, inputs, device):
x, beta = inputs
return functions.swish(x, beta=beta),
testing.run_module(__name__, __file__)
| 1,064 |
498 | package com.bizzan.bc.wallet.component;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bizzan.bc.wallet.entity.Coin;
import com.bizzan.bc.wallet.entity.Deposit;
import com.bizzan.bc.wallet.event.DepositEvent;
import com.bizzan.bc.wallet.service.AccountService;
import com.bizzan.bc.wallet.service.WatcherLogService;
import com.bizzan.bc.wallet.util.HttpClientUtil;
import lombok.Data;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Data
@Component
public class Watcher extends Thread{
@Value("${bizzan.blockApi}")
private String blockApi;
private Logger logger = LoggerFactory.getLogger(Watcher.class);
private boolean stop = false;
//默认同步间隔20秒
private DepositEvent depositEvent;
private Coin coin;
private WatcherLogService watcherLogService;
private int confirmation = 3;
private Long currentBlockHeight = 0L;
private int step = 5;
private Long checkInterval = 2000L;
@Autowired
private AccountService accountService;
public void check(){
try {
Thread.sleep(5000); // 避免连续访问btc.com
Long networkBlockNumber = getNetwortBlockHeight() - confirmation + 1;
Thread.sleep(5000); // 避免连续访问btc.com
if(currentBlockHeight < networkBlockNumber) {
long startBlockNumber = currentBlockHeight + 1;
currentBlockHeight = (networkBlockNumber - currentBlockHeight > step) ? currentBlockHeight + step : networkBlockNumber;
logger.info("replay block from {} to {}", startBlockNumber, networkBlockNumber);
List<Deposit> deposits = this.replayBlock(startBlockNumber, currentBlockHeight);
if(deposits != null) {
deposits.forEach(deposit -> {
depositEvent.onConfirmed(deposit);
});
//记录日志
watcherLogService.update(coin.getName(), currentBlockHeight);
}else {
// 未扫描成功
currentBlockHeight = startBlockNumber - 1;
}
}else {
logger.info("already latest height {},nothing to do!", currentBlockHeight);
}
}
catch (Exception e){
e.printStackTrace();
}
}
private List<Deposit> replayBlock(Long startBlockNumber, Long endBlockNumber) {
List<Deposit> deposits = new ArrayList<Deposit>();
try {
int[] addressIndex = {0};
// 获取高度
JSONObject param = new JSONObject();
param.put("jsonrpc", "2.0");
param.put("id", "0");
param.put("method", "get_transfers");
JSONObject param2 = new JSONObject();
param2.put("in", true);
param2.put("account_index", 0);
param2.put("filter_by_height", true);
param2.put("min_height", startBlockNumber); // 开始高度
param2.put("max_height", endBlockNumber); // 结束高度
Map<String, String> headerParam = new HashMap<String, String>();
headerParam.put("Content-Type", "application/json");
logger.info("获取区块区间交易: 开始区块:{}, 结束区块:{}", startBlockNumber, endBlockNumber);
String result = HttpClientUtil.doHttpPost(this.blockApi, param.toJSONString(), headerParam);
if(result != null) {
JSONObject obj = JSONObject.parseObject(result);
JSONArray incommings = obj.getJSONObject("result").getJSONArray("in");
if(incommings != null) {
logger.info("发现交易,共 {} 条", incommings.size());
for(int i = 0; i < incommings.size(); i++) {
JSONObject incommObj = incommings.getJSONObject(i);
BigDecimal amount = incommObj.getBigDecimal("amount").divide(BigDecimal.valueOf(1000000000000L));
String txId = incommObj.getString("txid");
Long blockHeight = incommObj.getLong("height");
String paymentId = incommObj.getString("payment_id");
// 解析UID
StringBuilder uidS = new StringBuilder();
for(int j = 0; j < 8; j++) {
uidS.append(paymentId.charAt(j*8 + 1));
}
Long uid = Long.parseLong(uidS.toString(), 16) + 345678;
logger.info("发现用户充值记录: 数量:{},用户:{},区块:{},paymentID:{}", amount, uid, blockHeight, paymentId);
Deposit deposit = new Deposit();
deposit.setUserId(uid); //此处无需对memo处理,wallet.jar会处理
deposit.setTxid(txId);
deposit.setBlockHeight(blockHeight);
deposit.setBlockHash("");
deposit.setAmount(amount);
deposit.setAddress(coin.getDepositAddress());
deposit.setTime(new Date());
deposits.add(deposit);
}
}else {
logger.info("没有发现交易!");
}
}else {
logger.info("获取区块区间交易失败,返回空!!!( 开始区块:{}, 结束区块:{})", startBlockNumber, endBlockNumber);
}
}
catch (Exception e){
e.printStackTrace();
return null;
}
return deposits;
}
@Override
public void run() {
stop = false;
long nextCheck = 0;
while(!(Thread.interrupted() || stop)) {
if (nextCheck <= System.currentTimeMillis()) {
try {
nextCheck = System.currentTimeMillis() + checkInterval;
logger.info("check transactions...");
check();
} catch (Exception ex) {
logger.info(ex.getMessage());
}
}
else {
try {
Thread.sleep(Math.max(nextCheck - System.currentTimeMillis(), 60000));
} catch (InterruptedException ex) {
logger.info(ex.getMessage());
}
}
}
}
public Long getNetwortBlockHeight() {
int[] addressIndex = {0};
// 获取高度
JSONObject param = new JSONObject();
param.put("jsonrpc", "2.0");
param.put("id", "0");
param.put("method", "get_height");
Map<String, String> headerParam = new HashMap<String, String>();
headerParam.put("Content-Type", "application/json");
try {
String result = HttpClientUtil.doHttpPost(this.blockApi, param.toJSONString(), headerParam);
if(!StringUtils.isEmpty(result)) {
JSONObject obj = JSONObject.parseObject(result);
logger.info("获取区块高度:{}", obj.getJSONObject("result").getLong("height"));
return obj.getJSONObject("result").getLong("height");
}
} catch (Exception e) {
e.printStackTrace();
}
return 0L;
}
}
| 3,354 |
305 | /*===--------------------------------------------------------------------------
* ATMI (Asynchronous Task and Memory Interface)
*
* This file is distributed under the MIT License. See LICENSE.txt for details.
*===------------------------------------------------------------------------*/
#include "rt.h"
/*
* Initialize/Finalize
*/
atmi_status_t atmi_init() { return core::Runtime::Initialize(); }
atmi_status_t atmi_finalize() { return core::Runtime::Finalize(); }
/*
* Machine Info
*/
atmi_machine_t *atmi_machine_get_info() {
return core::Runtime::GetMachineInfo();
}
/*
* Modules
*/
atmi_status_t atmi_module_register_from_memory_to_place(
void *module_bytes, size_t module_size, atmi_place_t place,
atmi_status_t (*on_deserialized_data)(void *data, size_t size,
void *cb_state),
void *cb_state) {
return core::Runtime::getInstance().RegisterModuleFromMemory(
module_bytes, module_size, place, on_deserialized_data, cb_state);
}
/*
* Data
*/
atmi_status_t atmi_memcpy(hsa_signal_t sig, void *dest, const void *src,
size_t size) {
return core::Runtime::Memcpy(sig, dest, src, size);
}
atmi_status_t atmi_free(void *ptr) { return core::Runtime::Memfree(ptr); }
atmi_status_t atmi_malloc(void **ptr, size_t size, atmi_mem_place_t place) {
return core::Runtime::Malloc(ptr, size, place);
}
| 526 |
776 | /*
* Copyright 2019-present HiveMQ GmbH
*
* 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.hivemq.mqtt.message.reason;
import com.hivemq.extension.sdk.api.annotations.NotNull;
import com.hivemq.extension.sdk.api.annotations.Nullable;
import com.hivemq.extension.sdk.api.packets.auth.AuthReasonCode;
/**
* MQTT Reason Codes that can be used in AUTH packets according to the MQTT 5 specification.
*
* @author <NAME>
*/
public enum Mqtt5AuthReasonCode implements Mqtt5ReasonCode {
SUCCESS(MqttCommonReasonCode.SUCCESS),
CONTINUE_AUTHENTICATION(0x18),
REAUTHENTICATE(0x19);
private final int code;
private final @NotNull AuthReasonCode authReasonCode;
Mqtt5AuthReasonCode(final int code) {
this.code = code;
authReasonCode = AuthReasonCode.valueOf(name());
}
Mqtt5AuthReasonCode(final @NotNull MqttCommonReasonCode reasonCode) {
this(reasonCode.getCode());
}
@Override
public int getCode() {
return code;
}
public @NotNull AuthReasonCode toAuthReasonCode() {
return authReasonCode;
}
private static final @NotNull Mqtt5AuthReasonCode @NotNull [] AUTH_LOOKUP =
new Mqtt5AuthReasonCode[AuthReasonCode.values().length];
static {
for (final Mqtt5AuthReasonCode reasonCode : values()) {
AUTH_LOOKUP[reasonCode.authReasonCode.ordinal()] = reasonCode;
}
}
/**
* Returns the AUTH Reason Code belonging to the given byte code.
*
* @param code the byte code.
* @return the AUTH Reason Code belonging to the given byte code or <code>null</code> if the byte code is not a
* valid AUTH Reason Code.
*/
public static @Nullable Mqtt5AuthReasonCode fromCode(final int code) {
if (code == SUCCESS.code) {
return SUCCESS;
} else if (code == CONTINUE_AUTHENTICATION.code) {
return CONTINUE_AUTHENTICATION;
} else if (code == REAUTHENTICATE.code) {
return REAUTHENTICATE;
}
return null;
}
public static @NotNull Mqtt5AuthReasonCode from(final @NotNull AuthReasonCode reasonCode) {
return AUTH_LOOKUP[reasonCode.ordinal()];
}
@Override
public boolean canBeSentByServer() {
return this != REAUTHENTICATE;
}
@Override
public boolean canBeSentByClient() {
return this != SUCCESS;
}
}
| 1,090 |
47,529 | <filename>src/test/java/io/reactivex/rxjava3/internal/schedulers/IoSchedulerInternalTest.java
/*
* Copyright (c) 2016-present, RxJava 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 io.reactivex.rxjava3.internal.schedulers;
import static org.junit.Assert.*;
import java.util.concurrent.ConcurrentLinkedQueue;
import org.junit.Test;
import io.reactivex.rxjava3.core.RxJavaTest;
import io.reactivex.rxjava3.disposables.CompositeDisposable;
import io.reactivex.rxjava3.internal.schedulers.IoScheduler.*;
import io.reactivex.rxjava3.testsupport.TestHelper;
public class IoSchedulerInternalTest extends RxJavaTest {
@Test
public void expiredQueueEmpty() {
ConcurrentLinkedQueue<ThreadWorker> expire = new ConcurrentLinkedQueue<>();
CompositeDisposable cd = new CompositeDisposable();
CachedWorkerPool.evictExpiredWorkers(expire, cd);
}
@Test
public void expiredWorkerRemoved() {
ConcurrentLinkedQueue<ThreadWorker> expire = new ConcurrentLinkedQueue<>();
CompositeDisposable cd = new CompositeDisposable();
ThreadWorker tw = new ThreadWorker(new RxThreadFactory("IoExpiryTest"));
try {
expire.add(tw);
cd.add(tw);
CachedWorkerPool.evictExpiredWorkers(expire, cd);
assertTrue(tw.isDisposed());
assertTrue(expire.isEmpty());
} finally {
tw.dispose();
}
}
@Test
public void noExpiredWorker() {
ConcurrentLinkedQueue<ThreadWorker> expire = new ConcurrentLinkedQueue<>();
CompositeDisposable cd = new CompositeDisposable();
ThreadWorker tw = new ThreadWorker(new RxThreadFactory("IoExpiryTest"));
tw.setExpirationTime(System.nanoTime() + 10_000_000_000L);
try {
expire.add(tw);
cd.add(tw);
CachedWorkerPool.evictExpiredWorkers(expire, cd);
assertFalse(tw.isDisposed());
assertFalse(expire.isEmpty());
} finally {
tw.dispose();
}
}
@Test
public void expireReuseRace() {
ConcurrentLinkedQueue<ThreadWorker> expire = new ConcurrentLinkedQueue<>();
CompositeDisposable cd = new CompositeDisposable();
ThreadWorker tw = new ThreadWorker(new RxThreadFactory("IoExpiryTest"));
tw.dispose();
for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) {
expire.add(tw);
cd.add(tw);
TestHelper.race(
() -> CachedWorkerPool.evictExpiredWorkers(expire, cd),
() -> expire.remove(tw)
);
}
}
}
| 1,283 |
2,706 | <filename>retro/cores/gba/src/gba/gba.c
/* Copyright (c) 2013-2015 <NAME>
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include <mgba/internal/gba/gba.h>
#include <mgba/internal/arm/isa-inlines.h>
#include <mgba/internal/arm/debugger/debugger.h>
#include <mgba/internal/arm/decoder.h>
#include <mgba/internal/gba/bios.h>
#include <mgba/internal/gba/cheats.h>
#include <mgba/internal/gba/io.h>
#include <mgba/internal/gba/overrides.h>
#include <mgba/internal/gba/rr/rr.h>
#include <mgba-util/patch.h>
#include <mgba-util/crc32.h>
#include <mgba-util/math.h>
#include <mgba-util/memory.h>
#include <mgba-util/vfs.h>
#ifdef USE_ELF
#include <mgba-util/elf-read.h>
#endif
mLOG_DEFINE_CATEGORY(GBA, "GBA", "gba");
mLOG_DEFINE_CATEGORY(GBA_DEBUG, "GBA Debug", "gba.debug");
const uint32_t GBA_COMPONENT_MAGIC = 0x1000000;
static const size_t GBA_ROM_MAGIC_OFFSET = 3;
static const uint8_t GBA_ROM_MAGIC[] = { 0xEA };
static const size_t GBA_ROM_MAGIC_OFFSET2 = 0xB2;
static const uint8_t GBA_ROM_MAGIC2[] = { 0x96 };
static const size_t GBA_MB_MAGIC_OFFSET = 0xC0;
static void GBAInit(void* cpu, struct mCPUComponent* component);
static void GBAInterruptHandlerInit(struct ARMInterruptHandler* irqh);
static void GBAProcessEvents(struct ARMCore* cpu);
static void GBAHitStub(struct ARMCore* cpu, uint32_t opcode);
static void GBAIllegal(struct ARMCore* cpu, uint32_t opcode);
static void GBABreakpoint(struct ARMCore* cpu, int immediate);
static bool _setSoftwareBreakpoint(struct ARMDebugger*, uint32_t address, enum ExecutionMode mode, uint32_t* opcode);
static bool _clearSoftwareBreakpoint(struct ARMDebugger*, uint32_t address, enum ExecutionMode mode, uint32_t opcode);
#ifdef FIXED_ROM_BUFFER
extern uint32_t* romBuffer;
extern size_t romBufferSize;
#endif
void GBACreate(struct GBA* gba) {
gba->d.id = GBA_COMPONENT_MAGIC;
gba->d.init = GBAInit;
gba->d.deinit = 0;
}
static void GBAInit(void* cpu, struct mCPUComponent* component) {
struct GBA* gba = (struct GBA*) component;
gba->cpu = cpu;
gba->debugger = 0;
gba->sync = 0;
GBAInterruptHandlerInit(&gba->cpu->irqh);
GBAMemoryInit(gba);
gba->memory.savedata.timing = &gba->timing;
GBASavedataInit(&gba->memory.savedata, NULL);
gba->video.p = gba;
GBAVideoInit(&gba->video);
gba->audio.p = gba;
GBAAudioInit(&gba->audio, GBA_AUDIO_SAMPLES);
GBAIOInit(gba);
gba->sio.p = gba;
GBASIOInit(&gba->sio);
GBAHardwareInit(&gba->memory.hw, NULL);
gba->springIRQ = 0;
gba->keySource = 0;
gba->rotationSource = 0;
gba->luminanceSource = 0;
gba->rtcSource = 0;
gba->rumble = 0;
gba->rr = 0;
gba->romVf = 0;
gba->biosVf = 0;
gba->stream = NULL;
gba->keyCallback = NULL;
mCoreCallbacksListInit(&gba->coreCallbacks, 0);
gba->biosChecksum = GBAChecksum(gba->memory.bios, SIZE_BIOS);
gba->idleOptimization = IDLE_LOOP_REMOVE;
gba->idleLoop = IDLE_LOOP_NONE;
gba->realisticTiming = true;
gba->hardCrash = true;
gba->allowOpposingDirections = true;
gba->performingDMA = false;
gba->isPristine = false;
gba->pristineRomSize = 0;
gba->yankedRomSize = 0;
mTimingInit(&gba->timing, &gba->cpu->cycles, &gba->cpu->nextEvent);
}
void GBAUnloadROM(struct GBA* gba) {
if (gba->memory.rom && !gba->isPristine) {
if (gba->yankedRomSize) {
gba->yankedRomSize = 0;
}
mappedMemoryFree(gba->memory.rom, SIZE_CART0);
}
if (gba->romVf) {
#ifndef FIXED_ROM_BUFFER
if (gba->isPristine) {
gba->romVf->unmap(gba->romVf, gba->memory.rom, gba->pristineRomSize);
}
#endif
gba->romVf->close(gba->romVf);
gba->romVf = NULL;
}
gba->memory.rom = NULL;
gba->isPristine = false;
GBASavedataDeinit(&gba->memory.savedata);
if (gba->memory.savedata.realVf) {
gba->memory.savedata.realVf->close(gba->memory.savedata.realVf);
gba->memory.savedata.realVf = 0;
}
gba->idleLoop = IDLE_LOOP_NONE;
}
void GBADestroy(struct GBA* gba) {
GBAUnloadROM(gba);
if (gba->biosVf) {
gba->biosVf->unmap(gba->biosVf, gba->memory.bios, SIZE_BIOS);
gba->biosVf->close(gba->biosVf);
gba->biosVf = 0;
}
GBAMemoryDeinit(gba);
GBAVideoDeinit(&gba->video);
GBAAudioDeinit(&gba->audio);
GBASIODeinit(&gba->sio);
gba->rr = 0;
mTimingDeinit(&gba->timing);
mCoreCallbacksListDeinit(&gba->coreCallbacks);
}
void GBAInterruptHandlerInit(struct ARMInterruptHandler* irqh) {
irqh->reset = GBAReset;
irqh->processEvents = GBAProcessEvents;
irqh->swi16 = GBASwi16;
irqh->swi32 = GBASwi32;
irqh->hitIllegal = GBAIllegal;
irqh->readCPSR = GBATestIRQ;
irqh->hitStub = GBAHitStub;
irqh->bkpt16 = GBABreakpoint;
irqh->bkpt32 = GBABreakpoint;
}
void GBAReset(struct ARMCore* cpu) {
ARMSetPrivilegeMode(cpu, MODE_IRQ);
cpu->gprs[ARM_SP] = SP_BASE_IRQ;
ARMSetPrivilegeMode(cpu, MODE_SUPERVISOR);
cpu->gprs[ARM_SP] = SP_BASE_SUPERVISOR;
ARMSetPrivilegeMode(cpu, MODE_SYSTEM);
cpu->gprs[ARM_SP] = SP_BASE_SYSTEM;
struct GBA* gba = (struct GBA*) cpu->master;
if (!gba->rr || (!gba->rr->isPlaying(gba->rr) && !gba->rr->isRecording(gba->rr))) {
GBASavedataUnmask(&gba->memory.savedata);
}
gba->cpuBlocked = false;
gba->earlyExit = false;
if (gba->yankedRomSize) {
gba->memory.romSize = gba->yankedRomSize;
gba->memory.romMask = toPow2(gba->memory.romSize) - 1;
gba->yankedRomSize = 0;
}
mTimingClear(&gba->timing);
GBAMemoryReset(gba);
GBAVideoReset(&gba->video);
GBAAudioReset(&gba->audio);
GBAIOInit(gba);
GBATimerInit(gba);
GBASIOReset(&gba->sio);
gba->lastJump = 0;
gba->haltPending = false;
gba->idleDetectionStep = 0;
gba->idleDetectionFailures = 0;
gba->debug = false;
memset(gba->debugString, 0, sizeof(gba->debugString));
if (gba->pristineRomSize > SIZE_CART0) {
GBAMatrixReset(gba);
}
if (!gba->romVf && gba->memory.rom) {
GBASkipBIOS(gba);
}
}
void GBASkipBIOS(struct GBA* gba) {
struct ARMCore* cpu = gba->cpu;
if (cpu->gprs[ARM_PC] == BASE_RESET + WORD_SIZE_ARM) {
if (gba->memory.rom) {
cpu->gprs[ARM_PC] = BASE_CART0;
} else {
cpu->gprs[ARM_PC] = BASE_WORKING_RAM;
}
gba->memory.io[REG_VCOUNT >> 1] = 0x7E;
gba->memory.io[REG_POSTFLG >> 1] = 1;
int currentCycles = 0;
ARM_WRITE_PC;
}
}
static void GBAProcessEvents(struct ARMCore* cpu) {
struct GBA* gba = (struct GBA*) cpu->master;
gba->bus = cpu->prefetch[1];
if (cpu->executionMode == MODE_THUMB) {
gba->bus |= cpu->prefetch[1] << 16;
}
if (gba->springIRQ && !cpu->cpsr.i) {
ARMRaiseIRQ(cpu);
gba->springIRQ = 0;
}
int32_t nextEvent = cpu->nextEvent;
while (cpu->cycles >= nextEvent) {
cpu->nextEvent = INT_MAX;
nextEvent = 0;
do {
int32_t cycles = cpu->cycles;
cpu->cycles = 0;
#ifndef NDEBUG
if (cycles < 0) {
mLOG(GBA, FATAL, "Negative cycles passed: %i", cycles);
}
#endif
nextEvent = mTimingTick(&gba->timing, nextEvent + cycles);
} while (gba->cpuBlocked);
cpu->nextEvent = nextEvent;
if (gba->earlyExit) {
gba->earlyExit = false;
break;
}
if (cpu->halted) {
cpu->cycles = nextEvent;
if (!gba->memory.io[REG_IME >> 1] || !gba->memory.io[REG_IE >> 1]) {
break;
}
}
#ifndef NDEBUG
else if (nextEvent < 0) {
mLOG(GBA, FATAL, "Negative cycles will pass: %i", nextEvent);
}
#endif
}
#ifndef NDEBUG
if (gba->cpuBlocked) {
mLOG(GBA, FATAL, "CPU is blocked!");
}
#endif
}
#ifdef USE_DEBUGGERS
void GBAAttachDebugger(struct GBA* gba, struct mDebugger* debugger) {
gba->debugger = (struct ARMDebugger*) debugger->platform;
gba->debugger->setSoftwareBreakpoint = _setSoftwareBreakpoint;
gba->debugger->clearSoftwareBreakpoint = _clearSoftwareBreakpoint;
gba->cpu->components[CPU_COMPONENT_DEBUGGER] = &debugger->d;
ARMHotplugAttach(gba->cpu, CPU_COMPONENT_DEBUGGER);
}
void GBADetachDebugger(struct GBA* gba) {
if (gba->debugger) {
ARMHotplugDetach(gba->cpu, CPU_COMPONENT_DEBUGGER);
}
gba->cpu->components[CPU_COMPONENT_DEBUGGER] = NULL;
gba->debugger = NULL;
}
#endif
bool GBALoadNull(struct GBA* gba) {
GBAUnloadROM(gba);
gba->romVf = NULL;
gba->pristineRomSize = 0;
#ifndef FIXED_ROM_BUFFER
gba->memory.rom = anonymousMemoryMap(SIZE_CART0);
#else
gba->memory.rom = romBuffer;
#endif
gba->isPristine = false;
gba->yankedRomSize = 0;
gba->memory.romSize = SIZE_CART0;
gba->memory.romMask = SIZE_CART0 - 1;
gba->memory.mirroring = false;
gba->romCrc32 = 0;
if (gba->cpu) {
gba->cpu->memory.setActiveRegion(gba->cpu, gba->cpu->gprs[ARM_PC]);
}
return true;
}
bool GBALoadMB(struct GBA* gba, struct VFile* vf) {
GBAUnloadROM(gba);
gba->romVf = vf;
gba->pristineRomSize = vf->size(vf);
vf->seek(vf, 0, SEEK_SET);
if (gba->pristineRomSize > SIZE_WORKING_RAM) {
gba->pristineRomSize = SIZE_WORKING_RAM;
}
gba->isPristine = true;
memset(gba->memory.wram, 0, SIZE_WORKING_RAM);
vf->read(vf, gba->memory.wram, gba->pristineRomSize);
if (!gba->memory.wram) {
mLOG(GBA, WARN, "Couldn't map ROM");
return false;
}
gba->yankedRomSize = 0;
gba->memory.romSize = 0;
gba->memory.romMask = 0;
gba->romCrc32 = doCrc32(gba->memory.wram, gba->pristineRomSize);
if (gba->cpu && gba->memory.activeRegion == REGION_WORKING_RAM) {
gba->cpu->memory.setActiveRegion(gba->cpu, gba->cpu->gprs[ARM_PC]);
}
return true;
}
bool GBALoadROM(struct GBA* gba, struct VFile* vf) {
if (!vf) {
return false;
}
GBAUnloadROM(gba);
gba->romVf = vf;
gba->pristineRomSize = vf->size(vf);
vf->seek(vf, 0, SEEK_SET);
if (gba->pristineRomSize > SIZE_CART0) {
gba->isPristine = false;
gba->memory.romSize = 0x01000000;
#ifdef FIXED_ROM_BUFFER
gba->memory.rom = romBuffer;
#else
gba->memory.rom = anonymousMemoryMap(SIZE_CART0);
#endif
} else {
gba->isPristine = true;
#ifdef FIXED_ROM_BUFFER
if (gba->pristineRomSize <= romBufferSize) {
gba->memory.rom = romBuffer;
vf->read(vf, romBuffer, gba->pristineRomSize);
}
#else
gba->memory.rom = vf->map(vf, gba->pristineRomSize, MAP_READ);
#endif
gba->memory.romSize = gba->pristineRomSize;
}
if (!gba->memory.rom) {
mLOG(GBA, WARN, "Couldn't map ROM");
return false;
}
gba->yankedRomSize = 0;
gba->memory.romMask = toPow2(gba->memory.romSize) - 1;
gba->memory.mirroring = false;
gba->romCrc32 = doCrc32(gba->memory.rom, gba->memory.romSize);
GBAHardwareInit(&gba->memory.hw, &((uint16_t*) gba->memory.rom)[GPIO_REG_DATA >> 1]);
GBAVFameDetect(&gba->memory.vfame, gba->memory.rom, gba->memory.romSize);
if (popcount32(gba->memory.romSize) != 1) {
// This ROM is either a bad dump or homebrew. Emulate flash cart behavior.
#ifndef FIXED_ROM_BUFFER
void* newRom = anonymousMemoryMap(SIZE_CART0);
memcpy(newRom, gba->memory.rom, gba->pristineRomSize);
gba->memory.rom = newRom;
#endif
gba->memory.romSize = SIZE_CART0;
gba->isPristine = false;
}
if (gba->cpu && gba->memory.activeRegion >= REGION_CART0) {
gba->cpu->memory.setActiveRegion(gba->cpu, gba->cpu->gprs[ARM_PC]);
}
// TODO: error check
return true;
}
bool GBALoadSave(struct GBA* gba, struct VFile* sav) {
GBASavedataInit(&gba->memory.savedata, sav);
return true;
}
void GBAYankROM(struct GBA* gba) {
gba->yankedRomSize = gba->memory.romSize;
gba->memory.romSize = 0;
gba->memory.romMask = 0;
GBARaiseIRQ(gba, IRQ_GAMEPAK);
}
void GBALoadBIOS(struct GBA* gba, struct VFile* vf) {
gba->biosVf = vf;
uint32_t* bios = vf->map(vf, SIZE_BIOS, MAP_READ);
if (!bios) {
mLOG(GBA, WARN, "Couldn't map BIOS");
return;
}
gba->memory.bios = bios;
gba->memory.fullBios = 1;
uint32_t checksum = GBAChecksum(gba->memory.bios, SIZE_BIOS);
mLOG(GBA, DEBUG, "BIOS Checksum: 0x%X", checksum);
if (checksum == GBA_BIOS_CHECKSUM) {
mLOG(GBA, INFO, "Official GBA BIOS detected");
} else if (checksum == GBA_DS_BIOS_CHECKSUM) {
mLOG(GBA, INFO, "Official GBA (DS) BIOS detected");
} else {
mLOG(GBA, WARN, "BIOS checksum incorrect");
}
gba->biosChecksum = checksum;
if (gba->memory.activeRegion == REGION_BIOS) {
gba->cpu->memory.activeRegion = gba->memory.bios;
}
// TODO: error check
}
void GBAApplyPatch(struct GBA* gba, struct Patch* patch) {
size_t patchedSize = patch->outputSize(patch, gba->memory.romSize);
if (!patchedSize || patchedSize > SIZE_CART0) {
return;
}
void* newRom = anonymousMemoryMap(SIZE_CART0);
if (!patch->applyPatch(patch, gba->memory.rom, gba->pristineRomSize, newRom, patchedSize)) {
mappedMemoryFree(newRom, SIZE_CART0);
return;
}
if (gba->romVf) {
#ifndef FIXED_ROM_BUFFER
gba->romVf->unmap(gba->romVf, gba->memory.rom, gba->pristineRomSize);
#endif
gba->romVf->close(gba->romVf);
gba->romVf = NULL;
}
gba->isPristine = false;
gba->memory.rom = newRom;
gba->memory.hw.gpioBase = &((uint16_t*) gba->memory.rom)[GPIO_REG_DATA >> 1];
gba->memory.romSize = patchedSize;
gba->memory.romMask = SIZE_CART0 - 1;
gba->romCrc32 = doCrc32(gba->memory.rom, gba->memory.romSize);
}
void GBAWriteIE(struct GBA* gba, uint16_t value) {
if (gba->memory.io[REG_IME >> 1] && value & gba->memory.io[REG_IF >> 1]) {
ARMRaiseIRQ(gba->cpu);
}
}
void GBAWriteIME(struct GBA* gba, uint16_t value) {
if (value && gba->memory.io[REG_IE >> 1] & gba->memory.io[REG_IF >> 1]) {
ARMRaiseIRQ(gba->cpu);
}
}
void GBARaiseIRQ(struct GBA* gba, enum GBAIRQ irq) {
gba->memory.io[REG_IF >> 1] |= 1 << irq;
if (gba->memory.io[REG_IE >> 1] & 1 << irq) {
gba->cpu->halted = 0;
if (gba->memory.io[REG_IME >> 1]) {
ARMRaiseIRQ(gba->cpu);
}
}
}
void GBATestIRQ(struct ARMCore* cpu) {
struct GBA* gba = (struct GBA*) cpu->master;
if (gba->memory.io[REG_IME >> 1] && gba->memory.io[REG_IE >> 1] & gba->memory.io[REG_IF >> 1]) {
gba->springIRQ = gba->memory.io[REG_IE >> 1] & gba->memory.io[REG_IF >> 1];
gba->cpu->nextEvent = gba->cpu->cycles;
}
}
void GBAHalt(struct GBA* gba) {
gba->cpu->nextEvent = gba->cpu->cycles;
gba->cpu->halted = 1;
}
void GBAStop(struct GBA* gba) {
size_t c;
for (c = 0; c < mCoreCallbacksListSize(&gba->coreCallbacks); ++c) {
struct mCoreCallbacks* callbacks = mCoreCallbacksListGetPointer(&gba->coreCallbacks, c);
if (callbacks->sleep) {
callbacks->sleep(callbacks->context);
}
}
gba->cpu->nextEvent = gba->cpu->cycles;
}
void GBADebug(struct GBA* gba, uint16_t flags) {
gba->debugFlags = flags;
if (GBADebugFlagsIsSend(gba->debugFlags)) {
int level = 1 << GBADebugFlagsGetLevel(gba->debugFlags);
level &= 0x1F;
char oolBuf[0x101];
strncpy(oolBuf, gba->debugString, sizeof(gba->debugString));
oolBuf[0x100] = '\0';
mLog(_mLOG_CAT_GBA_DEBUG(), level, "%s", oolBuf);
}
gba->debugFlags = GBADebugFlagsClearSend(gba->debugFlags);
}
bool GBAIsROM(struct VFile* vf) {
#ifdef USE_ELF
struct ELF* elf = ELFOpen(vf);
if (elf) {
uint32_t entry = ELFEntry(elf);
bool isGBA = true;
isGBA = isGBA && ELFMachine(elf) == EM_ARM;
isGBA = isGBA && (entry == BASE_CART0 || entry == BASE_WORKING_RAM);
ELFClose(elf);
return isGBA;
}
#endif
if (!vf) {
return false;
}
uint8_t signature[sizeof(GBA_ROM_MAGIC) + sizeof(GBA_ROM_MAGIC2)];
if (vf->seek(vf, GBA_ROM_MAGIC_OFFSET, SEEK_SET) < 0) {
return false;
}
if (vf->read(vf, &signature, sizeof(GBA_ROM_MAGIC)) != sizeof(GBA_ROM_MAGIC)) {
return false;
}
if (memcmp(signature, GBA_ROM_MAGIC, sizeof(GBA_ROM_MAGIC)) != 0) {
return false;
}
if (vf->seek(vf, GBA_ROM_MAGIC_OFFSET2, SEEK_SET) < 0) {
return false;
}
if (vf->read(vf, &signature, sizeof(GBA_ROM_MAGIC2)) != sizeof(GBA_ROM_MAGIC2)) {
return false;
}
if (memcmp(signature, GBA_ROM_MAGIC2, sizeof(GBA_ROM_MAGIC2)) != 0) {
// If the signature byte is missing then we must be using an unfixed ROM
uint32_t buffer[0x9C / sizeof(uint32_t)];
if (vf->seek(vf, 0x4, SEEK_SET) < 0) {
return false;
}
if (vf->read(vf, &buffer, sizeof(buffer)) != sizeof(buffer)) {
return false;
}
uint32_t bits = 0;
size_t i;
for (i = 0; i < sizeof(buffer) / sizeof(*buffer); ++i) {
bits |= buffer[i];
}
if (bits) {
return false;
}
}
if (GBAIsBIOS(vf)) {
return false;
}
return true;
}
bool GBAIsMB(struct VFile* vf) {
if (!GBAIsROM(vf)) {
return false;
}
#ifdef USE_ELF
struct ELF* elf = ELFOpen(vf);
if (elf) {
bool isMB = ELFEntry(elf) == BASE_WORKING_RAM;
ELFClose(elf);
return isMB;
}
#endif
if (vf->size(vf) > SIZE_WORKING_RAM) {
return false;
}
if (vf->seek(vf, GBA_MB_MAGIC_OFFSET, SEEK_SET) < 0) {
return false;
}
uint32_t signature;
if (vf->read(vf, &signature, sizeof(signature)) != sizeof(signature)) {
return false;
}
uint32_t opcode;
LOAD_32(opcode, 0, &signature);
struct ARMInstructionInfo info;
ARMDecodeARM(opcode, &info);
if (info.branchType == ARM_BRANCH) {
if (info.op1.immediate <= 0) {
return false;
} else if (info.op1.immediate == 28) {
// Ancient toolchain that is known to throw MB detection for a loop
return false;
} else if (info.op1.immediate != 24) {
return true;
}
}
uint32_t pc = GBA_MB_MAGIC_OFFSET;
int i;
for (i = 0; i < 80; ++i) {
if (vf->read(vf, &signature, sizeof(signature)) != sizeof(signature)) {
break;
}
pc += 4;
LOAD_32(opcode, 0, &signature);
ARMDecodeARM(opcode, &info);
if (info.mnemonic != ARM_MN_LDR) {
continue;
}
if ((info.operandFormat & ARM_OPERAND_MEMORY) && info.memory.baseReg == ARM_PC && info.memory.format & ARM_MEMORY_IMMEDIATE_OFFSET) {
uint32_t immediate = info.memory.offset.immediate;
if (info.memory.format & ARM_MEMORY_OFFSET_SUBTRACT) {
immediate = -immediate;
}
immediate += pc + 8;
if (vf->seek(vf, immediate, SEEK_SET) < 0) {
break;
}
if (vf->read(vf, &signature, sizeof(signature)) != sizeof(signature)) {
break;
}
LOAD_32(immediate, 0, &signature);
if (vf->seek(vf, pc, SEEK_SET) < 0) {
break;
}
if ((immediate & ~0x7FF) == BASE_WORKING_RAM) {
return true;
}
}
}
// Found a libgba-linked cart...these are a bit harder to detect.
return false;
}
bool GBAIsBIOS(struct VFile* vf) {
if (vf->seek(vf, 0, SEEK_SET) < 0) {
return false;
}
uint8_t interruptTable[7 * 4];
if (vf->read(vf, &interruptTable, sizeof(interruptTable)) != sizeof(interruptTable)) {
return false;
}
int i;
for (i = 0; i < 7; ++i) {
if (interruptTable[4 * i + 3] != 0xEA || interruptTable[4 * i + 2]) {
return false;
}
}
return true;
}
void GBAGetGameCode(const struct GBA* gba, char* out) {
memset(out, 0, 8);
if (!gba->memory.rom) {
return;
}
memcpy(out, "AGB-", 4);
memcpy(&out[4], &((struct GBACartridge*) gba->memory.rom)->id, 4);
}
void GBAGetGameTitle(const struct GBA* gba, char* out) {
if (gba->memory.rom) {
memcpy(out, &((struct GBACartridge*) gba->memory.rom)->title, 12);
return;
}
if (gba->isPristine && gba->memory.wram) {
memcpy(out, &((struct GBACartridge*) gba->memory.wram)->title, 12);
return;
}
strncpy(out, "(BIOS)", 12);
}
void GBAHitStub(struct ARMCore* cpu, uint32_t opcode) {
struct GBA* gba = (struct GBA*) cpu->master;
#ifdef USE_DEBUGGERS
if (gba->debugger) {
struct mDebuggerEntryInfo info = {
.address = _ARMPCAddress(cpu),
.type.bp.opcode = opcode
};
mDebuggerEnter(gba->debugger->d.p, DEBUGGER_ENTER_ILLEGAL_OP, &info);
}
#endif
// TODO: More sensible category?
mLOG(GBA, ERROR, "Stub opcode: %08x", opcode);
}
void GBAIllegal(struct ARMCore* cpu, uint32_t opcode) {
struct GBA* gba = (struct GBA*) cpu->master;
if (!gba->yankedRomSize) {
// TODO: More sensible category?
mLOG(GBA, WARN, "Illegal opcode: %08x", opcode);
}
if (cpu->executionMode == MODE_THUMB && (opcode & 0xFFC0) == 0xE800) {
mLOG(GBA, DEBUG, "Hit Wii U VC opcode: %08x", opcode);
return;
}
#ifdef USE_DEBUGGERS
if (gba->debugger) {
struct mDebuggerEntryInfo info = {
.address = _ARMPCAddress(cpu),
.type.bp.opcode = opcode
};
mDebuggerEnter(gba->debugger->d.p, DEBUGGER_ENTER_ILLEGAL_OP, &info);
} else
#endif
{
ARMRaiseUndefined(cpu);
}
}
void GBABreakpoint(struct ARMCore* cpu, int immediate) {
struct GBA* gba = (struct GBA*) cpu->master;
if (immediate >= CPU_COMPONENT_MAX) {
return;
}
switch (immediate) {
#ifdef USE_DEBUGGERS
case CPU_COMPONENT_DEBUGGER:
if (gba->debugger) {
struct mDebuggerEntryInfo info = {
.address = _ARMPCAddress(cpu),
.type.bp.breakType = BREAKPOINT_SOFTWARE
};
mDebuggerEnter(gba->debugger->d.p, DEBUGGER_ENTER_BREAKPOINT, &info);
}
break;
#endif
case CPU_COMPONENT_CHEAT_DEVICE:
if (gba->cpu->components[CPU_COMPONENT_CHEAT_DEVICE]) {
struct mCheatDevice* device = (struct mCheatDevice*) gba->cpu->components[CPU_COMPONENT_CHEAT_DEVICE];
struct GBACheatHook* hook = 0;
size_t i;
for (i = 0; i < mCheatSetsSize(&device->cheats); ++i) {
struct GBACheatSet* cheats = (struct GBACheatSet*) *mCheatSetsGetPointer(&device->cheats, i);
if (cheats->hook && cheats->hook->address == _ARMPCAddress(cpu)) {
mCheatRefresh(device, &cheats->d);
hook = cheats->hook;
}
}
if (hook) {
ARMRunFake(cpu, hook->patchedOpcode);
}
}
break;
default:
break;
}
}
void GBAFrameStarted(struct GBA* gba) {
GBATestKeypadIRQ(gba);
size_t c;
for (c = 0; c < mCoreCallbacksListSize(&gba->coreCallbacks); ++c) {
struct mCoreCallbacks* callbacks = mCoreCallbacksListGetPointer(&gba->coreCallbacks, c);
if (callbacks->videoFrameStarted) {
callbacks->videoFrameStarted(callbacks->context);
}
}
}
void GBAFrameEnded(struct GBA* gba) {
GBASavedataClean(&gba->memory.savedata, gba->video.frameCounter);
if (gba->rr) {
gba->rr->nextFrame(gba->rr);
}
if (gba->cpu->components && gba->cpu->components[CPU_COMPONENT_CHEAT_DEVICE]) {
struct mCheatDevice* device = (struct mCheatDevice*) gba->cpu->components[CPU_COMPONENT_CHEAT_DEVICE];
size_t i;
for (i = 0; i < mCheatSetsSize(&device->cheats); ++i) {
struct GBACheatSet* cheats = (struct GBACheatSet*) *mCheatSetsGetPointer(&device->cheats, i);
mCheatRefresh(device, &cheats->d);
}
}
if (gba->stream && gba->stream->postVideoFrame) {
const color_t* pixels;
size_t stride;
gba->video.renderer->getPixels(gba->video.renderer, &stride, (const void**) &pixels);
gba->stream->postVideoFrame(gba->stream, pixels, stride);
}
if (gba->memory.hw.devices & (HW_GB_PLAYER | HW_GB_PLAYER_DETECTION)) {
GBAHardwarePlayerUpdate(gba);
}
size_t c;
for (c = 0; c < mCoreCallbacksListSize(&gba->coreCallbacks); ++c) {
struct mCoreCallbacks* callbacks = mCoreCallbacksListGetPointer(&gba->coreCallbacks, c);
if (callbacks->videoFrameEnded) {
callbacks->videoFrameEnded(callbacks->context);
}
}
}
void GBATestKeypadIRQ(struct GBA* gba) {
uint16_t keycnt = gba->memory.io[REG_KEYCNT >> 1];
if (!(keycnt & 0x4000)) {
return;
}
int isAnd = keycnt & 0x8000;
if (!gba->keySource) {
// TODO?
return;
}
keycnt &= 0x3FF;
uint16_t keyInput = *gba->keySource & keycnt;
if (isAnd && keycnt == keyInput) {
GBARaiseIRQ(gba, IRQ_KEYPAD);
} else if (!isAnd && keyInput) {
GBARaiseIRQ(gba, IRQ_KEYPAD);
}
}
void GBASetBreakpoint(struct GBA* gba, struct mCPUComponent* component, uint32_t address, enum ExecutionMode mode, uint32_t* opcode) {
size_t immediate;
for (immediate = 0; immediate < gba->cpu->numComponents; ++immediate) {
if (gba->cpu->components[immediate] == component) {
break;
}
}
if (immediate == gba->cpu->numComponents) {
return;
}
if (mode == MODE_ARM) {
int32_t value;
int32_t old;
value = 0xE1200070;
value |= immediate & 0xF;
value |= (immediate & 0xFFF0) << 4;
GBAPatch32(gba->cpu, address, value, &old);
*opcode = old;
} else {
int16_t value;
int16_t old;
value = 0xBE00;
value |= immediate & 0xFF;
GBAPatch16(gba->cpu, address, value, &old);
*opcode = (uint16_t) old;
}
}
void GBAClearBreakpoint(struct GBA* gba, uint32_t address, enum ExecutionMode mode, uint32_t opcode) {
if (mode == MODE_ARM) {
GBAPatch32(gba->cpu, address, opcode, 0);
} else {
GBAPatch16(gba->cpu, address, opcode, 0);
}
}
static bool _setSoftwareBreakpoint(struct ARMDebugger* debugger, uint32_t address, enum ExecutionMode mode, uint32_t* opcode) {
GBASetBreakpoint((struct GBA*) debugger->cpu->master, &debugger->d.p->d, address, mode, opcode);
return true;
}
static bool _clearSoftwareBreakpoint(struct ARMDebugger* debugger, uint32_t address, enum ExecutionMode mode, uint32_t opcode) {
GBAClearBreakpoint((struct GBA*) debugger->cpu->master, address, mode, opcode);
return true;
}
| 10,908 |
528 | <reponame>anukaal/opytimizer
from opytimizer.spaces.search import SearchSpace
# Define the number of agents and decision variables
n_agents = 2
n_variables = 5
# Also defines the corresponding lower and upper bounds
# Note that they have to be the same size as `n_variables`
lower_bound = [0.1, 0.3, 0.5, 0.7, 0.9]
upper_bound = [0.2, 0.4, 0.6, 0.8, 1.0]
# Creates the SearchSpace
s = SearchSpace(n_agents=n_agents, n_variables=n_variables,
lower_bound=lower_bound, upper_bound=upper_bound)
# Prints out some properties
print(s.n_agents, s.n_variables)
print(s.agents, s.best_agent)
print(s.best_agent.position)
| 245 |
407 | <filename>paas/appmanager/tesla-appmanager-server/src/main/java/com/alibaba/tesla/appmanager/server/job/CleanAppPackageJob.java<gh_stars>100-1000
package com.alibaba.tesla.appmanager.server.job;
import com.alibaba.tesla.appmanager.autoconfig.PackageProperties;
import com.alibaba.tesla.appmanager.common.pagination.Pagination;
import com.alibaba.tesla.appmanager.server.repository.condition.AppPackageQueryCondition;
import com.alibaba.tesla.appmanager.server.repository.domain.AppPackageDO;
import com.alibaba.tesla.appmanager.server.service.apppackage.AppPackageService;
import com.alibaba.tesla.appmanager.server.storage.Storage;
import lombok.extern.slf4j.Slf4j;
import net.javacrumbs.shedlock.spring.annotation.SchedulerLock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
/**
* 清理 DB 和 MinIO 中的历史应用包/组件包,并清理远端存储里的无用数据
*
* @author <EMAIL>
*/
@Component
@Slf4j
public class CleanAppPackageJob {
@Autowired
private AppPackageService appPackageService;
@Autowired
private PackageProperties packageProperties;
@Autowired
private Storage storage;
@Scheduled(cron = "${appmanager.cron-job.clean-app-package:-}")
@SchedulerLock(name = "cleanAppPackage")
public void execute() {
Integer defaultKeepNumbers = packageProperties.getDefaultKeepNumbers();
}
/**
* 清理当前存储中,没有在当前 DB 中存有记录的 AppPackage / ComponentPackage 包
*/
private void cleanUselessStoragePackages() {
String bucketName = packageProperties.getBucketName();
Pagination<AppPackageDO> appPackages = appPackageService.list(AppPackageQueryCondition.builder().build());
for (AppPackageDO appPackageDO : appPackages.getItems()) {
String packagePath = appPackageDO.getPackagePath();
}
}
}
| 735 |
2,344 | #!/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.
import warnings
from contextlib import ExitStack
from itertools import product
from random import random
from unittest import mock
import torch
from botorch import settings
from botorch.acquisition.analytic import PosteriorMean
from botorch.acquisition.fixed_feature import FixedFeatureAcquisitionFunction
from botorch.acquisition.knowledge_gradient import qKnowledgeGradient
from botorch.acquisition.monte_carlo import (
qExpectedImprovement,
qNoisyExpectedImprovement,
)
from botorch.acquisition.multi_objective.monte_carlo import (
qNoisyExpectedHypervolumeImprovement,
)
from botorch.exceptions import BadInitialCandidatesWarning, SamplingWarning
from botorch.exceptions.errors import BotorchTensorDimensionError
from botorch.exceptions.warnings import BotorchWarning
from botorch.models import SingleTaskGP
from botorch.optim import initialize_q_batch, initialize_q_batch_nonneg
from botorch.optim.initializers import (
gen_batch_initial_conditions,
gen_one_shot_kg_initial_conditions,
gen_value_function_initial_conditions,
sample_perturbed_subset_dims,
sample_points_around_best,
sample_truncated_normal_perturbations,
)
from botorch.sampling import IIDNormalSampler
from botorch.utils.sampling import draw_sobol_samples
from botorch.utils.testing import (
BotorchTestCase,
MockAcquisitionFunction,
MockModel,
MockPosterior,
)
class TestInitializeQBatch(BotorchTestCase):
def test_initialize_q_batch_nonneg(self):
for dtype in (torch.float, torch.double):
# basic test
X = torch.rand(5, 3, 4, device=self.device, dtype=dtype)
Y = torch.rand(5, device=self.device, dtype=dtype)
ics = initialize_q_batch_nonneg(X=X, Y=Y, n=2)
self.assertEqual(ics.shape, torch.Size([2, 3, 4]))
self.assertEqual(ics.device, X.device)
self.assertEqual(ics.dtype, X.dtype)
# ensure nothing happens if we want all samples
ics = initialize_q_batch_nonneg(X=X, Y=Y, n=5)
self.assertTrue(torch.equal(X, ics))
# make sure things work with constant inputs
Y = torch.ones(5, device=self.device, dtype=dtype)
ics = initialize_q_batch_nonneg(X=X, Y=Y, n=2)
self.assertEqual(ics.shape, torch.Size([2, 3, 4]))
self.assertEqual(ics.device, X.device)
self.assertEqual(ics.dtype, X.dtype)
# ensure raises correct warning
Y = torch.zeros(5, device=self.device, dtype=dtype)
with warnings.catch_warnings(record=True) as w, settings.debug(True):
ics = initialize_q_batch_nonneg(X=X, Y=Y, n=2)
self.assertEqual(len(w), 1)
self.assertTrue(issubclass(w[-1].category, BadInitialCandidatesWarning))
self.assertEqual(ics.shape, torch.Size([2, 3, 4]))
with self.assertRaises(RuntimeError):
initialize_q_batch_nonneg(X=X, Y=Y, n=10)
# test less than `n` positive acquisition values
Y = torch.arange(5, device=self.device, dtype=dtype) - 3
ics = initialize_q_batch_nonneg(X=X, Y=Y, n=2)
self.assertEqual(ics.shape, torch.Size([2, 3, 4]))
self.assertEqual(ics.device, X.device)
self.assertEqual(ics.dtype, X.dtype)
# check that we chose the point with the positive acquisition value
self.assertTrue(torch.equal(ics[0], X[-1]) or torch.equal(ics[1], X[-1]))
# test less than `n` alpha_pos values
Y = torch.arange(5, device=self.device, dtype=dtype)
ics = initialize_q_batch_nonneg(X=X, Y=Y, n=2, alpha=1.0)
self.assertEqual(ics.shape, torch.Size([2, 3, 4]))
self.assertEqual(ics.device, X.device)
self.assertEqual(ics.dtype, X.dtype)
def test_initialize_q_batch(self):
for dtype in (torch.float, torch.double):
for batch_shape in (torch.Size(), [3, 2], (2,), torch.Size([2, 3, 4]), []):
# basic test
X = torch.rand(5, *batch_shape, 3, 4, device=self.device, dtype=dtype)
Y = torch.rand(5, *batch_shape, device=self.device, dtype=dtype)
ics = initialize_q_batch(X=X, Y=Y, n=2)
self.assertEqual(ics.shape, torch.Size([2, *batch_shape, 3, 4]))
self.assertEqual(ics.device, X.device)
self.assertEqual(ics.dtype, X.dtype)
# ensure nothing happens if we want all samples
ics = initialize_q_batch(X=X, Y=Y, n=5)
self.assertTrue(torch.equal(X, ics))
# ensure raises correct warning
Y = torch.zeros(5, device=self.device, dtype=dtype)
with warnings.catch_warnings(record=True) as w, settings.debug(True):
ics = initialize_q_batch(X=X, Y=Y, n=2)
self.assertEqual(len(w), 1)
self.assertTrue(
issubclass(w[-1].category, BadInitialCandidatesWarning)
)
self.assertEqual(ics.shape, torch.Size([2, *batch_shape, 3, 4]))
with self.assertRaises(RuntimeError):
initialize_q_batch(X=X, Y=Y, n=10)
def test_initialize_q_batch_largeZ(self):
for dtype in (torch.float, torch.double):
# testing large eta*Z
X = torch.rand(5, 3, 4, device=self.device, dtype=dtype)
Y = torch.tensor([-1e12, 0, 0, 0, 1e12], device=self.device, dtype=dtype)
ics = initialize_q_batch(X=X, Y=Y, n=2, eta=100)
self.assertEqual(ics.shape[0], 2)
class TestGenBatchInitialCandidates(BotorchTestCase):
def test_gen_batch_initial_conditions(self):
bounds = torch.stack([torch.zeros(2), torch.ones(2)])
mock_acqf = MockAcquisitionFunction()
mock_acqf.objective = lambda y: y.squeeze(-1)
for dtype in (torch.float, torch.double):
bounds = bounds.to(device=self.device, dtype=dtype)
mock_acqf.X_baseline = bounds # for testing sample_around_best
mock_acqf.model = MockModel(MockPosterior(mean=bounds[:, :1]))
for nonnegative, seed, init_batch_limit, ffs, sample_around_best in product(
[True, False], [None, 1234], [None, 1], [None, {0: 0.5}], [True, False]
):
with mock.patch.object(
MockAcquisitionFunction,
"__call__",
wraps=mock_acqf.__call__,
) as mock_acqf_call:
batch_initial_conditions = gen_batch_initial_conditions(
acq_function=mock_acqf,
bounds=bounds,
q=1,
num_restarts=2,
raw_samples=10,
fixed_features=ffs,
options={
"nonnegative": nonnegative,
"eta": 0.01,
"alpha": 0.1,
"seed": seed,
"init_batch_limit": init_batch_limit,
"sample_around_best": sample_around_best,
},
)
expected_shape = torch.Size([2, 1, 2])
self.assertEqual(batch_initial_conditions.shape, expected_shape)
self.assertEqual(batch_initial_conditions.device, bounds.device)
self.assertEqual(batch_initial_conditions.dtype, bounds.dtype)
batch_shape = (
torch.Size([])
if init_batch_limit is None
else torch.Size([init_batch_limit])
)
raw_samps = mock_acqf_call.call_args[0][0]
batch_shape = (
torch.Size([20 if sample_around_best else 10])
if init_batch_limit is None
else torch.Size([init_batch_limit])
)
expected_raw_samps_shape = batch_shape + torch.Size([1, 2])
self.assertEqual(raw_samps.shape, expected_raw_samps_shape)
if ffs is not None:
for idx, val in ffs.items():
self.assertTrue(
torch.all(batch_initial_conditions[..., idx] == val)
)
def test_gen_batch_initial_conditions_highdim(self):
d = 2200 # 2200 * 10 (q) > 21201 (sobol max dim)
bounds = torch.stack([torch.zeros(d), torch.ones(d)])
ffs_map = {i: random() for i in range(0, d, 2)}
mock_acqf = MockAcquisitionFunction()
mock_acqf.objective = lambda y: y.squeeze(-1)
for dtype in (torch.float, torch.double):
bounds = bounds.to(device=self.device, dtype=dtype)
mock_acqf.X_baseline = bounds # for testing sample_around_best
mock_acqf.model = MockModel(MockPosterior(mean=bounds[:, :1]))
for nonnegative, seed, ffs, sample_around_best in product(
[True, False], [None, 1234], [None, ffs_map], [True, False]
):
with warnings.catch_warnings(record=True) as ws, settings.debug(True):
batch_initial_conditions = gen_batch_initial_conditions(
acq_function=MockAcquisitionFunction(),
bounds=bounds,
q=10,
num_restarts=1,
raw_samples=2,
fixed_features=ffs,
options={
"nonnegative": nonnegative,
"eta": 0.01,
"alpha": 0.1,
"seed": seed,
"sample_around_best": sample_around_best,
},
)
self.assertTrue(
any(issubclass(w.category, SamplingWarning) for w in ws)
)
expected_shape = torch.Size([1, 10, d])
self.assertEqual(batch_initial_conditions.shape, expected_shape)
self.assertEqual(batch_initial_conditions.device, bounds.device)
self.assertEqual(batch_initial_conditions.dtype, bounds.dtype)
if ffs is not None:
for idx, val in ffs.items():
self.assertTrue(
torch.all(batch_initial_conditions[..., idx] == val)
)
def test_gen_batch_initial_conditions_warning(self):
for dtype in (torch.float, torch.double):
bounds = torch.tensor([[0, 0], [1, 1]], device=self.device, dtype=dtype)
samples = torch.zeros(10, 1, 2, device=self.device, dtype=dtype)
with ExitStack() as es:
ws = es.enter_context(warnings.catch_warnings(record=True))
es.enter_context(settings.debug(True))
es.enter_context(
mock.patch(
"botorch.optim.initializers.draw_sobol_samples",
return_value=samples,
)
)
batch_initial_conditions = gen_batch_initial_conditions(
acq_function=MockAcquisitionFunction(),
bounds=bounds,
q=1,
num_restarts=2,
raw_samples=10,
options={"seed": 1234},
)
self.assertEqual(len(ws), 1)
self.assertTrue(
any(issubclass(w.category, BadInitialCandidatesWarning) for w in ws)
)
self.assertTrue(
torch.equal(
batch_initial_conditions,
torch.zeros(2, 1, 2, device=self.device, dtype=dtype),
)
)
def test_gen_batch_initial_conditions_constraints(self):
for dtype in (torch.float, torch.double):
bounds = torch.tensor([[0, 0], [1, 1]], device=self.device, dtype=dtype)
inequality_constraints = [
(
torch.tensor([1], device=self.device, dtype=dtype),
torch.tensor([-4], device=self.device, dtype=dtype),
torch.tensor(-3, device=self.device, dtype=dtype),
)
]
equality_constraints = [
(
torch.tensor([0], device=self.device, dtype=dtype),
torch.tensor([1], device=self.device, dtype=dtype),
torch.tensor(0.5, device=self.device, dtype=dtype),
)
]
for nonnegative, seed, init_batch_limit, ffs in product(
[True, False], [None, 1234], [None, 1], [None, {0: 0.5}]
):
mock_acqf = MockAcquisitionFunction()
with mock.patch.object(
MockAcquisitionFunction,
"__call__",
wraps=mock_acqf.__call__,
) as mock_acqf_call:
batch_initial_conditions = gen_batch_initial_conditions(
acq_function=mock_acqf,
bounds=bounds,
q=1,
num_restarts=2,
raw_samples=10,
options={
"nonnegative": nonnegative,
"eta": 0.01,
"alpha": 0.1,
"seed": seed,
"init_batch_limit": init_batch_limit,
"thinning": 2,
"n_burnin": 3,
},
inequality_constraints=inequality_constraints,
equality_constraints=equality_constraints,
)
expected_shape = torch.Size([2, 1, 2])
self.assertEqual(batch_initial_conditions.shape, expected_shape)
self.assertEqual(batch_initial_conditions.device, bounds.device)
self.assertEqual(batch_initial_conditions.dtype, bounds.dtype)
batch_shape = (
torch.Size([])
if init_batch_limit is None
else torch.Size([init_batch_limit])
)
raw_samps = mock_acqf_call.call_args[0][0]
batch_shape = (
torch.Size([10])
if init_batch_limit is None
else torch.Size([init_batch_limit])
)
expected_raw_samps_shape = batch_shape + torch.Size([1, 2])
self.assertEqual(raw_samps.shape, expected_raw_samps_shape)
self.assertTrue((raw_samps[..., 0] == 0.5).all())
self.assertTrue((-4 * raw_samps[..., 1] >= -3).all())
if ffs is not None:
for idx, val in ffs.items():
self.assertTrue(
torch.all(batch_initial_conditions[..., idx] == val)
)
class TestGenOneShotKGInitialConditions(BotorchTestCase):
def test_gen_one_shot_kg_initial_conditions(self):
num_fantasies = 8
num_restarts = 4
raw_samples = 16
for dtype in (torch.float, torch.double):
mean = torch.zeros(1, 1, device=self.device, dtype=dtype)
mm = MockModel(MockPosterior(mean=mean))
mock_kg = qKnowledgeGradient(model=mm, num_fantasies=num_fantasies)
bounds = torch.tensor([[0, 0], [1, 1]], device=self.device, dtype=dtype)
# test option error
with self.assertRaises(ValueError):
gen_one_shot_kg_initial_conditions(
acq_function=mock_kg,
bounds=bounds,
q=1,
num_restarts=num_restarts,
raw_samples=raw_samples,
options={"frac_random": 2.0},
)
# test generation logic
q = 2
mock_random_ics = torch.rand(num_restarts, q + num_fantasies, 2)
mock_fantasy_cands = torch.ones(20, 1, 2)
mock_fantasy_vals = torch.randn(20)
with ExitStack() as es:
mock_gbics = es.enter_context(
mock.patch(
"botorch.optim.initializers.gen_batch_initial_conditions",
return_value=mock_random_ics,
)
)
mock_optacqf = es.enter_context(
mock.patch(
"botorch.optim.optimize.optimize_acqf",
return_value=(mock_fantasy_cands, mock_fantasy_vals),
)
)
ics = gen_one_shot_kg_initial_conditions(
acq_function=mock_kg,
bounds=bounds,
q=q,
num_restarts=num_restarts,
raw_samples=raw_samples,
)
mock_gbics.assert_called_once()
mock_optacqf.assert_called_once()
n_value = int((1 - 0.1) * num_fantasies)
self.assertTrue(
torch.equal(
ics[..., :-n_value, :], mock_random_ics[..., :-n_value, :]
)
)
self.assertTrue(torch.all(ics[..., -n_value:, :] == 1))
class TestGenValueFunctionInitialConditions(BotorchTestCase):
def test_gen_value_function_initial_conditions(self):
num_fantasies = 2
num_solutions = 3
num_restarts = 4
raw_samples = 5
n_train = 6
dim = 2
dtype = torch.float
# run a thorough test with dtype float
train_X = torch.rand(n_train, dim, device=self.device, dtype=dtype)
train_Y = torch.rand(n_train, 1, device=self.device, dtype=dtype)
model = SingleTaskGP(train_X, train_Y)
fant_X = torch.rand(num_solutions, 1, dim, device=self.device, dtype=dtype)
fantasy_model = model.fantasize(fant_X, IIDNormalSampler(num_fantasies))
bounds = torch.tensor([[0, 0], [1, 1]], device=self.device, dtype=dtype)
value_function = PosteriorMean(fantasy_model)
# test option error
with self.assertRaises(ValueError):
gen_value_function_initial_conditions(
acq_function=value_function,
bounds=bounds,
num_restarts=num_restarts,
raw_samples=raw_samples,
current_model=model,
options={"frac_random": 2.0},
)
# test output shape
ics = gen_value_function_initial_conditions(
acq_function=value_function,
bounds=bounds,
num_restarts=num_restarts,
raw_samples=raw_samples,
current_model=model,
)
self.assertEqual(
ics.shape, torch.Size([num_restarts, num_fantasies, num_solutions, 1, dim])
)
# test bounds
self.assertTrue(torch.all(ics >= bounds[0]))
self.assertTrue(torch.all(ics <= bounds[1]))
# test dtype
self.assertEqual(dtype, ics.dtype)
# minimal test cases for when all raw samples are random, with dtype double
dtype = torch.double
n_train = 2
dim = 1
num_solutions = 1
train_X = torch.rand(n_train, dim, device=self.device, dtype=dtype)
train_Y = torch.rand(n_train, 1, device=self.device, dtype=dtype)
model = SingleTaskGP(train_X, train_Y)
fant_X = torch.rand(1, 1, dim, device=self.device, dtype=dtype)
fantasy_model = model.fantasize(fant_X, IIDNormalSampler(num_fantasies))
bounds = torch.tensor([[0], [1]], device=self.device, dtype=dtype)
value_function = PosteriorMean(fantasy_model)
ics = gen_value_function_initial_conditions(
acq_function=value_function,
bounds=bounds,
num_restarts=1,
raw_samples=1,
current_model=model,
options={"frac_random": 0.99},
)
self.assertEqual(
ics.shape, torch.Size([1, num_fantasies, num_solutions, 1, dim])
)
# test bounds
self.assertTrue(torch.all(ics >= bounds[0]))
self.assertTrue(torch.all(ics <= bounds[1]))
# test dtype
self.assertEqual(dtype, ics.dtype)
class TestSampleAroundBest(BotorchTestCase):
def test_sample_truncated_normal_perturbations(self):
tkwargs = {"device": self.device}
n_discrete_points = 5
_bounds = torch.ones(2, 4)
_bounds[1] = 2
for dtype in (torch.float, torch.double):
tkwargs["dtype"] = dtype
bounds = _bounds.to(**tkwargs)
for n_best in (1, 2):
X = 1 + torch.rand(n_best, 4, **tkwargs)
# basic test
perturbed_X = sample_truncated_normal_perturbations(
X=X,
n_discrete_points=n_discrete_points,
sigma=4,
bounds=bounds,
qmc=False,
)
self.assertEqual(perturbed_X.shape, torch.Size([n_discrete_points, 4]))
self.assertTrue((perturbed_X >= 1).all())
self.assertTrue((perturbed_X <= 2).all())
# test qmc
with mock.patch(
"botorch.optim.initializers.draw_sobol_samples",
wraps=draw_sobol_samples,
) as mock_sobol:
perturbed_X = sample_truncated_normal_perturbations(
X=X,
n_discrete_points=n_discrete_points,
sigma=4,
bounds=bounds,
qmc=True,
)
mock_sobol.assert_called_once()
self.assertEqual(perturbed_X.shape, torch.Size([n_discrete_points, 4]))
self.assertTrue((perturbed_X >= 1).all())
self.assertTrue((perturbed_X <= 2).all())
def test_sample_perturbed_subset_dims(self):
tkwargs = {"device": self.device}
n_discrete_points = 5
# test that errors are raised
with self.assertRaises(BotorchTensorDimensionError):
sample_perturbed_subset_dims(
X=torch.zeros(1, 1),
n_discrete_points=1,
sigma=1e-3,
bounds=torch.zeros(1, 2, 1),
)
with self.assertRaises(BotorchTensorDimensionError):
sample_perturbed_subset_dims(
X=torch.zeros(1, 1, 1),
n_discrete_points=1,
sigma=1e-3,
bounds=torch.zeros(2, 1),
)
for dtype in (torch.float, torch.double):
for n_best in (1, 2):
tkwargs["dtype"] = dtype
bounds = torch.zeros(2, 21, **tkwargs)
bounds[1] = 1
X = torch.rand(n_best, 21, **tkwargs)
# basic test
with mock.patch(
"botorch.optim.initializers.draw_sobol_samples",
) as mock_sobol:
perturbed_X = sample_perturbed_subset_dims(
X=X,
n_discrete_points=n_discrete_points,
qmc=False,
sigma=1e-3,
bounds=bounds,
)
mock_sobol.assert_not_called()
self.assertEqual(perturbed_X.shape, torch.Size([n_discrete_points, 21]))
self.assertTrue((perturbed_X >= 0).all())
self.assertTrue((perturbed_X <= 1).all())
# test qmc
with mock.patch(
"botorch.optim.initializers.draw_sobol_samples",
wraps=draw_sobol_samples,
) as mock_sobol:
perturbed_X = sample_perturbed_subset_dims(
X=X,
n_discrete_points=n_discrete_points,
sigma=1e-3,
bounds=bounds,
)
mock_sobol.assert_called_once()
self.assertEqual(perturbed_X.shape, torch.Size([n_discrete_points, 21]))
self.assertTrue((perturbed_X >= 0).all())
self.assertTrue((perturbed_X <= 1).all())
# for each point in perturbed_X compute the number of
# dimensions it has in common with each point in X
# and take the maximum number
max_equal_dims = (
(perturbed_X.unsqueeze(0) == X.unsqueeze(1))
.sum(dim=-1)
.max(dim=0)
.values
)
# check that at least one dimension is perturbed
self.assertTrue((20 - max_equal_dims >= 1).all())
def test_sample_points_around_best(self):
tkwargs = {"device": self.device}
_bounds = torch.ones(2, 2)
_bounds[1] = 2
for dtype in (torch.float, torch.double):
tkwargs["dtype"] = dtype
bounds = _bounds.to(**tkwargs)
X_train = 1 + torch.rand(20, 2, **tkwargs)
model = MockModel(
MockPosterior(mean=(2 * X_train + 1).sum(dim=-1, keepdim=True))
)
# test NEI with X_baseline
acqf = qNoisyExpectedImprovement(model, X_baseline=X_train)
with mock.patch(
"botorch.optim.initializers.sample_perturbed_subset_dims"
) as mock_subset_dims:
X_rnd = sample_points_around_best(
acq_function=acqf,
n_discrete_points=4,
sigma=1e-3,
bounds=bounds,
)
mock_subset_dims.assert_not_called()
self.assertTrue(X_rnd.shape, torch.Size([4, 2]))
self.assertTrue((X_rnd >= 1).all())
self.assertTrue((X_rnd <= 2).all())
# test model that returns a batched mean
model = MockModel(
MockPosterior(
mean=(2 * X_train + 1).sum(dim=-1, keepdim=True).unsqueeze(0)
)
)
acqf = qNoisyExpectedImprovement(model, X_baseline=X_train)
X_rnd = sample_points_around_best(
acq_function=acqf,
n_discrete_points=4,
sigma=1e-3,
bounds=bounds,
)
self.assertTrue(X_rnd.shape, torch.Size([4, 2]))
self.assertTrue((X_rnd >= 1).all())
self.assertTrue((X_rnd <= 2).all())
# test EI without X_baseline
acqf = qExpectedImprovement(model, best_f=0.0)
with warnings.catch_warnings(record=True) as w, settings.debug(True):
X_rnd = sample_points_around_best(
acq_function=acqf,
n_discrete_points=4,
sigma=1e-3,
bounds=bounds,
)
self.assertEqual(len(w), 1)
self.assertTrue(issubclass(w[-1].category, BotorchWarning))
self.assertIsNone(X_rnd)
# set train inputs
model.train_inputs = (X_train,)
X_rnd = sample_points_around_best(
acq_function=acqf,
n_discrete_points=4,
sigma=1e-3,
bounds=bounds,
)
self.assertTrue(X_rnd.shape, torch.Size([4, 2]))
self.assertTrue((X_rnd >= 1).all())
self.assertTrue((X_rnd <= 2).all())
# test an acquisition function that has objective=None
# and maximize=False
pm = PosteriorMean(model, maximize=False)
self.assertIsNone(pm.objective)
self.assertFalse(pm.maximize)
X_rnd = sample_points_around_best(
acq_function=pm,
n_discrete_points=4,
sigma=0,
bounds=bounds,
best_pct=1e-8, # ensures that we only use best value
)
idx = (-model.posterior(X_train).mean).argmax()
self.assertTrue((X_rnd == X_train[idx : idx + 1]).all(dim=-1).all())
# test acquisition function that has no model
ff = FixedFeatureAcquisitionFunction(pm, d=2, columns=[0], values=[0])
# set X_baseline for testing purposes
ff.X_baseline = X_train
with warnings.catch_warnings(record=True) as w, settings.debug(True):
X_rnd = sample_points_around_best(
acq_function=ff,
n_discrete_points=4,
sigma=1e-3,
bounds=bounds,
)
self.assertEqual(len(w), 1)
self.assertTrue(issubclass(w[-1].category, BotorchWarning))
self.assertIsNone(X_rnd)
# test constraints with NEHVI
constraints = [lambda Y: Y[..., 0]]
ref_point = torch.zeros(2, **tkwargs)
# test cases when there are and are not any feasible points
for any_feas in (True, False):
Y_train = torch.stack(
[
torch.linspace(-0.5, 0.5, X_train.shape[0], **tkwargs)
if any_feas
else torch.ones(X_train.shape[0], **tkwargs),
X_train.sum(dim=-1),
],
dim=-1,
)
moo_model = MockModel(MockPosterior(mean=Y_train, samples=Y_train))
acqf = qNoisyExpectedHypervolumeImprovement(
moo_model,
ref_point=ref_point,
X_baseline=X_train,
constraints=constraints,
cache_root=False,
)
X_rnd = sample_points_around_best(
acq_function=acqf,
n_discrete_points=4,
sigma=0.0,
bounds=bounds,
)
self.assertTrue(X_rnd.shape, torch.Size([4, 2]))
# this should be true since sigma=0
# and we should only be returning feasible points
violation = constraints[0](Y_train)
neg_violation = -violation.clamp_min(0.0)
feas = neg_violation == 0
eq_mask = (X_train.unsqueeze(1) == X_rnd.unsqueeze(0)).all(dim=-1)
if feas.any():
# determine
# create n_train x n_rnd tensor of booleans
eq_mask = (X_train.unsqueeze(1) == X_rnd.unsqueeze(0)).all(dim=-1)
# check that all X_rnd correspond to feasible points
self.assertEqual(eq_mask[feas].sum(), 4)
else:
idcs = torch.topk(neg_violation, k=2).indices
self.assertEqual(eq_mask[idcs].sum(), 4)
self.assertTrue((X_rnd >= 1).all())
self.assertTrue((X_rnd <= 2).all())
# test that subset_dims is called if d>=21
X_train = 1 + torch.rand(20, 21, **tkwargs)
model = MockModel(
MockPosterior(mean=(2 * X_train + 1).sum(dim=-1, keepdim=True))
)
bounds = torch.ones(2, 21, **tkwargs)
bounds[1] = 2
# test NEI with X_baseline
acqf = qNoisyExpectedImprovement(model, X_baseline=X_train)
with mock.patch(
"botorch.optim.initializers.sample_perturbed_subset_dims",
wraps=sample_perturbed_subset_dims,
) as mock_subset_dims:
X_rnd = sample_points_around_best(
acq_function=acqf, n_discrete_points=5, sigma=1e-3, bounds=bounds
)
self.assertTrue(X_rnd.shape, torch.Size([5, 2]))
self.assertTrue((X_rnd >= 1).all())
self.assertTrue((X_rnd <= 2).all())
mock_subset_dims.assert_called_once()
# test tiny prob_perturb to make sure we perturb at least one dimension
X_rnd = sample_points_around_best(
acq_function=acqf,
n_discrete_points=5,
sigma=1e-3,
bounds=bounds,
prob_perturb=1e-8,
)
self.assertTrue(
((X_rnd.unsqueeze(0) == X_train.unsqueeze(1)).all(dim=-1)).sum() == 0
)
| 18,861 |
778 | <reponame>clazaro/Kratos
// Author: <NAME> (<EMAIL>)
// Date: April 2021
//This drag law is explained and implemented in detail in the following paper:
//Lattice Boltzmann investigation on fluid flows through packed beds: Interaction between fluid rheology and bed properties
//Qi et al. 2020
#include "swimming_DEM_application.h"
#include "dallavalle_drag_law.h"
namespace Kratos {
DragLaw::Pointer DallavalleDragLaw::Clone() const {
DallavalleDragLaw::Pointer p_clone(new DallavalleDragLaw(*this));
return p_clone;
}
void DallavalleDragLaw::Initialize(const ProcessInfo& r_process_info) {}
std::string DallavalleDragLaw::GetTypeOfLaw() {
std::string type_of_law = "Dallavalle drag law";
return type_of_law;
}
void DallavalleDragLaw::ComputeForce(SphericParticle* p_particle,
const double reynolds_number,
double particle_radius,
double fluid_density,
double fluid_kinematic_viscosity,
array_1d<double, 3>& minus_slip_velocity,
array_1d<double, 3>& drag_force,
const ProcessInfo& r_current_process_info)
{
double drag_coeff;
const double equivalent_diameter = this->CalculateEquivalentDiameter(p_particle);
Geometry<Node<3> >& r_geometry = p_particle->GetGeometry();
const double eps = r_geometry[0].FastGetSolutionStepValue(FLUID_FRACTION_PROJECTED);
double weighting_sum = this->CalculateWeightingSum(p_particle, equivalent_diameter);
if (reynolds_number < 0.01){
return StokesDragLaw::ComputeForce(p_particle,
reynolds_number,
particle_radius,
fluid_density,
fluid_kinematic_viscosity,
minus_slip_velocity,
drag_force,
r_current_process_info);
}
double y = (2 * particle_radius) / equivalent_diameter;
const double weighting_parameter = 0.5 * (eps) / weighting_sum + 0.5 * y + 0.5 * (1 - eps) * std::pow(y, 2);
const double norm_minus_slip_velocity = SWIMMING_MODULUS_3(minus_slip_velocity);
const double mean_reynolds_particle = eps * norm_minus_slip_velocity * equivalent_diameter / fluid_kinematic_viscosity;
array_1d<double, 3>& slip_vel = r_geometry[0].FastGetSolutionStepValue(SLIP_VELOCITY);
slip_vel = minus_slip_velocity;
const double beta = 2.65 * (eps + 1) - (5.3 - 3.5 * eps) * std::pow(eps, 2) * std::exp(-std::pow(1.5 - std::log(mean_reynolds_particle), 2) / 2);
drag_coeff = std::pow((2.654 / (1.0 + 3.213) + 4.8 / (std::sqrt(mean_reynolds_particle))),2);
noalias(drag_force) = 1.0 / 8.0 * drag_coeff * Globals::Pi * fluid_density * y * weighting_parameter * std::pow(equivalent_diameter, 2) * norm_minus_slip_velocity * minus_slip_velocity * std::pow(eps, 2.0 - beta);
}
double DallavalleDragLaw::CalculateEquivalentDiameter(SphericParticle* p_particle){
const double particle_radius = p_particle->GetRadius();
double particle_equivalent_diameter = this->GetParticleMassFraction(p_particle) / (2 * particle_radius);
double particle_diameter = 2 * particle_radius;
std::vector<double> vector_diameter;
vector_diameter.push_back(particle_diameter);
for (unsigned int i = 0; i < p_particle->mNeighbourElements.size(); ++i){
const double neigh_diameter = 2 * p_particle->mNeighbourElements[i]->GetRadius();
std::vector<double>::iterator it = std::find(vector_diameter.begin(), vector_diameter.end(), neigh_diameter);
if(it == vector_diameter.end()){
vector_diameter.push_back(neigh_diameter);
particle_equivalent_diameter += this->GetParticleMassFraction(p_particle->mNeighbourElements[i])
/ (neigh_diameter);
}
}
return 1.0 / particle_equivalent_diameter;
}
double DallavalleDragLaw::GetParticleMassFraction(SphericParticle* p_particle){
double particle_i_component_volume = p_particle->CalculateVolume();
double sum_volume = particle_i_component_volume;
for (unsigned int i = 0; i < p_particle->mNeighbourElements.size(); ++i){
if (p_particle->mNeighbourElements[i]->GetRadius() == p_particle->GetRadius()){
particle_i_component_volume += p_particle->mNeighbourElements[i]->CalculateVolume();
}
sum_volume += p_particle->mNeighbourElements[i]->CalculateVolume();
}
return particle_i_component_volume / sum_volume;
}
double DallavalleDragLaw::CalculateWeightingSum(SphericParticle* p_particle, const double& equivalent_diameter){
const double mass_fraction = this->GetParticleMassFraction(p_particle);
const double particle_diameter = 2 * p_particle->GetRadius();
std::vector<double> vector_diameter;
vector_diameter.push_back(particle_diameter);
double sum_parameter = mass_fraction * std::pow(equivalent_diameter / particle_diameter, 2);
for (unsigned int i = 0; i < p_particle->mNeighbourElements.size(); ++i){
const double neigh_diameter = 2 * p_particle->mNeighbourElements[i]->GetRadius();
std::vector<double>::iterator it = std::find(vector_diameter.begin(), vector_diameter.end(), neigh_diameter);
if(it == vector_diameter.end()){
vector_diameter.push_back(neigh_diameter);
sum_parameter += this->GetParticleMassFraction(p_particle->mNeighbourElements[i]) * std::pow(equivalent_diameter / neigh_diameter, 2);
}
}
return sum_parameter;
}
} // namespace Kratos | 2,898 |
918 | /*
* 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.gobblin.dataset;
import java.io.IOException;
import java.util.List;
import org.apache.hadoop.fs.Path;
/**
* Finds {@link Dataset}s in the file system.
*
* <p>
* Concrete subclasses should have a constructor with signature
* ({@link org.apache.hadoop.fs.FileSystem}, {@link java.util.Properties}).
* </p>
*/
public interface DatasetsFinder<T extends Dataset> {
/**
* Find all {@link Dataset}s in the file system.
* @return List of {@link Dataset}s in the file system.
* @throws IOException
*/
public List<T> findDatasets() throws IOException;
/**
* @return The deepest common root shared by all {@link Dataset}s root paths returned by this finder.
*/
@Deprecated
public Path commonDatasetRoot();
}
| 459 |
955 | """Backend supported: tensorflow.compat.v1, tensorflow, pytorch"""
import deepxde as dde
import numpy as np
a = 1
d = 1
Re = 1
def pde(x, u):
u_vel, v_vel, w_vel, p = u[:, 0:1], u[:, 1:2], u[:, 2:3], u[:, 3:4]
u_vel_x = dde.grad.jacobian(u, x, i=0, j=0)
u_vel_y = dde.grad.jacobian(u, x, i=0, j=1)
u_vel_z = dde.grad.jacobian(u, x, i=0, j=2)
u_vel_t = dde.grad.jacobian(u, x, i=0, j=3)
u_vel_xx = dde.grad.hessian(u, x, component=0, i=0, j=0)
u_vel_yy = dde.grad.hessian(u, x, component=0, i=1, j=1)
u_vel_zz = dde.grad.hessian(u, x, component=0, i=2, j=2)
v_vel_x = dde.grad.jacobian(u, x, i=1, j=0)
v_vel_y = dde.grad.jacobian(u, x, i=1, j=1)
v_vel_z = dde.grad.jacobian(u, x, i=1, j=2)
v_vel_t = dde.grad.jacobian(u, x, i=1, j=3)
v_vel_xx = dde.grad.hessian(u, x, component=1, i=0, j=0)
v_vel_yy = dde.grad.hessian(u, x, component=1, i=1, j=1)
v_vel_zz = dde.grad.hessian(u, x, component=1, i=2, j=2)
w_vel_x = dde.grad.jacobian(u, x, i=2, j=0)
w_vel_y = dde.grad.jacobian(u, x, i=2, j=1)
w_vel_z = dde.grad.jacobian(u, x, i=2, j=2)
w_vel_t = dde.grad.jacobian(u, x, i=2, j=3)
w_vel_xx = dde.grad.hessian(u, x, component=2, i=0, j=0)
w_vel_yy = dde.grad.hessian(u, x, component=2, i=1, j=1)
w_vel_zz = dde.grad.hessian(u, x, component=2, i=2, j=2)
p_x = dde.grad.jacobian(u, x, i=3, j=0)
p_y = dde.grad.jacobian(u, x, i=3, j=1)
p_z = dde.grad.jacobian(u, x, i=3, j=2)
momentum_x = (
u_vel_t
+ (u_vel * u_vel_x + v_vel * u_vel_y + w_vel * u_vel_z)
+ p_x
- 1 / Re * (u_vel_xx + u_vel_yy + u_vel_zz)
)
momentum_y = (
v_vel_t
+ (u_vel * v_vel_x + v_vel * v_vel_y + w_vel * v_vel_z)
+ p_y
- 1 / Re * (v_vel_xx + v_vel_yy + v_vel_zz)
)
momentum_z = (
w_vel_t
+ (u_vel * w_vel_x + v_vel * w_vel_y + w_vel * w_vel_z)
+ p_z
- 1 / Re * (w_vel_xx + w_vel_yy + w_vel_zz)
)
continuity = u_vel_x + v_vel_y + w_vel_z
return [momentum_x, momentum_y, momentum_z, continuity]
def u_func(x):
return (
-a
* (
np.exp(a * x[:, 0:1]) * np.sin(a * x[:, 1:2] + d * x[:, 2:3])
+ np.exp(a * x[:, 2:3]) * np.cos(a * x[:, 0:1] + d * x[:, 1:2])
)
* np.exp(-(d ** 2) * x[:, 3:4])
)
def v_func(x):
return (
-a
* (
np.exp(a * x[:, 1:2]) * np.sin(a * x[:, 2:3] + d * x[:, 0:1])
+ np.exp(a * x[:, 0:1]) * np.cos(a * x[:, 1:2] + d * x[:, 2:3])
)
* np.exp(-(d ** 2) * x[:, 3:4])
)
def w_func(x):
return (
-a
* (
np.exp(a * x[:, 2:3]) * np.sin(a * x[:, 0:1] + d * x[:, 1:2])
+ np.exp(a * x[:, 1:2]) * np.cos(a * x[:, 2:3] + d * x[:, 0:1])
)
* np.exp(-(d ** 2) * x[:, 3:4])
)
def p_func(x):
return (
-0.5
* a ** 2
* (
np.exp(2 * a * x[:, 0:1])
+ np.exp(2 * a * x[:, 1:2])
+ np.exp(2 * a * x[:, 2:3])
+ 2
* np.sin(a * x[:, 0:1] + d * x[:, 1:2])
* np.cos(a * x[:, 2:3] + d * x[:, 0:1])
* np.exp(a * (x[:, 1:2] + x[:, 2:3]))
+ 2
* np.sin(a * x[:, 1:2] + d * x[:, 2:3])
* np.cos(a * x[:, 0:1] + d * x[:, 1:2])
* np.exp(a * (x[:, 2:3] + x[:, 0:1]))
+ 2
* np.sin(a * x[:, 2:3] + d * x[:, 0:1])
* np.cos(a * x[:, 1:2] + d * x[:, 2:3])
* np.exp(a * (x[:, 0:1] + x[:, 1:2]))
)
* np.exp(-2 * d ** 2 * x[:, 3:4])
)
spatial_domain = dde.geometry.Cuboid(xmin=[-1, -1, -1], xmax=[1, 1, 1])
temporal_domain = dde.geometry.TimeDomain(0, 1)
spatio_temporal_domain = dde.geometry.GeometryXTime(spatial_domain, temporal_domain)
boundary_condition_u = dde.DirichletBC(
spatio_temporal_domain, u_func, lambda _, on_boundary: on_boundary, component=0
)
boundary_condition_v = dde.DirichletBC(
spatio_temporal_domain, v_func, lambda _, on_boundary: on_boundary, component=1
)
boundary_condition_w = dde.DirichletBC(
spatio_temporal_domain, w_func, lambda _, on_boundary: on_boundary, component=2
)
initial_condition_u = dde.IC(
spatio_temporal_domain, u_func, lambda _, on_initial: on_initial, component=0
)
initial_condition_v = dde.IC(
spatio_temporal_domain, v_func, lambda _, on_initial: on_initial, component=1
)
initial_condition_w = dde.IC(
spatio_temporal_domain, w_func, lambda _, on_initial: on_initial, component=2
)
data = dde.data.TimePDE(
spatio_temporal_domain,
pde,
[
boundary_condition_u,
boundary_condition_v,
boundary_condition_w,
initial_condition_u,
initial_condition_v,
initial_condition_w,
],
num_domain=50000,
num_boundary=5000,
num_initial=5000,
num_test=10000,
)
net = dde.maps.FNN([4] + 4 * [50] + [4], "tanh", "Glorot normal")
model = dde.Model(data, net)
model.compile("adam", lr=1e-3, loss_weights=[1, 1, 1, 1, 100, 100, 100, 100, 100, 100])
model.train(epochs=30000)
model.compile("L-BFGS", loss_weights=[1, 1, 1, 1, 100, 100, 100, 100, 100, 100])
losshistory, train_state = model.train()
x, y, z = np.meshgrid(
np.linspace(-1, 1, 10), np.linspace(-1, 1, 10), np.linspace(-1, 1, 10)
)
X = np.vstack((np.ravel(x), np.ravel(y), np.ravel(z))).T
t_0 = np.zeros(1000).reshape(1000, 1)
t_1 = np.ones(1000).reshape(1000, 1)
X_0 = np.hstack((X, t_0))
X_1 = np.hstack((X, t_1))
output_0 = model.predict(X_0)
output_1 = model.predict(X_1)
u_pred_0 = output_0[:, 0].reshape(-1)
v_pred_0 = output_0[:, 1].reshape(-1)
w_pred_0 = output_0[:, 2].reshape(-1)
p_pred_0 = output_0[:, 3].reshape(-1)
u_exact_0 = u_func(X_0).reshape(-1)
v_exact_0 = v_func(X_0).reshape(-1)
w_exact_0 = w_func(X_0).reshape(-1)
p_exact_0 = p_func(X_0).reshape(-1)
u_pred_1 = output_1[:, 0].reshape(-1)
v_pred_1 = output_1[:, 1].reshape(-1)
w_pred_1 = output_1[:, 2].reshape(-1)
p_pred_1 = output_1[:, 3].reshape(-1)
u_exact_1 = u_func(X_1).reshape(-1)
v_exact_1 = v_func(X_1).reshape(-1)
w_exact_1 = w_func(X_1).reshape(-1)
p_exact_1 = p_func(X_1).reshape(-1)
f_0 = model.predict(X_0, operator=pde)
f_1 = model.predict(X_1, operator=pde)
l2_difference_u_0 = dde.metrics.l2_relative_error(u_exact_0, u_pred_0)
l2_difference_v_0 = dde.metrics.l2_relative_error(v_exact_0, v_pred_0)
l2_difference_w_0 = dde.metrics.l2_relative_error(w_exact_0, w_pred_0)
l2_difference_p_0 = dde.metrics.l2_relative_error(p_exact_0, p_pred_0)
residual_0 = np.mean(np.absolute(f_0))
l2_difference_u_1 = dde.metrics.l2_relative_error(u_exact_1, u_pred_1)
l2_difference_v_1 = dde.metrics.l2_relative_error(v_exact_1, v_pred_1)
l2_difference_w_1 = dde.metrics.l2_relative_error(w_exact_1, w_pred_1)
l2_difference_p_1 = dde.metrics.l2_relative_error(p_exact_1, p_pred_1)
residual_1 = np.mean(np.absolute(f_1))
print("Accuracy at t = 0:")
print("Mean residual:", residual_0)
print("L2 relative error in u:", l2_difference_u_0)
print("L2 relative error in v:", l2_difference_v_0)
print("L2 relative error in w:", l2_difference_w_0)
print("\n")
print("Accuracy at t = 1:")
print("Mean residual:", residual_1)
print("L2 relative error in u:", l2_difference_u_1)
print("L2 relative error in v:", l2_difference_v_1)
print("L2 relative error in w:", l2_difference_w_1)
| 4,057 |
701 | <reponame>snazari/Pyto
"""
Classes from the 'vCard' framework.
"""
try:
from rubicon.objc import ObjCClass
except ValueError:
def ObjCClass(name):
return None
def _Class(name):
try:
return ObjCClass(name)
except NameError:
return None
CNVCardData = _Class("CNVCardData")
CNVCardUserDefaults = _Class("CNVCardUserDefaults")
CNVCardNameComponentPostProcessor = _Class("CNVCardNameComponentPostProcessor")
CNVCardProdIdString = _Class("CNVCardProdIdString")
CNVCardEncoding = _Class("CNVCardEncoding")
CNVCardValueEncoder = _Class("CNVCardValueEncoder")
CNVCardParameter = _Class("CNVCardParameter")
CNVCardWritingOptions = _Class("CNVCardWritingOptions")
CNVCardOptions = _Class("CNVCardOptions")
CNVCardNameComponents = _Class("CNVCardNameComponents")
CNVCardMutableNameComponents = _Class("CNVCardMutableNameComponents")
CNMECARDParser = _Class("CNMECARDParser")
_CNVCardParsingConcurrentStrategy = _Class("_CNVCardParsingConcurrentStrategy")
_CNVCardParsingSerialStrategy = _Class("_CNVCardParsingSerialStrategy")
CNVCardParsingConcurrencyStrategy = _Class("CNVCardParsingConcurrencyStrategy")
CNVCardNameSerialization = _Class("CNVCardNameSerialization")
CNVCard30PHOTOHelper = _Class("CNVCard30PHOTOHelper")
CNVCardPropertyItem = _Class("CNVCardPropertyItem")
CNVCardParameterEncoder = _Class("CNVCardParameterEncoder")
CNVCardParameterDecoder = _Class("CNVCardParameterDecoder")
CNVCardFilteredPersonScope = _Class("CNVCardFilteredPersonScope")
CNVCardDataStorage = _Class("CNVCardDataStorage")
CNVCardStringStorage = _Class("CNVCardStringStorage")
CNVCardSerializationStorage = _Class("CNVCardSerializationStorage")
CNVCardLineSerializationStrategyImpl = _Class("CNVCardLineSerializationStrategyImpl")
CNVCardLine21SerializationStrategy = _Class("CNVCardLine21SerializationStrategy")
CNVCardLine30SerializationStrategy = _Class("CNVCardLine30SerializationStrategy")
CNVCardLineSerializationStrategy = _Class("CNVCardLineSerializationStrategy")
CNVCardLineGenerator = _Class("CNVCardLineGenerator")
CNVCardActivityAlertLineGenerator = _Class("CNVCardActivityAlertLineGenerator")
CNVCardStreetAddressLineGenerator = _Class("CNVCardStreetAddressLineGenerator")
CNVCardPhoneLineGenerator = _Class("CNVCardPhoneLineGenerator")
CNVCardEmailLineGenerator = _Class("CNVCardEmailLineGenerator")
CNVCardSocialProfileLineGenerator = _Class("CNVCardSocialProfileLineGenerator")
CNVCardLegacyInstantMessagingLineGenerator = _Class(
"CNVCardLegacyInstantMessagingLineGenerator"
)
CNVCardInstantMessagingLineGenerator = _Class("CNVCardInstantMessagingLineGenerator")
CNVCardAlternateDateComponentsLineGenerator = _Class(
"CNVCardAlternateDateComponentsLineGenerator"
)
CNVCardDateComponentsLineGenerator = _Class("CNVCardDateComponentsLineGenerator")
CNVCardLineFactory = _Class("CNVCardLineFactory")
CNVCardImage = _Class("CNVCardImage")
CNVCardMutableImage = _Class("CNVCardMutableImage")
CGImageRefWithFormat = _Class("CGImageRefWithFormat")
CNVCardLine = _Class("CNVCardLine")
CNVCardVersionPlaceholderLine = _Class("CNVCardVersionPlaceholderLine")
CNVCardLiteralLine = _Class("CNVCardLiteralLine")
CNVCardPerson = _Class("CNVCardPerson")
CNVCardUnknownPropertyDescription = _Class("CNVCardUnknownPropertyDescription")
CNVCard30CardBuilder = _Class("CNVCard30CardBuilder")
CNVCardFilteredPerson = _Class("CNVCardFilteredPerson")
CNVCardWriting = _Class("CNVCardWriting")
CNVCardParsedDictionaryResultBuilder = _Class("CNVCardParsedDictionaryResultBuilder")
CNVCardLexer = _Class("CNVCardLexer")
CNVCardParsedParameter = _Class("CNVCardParsedParameter")
CNVCardReadingOptions = _Class("CNVCardReadingOptions")
CNVCardParsedLine = _Class("CNVCardParsedLine")
CNVCardXSOCIALPROFILEParser = _Class("CNVCardXSOCIALPROFILEParser")
CNVCardActivityAlertEscapingSerializationStrategy = _Class(
"CNVCardActivityAlertEscapingSerializationStrategy"
)
CNVCardActivityAlertQuotingSerializationStrategy = _Class(
"CNVCardActivityAlertQuotingSerializationStrategy"
)
CNVCardActivityAlertSerializer = _Class("CNVCardActivityAlertSerializer")
CNVCardActivityAlertSerialization = _Class("CNVCardActivityAlertSerialization")
CNVCardRangeFinder = _Class("CNVCardRangeFinder")
CNVCardActivityAlertScanner = _Class("CNVCardActivityAlertScanner")
_CNVCardParsedResultBuilderBlockFactory = _Class(
"_CNVCardParsedResultBuilderBlockFactory"
)
CNVCardParsedResultBuilderFactory = _Class("CNVCardParsedResultBuilderFactory")
CNVCardXACTIVITYALERTParser = _Class("CNVCardXACTIVITYALERTParser")
CNVCardXABPHOTOParser = _Class("CNVCardXABPHOTOParser")
CNVCardURLParser = _Class("CNVCardURLParser")
CNVCardPHOTOParser = _Class("CNVCardPHOTOParser")
CNVCardInstantMessageParser = _Class("CNVCardInstantMessageParser")
CNVCardDateScanner = _Class("CNVCardDateScanner")
CNVCardDateComponentsParser = _Class("CNVCardDateComponentsParser")
CNVCardADRParser = _Class("CNVCardADRParser")
CNVCardSelectorMap = _Class("CNVCardSelectorMap")
CNVCardTesting = _Class("CNVCardTesting")
CNVCardDictionarySerialization = _Class("CNVCardDictionarySerialization")
CNVCardParser = _Class("CNVCardParser")
CNVCardDataAnalyzer = _Class("CNVCardDataAnalyzer")
CNVCardReading = _Class("CNVCardReading")
CNVCardDateComponentsFormatter = _Class("CNVCardDateComponentsFormatter")
| 1,723 |
325 | <gh_stars>100-1000
from unittest import TestCase
from unittest.mock import patch, PropertyMock, MagicMock
from basketball_reference_web_scraper.html import PlayerSearchResult
class TestPlayerSearchResult(TestCase):
def test_league_abbreviation_query(self):
self.assertEqual(
PlayerSearchResult(html=MagicMock()).league_abbreviation_query,
'./div[@class="search-item-league"]'
)
@patch.object(PlayerSearchResult, 'league_abbreviation_query', new_callable=PropertyMock)
def test_league_abbreviations_are_none_when_no_matching_abbreviations(self, mocked_query):
mocked_query.return_value = "some query"
html = MagicMock()
html.xpath = MagicMock(return_value=[])
self.assertIsNone(PlayerSearchResult(html=html).league_abbreviations)
html.xpath.assert_called_once_with("some query")
@patch.object(PlayerSearchResult, 'league_abbreviation_query', new_callable=PropertyMock)
def test_league_abbreviations_are_first_abbreviation_text_content_when__matching_abbreviations(self, mocked_query):
mocked_query.return_value = "some query"
first_abbreviation = MagicMock()
first_abbreviation.text_content = MagicMock(return_value="first abbreviation")
second_abbreviation = MagicMock()
second_abbreviation.text_content = MagicMock(return_value="second abbreviation")
html = MagicMock()
html.xpath = MagicMock(return_value=[first_abbreviation, second_abbreviation])
self.assertEqual(
PlayerSearchResult(html=html).league_abbreviations,
"first abbreviation",
)
html.xpath.assert_called_once_with("some query")
| 663 |
384 | #include "../gmx_blas.h"
void
F77_FUNC(daxpy,DAXPY)(int * n_arg,
double * da_arg,
double * dx,
int * incx_arg,
double * dy,
int * incy_arg)
{
int i,ix,iy;
int n=*n_arg;
double da=*da_arg;
int incx = *incx_arg;
int incy = *incy_arg;
if (n<=0)
return;
if(incx!=1 || incy!=1) {
ix = 0;
iy = 0;
if(incx<0)
ix = (1-n)*incx;
if(incy<0)
iy = (1-n)*incy;
for(i=0;i<n;i++,ix+=incx,iy+=incy)
dy[iy] += da*dx[ix];
return;
} else {
/* unroll */
for(i=0;i<(n-4);i+=4) {
dy[i] += da*dx[i];
dy[i+1] += da*dx[i+1];
dy[i+2] += da*dx[i+2];
dy[i+3] += da*dx[i+3];
}
/* continue with current value of i */
for(;i<n;i++)
dy[i] += da*dx[i];
}
}
| 588 |
333 | package com.alipay.api.domain;
import java.util.List;
import com.alipay.api.AlipayObject;
import com.alipay.api.internal.mapping.ApiField;
import com.alipay.api.internal.mapping.ApiListField;
/**
* 口碑菜谱分类置顶同步
*
* @author auto create
* @since 1.0, 2020-08-31 11:12:05
*/
public class KoubeiCateringDishCookcatetopSyncModel extends AlipayObject {
private static final long serialVersionUID = 5437261957499771168L;
/**
* 菜谱类目置顶操作列表,一次批量操作最多100个
*/
@ApiListField("kbdish_cook_cate_top_info_list")
@ApiField("kbdish_cook_cate_top_info")
private List<KbdishCookCateTopInfo> kbdishCookCateTopInfoList;
public List<KbdishCookCateTopInfo> getKbdishCookCateTopInfoList() {
return this.kbdishCookCateTopInfoList;
}
public void setKbdishCookCateTopInfoList(List<KbdishCookCateTopInfo> kbdishCookCateTopInfoList) {
this.kbdishCookCateTopInfoList = kbdishCookCateTopInfoList;
}
}
| 451 |
3,348 | <reponame>wromansky/incubator-heron
/**
* 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.
*/
#include "network/networkoptions.h"
#include <arpa/inet.h>
#include <string>
#include "basics/spconsts.h"
// This is the default high water mark on the num of bytes that can be left outstanding on
// a connection
const sp_int64 systemHWMOutstandingBytes = 100_MB;
// This is the default low water mark on the num of bytes that can be left outstanding on
// a connection
const sp_int64 systemLWMOutstandingBytes = 50_MB;
NetworkOptions::NetworkOptions() {
host_ = "127.0.0.1";
port_ = 8080;
max_packet_size_ = 1_KB;
socket_family_ = PF_INET;
sin_path_ = "";
high_watermark_ = systemHWMOutstandingBytes;
low_watermark_ = systemLWMOutstandingBytes;
}
NetworkOptions::NetworkOptions(const NetworkOptions& _copyFrom) {
host_ = _copyFrom.get_host();
port_ = _copyFrom.get_port();
max_packet_size_ = _copyFrom.get_max_packet_size();
socket_family_ = _copyFrom.get_socket_family();
high_watermark_ = _copyFrom.get_high_watermark();
low_watermark_ = _copyFrom.get_low_watermark();
sin_path_ = _copyFrom.get_sin_path();
}
NetworkOptions::~NetworkOptions() {}
void NetworkOptions::set_host(const std::string& _host) { host_ = _host; }
std::string NetworkOptions::get_host() const { return host_; }
void NetworkOptions::set_port(sp_int32 _port) { port_ = _port; }
sp_int32 NetworkOptions::get_port() const { return port_; }
void NetworkOptions::set_max_packet_size(sp_uint32 _max_packet_size) {
max_packet_size_ = _max_packet_size;
}
sp_uint32 NetworkOptions::get_max_packet_size() const { return max_packet_size_; }
void NetworkOptions::set_high_watermark(sp_int64 _high_watermark) {
high_watermark_ = _high_watermark;
}
sp_int64 NetworkOptions::get_high_watermark() const { return high_watermark_; }
void NetworkOptions::set_low_watermark(sp_int64 _low_watermark) {
low_watermark_ = _low_watermark;
}
sp_int64 NetworkOptions::get_low_watermark() const { return low_watermark_; }
void NetworkOptions::set_socket_family(sp_int32 _socket_family) { socket_family_ = _socket_family; }
sp_int32 NetworkOptions::get_socket_family() const { return socket_family_; }
sp_int32 NetworkOptions::get_sin_family() const {
if (socket_family_ == PF_INET)
return AF_INET;
else
return AF_UNIX;
}
void NetworkOptions::set_sin_path(const std::string& _sin_path) { sin_path_ = _sin_path; }
const std::string& NetworkOptions::get_sin_path() const { return sin_path_; }
| 1,057 |
2,564 | //
// Created by CainHuang on 2020-02-24.
//
#ifndef AVMEDIAPLAYER_H
#define AVMEDIAPLAYER_H
#include <SafetyQueue.h>
#include <android/native_window.h>
#include <player/AudioStreamPlayer.h>
#include <player/VideoStreamPlayer.h>
#include <MessageQueue.h>
#include <player/OnPlayListener.h>
#include <player/Timestamp.h>
/**
* 播放器事件类型
*/
enum media_player_event_type {
MEDIA_NOP = 0,
MEDIA_PREPARED = 1,
MEDIA_STARTED = 2,
MEDIA_PLAYBACK_COMPLETE = 3,
MEDIA_SEEK_COMPLETE = 4,
MEDIA_BUFFERING_UPDATE = 5,
MEDIA_SET_VIDEO_SIZE = 6,
MEDIA_ERROR = 100,
MEDIA_INFO = 200,
MEDIA_CURRENT = 300,
MEDIA_SET_VIDEO_SAR = 10001
};
/**
* 播放出错类型
*/
enum media_player_error_type {
// 0xx
MEDIA_ERROR_UNKNOWN = 1,
// 1xx
MEDIA_ERROR_SERVER_DIED = 100,
// 2xx
MEDIA_ERROR_NOT_VALID_FOR_PROGRESSIVE_PLAYBACK = 200,
// 3xx
};
/**
* 媒体播放器信息类型
*/
enum media_player_info_type {
// 0xx
MEDIA_INFO_UNKNOWN = 1,
// The player was started because it was used as the next player for another
// player, which just completed playback
MEDIA_INFO_STARTED_AS_NEXT = 2,
// The player just pushed the very first video frame for rendering
MEDIA_INFO_RENDERING_START = 3,
// 7xx
// The video is too complex for the decoder: it can't decode frames fast
// enough. Possibly only the audio plays fine at this stage.
MEDIA_INFO_VIDEO_TRACK_LAGGING = 700,
// MediaPlayer is temporarily pausing playback internally in order to
// buffer more data.
MEDIA_INFO_BUFFERING_START = 701,
// MediaPlayer is resuming playback after filling buffers.
MEDIA_INFO_BUFFERING_END = 702,
// Bandwidth in recent past
MEDIA_INFO_NETWORK_BANDWIDTH = 703,
// 8xx
// Bad interleaving means that a media has been improperly interleaved or not
// interleaved at all, e.g has all the video samples first then all the audio
// ones. Video is playing but a lot of disk seek may be happening.
MEDIA_INFO_BAD_INTERLEAVING = 800,
// The media is not seekable (e.g live stream).
MEDIA_INFO_NOT_SEEKABLE = 801,
// New media metadata is available.
MEDIA_INFO_METADATA_UPDATE = 802,
// Audio can not be played.
MEDIA_INFO_PLAY_AUDIO_ERROR = 804,
// Video can not be played.
MEDIA_INFO_PLAY_VIDEO_ERROR = 805,
//9xx
MEDIA_INFO_TIMED_TEXT_ERROR = 900,
};
/**
* 媒体播放器
*/
class AVMediaPlayer : Runnable {
public:
AVMediaPlayer();
virtual ~AVMediaPlayer();
// 初始化
void init();
void release();
void setOnPlayingListener(std::shared_ptr<OnPlayListener> listener);
status_t setDataSource(const char *url, int64_t offset = 0, const char *headers = nullptr);
status_t setAudioDecoder(const char *decoder);
status_t setVideoDecoder(const char *decoder);
#if defined(__ANDROID__)
status_t setVideoSurface(ANativeWindow *window);
#endif
status_t setSpeed(float speed);
status_t setLooping(bool looping);
status_t setRange(float start, float end);
status_t setVolume(float leftVolume, float rightVolume);
status_t setMute(bool mute);
status_t prepare();
status_t start();
status_t pause();
status_t stop();
status_t setDecodeOnPause(bool decodeOnPause);
status_t seekTo(float timeMs);
long getCurrentPosition();
float getDuration();
int getRotate();
int getVideoWidth();
int getVideoHeight();
bool isLooping();
bool isPlaying();
void onPlaying(float pts);
void onSeekComplete(AVMediaType type);
void onCompletion(AVMediaType type);
// 通知回调
void notify(int msg, int arg1 = -1, int arg2 = -1);
private:
void run() override;
void postEvent(int what, int arg1 = -1, int arg2 = -1, void *obj = nullptr);
void preparePlayer();
void startPlayer();
void pausePlayer();
void stopPlayer();
void seekPlayer(float timeMs);
private:
Mutex mMutex;
Condition mCondition;
Thread *mThread;
bool mAbortRequest;
std::shared_ptr<OnPlayListener> mPlayListener;
std::shared_ptr<StreamPlayListener> mStreamPlayListener;
std::shared_ptr<AudioStreamPlayer> mAudioPlayer;
std::shared_ptr<VideoStreamPlayer> mVideoPlayer;
std::unique_ptr<MessageQueue> mMessageQueue;
std::shared_ptr<Timestamp> mTimestamp;
};
/**
* 媒体流播放监听器
*/
class MediaPlayerListener : public StreamPlayListener {
public:
MediaPlayerListener(AVMediaPlayer *player);
virtual ~MediaPlayerListener();
void onPrepared(AVMediaType type) override;
void onPlaying(AVMediaType type, float pts) override;
void onSeekComplete(AVMediaType type) override;
void onCompletion(AVMediaType type) override;
void onError(AVMediaType type, int errorCode, const char *msg) override;
private:
AVMediaPlayer *player;
};
#endif //AVMEDIAPLAYER_H
| 1,979 |
2,232 | <reponame>JLimperg/lean
/*
Copyright (c) 2015 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: <NAME>
*/
#include "kernel/environment.h"
#include "kernel/standard_kernel.h"
#include "library/module.h"
#include "api/decl.h"
#include "api/string.h"
#include "api/exception.h"
#include "api/lean_env.h"
using namespace lean; // NOLINT
lean_bool lean_env_mk_std(unsigned t, lean_env * r, lean_exception * ex) {
LEAN_TRY;
*r = of_env(new environment(mk_environment(t)));
LEAN_CATCH;
}
lean_bool lean_env_add(lean_env e, lean_cert_decl d, lean_env * r, lean_exception * ex) {
LEAN_TRY;
check_nonnull(e);
check_nonnull(d);
*r = of_env(new environment(module::add(to_env_ref(e), to_cert_decl_ref(d))));
LEAN_CATCH;
}
lean_bool lean_env_replace(lean_env e, lean_cert_decl d, lean_env * r, lean_exception * ex) {
LEAN_TRY;
check_nonnull(e);
check_nonnull(d);
*r = of_env(new environment(to_env_ref(e).replace(to_cert_decl_ref(d))));
LEAN_CATCH;
}
void lean_env_del(lean_env e) {
delete to_env(e);
}
unsigned lean_env_trust_level(lean_env e) {
return e ? to_env_ref(e).trust_lvl() : 0;
}
lean_bool lean_env_contains_decl(lean_env e, lean_name n) {
return e && n && to_env_ref(e).find(to_name_ref(n));
}
lean_bool lean_env_get_decl(lean_env e, lean_name n, lean_decl * d, lean_exception * ex) {
LEAN_TRY;
check_nonnull(e);
check_nonnull(n);
*d = of_decl(new declaration(to_env_ref(e).get(to_name_ref(n))));
LEAN_CATCH;
}
lean_bool lean_env_is_descendant(lean_env e1, lean_env e2) {
return e1 && e2 && to_env_ref(e1).is_descendant(to_env_ref(e2));
}
lean_bool lean_env_forget(lean_env e, lean_env * r, lean_exception * ex) {
LEAN_TRY;
check_nonnull(e);
*r = of_env(new environment(to_env_ref(e).forget()));
LEAN_CATCH;
}
lean_bool lean_env_for_each_decl(lean_env e, void (*f)(lean_decl), lean_exception * ex) {
LEAN_TRY;
check_nonnull(e);
to_env_ref(e).for_each_declaration([&](declaration const & d) {
f(of_decl(new declaration(d)));
});
return lean_true;
LEAN_CATCH;
}
| 966 |
386 | """
This module is run with mypy to check types can be used correctly externally.
"""
from dirty_equals import HasName, HasRepr, IsStr
assert 123 == HasName('int')
assert 123 == HasRepr('123')
assert 123 == HasName(IsStr(regex='i..'))
assert 123 == HasRepr(IsStr(regex=r'\d{3}'))
# type ignore is required (if it wasn't, there would be an error
assert 123 != HasName(123) # type: ignore[arg-type]
| 134 |
2,109 | /*
* This file is part of John the Ripper password cracker.
*
* Functions common to OpenCL and other accelerators (eg. FPGA) go in this file.
*
* This software is
* Copyright (c) 2010-2012 <NAME> <samu at linuxasylum dot net>
* Copyright (c) 2010-2013 <NAME> <<EMAIL>>
* Copyright (c) 2010-2013 magnum
* Copyright (c) 2012-2015 <NAME> <<EMAIL> at <EMAIL>>
* and is hereby released to the general public under the following terms:
* Redistribution and use in source and binary forms, with or without
* modifications, are permitted.
*/
#if defined (HAVE_OPENCL)
#ifdef AC_BUILT
#include "autoconfig.h"
#endif
#include <stdio.h>
#include <stdlib.h>
#if HAVE_LIBDL
#include <dlfcn.h>
#elif HAVE_WINDOWS_H
// For mingw/VC
#include "Win32-dlfcn-port.h"
#define HAVE_LIBDL 1
#endif
#include <string.h>
#include "common-gpu.h"
#include "john.h"
#include "memory.h"
#include "params.h"
#include "logger.h"
#include "signals.h"
#include "memdbg.h"
int gpu_id;
int gpu_device_list[MAX_GPU_DEVICES];
int requested_devices[MAX_GPU_DEVICES];
hw_bus gpu_device_bus[MAX_GPU_DEVICES];
int gpu_temp_limit;
char gpu_degree_sign[8] = "";
void *nvml_lib;
#if __linux__ && HAVE_LIBDL
NVMLINIT nvmlInit;
NVMLSHUTDOWN nvmlShutdown;
NVMLDEVICEGETHANDLEBYINDEX nvmlDeviceGetHandleByIndex;
NVMLDEVICEGETTEMPERATURE nvmlDeviceGetTemperature;
NVMLDEVICEGETFANSPEED nvmlDeviceGetFanSpeed;
NVMLDEVICEGETUTILIZATIONRATES nvmlDeviceGetUtilizationRates;
NVMLDEVICEGETPCIINFO nvmlDeviceGetPciInfo;
NVMLDEVICEGETNAME nvmlDeviceGetName;
NVMLDEVICEGETHANDLEBYPCIBUSID nvmlDeviceGetHandleByPciBusId;
NVMLDEVICEGETINDEX nvmlDeviceGetIndex;
NVMLDEVICEGETCURRPCIELINKWIDTH nvmlDeviceGetCurrPcieLinkWidth;
NVMLDEVICEGETMAXPCIELINKWIDTH nvmlDeviceGetMaxPcieLinkWidth;
#endif /* __linux__ && HAVE_LIBDL */
void *adl_lib;
#if HAVE_LIBDL
static int amd = 0;
int amd2adl[MAX_GPU_DEVICES];
int adl2od[MAX_GPU_DEVICES];
ADL_MAIN_CONTROL_CREATE ADL_Main_Control_Create;
ADL_MAIN_CONTROL_DESTROY ADL_Main_Control_Destroy;
ADL_ADAPTER_NUMBEROFADAPTERS_GET ADL_Adapter_NumberOfAdapters_Get;
ADL_ADAPTER_ADAPTERINFO_GET ADL_Adapter_AdapterInfo_Get;
ADL_ADAPTER_ACTIVE_GET ADL_Adapter_Active_Get;
ADL_OVERDRIVE_CAPS ADL_Overdrive_Caps;
ADL_OVERDRIVE5_THERMALDEVICES_ENUM ADL_Overdrive5_ThermalDevices_Enum;
ADL_OVERDRIVE5_ODPARAMETERS_GET ADL_Overdrive5_ODParameters_Get;
ADL_OVERDRIVE5_TEMPERATURE_GET ADL_Overdrive5_Temperature_Get;
ADL_OVERDRIVE5_FANSPEED_GET ADL_Overdrive5_FanSpeed_Get;
ADL_OVERDRIVE5_FANSPEEDINFO_GET ADL_Overdrive5_FanSpeedInfo_Get;
ADL_OVERDRIVE5_CURRENTACTIVITY_GET ADL_Overdrive5_CurrentActivity_Get;
ADL_OVERDRIVE6_FANSPEED_GET ADL_Overdrive6_FanSpeed_Get;
ADL_OVERDRIVE6_THERMALCONTROLLER_CAPS ADL_Overdrive6_ThermalController_Caps;
ADL_OVERDRIVE6_TEMPERATURE_GET ADL_Overdrive6_Temperature_Get;
ADL_OVERDRIVE6_CURRENTSTATUS_GET ADL_Overdrive6_CurrentStatus_Get;
ADL_OVERDRIVE6_CAPABILITIES_GET ADL_Overdrive6_Capabilities_Get;
// Memory allocation callback function
static void* ADL_Main_Memory_Alloc(int iSize)
{
void*lpBuffer = malloc(iSize);
return lpBuffer;
}
#endif /* HAVE_LIBDL */
void advance_cursor()
{
static int pos = 0;
char cursor[4] = { '/', '-', '\\', '|' };
if (john_main_process) {
fprintf(stderr, "%c\b", cursor[pos]);
pos = (pos + 1) % 4;
}
}
/* Function pointer to read temperature for device n */
void (*dev_get_temp[MAX_GPU_DEVICES]) (int id, int *temp, int *fanspeed,
int *util, int *cl, int *ml);
/* Map OpenCL device number to ADL/NVML device number */
unsigned int temp_dev_id[MAX_GPU_DEVICES];
void nvidia_probe(void)
{
#if __linux__ && HAVE_LIBDL
if (nvml_lib)
return;
if (!(nvml_lib = dlopen("libnvidia-ml.so", RTLD_LAZY|RTLD_GLOBAL)))
return;
nvmlInit = (NVMLINIT) dlsym(nvml_lib, "nvmlInit");
nvmlShutdown = (NVMLSHUTDOWN) dlsym(nvml_lib, "nvmlShutdown");
nvmlDeviceGetHandleByIndex = (NVMLDEVICEGETHANDLEBYINDEX) dlsym(nvml_lib, "nvmlDeviceGetHandleByIndex");
nvmlDeviceGetTemperature = (NVMLDEVICEGETTEMPERATURE) dlsym(nvml_lib, "nvmlDeviceGetTemperature");
nvmlDeviceGetFanSpeed = (NVMLDEVICEGETFANSPEED) dlsym(nvml_lib, "nvmlDeviceGetFanSpeed");
nvmlDeviceGetUtilizationRates = (NVMLDEVICEGETUTILIZATIONRATES) dlsym(nvml_lib, "nvmlDeviceGetUtilizationRates");
nvmlDeviceGetPciInfo = (NVMLDEVICEGETPCIINFO) dlsym(nvml_lib, "nvmlDeviceGetPciInfo");
nvmlDeviceGetName = (NVMLDEVICEGETNAME) dlsym(nvml_lib, "nvmlDeviceGetName");
nvmlDeviceGetHandleByPciBusId = (NVMLDEVICEGETHANDLEBYPCIBUSID) dlsym(nvml_lib, "nvmlDeviceGetHandleByPciBusId");
nvmlDeviceGetIndex = (NVMLDEVICEGETINDEX) dlsym(nvml_lib, "nvmlDeviceGetIndex");
//nvmlUnitGetCount = (NVMLUNITGETCOUNT) dlsym(nvml_lib, "nvmlUnitGetCount");
nvmlDeviceGetCurrPcieLinkWidth = (NVMLDEVICEGETCURRPCIELINKWIDTH) dlsym(nvml_lib, "nvmlDeviceGetCurrPcieLinkWidth");
nvmlDeviceGetMaxPcieLinkWidth = (NVMLDEVICEGETMAXPCIELINKWIDTH) dlsym(nvml_lib, "nvmlDeviceGetMaxPcieLinkWidth");
nvmlInit();
#endif
}
void amd_probe(void)
{
#if HAVE_LIBDL
LPAdapterInfo lpAdapterInfo = NULL;
int i, ret;
int iNumberAdapters = 0;
int iOverdriveSupported = 0;
int iOverdriveEnabled = 0;
int iOverdriveVersion = 0;
char *env;
if (adl_lib)
return;
#if HAVE_WINDOWS_H
if (!(adl_lib = dlopen("atiadlxx.dll", RTLD_LAZY|RTLD_GLOBAL)) &&
!(adl_lib = dlopen("atiadlxy.dll", RTLD_LAZY|RTLD_GLOBAL)))
return;
#else
if (!(adl_lib = dlopen("libatiadlxx.so", RTLD_LAZY|RTLD_GLOBAL)))
return;
#endif
env = getenv("COMPUTE");
if (env && *env)
setenv("DISPLAY", env, 1);
else {
env = getenv("DISPLAY");
if (!env || !*env)
setenv("DISPLAY", ":0", 1);
}
ADL_Main_Control_Create = (ADL_MAIN_CONTROL_CREATE) dlsym(adl_lib,"ADL_Main_Control_Create");
ADL_Main_Control_Destroy = (ADL_MAIN_CONTROL_DESTROY) dlsym(adl_lib,"ADL_Main_Control_Destroy");
ADL_Adapter_NumberOfAdapters_Get = (ADL_ADAPTER_NUMBEROFADAPTERS_GET) dlsym(adl_lib,"ADL_Adapter_NumberOfAdapters_Get");
ADL_Adapter_AdapterInfo_Get = (ADL_ADAPTER_ADAPTERINFO_GET) dlsym(adl_lib,"ADL_Adapter_AdapterInfo_Get");
ADL_Adapter_Active_Get = (ADL_ADAPTER_ACTIVE_GET)dlsym(adl_lib, "ADL_Adapter_Active_Get");
ADL_Overdrive_Caps = (ADL_OVERDRIVE_CAPS)dlsym(adl_lib, "ADL_Overdrive_Caps");
ADL_Overdrive5_ThermalDevices_Enum = (ADL_OVERDRIVE5_THERMALDEVICES_ENUM) dlsym(adl_lib, "ADL_Overdrive5_ThermalDevices_Enum");
ADL_Overdrive5_Temperature_Get = (ADL_OVERDRIVE5_TEMPERATURE_GET) dlsym(adl_lib, "ADL_Overdrive5_Temperature_Get");
ADL_Overdrive5_FanSpeed_Get = (ADL_OVERDRIVE5_FANSPEED_GET) dlsym(adl_lib, "ADL_Overdrive5_FanSpeed_Get");
ADL_Overdrive5_FanSpeedInfo_Get = (ADL_OVERDRIVE5_FANSPEEDINFO_GET) dlsym(adl_lib, "ADL_Overdrive5_FanSpeedInfo_Get");
ADL_Overdrive5_ODParameters_Get = (ADL_OVERDRIVE5_ODPARAMETERS_GET) dlsym(adl_lib, "ADL_Overdrive5_ODParameters_Get");
ADL_Overdrive5_CurrentActivity_Get = (ADL_OVERDRIVE5_CURRENTACTIVITY_GET) dlsym(adl_lib, "ADL_Overdrive5_CurrentActivity_Get");
ADL_Overdrive6_FanSpeed_Get = (ADL_OVERDRIVE6_FANSPEED_GET) dlsym(adl_lib,"ADL_Overdrive6_FanSpeed_Get");
ADL_Overdrive6_ThermalController_Caps = (ADL_OVERDRIVE6_THERMALCONTROLLER_CAPS)dlsym(adl_lib, "ADL_Overdrive6_ThermalController_Caps");
ADL_Overdrive6_Temperature_Get = (ADL_OVERDRIVE6_TEMPERATURE_GET)dlsym(adl_lib, "ADL_Overdrive6_Temperature_Get");
ADL_Overdrive6_CurrentStatus_Get = (ADL_OVERDRIVE6_CURRENTSTATUS_GET)dlsym(adl_lib, "ADL_Overdrive6_CurrentStatus_Get");
ADL_Overdrive6_Capabilities_Get = (ADL_OVERDRIVE6_CAPABILITIES_GET)dlsym(adl_lib, "ADL_Overdrive6_Capabilities_Get");
if ((ret = ADL_Main_Control_Create(ADL_Main_Memory_Alloc, 1)) != ADL_OK)
return;
// Obtain the number of adapters for the system
if (ADL_Adapter_NumberOfAdapters_Get(&iNumberAdapters) != ADL_OK)
return;
if (iNumberAdapters > 0) {
lpAdapterInfo = (LPAdapterInfo)mem_alloc(sizeof(AdapterInfo) * iNumberAdapters);
memset(lpAdapterInfo,'\0', sizeof(AdapterInfo) * iNumberAdapters);
ADL_Adapter_AdapterInfo_Get(lpAdapterInfo, sizeof(AdapterInfo) * iNumberAdapters);
}
for (i = 0; i < iNumberAdapters; i++) {
int adapterActive = 0;
AdapterInfo adapterInfo = lpAdapterInfo[i];
ADL_Adapter_Active_Get(adapterInfo.iAdapterIndex , &adapterActive);
if (adapterActive) {
int adl_id = adapterInfo.iAdapterIndex;
amd2adl[amd] = adl_id;
adl2od[adl_id] = 0;
gpu_device_bus[amd].bus = adapterInfo.iBusNumber;
gpu_device_bus[amd].device = adapterInfo.iDeviceNumber;
gpu_device_bus[amd].function = adapterInfo.iFunctionNumber;
#if OCL_DEBUG
printf("amd %u adl %u hardware id %02x:%02x.%x\n", amd, adl_id, gpu_device_bus[amd].bus, gpu_device_bus[amd].device,gpu_device_bus[amd].function);
#endif
memset(gpu_device_bus[amd].busId, '\0', sizeof(gpu_device_bus[amd].busId));
sprintf(gpu_device_bus[amd].busId, "%02x:%02x.%x", gpu_device_bus[amd].bus,
gpu_device_bus[amd].device,gpu_device_bus[amd].function);
amd++;
if (ADL_Overdrive_Caps(adl_id, &iOverdriveSupported, &iOverdriveEnabled, &iOverdriveVersion) != ADL_OK) {
MEM_FREE(lpAdapterInfo);
ADL_Main_Control_Destroy();
return;
}
if (!iOverdriveSupported) {
MEM_FREE(lpAdapterInfo);
ADL_Main_Control_Destroy();
return;
}
if (iOverdriveVersion == 5)
adl2od[adl_id] = 5;
else if (iOverdriveVersion == 6)
adl2od[adl_id] = 6;
else
adl2od[adl_id] = 0;
}
}
MEM_FREE(lpAdapterInfo);
ADL_Main_Control_Destroy();
#endif
}
void nvidia_get_temp(int nvml_id, int *temp, int *fanspeed, int *util,
int *cl, int *ml)
{
#if __linux__ && HAVE_LIBDL
nvmlUtilization_t s_util;
nvmlDevice_t dev;
unsigned int value;
if (nvmlDeviceGetHandleByIndex(nvml_id, &dev) != NVML_SUCCESS) {
*temp = *fanspeed = *util = *cl = *ml = -1;
return;
}
if (nvmlDeviceGetTemperature(dev, NVML_TEMPERATURE_GPU, &value) == NVML_SUCCESS)
*temp = value;
else
*temp = -1;
if (nvmlDeviceGetFanSpeed(dev, &value) == NVML_SUCCESS)
*fanspeed = value;
else
*fanspeed = -1;
if (nvmlDeviceGetUtilizationRates(dev, &s_util) == NVML_SUCCESS)
*util = s_util.gpu;
else
*util = -1;
if (nvmlDeviceGetMaxPcieLinkWidth(dev, &value) == NVML_SUCCESS)
*ml = value;
if (nvmlDeviceGetCurrPcieLinkWidth(dev, &value) == NVML_SUCCESS)
*cl = value;
else
*cl = *ml;
if (*ml < *cl)
*ml = *cl;
#endif /* __linux__ && HAVE_LIBDL */
}
#if HAVE_LIBDL
static void get_temp_od5(int adl_id, int *temp, int *fanspeed, int *util,
int *cl, int *ml)
{
int ADL_Err = ADL_ERR;
ADLFanSpeedInfo fanSpeedInfo = { 0 };
int fanSpeedReportingMethod = 0;
int iThermalControllerIndex;
ADLThermalControllerInfo termalControllerInfo = { 0 };
ADLODParameters overdriveParameters = { 0 };
ADLPMActivity activity = { 0 };
if (ADL_Main_Control_Create(ADL_Main_Memory_Alloc, 1) != ADL_OK)
return;
*temp = *fanspeed = *util = *cl = *ml = -1;
if (!ADL_Overdrive5_ThermalDevices_Enum ||
!ADL_Overdrive5_Temperature_Get ||
!ADL_Overdrive5_FanSpeed_Get ||
!ADL_Overdrive5_FanSpeedInfo_Get ||
!ADL_Overdrive5_ODParameters_Get ||
!ADL_Overdrive5_CurrentActivity_Get)
return;
termalControllerInfo.iSize = sizeof(ADLThermalControllerInfo);
for (iThermalControllerIndex = 0; iThermalControllerIndex < 10; iThermalControllerIndex++) {
ADL_Err = ADL_Overdrive5_ThermalDevices_Enum(adl_id, iThermalControllerIndex, &termalControllerInfo);
if (ADL_Err == ADL_WARNING_NO_DATA)
break;
if (termalControllerInfo.iThermalDomain == ADL_DL_THERMAL_DOMAIN_GPU) {
ADLTemperature adlTemperature = { 0 };
ADLFanSpeedValue fanSpeedValue = { 0 };
adlTemperature.iSize = sizeof(ADLTemperature);
if (ADL_Overdrive5_Temperature_Get(adl_id, iThermalControllerIndex, &adlTemperature) == ADL_OK)
*temp = adlTemperature.iTemperature / 1000;
fanSpeedInfo.iSize = sizeof(ADLFanSpeedInfo);
if (ADL_Overdrive5_FanSpeedInfo_Get(adl_id, iThermalControllerIndex, &fanSpeedInfo) == ADL_OK)
if ((fanSpeedReportingMethod = (fanSpeedInfo.iFlags & ADL_DL_FANCTRL_SUPPORTS_PERCENT_READ))) {
fanSpeedValue.iSpeedType = fanSpeedReportingMethod;
if (ADL_Overdrive5_FanSpeed_Get(adl_id, iThermalControllerIndex, &fanSpeedValue) == ADL_OK)
*fanspeed = fanSpeedValue.iFanSpeed;
}
}
}
overdriveParameters.iSize = sizeof(ADLODParameters);
if (ADL_Overdrive5_ODParameters_Get(adl_id, &overdriveParameters) == ADL_OK) {
activity.iSize = sizeof(ADLPMActivity);
if (ADL_Overdrive5_CurrentActivity_Get(adl_id, &activity) == ADL_OK)
if (overdriveParameters.iActivityReportingSupported) {
*util = activity.iActivityPercent;
*cl = activity.iCurrentBusLanes;
*ml = activity.iMaximumBusLanes;
}
}
ADL_Main_Control_Destroy();
return;
}
static void get_temp_od6(int adl_id, int *temp, int *fanspeed, int *util,
int *cl, int *ml)
{
ADLOD6FanSpeedInfo fanSpeedInfo = { 0 };
ADLOD6ThermalControllerCaps thermalControllerCaps = { 0 };
ADLOD6Capabilities od6Capabilities = { 0 };
int temperature = 0;
ADLOD6CurrentStatus currentStatus = { 0 };
if (ADL_Main_Control_Create(ADL_Main_Memory_Alloc, 1) != ADL_OK)
return;
*temp = *fanspeed = *util = -1;
if (!ADL_Overdrive6_FanSpeed_Get ||
!ADL_Overdrive6_ThermalController_Caps ||
!ADL_Overdrive6_Temperature_Get ||
!ADL_Overdrive6_CurrentStatus_Get)
return;
if (ADL_Overdrive6_ThermalController_Caps(adl_id, &thermalControllerCaps) == ADL_OK) {
if (thermalControllerCaps.iCapabilities & ADL_OD6_TCCAPS_FANSPEED_CONTROL)
if (thermalControllerCaps.iCapabilities & ADL_OD6_TCCAPS_FANSPEED_PERCENT_READ)
if (ADL_Overdrive6_FanSpeed_Get(adl_id, &fanSpeedInfo) == ADL_OK)
if (fanSpeedInfo.iSpeedType & ADL_OD6_FANSPEED_TYPE_PERCENT)
*fanspeed = fanSpeedInfo.iFanSpeedPercent;
if (thermalControllerCaps.iCapabilities & ADL_OD6_TCCAPS_THERMAL_CONTROLLER)
if (ADL_Overdrive6_Temperature_Get(adl_id, &temperature) == ADL_OK)
*temp = temperature / 1000;
if (ADL_Overdrive6_Capabilities_Get(adl_id, &od6Capabilities) == ADL_OK)
if (od6Capabilities.iCapabilities & ADL_OD6_CAPABILITY_GPU_ACTIVITY_MONITOR)
if (ADL_Overdrive6_CurrentStatus_Get(adl_id, ¤tStatus) == ADL_OK)
{
*util = currentStatus.iActivityPercent;
*cl = currentStatus.iCurrentBusLanes;
*ml = currentStatus.iMaximumBusLanes;
}
}
ADL_Main_Control_Destroy();
return;
}
#endif
void amd_get_temp(int amd_id, int *temp, int *fanspeed, int *util, int *cl,
int *ml)
{
#if HAVE_LIBDL
int adl_id = amd_id;
if (adl2od[adl_id] == 5) {
get_temp_od5(adl_id, temp, fanspeed, util, cl, ml);
} else if (adl2od[adl_id] == 6) {
get_temp_od6(adl_id, temp, fanspeed, util, cl, ml);
} else
#endif
*temp = *fanspeed = *util = *cl = *ml = -1;
}
int id2nvml(const hw_bus busInfo) {
#if __linux__ && HAVE_LIBDL
nvmlDevice_t dev;
if (nvmlDeviceGetHandleByPciBusId &&
nvmlDeviceGetHandleByPciBusId(busInfo.busId, &dev) == NVML_SUCCESS &&
nvmlDeviceGetIndex)
{
unsigned int id_NVML;
if (nvmlDeviceGetIndex(dev, &id_NVML) == NVML_SUCCESS)
return id_NVML;
}
#endif
return -1;
}
int id2adl(const hw_bus busInfo) {
#if HAVE_LIBDL
int hardware_id = 0;
while (hardware_id < amd) {
if (gpu_device_bus[hardware_id].bus == busInfo.bus &&
gpu_device_bus[hardware_id].device == busInfo.device &&
gpu_device_bus[hardware_id].function == busInfo.function)
return amd2adl[hardware_id];
hardware_id++;
}
#endif
return -1;
}
void gpu_check_temp(void)
{
#if HAVE_LIBDL
static int warned;
int i;
if (gpu_temp_limit < 0)
return;
for (i = 0; i < MAX_GPU_DEVICES && gpu_device_list[i] != -1; i++)
if (dev_get_temp[gpu_device_list[i]]) {
int fan, temp, util, cl, ml;
int dev = gpu_device_list[i];
dev_get_temp[dev](temp_dev_id[dev], &temp, &fan, &util, &cl, &ml);
if (temp > 125 || temp < 10) {
if (!warned++) {
log_event("GPU %d probably invalid temp reading (%d%sC).",
dev, temp, gpu_degree_sign);
fprintf(stderr,
"GPU %d probably invalid temp reading (%d%sC).\n",
dev, temp, gpu_degree_sign);
}
return;
}
if (temp >= gpu_temp_limit) {
char s_fan[16] = "n/a";
if (fan >= 0)
sprintf(s_fan, "%u%%", fan);
if (!event_abort) {
log_event("GPU %d overheat (%d%sC, fan %s), aborting job.",
dev, temp, gpu_degree_sign, s_fan);
fprintf(stderr,
"GPU %d overheat (%d%sC, fan %s), aborting job.\n",
dev, temp, gpu_degree_sign, s_fan);
}
event_abort++;
}
}
#endif
}
void gpu_log_temp(void)
{
#if HAVE_LIBDL
int i;
for (i = 0; i < MAX_GPU_DEVICES && gpu_device_list[i] != -1; i++)
if (dev_get_temp[gpu_device_list[i]]) {
char s_gpu[256] = "";
int n, fan, temp, util, cl, ml;
int dev = gpu_device_list[i];
fan = temp = util = -1;
dev_get_temp[dev](temp_dev_id[dev], &temp, &fan, &util, &cl, &ml);
n = sprintf(s_gpu, "GPU %d:", dev);
if (temp >= 0)
n += sprintf(s_gpu + n, " temp: %u%sC", temp, gpu_degree_sign);
if (util > 0)
n += sprintf(s_gpu + n, " util: %u%%", util);
if (fan >= 0)
n += sprintf(s_gpu + n, " fan: %u%%", fan);
if (temp >= 0 || util > 0 || fan > 0)
log_event("- %s", s_gpu);
}
#endif
}
#endif /* defined (HAVE_OPENCL) */
| 7,518 |
1,056 | <reponame>arusinha/incubator-netbeans<gh_stars>1000+
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.netbeans.modules.xml.tax.beans.editor;
import javax.swing.JPanel;
import org.openide.explorer.propertysheet.editors.EnhancedCustomPropertyEditor;
/**
*
* @author <NAME>
* @version
*/
public class NullStringCustomEditor extends JPanel implements EnhancedCustomPropertyEditor {
/** Serial Version UID */
private static final long serialVersionUID =-7120244860529998751L;
//
// init
//
/** Creates new customizer NullStringCustomEditor */
public NullStringCustomEditor (NullStringEditor editor) {
initComponents ();
textArea.setText (editor.getAsText());
textArea.setEditable (editor.isEditable());
initAccessibility();
}
//
// EnhancedCustomPropertyEditor
//
/**
* @return Returns the property value that is result of the CustomPropertyEditor.
* @exception InvalidStateException when the custom property editor does not represent valid property value
* (and thus it should not be set)
*/
public Object getPropertyValue () throws IllegalStateException {
String text = textArea.getText();
if ( NullStringEditor.DEFAULT_NULL.equals (text) ) {
return null;
} else if ( text.length() == 0 ) {
return null;
} else {
return text;
}
}
//
// form
//
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the FormEditor.
*/
private void initComponents() {//GEN-BEGIN:initComponents
textAreaScroll = new javax.swing.JScrollPane();
textArea = new javax.swing.JTextArea();
setLayout(new java.awt.BorderLayout());
setBorder(new javax.swing.border.EmptyBorder(new java.awt.Insets(6, 6, 6, 6)));
setPreferredSize(new java.awt.Dimension(350, 230));
textAreaScroll.setViewportView(textArea);
add(textAreaScroll, java.awt.BorderLayout.CENTER);
}//GEN-END:initComponents
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JTextArea textArea;
private javax.swing.JScrollPane textAreaScroll;
// End of variables declaration//GEN-END:variables
/** Initialize accesibility
*/
public void initAccessibility(){
this.getAccessibleContext().setAccessibleDescription(Util.THIS.getString("ACSD_NullStringCustomEditor"));
textArea.getAccessibleContext().setAccessibleDescription(Util.THIS.getString("ACSD_textArea"));
}
}
| 1,145 |
12,252 | <reponame>rmartinc/keycloak
/*
D-Bus Java Implementation
Copyright (c) 2005-2006 <NAME>
This program is free software; you can redistribute it and/or modify it
under the terms of either the GNU Lesser General Public License Version 2 or the
Academic Free Licence Version 2.1.
Full licence texts are included in the COPYING file with this program.
*/
package org.freedesktop.dbus;
import java.lang.reflect.Field;
import java.lang.reflect.Type;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
/**
* This class is the super class of both Structs and Tuples
* and holds common methods.
*/
abstract class Container {
private static Map<Type, Type[]> typecache = new HashMap<Type, Type[]>();
static void putTypeCache(Type k, Type[] v) {
typecache.put(k, v);
}
static Type[] getTypeCache(Type k) {
return typecache.get(k);
}
private Object[] parameters = null;
public Container() {
}
private void setup() {
Field[] fs = getClass().getDeclaredFields();
Object[] args = new Object[fs.length];
int diff = 0;
for (Field f : fs) {
Position p = f.getAnnotation(Position.class);
if (null == p) {
diff++;
continue;
}
try {
args[p.value()] = f.get(this);
} catch (IllegalAccessException IAe) {
}
}
this.parameters = new Object[args.length - diff];
System.arraycopy(args, 0, parameters, 0, parameters.length);
}
/**
* Returns the struct contents in order.
*
* @throws DBusException If there is a problem doing this.
*/
public final Object[] getParameters() {
if (null != parameters) return parameters;
setup();
return parameters;
}
/**
* Returns this struct as a string.
*/
public final String toString() {
String s = getClass().getName() + "<";
if (null == parameters)
setup();
if (0 == parameters.length)
return s + ">";
for (Object o : parameters)
s += o + ", ";
return s.replaceAll(", $", ">");
}
public final boolean equals(Object other) {
if (other instanceof Container) {
Container that = (Container) other;
if (this.getClass().equals(that.getClass()))
return Arrays.equals(this.getParameters(), that.getParameters());
else return false;
} else return false;
}
}
| 1,063 |
335 | <filename>P/Playback_noun.json
{
"word": "Playback",
"definitions": [
"The reproduction of previously recorded sounds or moving images.",
"A pre-recorded musical soundtrack mimed to by an actor."
],
"parts-of-speech": "Noun"
} | 97 |
1,380 | <gh_stars>1000+
/*
* sophia database
* sphia.org
*
* Copyright (c) <NAME>
* BSD License
*/
#include <libss.h>
#include <libsf.h>
#include <libsr.h>
#include <libso.h>
#include <libsv.h>
#include <libsd.h>
#include <libsi.h>
static int
si_redistribute(si *index, sr *r, sdc *c, sinode *node, ssbuf *result)
{
(void)index;
int rc;
svindex *vindex = si_nodeindex(node);
ssiter i;
ss_iterinit(sv_indexiter, &i);
ss_iteropen(sv_indexiter, &i, r, vindex, SS_GTE, NULL);
while (ss_iterhas(sv_indexiter, &i))
{
svv *v = sv_vv(ss_iterof(sv_indexiter, &i));
rc = ss_bufadd(&c->b, r->a, &v, sizeof(svv**));
if (ssunlikely(rc == -1))
return sr_oom_malfunction(r->e);
ss_iternext(sv_indexiter, &i);
}
if (ssunlikely(ss_bufused(&c->b) == 0))
return 0;
ss_iterinit(ss_bufiterref, &i);
ss_iteropen(ss_bufiterref, &i, &c->b, sizeof(svv*));
ssiter j;
ss_iterinit(ss_bufiterref, &j);
ss_iteropen(ss_bufiterref, &j, result, sizeof(sinode*));
sinode *prev = ss_iterof(ss_bufiterref, &j);
ss_iternext(ss_bufiterref, &j);
while (1)
{
sinode *p = ss_iterof(ss_bufiterref, &j);
if (p == NULL) {
assert(prev != NULL);
while (ss_iterhas(ss_bufiterref, &i)) {
svv *v = ss_iterof(ss_bufiterref, &i);
v->next = NULL;
sv_indexset(&prev->i0, r, v);
ss_iternext(ss_bufiterref, &i);
}
break;
}
while (ss_iterhas(ss_bufiterref, &i))
{
svv *v = ss_iterof(ss_bufiterref, &i);
v->next = NULL;
sdindexpage *page = sd_indexmin(&p->index);
rc = sf_compare(r->scheme, sv_vpointer(v),
sd_indexpage_min(&p->index, page));
if (ssunlikely(rc >= 0))
break;
sv_indexset(&prev->i0, r, v);
ss_iternext(ss_bufiterref, &i);
}
if (ssunlikely(! ss_iterhas(ss_bufiterref, &i)))
break;
prev = p;
ss_iternext(ss_bufiterref, &j);
}
assert(ss_iterof(ss_bufiterref, &i) == NULL);
return 0;
}
static inline void
si_redistribute_set(si *index, sr *r, svv *v)
{
/* match node */
ssiter i;
ss_iterinit(si_iter, &i);
ss_iteropen(si_iter, &i, r, index, SS_GTE, sv_vpointer(v));
sinode *node = ss_iterof(si_iter, &i);
assert(node != NULL);
/* update node */
svindex *vindex = si_nodeindex(node);
sv_indexset(vindex, r, v);
node->used += sv_vsize(v, &index->r);
/* schedule node */
si_plannerupdate(&index->p, node);
}
static int
si_redistribute_index(si *index, sr *r, sdc *c, sinode *node)
{
svindex *vindex = si_nodeindex(node);
ssiter i;
ss_iterinit(sv_indexiter, &i);
ss_iteropen(sv_indexiter, &i, r, vindex, SS_GTE, NULL);
while (ss_iterhas(sv_indexiter, &i)) {
svv *v = sv_vv(ss_iterof(sv_indexiter, &i));
int rc = ss_bufadd(&c->b, r->a, &v, sizeof(svv**));
if (ssunlikely(rc == -1))
return sr_oom_malfunction(r->e);
ss_iternext(sv_indexiter, &i);
}
if (ssunlikely(ss_bufused(&c->b) == 0))
return 0;
ss_iterinit(ss_bufiterref, &i);
ss_iteropen(ss_bufiterref, &i, &c->b, sizeof(svv*));
while (ss_iterhas(ss_bufiterref, &i)) {
svv *v = ss_iterof(ss_bufiterref, &i);
v->next = NULL;
si_redistribute_set(index, r, v);
ss_iternext(ss_bufiterref, &i);
}
return 0;
}
static int
si_splitfree(ssbuf *result, sr *r)
{
ssiter i;
ss_iterinit(ss_bufiterref, &i);
ss_iteropen(ss_bufiterref, &i, result, sizeof(sinode*));
while (ss_iterhas(ss_bufiterref, &i))
{
sinode *p = ss_iterof(ss_bufiterref, &i);
si_nodefree(p, r, 0);
ss_iternext(ss_bufiterref, &i);
}
return 0;
}
static inline int
si_split(si *index, sdc *c, ssbuf *result,
sinode *parent,
ssiter *i,
uint64_t size_node,
uint64_t size_stream,
uint32_t stream,
uint64_t vlsn)
{
sr *r = &index->r;
uint32_t timestamp = ss_timestamp();
int rc;
sdmergeconf mergeconf = {
.stream = stream,
.size_stream = size_stream,
.size_node = size_node,
.size_page = index->scheme.compaction.node_page_size,
.checksum = index->scheme.compaction.node_page_checksum,
.expire = index->scheme.expire,
.timestamp = timestamp,
.compression = index->scheme.compression,
.compression_if = index->scheme.compression_if,
.direct_io = index->scheme.direct_io,
.direct_io_page_size = index->scheme.direct_io_page_size,
.vlsn = vlsn
};
sinode *n = NULL;
sdmerge merge;
rc = sd_mergeinit(&merge, r, i, &c->build, &c->build_index,
&c->upsert, &mergeconf);
if (ssunlikely(rc == -1))
return -1;
while ((rc = sd_merge(&merge)) > 0)
{
/* create new node */
uint64_t id = sr_seq(index->r.seq, SR_NSNNEXT);
n = si_nodenew(r, id, parent->id);
if (ssunlikely(n == NULL))
goto error;
rc = si_nodecreate(n, r, &index->scheme);
if (ssunlikely(rc == -1))
goto error;
/* write pages */
uint64_t offset;
offset = sd_iosize(&c->io, &n->file);
while ((rc = sd_mergepage(&merge, offset)) == 1) {
rc = sd_writepage(r, &n->file, &c->io, merge.build);
if (ssunlikely(rc == -1))
goto error;
offset = sd_iosize(&c->io, &n->file);
}
if (ssunlikely(rc == -1))
goto error;
offset = sd_iosize(&c->io, &n->file);
rc = sd_mergeend(&merge, offset);
if (ssunlikely(rc == -1))
goto error;
/* write index */
rc = sd_writeindex(r, &n->file, &c->io, &merge.index);
if (ssunlikely(rc == -1))
goto error;
/* mmap mode */
if (index->scheme.mmap) {
rc = si_nodemap(n, r);
if (ssunlikely(rc == -1))
goto error;
}
/* add node to the list */
rc = ss_bufadd(result, index->r.a, &n, sizeof(sinode*));
if (ssunlikely(rc == -1)) {
sr_oom_malfunction(index->r.e);
goto error;
}
n->index = merge.index;
}
if (ssunlikely(rc == -1))
goto error;
return 0;
error:
if (n)
si_nodefree(n, r, 0);
sd_mergefree(&merge);
si_splitfree(result, r);
return -1;
}
static int
si_merge(si *index, sdc *c, sinode *node,
uint64_t vlsn,
ssiter *stream,
uint64_t size_stream,
uint32_t n_stream)
{
sr *r = &index->r;
ssbuf *result = &c->a;
ssiter i;
/* begin compaction.
*
* Split merge stream into a number of
* a new nodes.
*/
int rc;
rc = si_split(index, c, result,
node, stream,
index->scheme.compaction.node_size,
size_stream,
n_stream,
vlsn);
if (ssunlikely(rc == -1))
return -1;
SS_INJECTION(r->i, SS_INJECTION_SI_COMPACTION_0,
si_splitfree(result, r);
sr_malfunction(r->e, "%s", "error injection");
return -1);
/* mask removal of a single node as a
* single node update */
int count = ss_bufused(result) / sizeof(sinode*);
int count_index;
si_lock(index);
count_index = index->n;
si_unlock(index);
sinode *n;
if (ssunlikely(count == 0 && count_index == 1))
{
n = si_bootstrap(index, node->id);
if (ssunlikely(n == NULL))
return -1;
rc = ss_bufadd(result, r->a, &n, sizeof(sinode*));
if (ssunlikely(rc == -1)) {
sr_oom_malfunction(r->e);
si_nodefree(n, r, 1);
return -1;
}
count++;
}
/* commit compaction changes */
si_lock(index);
svindex *j = si_nodeindex(node);
si_plannerremove(&index->p, node);
si_nodesplit(node);
switch (count) {
case 0: /* delete */
si_remove(index, node);
si_redistribute_index(index, r, c, node);
break;
case 1: /* self update */
n = *(sinode**)result->s;
n->i0 = *j;
n->used = j->used;
si_nodelock(n);
si_replace(index, node, n);
si_plannerupdate(&index->p, n);
break;
default: /* split */
rc = si_redistribute(index, r, c, node, result);
if (ssunlikely(rc == -1)) {
si_unlock(index);
si_splitfree(result, r);
return -1;
}
ss_iterinit(ss_bufiterref, &i);
ss_iteropen(ss_bufiterref, &i, result, sizeof(sinode*));
n = ss_iterof(ss_bufiterref, &i);
n->used = n->i0.used;
si_nodelock(n);
si_replace(index, node, n);
si_plannerupdate(&index->p, n);
for (ss_iternext(ss_bufiterref, &i); ss_iterhas(ss_bufiterref, &i);
ss_iternext(ss_bufiterref, &i)) {
n = ss_iterof(ss_bufiterref, &i);
n->used = n->i0.used;
si_nodelock(n);
si_insert(index, n);
si_plannerupdate(&index->p, n);
}
break;
}
sv_indexinit(j);
si_unlock(index);
/* compaction completion */
/* seal nodes */
ss_iterinit(ss_bufiterref, &i);
ss_iteropen(ss_bufiterref, &i, result, sizeof(sinode*));
while (ss_iterhas(ss_bufiterref, &i))
{
n = ss_iterof(ss_bufiterref, &i);
if (index->scheme.sync) {
rc = ss_filesync(&n->file);
if (ssunlikely(rc == -1)) {
sr_malfunction(r->e, "db file '%s' sync error: %s",
ss_pathof(&n->file.path),
strerror(errno));
return -1;
}
}
rc = si_noderename_seal(n, r, &index->scheme);
if (ssunlikely(rc == -1)) {
si_nodefree(node, r, 0);
return -1;
}
SS_INJECTION(r->i, SS_INJECTION_SI_COMPACTION_3,
si_nodefree(node, r, 0);
sr_malfunction(r->e, "%s", "error injection");
return -1);
ss_iternext(ss_bufiterref, &i);
}
SS_INJECTION(r->i, SS_INJECTION_SI_COMPACTION_1,
si_nodefree(node, r, 0);
sr_malfunction(r->e, "%s", "error injection");
return -1);
/* gc node */
uint16_t refs = si_noderefof(node);
if (sslikely(refs == 0)) {
rc = si_nodefree(node, r, 1);
if (ssunlikely(rc == -1))
return -1;
} else {
/* node concurrently being read, schedule for
* delayed removal */
si_nodegc(node, r, &index->scheme);
si_lock(index);
ss_listappend(&index->gc, &node->gc);
index->gc_count++;
si_unlock(index);
}
SS_INJECTION(r->i, SS_INJECTION_SI_COMPACTION_2,
sr_malfunction(r->e, "%s", "error injection");
return -1);
/* complete new nodes */
ss_iterinit(ss_bufiterref, &i);
ss_iteropen(ss_bufiterref, &i, result, sizeof(sinode*));
while (ss_iterhas(ss_bufiterref, &i))
{
n = ss_iterof(ss_bufiterref, &i);
rc = si_noderename_complete(n, r, &index->scheme);
if (ssunlikely(rc == -1))
return -1;
SS_INJECTION(r->i, SS_INJECTION_SI_COMPACTION_4,
sr_malfunction(r->e, "%s", "error injection");
return -1);
ss_iternext(ss_bufiterref, &i);
}
/* unlock */
si_lock(index);
ss_iterinit(ss_bufiterref, &i);
ss_iteropen(ss_bufiterref, &i, result, sizeof(sinode*));
while (ss_iterhas(ss_bufiterref, &i))
{
n = ss_iterof(ss_bufiterref, &i);
si_nodeunlock(n);
ss_iternext(ss_bufiterref, &i);
}
si_unlock(index);
return 0;
}
int si_compaction(si *index, sdc *c, siplan *plan, uint64_t vlsn)
{
sr *r = &index->r;
sinode *node = plan->node;
assert(node->flags & SI_LOCK);
si_lock(index);
svindex *vindex;
vindex = si_noderotate(node);
si_unlock(index);
uint64_t size_stream = vindex->used;
ssiter vindex_iter;
ss_iterinit(sv_indexiter, &vindex_iter);
ss_iteropen(sv_indexiter, &vindex_iter, &index->r, vindex, SS_GTE, NULL);
/* prepare direct_io stream */
int rc;
if (index->scheme.direct_io) {
rc = sd_ioprepare(&c->io, r,
index->scheme.direct_io,
index->scheme.direct_io_page_size,
index->scheme.direct_io_buffer_size);
if (ssunlikely(rc == -1))
return sr_oom(r->e);
}
/* prepare for compaction */
svmerge merge;
sv_mergeinit(&merge);
rc = sv_mergeprepare(&merge, r, 1 + 1);
if (ssunlikely(rc == -1))
return -1;
svmergesrc *s;
s = sv_mergeadd(&merge, &vindex_iter);
sdcbuf *cbuf = &c->e;
s = sv_mergeadd(&merge, NULL);
sdreadarg arg = {
.from_compaction = 1,
.io = &c->io,
.index = &node->index,
.buf = &cbuf->a,
.buf_read = &c->d,
.index_iter = &cbuf->index_iter,
.page_iter = &cbuf->page_iter,
.use_mmap = index->scheme.mmap,
.use_mmap_copy = 0,
.use_compression = index->scheme.compression,
.use_direct_io = index->scheme.direct_io,
.direct_io_page_size = index->scheme.direct_io_page_size,
.compression_if = index->scheme.compression_if,
.has = 0,
.has_vlsn = 0,
.o = SS_GTE,
.mmap = &node->map,
.file = &node->file,
.r = r
};
ss_iterinit(sd_read, &s->src);
rc = ss_iteropen(sd_read, &s->src, &arg, NULL);
if (ssunlikely(rc == -1))
return -1;
size_stream += sd_indextotal(&node->index);
ssiter i;
ss_iterinit(sv_mergeiter, &i);
ss_iteropen(sv_mergeiter, &i, r, &merge, SS_GTE);
rc = si_merge(index, c, node, vlsn, &i, size_stream,
sd_indexkeys(&node->index));
sv_mergefree(&merge, r->a);
return rc;
}
| 6,331 |
480 | /*
* Copyright [2013-2021], Alibaba Group Holding Limited
*
* 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.alibaba.polardbx.executor.sync;
import com.alibaba.polardbx.executor.cursor.ResultCursor;
import com.alibaba.polardbx.executor.cursor.impl.ArrayResultCursor;
import com.alibaba.polardbx.optimizer.core.datatype.DataTypes;
import com.alibaba.polardbx.optimizer.sequence.SequenceManagerProxy;
import static com.alibaba.polardbx.common.constants.SequenceAttribute.GROUP_SEQ_MIN_VALUE;
public class InspectGroupSeqMinValueSyncAction implements ISyncAction {
private String seqName;
private String schemaName;
public InspectGroupSeqMinValueSyncAction() {
}
public InspectGroupSeqMinValueSyncAction(String schemaName, String seqName) {
this.schemaName = schemaName;
this.seqName = seqName;
}
@Override
public ResultCursor sync() {
ArrayResultCursor resultCursor = new ArrayResultCursor("GROUP_SEQ_MIN_VALUE");
resultCursor.addColumn(GROUP_SEQ_MIN_VALUE, DataTypes.LongType);
resultCursor.initMeta();
Long minValue = SequenceManagerProxy.getInstance().getMinValueFromCurrentSeqRange(schemaName, seqName);
resultCursor.addRow(new Object[] {minValue});
return resultCursor;
}
public String getSeqName() {
return seqName;
}
public void setSeqName(String seqName) {
this.seqName = seqName;
}
public String getSchemaName() {
return schemaName;
}
public void setSchemaName(String schemaName) {
this.schemaName = schemaName;
}
}
| 721 |
450 | package com.pivotal.hawq.mapreduce.ao;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import com.pivotal.hawq.mapreduce.conf.HAWQConfiguration;
import com.pivotal.hawq.mapreduce.HAWQException;
import com.pivotal.hawq.mapreduce.HAWQRecord;
import com.pivotal.hawq.mapreduce.ao.io.HAWQAOFileReader;
import com.pivotal.hawq.mapreduce.ao.io.HAWQAORecord;
import com.pivotal.hawq.mapreduce.schema.HAWQSchema;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.mapreduce.InputSplit;
import org.apache.hadoop.mapreduce.RecordReader;
import org.apache.hadoop.mapreduce.TaskAttemptContext;
import java.io.IOException;
/**
* The record reader breaks the data into key/value pairs for input to mapper.
*/
public class HAWQAORecordReader extends RecordReader<Void, HAWQRecord>
{
private HAWQRecord value = null;
private HAWQAOFileReader filereader = null;
private boolean more = true;
/**
* Close the record reader.
*/
@Override
public void close() throws IOException
{
filereader.close();
}
/**
* Get the current key
*
* @return the current key or null if there is no current key
* @throws IOException
* @throws InterruptedException
*/
@Override
public Void getCurrentKey() throws IOException, InterruptedException
{
// Always null
return null;
}
/**
* Get the current value.
*
* @return the object that was read
* @throws IOException
* @throws InterruptedException
*/
@Override
public HAWQRecord getCurrentValue() throws IOException,
InterruptedException
{
return value;
}
/**
* The current progress of the record reader through its data.
*
* @return a number between 0.0 and 1.0 that is the fraction of the data
* read
* @throws IOException
* @throws InterruptedException
*/
@Override
public float getProgress() throws IOException, InterruptedException
{
return more ? 0f : 100f;
}
/**
* Called once at initialization.
*
* @param split
* the split that defines the range of records to read
* @param context
* the information about the task
* @throws IOException
* @throws InterruptedException
*/
@Override
public void initialize(InputSplit split, TaskAttemptContext context)
throws IOException, InterruptedException
{
// initialize the value
Configuration conf = context.getConfiguration();
// Extract the parameters needed by HAWQAOFileReader and HAWQAORecord
String encoding = HAWQConfiguration.getInputTableEncoding(conf);
HAWQSchema schema = HAWQConfiguration.getInputTableSchema(conf);
/*
* GPSQL-1047
*
* Get version from configuration and init HAWQAORecord with it
*/
String version = HAWQConfiguration.getDatabaseVersion(conf);
filereader = new HAWQAOFileReader(conf, split);
try
{
value = new HAWQAORecord(schema, encoding, version);
}
catch (HAWQException hawqE)
{
throw new IOException(hawqE.getMessage());
}
}
/**
* Read the next key, value pair.
*
* @return true if a key/value pair was read
* @throws IOException
* @throws InterruptedException
*/
@Override
public boolean nextKeyValue() throws IOException, InterruptedException
{
try
{
if (filereader.readRecord((HAWQAORecord) value))
{
return true;
}
}
catch (HAWQException hawqE)
{
throw new IOException(hawqE.getMessage());
}
more = false;
return false;
}
}
| 1,379 |
372 | from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
import yaml
from .kms import kms_simple_constructor
yaml.add_constructor('!kms', kms_simple_constructor)
| 65 |
348 | <reponame>chamberone/Leaflet.PixiOverlay
{"nom":"Mérindol","circ":"2ème circonscription","dpt":"Vaucluse","inscrits":1648,"abs":836,"votants":812,"blancs":18,"nuls":6,"exp":788,"res":[{"nuance":"REM","nom":"Mme <NAME>","voix":204},{"nuance":"LR","nom":"<NAME>","voix":183},{"nuance":"FN","nom":"<NAME>","voix":145},{"nuance":"SOC","nom":"M. <NAME>","voix":123},{"nuance":"FI","nom":"<NAME>","voix":72},{"nuance":"DLF","nom":"M. <NAME>","voix":21},{"nuance":"ECO","nom":"M. <NAME>","voix":19},{"nuance":"ECO","nom":"Mme <NAME>","voix":17},{"nuance":"DIV","nom":"Mme <NAME>","voix":3},{"nuance":"EXG","nom":"Mme <NAME>","voix":1}]} | 261 |
764 | {
"symbol": "ECU",
"address": "0xd3CDc4e75750DC1e59F8342200742B6B29490e70",
"overview":{
"en": "We at ECU are introducing an alternative to the current instabilities of cryptos with a token that will not depend on current BTC price thereby giving confidence to its holders and users that Decurian will always have a value in both digital and real worlds. Decurian will have an upper hand on most crypto assets because of it’s primary use as the sole token accepted by the meagainstu.com site.",
"zh": ""
},
"email": "<EMAIL>",
"website": "https://ecucoins.com",
"state": "NORMAL",
"published_on": "2019-12-11",
"initial_price":{
"ETH":"",
"USD":"5 USD",
"BTC":""
},
"links": {
"facebook": "https://www.facebook.com/decuriancrypto",
"twitter": "https://twitter.com/DecurianCrypto",
"telegram": "",
"github": "",
"reddit": "",
"medium": "",
"discord": ""
}
}
| 409 |
2,201 | <filename>cpp/lib/ApprovalTests.hpp<gh_stars>1000+
#ifndef APPROVAL_TEST_1_APPROVALTESTS_HPP
#define APPROVAL_TEST_1_APPROVALTESTS_HPP
#include "ApprovalTests.v.6.0.0.hpp"
#endif
| 89 |
1,068 | <filename>examples/imagenet-transfer-learning/register.py
from azureml.core import Workspace
from azureml.core.model import Model
from azureml.core import Run
import argparse
import json
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument(
'--dataset_name',
type=str,
default='',
help='Variant name you want to give to the model.'
)
parser.add_argument(
'--model_assets_path',
type=str,
default='outputs',
help='Location of trained model.'
)
args,unparsed = parser.parse_known_args()
print('dataset is '+args.dataset_name)
modelName = 'mn.'+args.dataset_name
run = Run.get_context()
ws = run.experiment.workspace
tags = {
"runId":str(run.id),
"trainingDataSet":args.dataset_name
}
print(args.model_assets_path)
print(json.dumps(tags))
model = Model.register(ws, model_name = modelName, model_path = args.model_assets_path, tags=tags)
print('Model registered: {} \nModel Description: {} \nModel Version: {}'.format(model.name, model.description, model.version)) | 427 |
432 | [
{
"slug": "gauntlt",
"name": "Gauntlt",
"description": "Gauntlt provides hooks to a variety of security tools and puts them within reach of security, dev and ops teams to collaborate to build rugged software. It is built to facilitate testing and communication between groups and create actionable tests that can be hooked into your deploy and testing processes.",
"tags": [
"linux",
"open-source",
"security",
"hardening",
"ruby"
],
"url": "http://gauntlt.org/"
}
]
| 176 |
360 | <gh_stars>100-1000
/*
* Copyright (c) 2020 Huawei Technologies Co.,Ltd.
*
* openGauss is licensed under Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
* -------------------------------------------------------------------------
*
* plan_tree_model.h
*
* IDENTIFICATION
* src/include/optimizer/ml_model.h
*
* DESCRIPTION
* Declaration of externel APIs of Code/src/backend/utils/learn/plan_tree_model.cpp
*
* -------------------------------------------------------------------------
*/
#ifndef PLAN_TREE_MODEL_H
#define PLAN_TREE_MODEL_H
#include "postgres.h"
extern char* TreeModelTrain(Form_gs_opt_model modelinfo, char* labels);
extern char* TreeModelPredict(const char* modelName, char* filepath, const char* ip, int port);
#define ParseConfigBuf(buf, conninfo, msg_str) \
do { \
pfree_ext(buf); \
DestroyConnInfo(conninfo); \
ereport(ERROR, (errmodule(MOD_OPT_AI), errcode(ERRCODE_UNEXPECTED_NODE_STATE), errmsg(msg_str))); \
} while (0)
#define ParseResBuf(buf, filename, msg_str) \
do { \
pfree_ext(buf); \
if ((filename) != NULL) { \
Unlinkfile(filename); \
} \
ereport(ERROR, (errmodule(MOD_OPT_AI), errcode(ERRCODE_UNEXPECTED_NODE_STATE), errmsg(msg_str))); \
} while (0)
#endif /* PLAN_TREE_MODEL_H */ | 1,422 |
17,337 | <reponame>SSYSS000/Proton
#include <stdarg.h>
#include <stdlib.h>
#include <stdio.h>
#include <dlfcn.h>
#include <limits.h>
#include <stdint.h>
#include "windef.h"
#include "winbase.h"
#include "winnls.h"
#include "wine/debug.h"
#include "vrclient_defs.h"
#include "vrclient_private.h"
#include "initguid.h"
#define COBJMACROS
#include "d3d11_4.h"
#ifdef VRCLIENT_HAVE_DXVK
#include "dxvk-interop.h"
#endif
#include "wined3d-interop.h"
#include "flatapi.h"
#include "cppIVRClientCore_IVRClientCore_003.h"
#include "cppIVRCompositor_IVRCompositor_021.h"
#include "cppIVRCompositor_IVRCompositor_022.h"
/* 0918 is binary compatible with 1015 */
typedef struct winRenderModel_t_0918 winRenderModel_t_0918;
typedef struct winRenderModel_TextureMap_t_0918 winRenderModel_TextureMap_t_0918;
#include "cppIVRRenderModels_IVRRenderModels_004.h"
typedef struct winRenderModel_t_1015 winRenderModel_t_1015;
typedef struct winRenderModel_TextureMap_t_1015 winRenderModel_TextureMap_t_1015;
#include "cppIVRRenderModels_IVRRenderModels_005.h"
/* this is cast to 1015 during load_linux_texture_map, so ensure they're
* binary compatible before updating this number */
typedef struct winRenderModel_t_1168 winRenderModel_t_1168;
typedef struct winRenderModel_TextureMap_t_1168 winRenderModel_TextureMap_t_1168;
#include "cppIVRRenderModels_IVRRenderModels_006.h"
#define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0]))
WINE_DEFAULT_DEBUG_CHANNEL(vrclient);
static void *vrclient_lib;
static struct
{
ID3D11Device *d3d11_device;
IWineD3D11Device *wined3d_device;
#ifdef VRCLIENT_HAVE_DXVK
IDXGIVkInteropDevice *dxvk_device;
#endif
BOOL d3d11_explicit_handoff, handoff_called;
void *client_core_linux_side;
#ifndef __x86_64__
/* Digital action state change fixup hack. */
struct
{
VRActionHandle_t action;
VRInputValueHandle_t origin;
LARGE_INTEGER update_qpf_time;
BOOL previous_state;
}
digital_actions_state[128];
unsigned int digital_action_count;
LARGE_INTEGER qpf_freq;
#endif
}
compositor_data;
BOOL WINAPI DllMain(HINSTANCE instance, DWORD reason, void *reserved)
{
TRACE("(%p, %u, %p)\n", instance, reason, reserved);
switch (reason)
{
case DLL_PROCESS_ATTACH:
DisableThreadLibraryCalls(instance);
break;
case DLL_PROCESS_DETACH:
if (vrclient_lib)
{
if (compositor_data.client_core_linux_side)
{
cppIVRClientCore_IVRClientCore_003_Cleanup(compositor_data.client_core_linux_side);
compositor_data.client_core_linux_side = NULL;
}
dlclose(vrclient_lib);
vrclient_lib = NULL;
}
break;
}
return TRUE;
}
/* returns the number of bytes written to dst, not including the NUL terminator */
unsigned int vrclient_unix_path_to_dos_path(bool api_result, const char *src, char *dst, uint32_t dst_bytes)
{
WCHAR *dosW;
uint32_t r;
if(!dst || !dst_bytes)
return 0;
if(!src || !api_result){
*dst = 0;
return 0;
}
dosW = wine_get_dos_file_name(src);
*dst = 0;
if(!dosW){
WARN("Unable to convert unix filename to DOS: %s\n", src);
return 0;
}
r = WideCharToMultiByte(CP_ACP, 0, dosW, -1, dst, dst_bytes,
NULL, NULL);
HeapFree(GetProcessHeap(), 0, dosW);
return r == 0 ? 0 : r - 1;
}
#define IS_ABSOLUTE(x) (*x == '/' || *x == '\\' || (*x && *(x + 1) == ':'))
/* returns non-zero on success, zero on failure */
bool vrclient_dos_path_to_unix_path(const char *src, char *dst)
{
*dst = 0;
if(!src || !*src)
return 0;
if(IS_ABSOLUTE(src)){
/* absolute path, use wine conversion */
WCHAR srcW[PATH_MAX];
char *unix_path;
uint32_t r;
r = MultiByteToWideChar(CP_UNIXCP, 0, src, -1, srcW, PATH_MAX);
if(r == 0)
return 0;
unix_path = wine_get_unix_file_name(srcW);
if(!unix_path){
WARN("Unable to convert DOS filename to unix: %s\n", src);
return 0;
}
if (!realpath(unix_path, dst))
{
ERR("Could not get real path for %s.\n", unix_path);
strncpy(dst, unix_path, PATH_MAX);
}
HeapFree(GetProcessHeap(), 0, unix_path);
}else{
/* relative path, just fix up backslashes */
const char *s;
char *d;
for(s = src, d = dst; *src; ++s, ++d){
if(*s == '\\')
*d = '/';
else
*d = *s;
}
*d = 0;
}
return 1;
}
static BOOL array_reserve(void **elements, SIZE_T *capacity, SIZE_T count, SIZE_T size)
{
SIZE_T max_capacity, new_capacity;
void *new_elements;
if (count <= *capacity)
return TRUE;
max_capacity = ~(SIZE_T)0 / size;
if (count > max_capacity)
return FALSE;
new_capacity = max(1, *capacity);
while (new_capacity < count && new_capacity <= max_capacity / 2)
new_capacity *= 2;
if (new_capacity < count)
new_capacity = count;
if (!*elements)
new_elements = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, new_capacity * size);
else
new_elements = HeapReAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, *elements, new_capacity * size);
if (!new_elements)
return FALSE;
*elements = new_elements;
*capacity = new_capacity;
return TRUE;
}
#include "win_constructors.h"
#include "win_destructors.h"
typedef void (*pfn_dtor)(void *);
static const struct {
const char *iface_version;
void *(*ctor)(void *);
void (*dtor)(void *);
} constructors[] = {
#include "win_constructors_table.dat"
};
void *create_win_interface(const char *name, void *linux_side)
{
unsigned int i;
TRACE("trying to create %s\n", name);
if(!linux_side)
return NULL;
for(i = 0; i < sizeof(constructors) / sizeof(*constructors); ++i){
if(!strcmp(name, constructors[i].iface_version))
return constructors[i].ctor(linux_side);
}
ERR("Don't recognize interface name: %s\n", name);
return NULL;
}
static pfn_dtor get_win_destructor(const char *name)
{
unsigned int i;
for(i = 0; i < sizeof(constructors) / sizeof(*constructors); ++i){
if(!strcmp(name, constructors[i].iface_version))
return constructors[i].dtor;
}
return NULL;
}
static void *(*vrclient_HmdSystemFactory)(const char *name, int *return_code);
static void *(*vrclient_VRClientCoreFactory)(const char *name, int *return_code);
static int load_vrclient(void)
{
WCHAR pathW[PATH_MAX];
char *pathU;
DWORD sz;
#ifdef _WIN64
static const char append_path[] = "/bin/linux64/vrclient.so";
#else
static const char append_path[] = "/bin/vrclient.so";
#endif
if(vrclient_lib)
return 1;
/* PROTON_VR_RUNTIME is provided by the proton setup script */
if(!GetEnvironmentVariableW(L"PROTON_VR_RUNTIME", pathW, ARRAY_SIZE(pathW)))
{
TRACE("Linux OpenVR runtime is not available\n");
return 0;
}
sz = WideCharToMultiByte(CP_UNIXCP, 0, pathW, -1, NULL, 0, NULL, NULL);
if(!sz)
{
ERR("Can't convert path to unixcp! %s\n", wine_dbgstr_w(pathW));
return 0;
}
pathU = HeapAlloc(GetProcessHeap(), 0, sz + sizeof(append_path));
sz = WideCharToMultiByte(CP_UNIXCP, 0, pathW, -1, pathU, sz, NULL, NULL);
if(!sz)
{
ERR("Can't convert path to unixcp! %s\n", wine_dbgstr_w(pathW));
return 0;
}
strcat(pathU, append_path);
TRACE("got openvr runtime path: %s\n", pathU);
vrclient_lib = dlopen(pathU, RTLD_NOW);
if(!vrclient_lib){
TRACE("unable to load vrclient.so\n");
return 0;
}
vrclient_HmdSystemFactory = dlsym(vrclient_lib, "HmdSystemFactory");
if(!vrclient_HmdSystemFactory){
ERR("unable to load HmdSystemFactory method\n");
return 0;
}
vrclient_VRClientCoreFactory = dlsym(vrclient_lib, "VRClientCoreFactory");
if(!vrclient_VRClientCoreFactory){
ERR("unable to load VRClientCoreFactory method\n");
return 0;
}
return 1;
}
void *CDECL HmdSystemFactory(const char *name, int *return_code)
{
TRACE("name: %s, return_code: %p\n", name, return_code);
if(!load_vrclient())
return NULL;
return create_win_interface(name, vrclient_HmdSystemFactory(name, return_code));
}
void *CDECL VRClientCoreFactory(const char *name, int *return_code)
{
TRACE("name: %s, return_code: %p\n", name, return_code);
if(!load_vrclient())
return NULL;
return create_win_interface(name, vrclient_VRClientCoreFactory(name, return_code));
}
static VkDevice_T *(WINAPI *get_native_VkDevice)(VkDevice_T *);
static VkInstance_T *(WINAPI *get_native_VkInstance)(VkInstance_T *);
static VkPhysicalDevice_T *(WINAPI *get_native_VkPhysicalDevice)(VkPhysicalDevice_T *);
static VkPhysicalDevice_T *(WINAPI *get_wrapped_VkPhysicalDevice)(VkInstance_T *, VkPhysicalDevice_T *);
static VkQueue_T *(WINAPI *get_native_VkQueue)(VkQueue_T *);
static void load_vk_unwrappers(void)
{
static HMODULE h = NULL;
if(h)
/* already loaded */
return;
h = LoadLibraryA("winevulkan");
if(!h){
ERR("unable to load winevulkan\n");
return;
}
get_native_VkDevice = (void*)GetProcAddress(h, "__wine_get_native_VkDevice");
get_native_VkInstance = (void*)GetProcAddress(h, "__wine_get_native_VkInstance");
get_native_VkPhysicalDevice = (void*)GetProcAddress(h, "__wine_get_native_VkPhysicalDevice");
get_wrapped_VkPhysicalDevice = (void*)GetProcAddress(h, "__wine_get_wrapped_VkPhysicalDevice");
get_native_VkQueue = (void*)GetProcAddress(h, "__wine_get_native_VkQueue");
}
static bool is_hmd_present_reg(void)
{
DWORD type, value, wait_status, size;
DWORD is_hmd_present = 0;
LSTATUS status;
HANDLE event;
HKEY vr_key;
if ((status = RegOpenKeyExA(HKEY_CURRENT_USER, "Software\\Wine\\VR", 0, KEY_READ, &vr_key)))
{
WINE_ERR("Could not create key, status %#x.\n", status);
return FALSE;
}
size = sizeof(value);
if ((status = RegQueryValueExA(vr_key, "state", NULL, &type, (BYTE *)&value, &size)))
{
WINE_ERR("Could not query value, status %#x.\n", status);
RegCloseKey(vr_key);
return FALSE;
}
if (type != REG_DWORD)
{
WINE_ERR("Unexpected value type %#x.\n", type);
RegCloseKey(vr_key);
return FALSE;
}
if (value)
{
RegCloseKey(vr_key);
return value == 1;
}
event = CreateEventA( NULL, FALSE, FALSE, NULL );
while (1)
{
if (RegNotifyChangeKeyValue(vr_key, FALSE, REG_NOTIFY_CHANGE_LAST_SET, event, TRUE))
{
WINE_ERR("Error registering registry change notification.\n");
goto done;
}
size = sizeof(value);
if ((status = RegQueryValueExA(vr_key, "state", NULL, &type, (BYTE *)&value, &size)))
{
WINE_ERR("Could not query value, status %#x.\n", status);
goto done;
}
if (value)
break;
while ((wait_status = WaitForSingleObject(event, 1000)) == WAIT_TIMEOUT)
WINE_ERR("VR state wait timeout.\n");
if (wait_status != WAIT_OBJECT_0)
{
WINE_ERR("Got unexpected wait status %#x.\n", wait_status);
break;
}
}
if (value != 1)
goto done;
size = sizeof(is_hmd_present);
if ((status = RegQueryValueExA(vr_key, "is_hmd_present", NULL, &type, (BYTE *)&is_hmd_present, &size)))
WINE_ERR("Could not query is_hmd_present value, status %#x.\n", status);
done:
CloseHandle(event);
RegCloseKey(vr_key);
return is_hmd_present;
}
bool ivrclientcore_is_hmd_present(bool (*cpp_func)(void *), void *linux_side, unsigned int version,
struct client_core_data *user_data)
{
TRACE("linux_side %p, compositor_data.client_core_linux_side %p.\n",
linux_side, compositor_data.client_core_linux_side);
/* BIsHmdPresent() currently always returns FALSE on Linux if called before Init().
* Return true if the value stored by steam.exe helper in registry says the HMD is presnt. */
if (compositor_data.client_core_linux_side || !is_hmd_present_reg())
return cpp_func(linux_side);
return TRUE;
}
EVRInitError ivrclientcore_002_init(EVRInitError (*cpp_func)(void *, EVRApplicationType),
void *linux_side, EVRApplicationType application_type,
unsigned int version, struct client_core_data *user_data)
{
EVRInitError error;
TRACE("%p, %#x\n", linux_side, application_type);
InitializeCriticalSection(&user_data->critical_section);
error = cpp_func(linux_side, application_type);
if (error)
WARN("error %#x\n", error);
return error;
}
EVRInitError ivrclientcore_init(EVRInitError (*cpp_func)(void *, EVRApplicationType, const char *),
void *linux_side, EVRApplicationType application_type, const char *startup_info,
unsigned int version, struct client_core_data *user_data)
{
char *startup_info_converted;
EVRInitError error;
TRACE("%p, %#x, %p\n", linux_side, application_type, startup_info);
startup_info_converted = json_convert_startup_info(startup_info);
InitializeCriticalSection(&user_data->critical_section);
error = cpp_func(linux_side, application_type, startup_info_converted
? startup_info_converted : startup_info);
free(startup_info_converted);
if (error)
WARN("error %#x\n", error);
else
compositor_data.client_core_linux_side = linux_side;
return error;
}
void *ivrclientcore_get_generic_interface(void *(*cpp_func)(void *, const char *, EVRInitError *),
void *linux_side, const char *name_and_version, EVRInitError *error,
unsigned int version, struct client_core_data *user_data)
{
const char *cpp_name_and_version = name_and_version;
struct generic_interface *iface;
pfn_dtor destructor;
void *win_object;
void *object;
TRACE("%p, %p, %p\n", linux_side, name_and_version, error);
/* In theory we could pass this along, but we'd have to generate a separate
* set of thunks for it. Hopefully this will work as it is. */
if (name_and_version && !strncmp(name_and_version, "FnTable:", 8))
cpp_name_and_version += 8;
if (!(object = cpp_func(linux_side, cpp_name_and_version, error)))
{
WARN("Failed to create %s.\n", name_and_version);
return NULL;
}
if (!(win_object = create_win_interface(name_and_version, object)))
{
ERR("Failed to create win object %s.\n", name_and_version);
return NULL;
}
if ((destructor = get_win_destructor(name_and_version)))
{
EnterCriticalSection(&user_data->critical_section);
if (array_reserve((void **)&user_data->created_interfaces,
&user_data->created_interfaces_size, user_data->created_interface_count + 1,
sizeof(*user_data->created_interfaces)))
{
iface = &user_data->created_interfaces[user_data->created_interface_count++];
iface->object = win_object;
iface->dtor = destructor;
}
else
{
ERR("Failed to add interface to array.\n");
}
LeaveCriticalSection(&user_data->critical_section);
}
if (name_and_version && !strncmp(name_and_version, "FnTable:", 8))
return *((void **)win_object);
return win_object;
}
static void destroy_compositor_data(void)
{
IWineD3D11Device *wined3d_device;
TRACE("Destroying compositor data.\n");
if ((wined3d_device = compositor_data.wined3d_device))
{
TRACE("Waiting for device %p\n", wined3d_device);
wined3d_device->lpVtbl->wait_idle(wined3d_device);
}
memset(&compositor_data, 0, sizeof(compositor_data));
}
void ivrclientcore_cleanup(void (*cpp_func)(void *), void *linux_side,
unsigned int version, struct client_core_data *user_data)
{
struct generic_interface *iface;
SIZE_T i;
TRACE("%p\n", linux_side);
EnterCriticalSection(&user_data->critical_section);
for (i = 0; i < user_data->created_interface_count; ++i)
{
iface = &user_data->created_interfaces[i];
iface->dtor(iface->object);
}
HeapFree(GetProcessHeap(), 0, user_data->created_interfaces);
user_data->created_interfaces = NULL;
user_data->created_interfaces_size = 0;
user_data->created_interface_count = 0;
LeaveCriticalSection(&user_data->critical_section);
DeleteCriticalSection(&user_data->critical_section);
cpp_func(linux_side);
destroy_compositor_data();
}
void get_dxgi_output_info(void *cpp_func, void *linux_side,
int32_t *adapter_idx, unsigned int version)
{
TRACE("%p\n", adapter_idx);
*adapter_idx = 0;
}
void get_dxgi_output_info2(void *cpp_func, void *linux_side,
int32_t *adapter_idx, int32_t *output_idx, unsigned int version)
{
TRACE("%p, %p\n", adapter_idx, output_idx);
*adapter_idx = 0;
*output_idx = 0;
}
void ivrsystem_016_get_output_device(
void (*cpp_func)(void *, uint64_t *, ETextureType),
void *linux_side, uint64_t *out_device, ETextureType type,
unsigned int version)
{
cpp_func(linux_side, out_device, type);
}
void ivrsystem_get_output_device(
void (*cpp_func)(void *, uint64_t *, ETextureType, VkInstance_T *),
void *linux_side, uint64_t *out_device, ETextureType type,
VkInstance_T *wrapped_instance, unsigned int version)
{
switch(type){
case TextureType_Vulkan:
{
VkInstance_T *native_instance;
load_vk_unwrappers();
native_instance = get_native_VkInstance(wrapped_instance);
cpp_func(linux_side, out_device, type, native_instance);
*out_device = (uint64_t)(intptr_t)get_wrapped_VkPhysicalDevice(wrapped_instance,
(VkPhysicalDevice_T *)(intptr_t)*out_device);
return;
}
default:
cpp_func(linux_side, out_device, type, wrapped_instance);
return;
}
}
struct submit_data
{
void *linux_side;
EVRCompositorError (*submit)(void *, EVREye, Texture_t *, VRTextureBounds_t *, EVRSubmitFlags);
EVREye eye;
Texture_t texture;
VRTextureWithPose_t texture_pose;
VRTextureWithDepth_t texture_depth;
VRTextureWithPoseAndDepth_t texture_both;
VRTextureBounds_t bounds;
EVRSubmitFlags flags;
};
static CDECL void d3d11_texture_callback(unsigned int gl_texture, unsigned int gl_depth_texture,
const void *data, unsigned int data_size)
{
const struct submit_data *submit_data = data;
VRTextureBounds_t bounds = submit_data->bounds;
VRTextureWithPoseAndDepth_t texture_both;
VRTextureWithDepth_t texture_depth;
VRTextureWithPose_t texture_pose;
VRCompositorError error = 0;
Texture_t texture;
void *tex;
TRACE("texture %u, depth_texture %u, data {%p, %u}\n",
gl_texture, gl_depth_texture, data, data_size);
switch (submit_data->flags & (Submit_TextureWithPose | Submit_TextureWithDepth))
{
case 0:
texture = submit_data->texture;
texture.handle = (void *)(UINT_PTR)gl_texture;
texture.eType = TextureType_OpenGL;
tex = &texture;
break;
case Submit_TextureWithPose:
texture_pose = submit_data->texture_pose;
texture_pose.texture.handle = (void *)(UINT_PTR)gl_texture;
texture_pose.texture.eType = TextureType_OpenGL;
tex = &texture_pose;
break;
case Submit_TextureWithDepth:
texture_depth = submit_data->texture_depth;
texture_depth.texture.handle = (void *)(UINT_PTR)gl_texture;
texture_depth.texture.eType = TextureType_OpenGL;
texture_depth.depth.handle = (void *)(UINT_PTR)gl_depth_texture;
tex = &texture_depth;
break;
case Submit_TextureWithPose | Submit_TextureWithDepth:
texture_both = submit_data->texture_both;
texture_both.texture.handle = (void *)(UINT_PTR)gl_texture;
texture_both.texture.eType = TextureType_OpenGL;
texture_both.depth.handle = (void *)(UINT_PTR)gl_depth_texture;
tex = &texture_both;
break;
}
error = submit_data->submit(submit_data->linux_side, submit_data->eye,
tex, &bounds, submit_data->flags);
if (error)
WARN("error %#x\n", error);
}
void ivrcompositor_005_submit(
void (*cpp_func)(void *, Hmd_Eye, void *, Compositor_TextureBounds *),
void *linux_side, Hmd_Eye eye, void *texture, Compositor_TextureBounds *bounds,
unsigned int version)
{
TRACE("%p, %#x, %p, %p\n", linux_side, eye, texture, bounds);
return cpp_func(linux_side, eye, texture, bounds);
}
VRCompositorError ivrcompositor_006_submit(
VRCompositorError (*cpp_func)(void *, Hmd_Eye, void *, VRTextureBounds_t *),
void *linux_side, Hmd_Eye eye, void *texture, VRTextureBounds_t *bounds,
unsigned int version)
{
TRACE("%p, %#x, %p, %p\n", linux_side, eye, texture, bounds);
return cpp_func(linux_side, eye, texture, bounds);
}
VRCompositorError ivrcompositor_007_submit(
VRCompositorError (*cpp_func)(void *, Hmd_Eye, GraphicsAPIConvention, void *, VRTextureBounds_t *),
void *linux_side, Hmd_Eye eye, GraphicsAPIConvention api, void *texture, VRTextureBounds_t *bounds,
unsigned int version)
{
TRACE("%p, %#x, %#x, %p, %p\n", linux_side, eye, api, texture, bounds);
if (api == API_DirectX)
FIXME("Not implemented Direct3D API!\n");
return cpp_func(linux_side, eye, api, texture, bounds);
}
VRCompositorError ivrcompositor_008_submit(
VRCompositorError (*cpp_func)(void *, Hmd_Eye, GraphicsAPIConvention, void *,
VRTextureBounds_t *, VRSubmitFlags_t),
void *linux_side, Hmd_Eye eye, GraphicsAPIConvention api, void *texture,
VRTextureBounds_t *bounds, VRSubmitFlags_t flags,
unsigned int version)
{
TRACE("%p, %#x, %#x, %p, %p, %#x\n", linux_side, eye, api, texture, bounds, flags);
if (api == API_DirectX)
FIXME("Not implemented Direct3D API!\n");
return cpp_func(linux_side, eye, api, texture, bounds, flags);
}
static EVRCompositorError ivrcompositor_submit_wined3d(
EVRCompositorError (*cpp_func)(void *, EVREye, Texture_t *, VRTextureBounds_t *, EVRSubmitFlags),
void *linux_side, EVREye eye, Texture_t *texture, VRTextureBounds_t *bounds, EVRSubmitFlags flags,
unsigned int version, IWineD3D11Texture2D *wine_texture)
{
IWineD3D11Texture2D *depth_texture = NULL;
IUnknown *depth_texture_unk = NULL;
IWineD3D11Device *wined3d_device;
struct submit_data submit_data;
EVRCompositorError error = 0;
ID3D11Device *device;
BOOL async = FALSE;
HRESULT hr;
wine_texture->lpVtbl->GetDevice(wine_texture, &device);
if (compositor_data.d3d11_device != device)
{
if (compositor_data.d3d11_device)
FIXME("Previous submit was from different D3D11 device.\n");
compositor_data.d3d11_device = device;
if (SUCCEEDED(hr = device->lpVtbl->QueryInterface(device,
&IID_IWineD3D11Device, (void **)&wined3d_device)))
{
compositor_data.wined3d_device = wined3d_device;
wined3d_device->lpVtbl->Release(wined3d_device);
}
else
{
WARN("Failed to get device, hr %#x.\n", hr);
compositor_data.wined3d_device = NULL;
}
switch (version)
{
/* older versions */
default:
TRACE("Using synchronous mode.\n");
break;
case 21:
TRACE("Enabling explicit timing mode.\n");
async = TRUE;
cppIVRCompositor_IVRCompositor_021_SetExplicitTimingMode(linux_side,
VRCompositorTimingMode_Explicit_ApplicationPerformsPostPresentHandoff);
break;
case 22:
TRACE("Enabling explicit timing mode.\n");
async = TRUE;
cppIVRCompositor_IVRCompositor_022_SetExplicitTimingMode(linux_side,
VRCompositorTimingMode_Explicit_ApplicationPerformsPostPresentHandoff);
break;
}
}
device->lpVtbl->Release(device);
submit_data.linux_side = linux_side;
submit_data.submit = cpp_func;
submit_data.eye = eye;
submit_data.flags = flags;
/* Textures are upside-down in wined3d. */
submit_data.bounds = *bounds;
submit_data.bounds.vMin = bounds->vMax;
submit_data.bounds.vMax = bounds->vMin;
switch (flags & (Submit_TextureWithPose | Submit_TextureWithDepth))
{
case 0:
submit_data.texture = *texture;
break;
case Submit_TextureWithPose:
submit_data.texture_pose = *(VRTextureWithPose_t *)texture;
break;
case Submit_TextureWithDepth:
submit_data.texture_depth = *(VRTextureWithDepth_t *)texture;
depth_texture_unk = submit_data.texture_depth.depth.handle;
break;
case Submit_TextureWithPose | Submit_TextureWithDepth:
submit_data.texture_both = *(VRTextureWithPoseAndDepth_t *)texture;
depth_texture_unk = submit_data.texture_both.depth.handle;
break;
}
if (depth_texture_unk)
{
if (FAILED(hr = depth_texture_unk->lpVtbl->QueryInterface(depth_texture_unk,
&IID_IWineD3D11Texture2D, (void **)&depth_texture)))
WARN("Failed to get IWineD3D11Texture2D from depth texture.\n");
}
if (async)
{
wine_texture->lpVtbl->access_gl_texture(wine_texture,
d3d11_texture_callback, depth_texture, &submit_data, sizeof(submit_data));
}
else
{
unsigned int gl_texture, gl_depth_texture = 0;
void *linux_texture;
gl_texture = wine_texture->lpVtbl->get_gl_texture(wine_texture);
if (depth_texture)
{
gl_depth_texture = depth_texture->lpVtbl->get_gl_texture(depth_texture);
TRACE("Depth texture %u.\n", gl_depth_texture);
}
switch (flags & (Submit_TextureWithPose | Submit_TextureWithDepth))
{
case 0:
submit_data.texture.handle = (void *)(UINT_PTR)gl_texture;
submit_data.texture.eType = TextureType_OpenGL;
linux_texture = &submit_data.texture;
break;
case Submit_TextureWithPose:
submit_data.texture_pose.texture.handle = (void *)(UINT_PTR)gl_texture;
submit_data.texture_pose.texture.eType = TextureType_OpenGL;
linux_texture = &submit_data.texture_pose;
break;
case Submit_TextureWithDepth:
submit_data.texture_depth.texture.handle = (void *)(UINT_PTR)gl_texture;
submit_data.texture_depth.texture.eType = TextureType_OpenGL;
submit_data.texture_depth.depth.handle = (void *)(UINT_PTR)gl_depth_texture;
linux_texture = &submit_data.texture_depth;
break;
case Submit_TextureWithPose | Submit_TextureWithDepth:
submit_data.texture_both.texture.handle = (void *)(UINT_PTR)gl_texture;
submit_data.texture_both.texture.eType = TextureType_OpenGL;
submit_data.texture_both.depth.handle = (void *)(UINT_PTR)gl_depth_texture;
linux_texture = &submit_data.texture_both;
break;
}
error = cpp_func(linux_side, eye, linux_texture, &submit_data.bounds, flags);
}
if (depth_texture)
depth_texture->lpVtbl->Release(depth_texture);
wine_texture->lpVtbl->Release(wine_texture);
return error;
}
#ifdef VRCLIENT_HAVE_DXVK
static Texture_t vrclient_translate_texture_dxvk(Texture_t *texture, struct VRVulkanTextureData_t *vkdata,
IDXGIVkInteropSurface *dxvk_surface, IDXGIVkInteropDevice **p_dxvk_device, VkImageLayout *image_layout,
VkImageCreateInfo *image_info)
{
struct Texture_t vktexture;
VkImage image_handle;
dxvk_surface->lpVtbl->GetDevice(dxvk_surface, p_dxvk_device);
(*p_dxvk_device)->lpVtbl->GetVulkanHandles(*p_dxvk_device, &vkdata->m_pInstance,
&vkdata->m_pPhysicalDevice, &vkdata->m_pDevice);
(*p_dxvk_device)->lpVtbl->GetSubmissionQueue(*p_dxvk_device, &vkdata->m_pQueue, &vkdata->m_nQueueFamilyIndex);
image_info->sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO;
image_info->pNext = NULL;
dxvk_surface->lpVtbl->GetVulkanImageInfo(dxvk_surface, &image_handle, image_layout, image_info);
load_vk_unwrappers();
vkdata->m_nImage = (uint64_t)image_handle;
vkdata->m_pDevice = get_native_VkDevice(vkdata->m_pDevice);
vkdata->m_pPhysicalDevice = get_native_VkPhysicalDevice(vkdata->m_pPhysicalDevice);
vkdata->m_pInstance = get_native_VkInstance(vkdata->m_pInstance);
vkdata->m_pQueue = get_native_VkQueue(vkdata->m_pQueue);
vkdata->m_nWidth = image_info->extent.width;
vkdata->m_nHeight = image_info->extent.height;
vkdata->m_nFormat = image_info->format;
vkdata->m_nSampleCount = image_info->samples;
vktexture = *texture;
vktexture.handle = vkdata;
vktexture.eType = TextureType_Vulkan;
return vktexture;
}
static EVROverlayError ivroverlay_set_overlay_texture_dxvk(
EVROverlayError (*cpp_func)(void *, VROverlayHandle_t, Texture_t *),
void *linux_side, VROverlayHandle_t overlayHandle, Texture_t *texture,
unsigned int version, IDXGIVkInteropSurface *dxvk_surface)
{
struct VRVulkanTextureData_t vkdata;
IDXGIVkInteropDevice *dxvk_device;
struct Texture_t vktexture;
VkImageLayout image_layout;
VkImageCreateInfo image_info;
VkImageSubresourceRange subresources;
EVRCompositorError err;
vktexture = vrclient_translate_texture_dxvk(texture, &vkdata, dxvk_surface, &dxvk_device, &image_layout, &image_info);
subresources.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
subresources.baseMipLevel = 0;
subresources.levelCount = image_info.mipLevels;
subresources.baseArrayLayer = 0;
subresources.layerCount = image_info.arrayLayers;
dxvk_device->lpVtbl->TransitionSurfaceLayout(dxvk_device, dxvk_surface, &subresources,
image_layout, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL);
dxvk_device->lpVtbl->FlushRenderingCommands(dxvk_device);
dxvk_device->lpVtbl->LockSubmissionQueue(dxvk_device);
err = cpp_func(linux_side, overlayHandle, &vktexture);
dxvk_device->lpVtbl->ReleaseSubmissionQueue(dxvk_device);
dxvk_device->lpVtbl->TransitionSurfaceLayout(dxvk_device, dxvk_surface, &subresources,
VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, image_layout);
dxvk_device->lpVtbl->Release(dxvk_device);
dxvk_surface->lpVtbl->Release(dxvk_surface);
return err;
}
static EVRCompositorError ivrcompositor_submit_dxvk(
EVRCompositorError (*cpp_func)(void *, EVREye, Texture_t *, VRTextureBounds_t *, EVRSubmitFlags),
void *linux_side, EVREye eye, Texture_t *texture, VRTextureBounds_t *bounds, EVRSubmitFlags flags,
unsigned int version, IDXGIVkInteropSurface *dxvk_surface)
{
static const EVRSubmitFlags supported_flags = Submit_LensDistortionAlreadyApplied | Submit_FrameDiscontinuty;
struct VRVulkanTextureArrayData_t vkdata;
IDXGIVkInteropDevice *dxvk_device;
struct Texture_t vktexture;
VkImageLayout image_layout;
VkImageCreateInfo image_info;
VkImageSubresourceRange subresources;
EVRCompositorError err;
vktexture = vrclient_translate_texture_dxvk(texture, &vkdata.t, dxvk_surface, &dxvk_device, &image_layout, &image_info);
compositor_data.dxvk_device = dxvk_device;
if (flags & ~supported_flags)
FIXME("Unhandled flags %#x.\n", flags);
if (image_info.arrayLayers > 1)
{
vkdata.m_unArrayIndex = eye;
vkdata.m_unArraySize = image_info.arrayLayers;
flags |= Submit_VulkanTextureWithArrayData;
}
subresources.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
subresources.baseMipLevel = 0;
subresources.levelCount = image_info.mipLevels;
subresources.baseArrayLayer = 0;
subresources.layerCount = image_info.arrayLayers;
dxvk_device->lpVtbl->TransitionSurfaceLayout(dxvk_device, dxvk_surface, &subresources,
image_layout, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL);
dxvk_device->lpVtbl->FlushRenderingCommands(dxvk_device);
dxvk_device->lpVtbl->LockSubmissionQueue(dxvk_device);
err = cpp_func(linux_side, eye, &vktexture, bounds, flags);
dxvk_device->lpVtbl->ReleaseSubmissionQueue(dxvk_device);
dxvk_device->lpVtbl->TransitionSurfaceLayout(dxvk_device, dxvk_surface, &subresources,
VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, image_layout);
dxvk_device->lpVtbl->Release(dxvk_device);
dxvk_surface->lpVtbl->Release(dxvk_surface);
return err;
}
#endif
static EVROverlayError ivroverlay_set_overlay_texture_vulkan(
EVROverlayError (*cpp_func)(void *, VROverlayHandle_t, Texture_t *),
void *linux_side, VROverlayHandle_t overlay_handle, Texture_t *texture,
unsigned int version)
{
struct VRVulkanTextureData_t our_vkdata, *their_vkdata;
Texture_t our_texture;
load_vk_unwrappers();
their_vkdata = texture->handle;
our_vkdata = *their_vkdata;
our_vkdata.m_pDevice = get_native_VkDevice(our_vkdata.m_pDevice);
our_vkdata.m_pPhysicalDevice = get_native_VkPhysicalDevice(our_vkdata.m_pPhysicalDevice);
our_vkdata.m_pInstance = get_native_VkInstance(our_vkdata.m_pInstance);
our_vkdata.m_pQueue = get_native_VkQueue(our_vkdata.m_pQueue);
our_texture = *texture;
our_texture.handle = &our_vkdata;
return cpp_func(linux_side, overlay_handle, &our_texture);
}
static EVRCompositorError ivrcompositor_submit_vulkan(
EVRCompositorError (*cpp_func)(void *, EVREye, Texture_t *, VRTextureBounds_t *, EVRSubmitFlags),
void *linux_side, EVREye eye, Texture_t *texture, VRTextureBounds_t *bounds, EVRSubmitFlags flags,
unsigned int version)
{
struct VRVulkanTextureData_t our_depth_vkdata, *their_vkdata;
struct VRVulkanTextureArrayData_t our_vkdata;
VRTextureWithPoseAndDepth_t our_both;
VRTextureWithDepth_t our_depth;
VRTextureWithPose_t our_pose;
Texture_t our_texture;
void *tex;
load_vk_unwrappers();
their_vkdata = texture->handle;
memcpy(&our_vkdata, their_vkdata, flags & Submit_VulkanTextureWithArrayData
? sizeof(struct VRVulkanTextureArrayData_t) : sizeof(struct VRVulkanTextureData_t));
our_vkdata.t.m_pDevice = get_native_VkDevice(our_vkdata.t.m_pDevice);
our_vkdata.t.m_pPhysicalDevice = get_native_VkPhysicalDevice(our_vkdata.t.m_pPhysicalDevice);
our_vkdata.t.m_pInstance = get_native_VkInstance(our_vkdata.t.m_pInstance);
our_vkdata.t.m_pQueue = get_native_VkQueue(our_vkdata.t.m_pQueue);
switch (flags & (Submit_TextureWithPose | Submit_TextureWithDepth))
{
case 0:
our_texture = *texture;
our_texture.handle = &our_vkdata;
tex = &our_texture;
break;
case Submit_TextureWithPose:
our_pose = *(VRTextureWithPose_t *)texture;
our_pose.texture.handle = &our_vkdata;
tex = &our_pose;
break;
case Submit_TextureWithDepth:
our_depth = *(VRTextureWithDepth_t *)texture;
our_depth.texture.handle = &our_vkdata;
tex = &our_depth;
break;
case Submit_TextureWithPose | Submit_TextureWithDepth:
our_both = *(VRTextureWithPoseAndDepth_t *)texture;
our_both.texture.handle = &our_vkdata;
their_vkdata = our_both.depth.handle;
our_depth_vkdata = *their_vkdata;
our_depth_vkdata.m_pDevice = get_native_VkDevice(our_depth_vkdata.m_pDevice);
our_depth_vkdata.m_pPhysicalDevice = get_native_VkPhysicalDevice(our_depth_vkdata.m_pPhysicalDevice);
our_depth_vkdata.m_pInstance = get_native_VkInstance(our_depth_vkdata.m_pInstance);
our_depth_vkdata.m_pQueue = get_native_VkQueue(our_depth_vkdata.m_pQueue);
our_both.depth.handle = &our_depth_vkdata;
tex = &our_both;
break;
}
return cpp_func(linux_side, eye, tex, bounds, flags);
}
EVROverlayError ivroverlay_set_overlay_texture(
EVROverlayError (*cpp_func)(void *, VROverlayHandle_t, Texture_t *),
void *linux_side, VROverlayHandle_t overlayHandle, Texture_t *texture,
unsigned int version)
{
IUnknown *texture_iface;
HRESULT hr;
TRACE("%p, overlayHandle = %#x, texture = %p\n", linux_side, overlayHandle, texture);
switch (texture->eType)
{
case TextureType_DirectX:
TRACE("D3D11\n");
if (!texture->handle) {
WARN("No D3D11 texture %p.\n", texture);
return cpp_func(linux_side, overlayHandle, texture);
}
texture_iface = texture->handle;
#ifdef VRCLIENT_HAVE_DXVK
{
IDXGIVkInteropSurface *dxvk_surface;
if (SUCCEEDED(hr = texture_iface->lpVtbl->QueryInterface(texture_iface, &IID_IDXGIVkInteropSurface, (void **)&dxvk_surface))) {
return ivroverlay_set_overlay_texture_dxvk(cpp_func, linux_side, overlayHandle, texture, version, dxvk_surface);
}
}
#endif
{
IWineD3D11Texture2D *wine_texture;
if (SUCCEEDED(hr = texture_iface->lpVtbl->QueryInterface(texture_iface,
&IID_IWineD3D11Texture2D, (void **)&wine_texture)))
{
FIXME("WineD3D not yet supported by IVROverlay::SetOverlayTexture\n");
}
}
WARN("Invalid D3D11 texture %p.\n", texture);
return cpp_func(linux_side, overlayHandle, texture);
case TextureType_Vulkan:
TRACE("Vulkan\n");
return ivroverlay_set_overlay_texture_vulkan(cpp_func, linux_side, overlayHandle, texture, version);
default:
return cpp_func(linux_side, overlayHandle, texture);
}
}
EVROverlayError ivroverlay_005_set_overlay_texture(
EVROverlayError (*cpp_func)(void *, VROverlayHandle_t, GraphicsAPIConvention, void *),
void *linux_side, VROverlayHandle_t overlayHandle, GraphicsAPIConvention api, void *texture,
unsigned int version)
{
/* hopefully no one actually uses this old interface... Vulkan support
* wasn't added until later; how can we pass in a DirectX texture? */
FIXME("unimplemented!\n");
return VROverlayError_InvalidHandle;
}
EVROverlayError ivroverlay_001_set_overlay_texture(
EVROverlayError (*cpp_func)(void *, VROverlayHandle_t, void *),
void *linux_side, VROverlayHandle_t overlayHandle, void *texture,
unsigned int version)
{
/* probably no one actually uses this old interface... */
FIXME("unimplemented!\n");
return VROverlayError_InvalidHandle;
}
EVRCompositorError ivrcompositor_submit(
EVRCompositorError (*cpp_func)(void *, EVREye, Texture_t *, VRTextureBounds_t *, EVRSubmitFlags),
void *linux_side, EVREye eye, Texture_t *texture, VRTextureBounds_t *bounds, EVRSubmitFlags flags,
unsigned int version)
{
IWineD3D11Texture2D *wine_texture;
IUnknown *texture_iface;
HRESULT hr;
TRACE("%p, %#x, %p, %p, %#x\n", linux_side, eye, texture, bounds, flags);
compositor_data.handoff_called = FALSE;
switch (texture->eType)
{
case TextureType_DirectX:
{
TRACE("D3D11\n");
if (!texture->handle) {
WARN("No D3D11 texture %p.\n", texture);
return cpp_func(linux_side, eye, texture, bounds, flags);
}
texture_iface = texture->handle;
if (SUCCEEDED(hr = texture_iface->lpVtbl->QueryInterface(texture_iface,
&IID_IWineD3D11Texture2D, (void **)&wine_texture)))
{
return ivrcompositor_submit_wined3d(cpp_func, linux_side,
eye, texture, bounds, flags, version, wine_texture);
}
#ifdef VRCLIENT_HAVE_DXVK
{
IDXGIVkInteropSurface *dxvk_surface;
if (SUCCEEDED(hr = texture_iface->lpVtbl->QueryInterface(texture_iface,
&IID_IDXGIVkInteropSurface, (void **)&dxvk_surface)))
{
return ivrcompositor_submit_dxvk(cpp_func, linux_side,
eye, texture, bounds, flags, version, dxvk_surface);
}
}
#endif
WARN("Invalid D3D11 texture %p.\n", texture);
return cpp_func(linux_side, eye, texture, bounds, flags);
}
case TextureType_Vulkan:
return ivrcompositor_submit_vulkan(cpp_func, linux_side,
eye, texture, bounds, flags, version);
default:
return cpp_func(linux_side, eye, texture, bounds, flags);
}
}
void ivrcompositor_008_set_skybox_override(
void (*cpp_func)(void *, GraphicsAPIConvention, void *, void *, void *, void *, void *, void *),
void *linux_side, GraphicsAPIConvention api, void *front, void *back, void *left, void *right, void *top, void *bottom,
unsigned int version)
{
TRACE("%p, %#x, %p, %p, %p, %p, %p, %p.\n", linux_side, api, front, back, left, right, top, bottom);
if (api == API_DirectX)
FIXME("Not implemented Direct3D API.\n");
cpp_func(linux_side, api, front, back, left, right, top, bottom);
}
static EVRCompositorError ivrcompositor_set_skybox_override_d3d11(
EVRCompositorError (*cpp_func)(void *, Texture_t *textures, uint32_t count),
void *linux_side, Texture_t *textures, uint32_t count)
{
struct VRVulkanTextureData_t vkdata[6];
IDXGIVkInteropSurface *dxvk_surface;
struct Texture_t vktexture[6];
EVRCompositorError result;
unsigned int i;
for (i = 0; i < count; ++i)
{
Texture_t *texture = &textures[i];
IUnknown *texture_iface;
if (!texture->handle)
{
ERR("No D3D11 texture %p.\n", texture);
return cpp_func(linux_side, textures, count);
}
if (textures[i].eType != TextureType_DirectX)
{
FIXME("Mixing texture types is not supported.\n");
return 0;
}
texture_iface = texture->handle;
#ifdef VRCLIENT_HAVE_DXVK
if (SUCCEEDED(texture_iface->lpVtbl->QueryInterface(texture_iface,
&IID_IDXGIVkInteropSurface, (void **)&dxvk_surface)))
{
VkImageSubresourceRange subresources;
IDXGIVkInteropDevice *dxvk_device;
VkImageCreateInfo image_info;
VkImageLayout image_layout;
vktexture[i] = vrclient_translate_texture_dxvk(texture, &vkdata[i], dxvk_surface, &dxvk_device, &image_layout, &image_info);
if (compositor_data.dxvk_device && dxvk_device != compositor_data.dxvk_device)
{
ERR("Invalid dxvk_device %p, previous %p.\n", dxvk_device, compositor_data.dxvk_device);
dxvk_surface->lpVtbl->Release(dxvk_surface);
dxvk_device->lpVtbl->Release(dxvk_device);
return 0;
}
compositor_data.dxvk_device = dxvk_device;
subresources.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
subresources.baseMipLevel = 0;
subresources.levelCount = image_info.mipLevels;
subresources.baseArrayLayer = 0;
subresources.layerCount = image_info.arrayLayers;
dxvk_device->lpVtbl->TransitionSurfaceLayout(dxvk_device, dxvk_surface, &subresources,
image_layout, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL);
dxvk_surface->lpVtbl->Release(dxvk_surface);
dxvk_device->lpVtbl->Release(dxvk_device);
continue;
}
#endif
FIXME("Unsupported d3d11 texture %p, i %u.\n", texture, i);
return 0;
}
compositor_data.dxvk_device->lpVtbl->FlushRenderingCommands(compositor_data.dxvk_device);
compositor_data.dxvk_device->lpVtbl->LockSubmissionQueue(compositor_data.dxvk_device);
result = cpp_func(linux_side, vktexture, count);
compositor_data.dxvk_device->lpVtbl->ReleaseSubmissionQueue(compositor_data.dxvk_device);
TRACE("result %u.\n", result);
return result;
}
EVRCompositorError ivrcompositor_set_skybox_override(
EVRCompositorError (*cpp_func)(void *, Texture_t *textures, uint32_t count),
void *linux_side, Texture_t *textures, uint32_t count,
unsigned int version)
{
TRACE("cpp_func %p, linux_side %p, textures %p, count %u, version %u.\n",
cpp_func, linux_side, textures, count, version);
if (!count || count > 6)
{
WARN("Invalid texture count %u.\n", count);
return cpp_func(linux_side, textures, count);
}
if (textures[0].eType == TextureType_DirectX)
return ivrcompositor_set_skybox_override_d3d11(cpp_func, linux_side, textures, count);
FIXME("Conversion for type %u is not supported.\n", textures[0].eType);
return 0;
}
struct post_present_handoff_data
{
void *linux_side;
void (*post_present_handoff)(void *linux_side);
};
static CDECL void d3d11_post_present_handoff_callback(const void *data, unsigned int data_size)
{
const struct post_present_handoff_data *callback_data = data;
TRACE("data {%p, %u}\n", data, data_size);
callback_data->post_present_handoff(callback_data->linux_side);
}
void ivrcompositor_post_present_handoff(void (*cpp_func)(void *),
void *linux_side, unsigned int version)
{
struct post_present_handoff_data data;
IWineD3D11Device *wined3d_device;
TRACE("%p\n", linux_side);
if ((wined3d_device = compositor_data.wined3d_device))
{
TRACE("wined3d device %p\n", wined3d_device);
data.linux_side = linux_side;
data.post_present_handoff = cpp_func;
wined3d_device->lpVtbl->run_on_command_stream(wined3d_device,
d3d11_post_present_handoff_callback, &data, sizeof(data));
return;
}
#ifdef VRCLIENT_HAVE_DXVK
if (compositor_data.dxvk_device)
{
compositor_data.dxvk_device->lpVtbl->LockSubmissionQueue(compositor_data.dxvk_device);
if (!compositor_data.d3d11_explicit_handoff && version >= 21)
{
/* PostPresentHandoff can be used with d3d11 without SetExplicitTimingMode
* (which is Vulkan / d3d12 only), but doing the same with Vulkan results
* in lockups and crashes. */
cppIVRCompositor_IVRCompositor_021_SetExplicitTimingMode(linux_side,
VRCompositorTimingMode_Explicit_ApplicationPerformsPostPresentHandoff);
compositor_data.d3d11_explicit_handoff = TRUE;
}
}
#endif
cpp_func(linux_side);
compositor_data.handoff_called = TRUE;
#ifdef VRCLIENT_HAVE_DXVK
if (compositor_data.dxvk_device)
compositor_data.dxvk_device->lpVtbl->ReleaseSubmissionQueue(compositor_data.dxvk_device);
#endif
}
struct explicit_timing_data
{
void *linux_side;
unsigned int version;
};
static CDECL void d3d11_explicit_timing_callback(const void *data, unsigned int data_size)
{
const struct explicit_timing_data *callback_data = data;
EVRCompositorError error;
TRACE("data {%p, %u}\n", data, data_size);
switch (callback_data->version)
{
case 21:
error = cppIVRCompositor_IVRCompositor_021_SubmitExplicitTimingData(callback_data->linux_side);
break;
case 22:
error = cppIVRCompositor_IVRCompositor_022_SubmitExplicitTimingData(callback_data->linux_side);
break;
default:
FIXME("Unhandled version %u.\n", callback_data->version);
break;
}
if (error)
WARN("error %#x\n", error);
}
EVRCompositorError ivrcompositor_wait_get_poses(
EVRCompositorError (cpp_func)(void *, TrackedDevicePose_t *, uint32_t, TrackedDevicePose_t *, uint32_t),
void *linux_side, TrackedDevicePose_t *render_poses, uint32_t render_pose_count,
TrackedDevicePose_t *game_poses, uint32_t game_pose_count,
unsigned int version)
{
struct explicit_timing_data data;
IWineD3D11Device *wined3d_device;
EVRCompositorError r;
TRACE("%p, %p, %u, %p, %u\n", linux_side, render_poses, render_pose_count, game_poses, game_pose_count);
#ifdef VRCLIENT_HAVE_DXVK
if (compositor_data.dxvk_device)
{
compositor_data.dxvk_device->lpVtbl->LockSubmissionQueue(compositor_data.dxvk_device);
if (compositor_data.d3d11_explicit_handoff && !compositor_data.handoff_called)
{
/* Calling handoff after submit is optional for d3d11 but mandatory for Vulkan
* if explicit timing mode is set. */
cppIVRCompositor_IVRCompositor_022_PostPresentHandoff(linux_side);
}
}
#endif
r = cpp_func(linux_side, render_poses, render_pose_count, game_poses, game_pose_count);
#ifdef VRCLIENT_HAVE_DXVK
if (compositor_data.dxvk_device)
{
if (compositor_data.d3d11_explicit_handoff)
cppIVRCompositor_IVRCompositor_022_SubmitExplicitTimingData(linux_side);
compositor_data.dxvk_device->lpVtbl->ReleaseSubmissionQueue(compositor_data.dxvk_device);
}
#endif
if ((wined3d_device = compositor_data.wined3d_device))
{
TRACE("wined3d device %p.\n", wined3d_device);
/* We need to call IVRCompositor::SubmitExplicitTimingData() before the
* first flush of the frame.
*
* Sending IVRCompositor::SubmitExplicitTimingData() to the command
* stream immediately after IVRCompositor::WaitGetPoses() seems
* reasonable.
*/
if (version == 21 || version == 22)
{
data.linux_side = linux_side;
data.version = version;
wined3d_device->lpVtbl->run_on_command_stream(wined3d_device,
d3d11_explicit_timing_callback, &data, sizeof(data));
}
}
return r;
}
uint32_t ivrcompositor_get_vulkan_device_extensions_required(
uint32_t (*cpp_func)(void *, VkPhysicalDevice_T *, char *, uint32_t),
void *linux_side, VkPhysicalDevice_T *phys_dev, char *value, uint32_t bufsize,
unsigned int version)
{
uint32_t ret;
load_vk_unwrappers();
phys_dev = get_native_VkPhysicalDevice(phys_dev);
ret = cpp_func(linux_side, phys_dev, value, bufsize);
TRACE("ret %u, value %s.\n", ret, value);
return ret;
}
#pragma pack( push, 8 )
struct winRenderModel_TextureMap_t_1015 {
uint16_t unWidth;
uint16_t unHeight;
const uint8_t *rubTextureMapData;
} __attribute__ ((ms_struct));
#pragma pack( pop )
static EVRRenderModelError load_into_texture_d3d11(ID3D11Texture2D *texture,
const struct winRenderModel_TextureMap_t_1015 *data)
{
D3D11_TEXTURE2D_DESC texture_desc;
ID3D11DeviceContext *context;
ID3D11Device *device;
texture->lpVtbl->GetDesc(texture, &texture_desc);
TRACE("Format %#x, width %u, height %u.\n",
texture_desc.Format, texture_desc.Width, texture_desc.Height);
TRACE("Array size %u, miplevels %u.\n",
texture_desc.ArraySize, texture_desc.MipLevels);
if (texture_desc.Format != DXGI_FORMAT_R8G8B8A8_UNORM_SRGB)
{
FIXME("Unexpected format %#x.\n", texture_desc.Format);
return VRRenderModelError_NotSupported;
}
if (texture_desc.Width != data->unWidth)
{
FIXME("Unexpected width %u.\n", texture_desc.Width);
return VRRenderModelError_NotSupported;
}
if (texture_desc.Height != data->unHeight)
{
FIXME("Unexpected height %u.\n", texture_desc.Height);
return VRRenderModelError_NotSupported;
}
texture->lpVtbl->GetDevice(texture, &device);
device->lpVtbl->GetImmediateContext(device, &context);
device->lpVtbl->Release(device);
context->lpVtbl->UpdateSubresource(context, (ID3D11Resource *)texture,
0, NULL, data->rubTextureMapData, data->unWidth * 4 * sizeof(uint8_t), 0);
context->lpVtbl->Release(context);
return VRRenderModelError_None;
}
static EVRRenderModelError load_linux_texture_map(void *linux_side, TextureID_t texture_id,
struct winRenderModel_TextureMap_t_1015 **texture_map, unsigned int version)
{
switch(version){
case 4:
return cppIVRRenderModels_IVRRenderModels_004_LoadTexture_Async(linux_side, texture_id, (struct winRenderModel_TextureMap_t_0918 **)texture_map);
case 5:
return cppIVRRenderModels_IVRRenderModels_005_LoadTexture_Async(linux_side, texture_id, texture_map);
case 6:
return cppIVRRenderModels_IVRRenderModels_006_LoadTexture_Async(linux_side, texture_id, (struct winRenderModel_TextureMap_t_1168 **)texture_map);
}
FIXME("Unsupported IVRRenderModels version! %u\n", version);
return VRRenderModelError_NotSupported;
}
static void free_linux_texture_map(void *linux_side,
struct winRenderModel_TextureMap_t_1015 *texture_map, unsigned int version)
{
switch(version){
case 4:
cppIVRRenderModels_IVRRenderModels_004_FreeTexture(linux_side, (struct winRenderModel_TextureMap_t_0918 *)texture_map);
break;
case 5:
cppIVRRenderModels_IVRRenderModels_005_FreeTexture(linux_side, texture_map);
break;
case 6:
cppIVRRenderModels_IVRRenderModels_006_FreeTexture(linux_side, (struct winRenderModel_TextureMap_t_1168 *)texture_map);
break;
default:
FIXME("Unsupported IVRRenderModels version! %u\n", version);
break;
}
}
EVRRenderModelError ivrrendermodels_load_texture_d3d11_async(
EVRRenderModelError (*cpp_func)(void *, TextureID_t, void *, void **),
void *linux_side, TextureID_t texture_id, void *device,
void **dst_texture, unsigned int version)
{
struct winRenderModel_TextureMap_t_1015 *texture_map;
EVRRenderModelError error;
D3D11_TEXTURE2D_DESC desc;
ID3D11Device *d3d11_device = device;
ID3D11Texture2D *texture;
HRESULT hr;
error = load_linux_texture_map(linux_side, texture_id, &texture_map, version);
if (error == VRRenderModelError_Loading)
{
TRACE("Loading.\n");
return error;
}
if (error != VRRenderModelError_None)
{
WARN("Failed to load texture %#x.\n", error);
return error;
}
desc.Width = texture_map->unWidth;
desc.Height = texture_map->unHeight;
desc.MipLevels = 1;
desc.ArraySize = 1;
desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM_SRGB;
desc.SampleDesc.Count = 1;
desc.SampleDesc.Quality = 0;
desc.Usage = D3D11_USAGE_DEFAULT;
desc.BindFlags = D3D11_BIND_SHADER_RESOURCE;
desc.CPUAccessFlags = 0;
desc.MiscFlags = 0;
hr = d3d11_device->lpVtbl->CreateTexture2D(d3d11_device, &desc, NULL, &texture);
if (FAILED(hr))
{
WARN("Failed to create D3D11 texture %#x\n", hr);
free_linux_texture_map(linux_side, texture_map, version);
return VRRenderModelError_InvalidTexture;
}
error = load_into_texture_d3d11(texture, texture_map);
if (error == VRRenderModelError_None)
{
*dst_texture = texture;
}
else
{
texture->lpVtbl->Release(texture);
*dst_texture = NULL;
}
free_linux_texture_map(linux_side, texture_map, version);
return error;
}
void ivrrendermodels_free_texture_d3d11(
void (*cpp_func)(void *, void *),
void *linux_side, void *dst_texture, unsigned int version)
{
ID3D11Texture2D *d3d11_texture = dst_texture;
d3d11_texture->lpVtbl->Release(d3d11_texture);
}
EVRRenderModelError ivrrendermodels_load_into_texture_d3d11_async(
EVRRenderModelError (*cpp_func)(void *, TextureID_t, void *),
void *linux_side, TextureID_t texture_id, void *dst_texture, unsigned int version)
{
struct winRenderModel_TextureMap_t_1015 *texture_map;
IUnknown *unk = dst_texture;
EVRRenderModelError error;
ID3D11Texture2D *texture;
if (!dst_texture)
return VRRenderModelError_InvalidArg;
error = load_linux_texture_map(linux_side, texture_id, &texture_map, version);
if (error == VRRenderModelError_Loading)
{
TRACE("Loading.\n");
return error;
}
if (error != VRRenderModelError_None)
{
WARN("Failed to load texture %#x.\n", error);
return error;
}
if (SUCCEEDED(unk->lpVtbl->QueryInterface(unk, &IID_ID3D11Texture2D, (void **)&texture)))
{
error = load_into_texture_d3d11(texture, texture_map);
texture->lpVtbl->Release(texture);
}
else
{
FIXME("Expected 2D texture.\n");
error = VRRenderModelError_NotSupported;
}
free_linux_texture_map(linux_side, texture_map, version);
return error;
}
vrmb_typeb ivrmailbox_undoc3(
vrmb_typeb (*cpp_func)(void *, vrmb_typea, const char *, const char *),
void *linux_side, vrmb_typea a, const char *b, const char *c, unsigned int version)
{
vrmb_typeb r;
char *converted = json_convert_paths(c);
r = cpp_func(linux_side, a, b, converted ? converted : c);
free(converted);
return r;
}
#pragma pack(push, 8)
struct winInputDigitalActionData_t {
bool bActive;
VRInputValueHandle_t activeOrigin;
bool bState;
bool bChanged;
float fUpdateTime;
} __attribute__ ((ms_struct));
#pragma pack(pop)
EVRInputError ivrinput_get_digital_action_data(
void *func,
void *linux_side, VRActionHandle_t action_handle, void *action_data, uint32_t action_data_size,
VRInputValueHandle_t restrict_to_device, unsigned int version)
{
EVRInputError (*cpp_func)(void *, VRActionHandle_t, struct winInputDigitalActionData_t *, uint32_t, VRInputValueHandle_t) = func;
#ifdef __x86_64__
return cpp_func(linux_side, action_handle, action_data, action_data_size, restrict_to_device);
#else
/* Digital action state change fixup hack. */
struct winInputDigitalActionData_t *data = action_data;
LARGE_INTEGER qpf;
EVRInputError ret;
unsigned int i;
ret = cpp_func(linux_side, action_handle, action_data, action_data_size, restrict_to_device);
TRACE("handle %s, data %p, data_size %u, restrict %s, origin %s, state %#x, changed %#x, ret %u, active %#x.\n",
wine_dbgstr_longlong(action_handle), action_data, action_data_size,
wine_dbgstr_longlong(restrict_to_device), wine_dbgstr_longlong(data->activeOrigin),
data->bState, data->bChanged, ret, data->bActive);
if (ret)
return ret;
if (action_data_size != sizeof(*data))
{
WARN("Unexpected action_data_size %u.\n", action_data_size);
return 0;
}
if (!data->bActive)
return 0;
if (!compositor_data.qpf_freq.QuadPart)
QueryPerformanceFrequency(&compositor_data.qpf_freq);
QueryPerformanceCounter(&qpf);
for (i = 0; i < compositor_data.digital_action_count; ++i)
{
if (compositor_data.digital_actions_state[i].action == action_handle
&& compositor_data.digital_actions_state[i].origin == data->activeOrigin)
{
if ((data->bChanged = (!compositor_data.digital_actions_state[i].previous_state != !data->bState)))
{
TRACE("action %s (%s) changed to %#x, data->fUpdateTime %f.\n", wine_dbgstr_longlong(action_handle),
wine_dbgstr_longlong(restrict_to_device), data->bState, data->fUpdateTime);
compositor_data.digital_actions_state[i].update_qpf_time = qpf;
compositor_data.digital_actions_state[i].previous_state = data->bState;
}
if (compositor_data.digital_actions_state[i].update_qpf_time.QuadPart)
data->fUpdateTime = -(float)(qpf.QuadPart
- compositor_data.digital_actions_state[i].update_qpf_time.QuadPart)
/ compositor_data.qpf_freq.QuadPart;
return 0;
}
}
if (i == ARRAY_SIZE(compositor_data.digital_actions_state))
{
static unsigned int once;
if (!once++)
WARN("Too many actions.\n");
return 0;
}
compositor_data.digital_actions_state[i].action = action_handle;
compositor_data.digital_actions_state[i].origin = data->activeOrigin;
compositor_data.digital_actions_state[i].previous_state = data->bState;
compositor_data.digital_actions_state[i].update_qpf_time = qpf;
++compositor_data.digital_action_count;
return 0;
#endif
}
| 27,558 |
2,508 | <reponame>nitinkr-aktivolabs/JTCalendar
//
// JTHorizontalCalendar.h
// JTCalendar
//
// Created by <NAME>
//
#import <UIKit/UIKit.h>
#import "JTContent.h"
@interface JTHorizontalCalendarView : UIScrollView<JTContent>
@property (nonatomic, weak) JTCalendarManager *manager;
@property (nonatomic) NSDate *date;
/*!
* Must be call if override the class
*/
- (void)commonInit;
@end
| 157 |
16,870 | <reponame>chi-w-ng/flatbuffers<filename>tests/MyGame/Example2/MonsterT.java
// automatically generated by the FlatBuffers compiler, do not modify
package MyGame.Example2;
import java.nio.*;
import java.lang.*;
import java.util.*;
import com.google.flatbuffers.*;
public class MonsterT {
public MonsterT() {
}
}
| 107 |
3,428 | <filename>lib/node_modules/@stdlib/datasets/spam-assassin/data/spam-2/00813.33bf420f192b90e27c45d3053ecbc6d4.json
{"id":"00813","group":"spam-2","checksum":{"type":"MD5","value":"33bf420f192b90e27c45d3053ecbc6d4"},"text":"From <EMAIL> Mon Jul 22 18:39:20 2002\nReturn-Path: <<EMAIL>>\nDelivered-To: [email protected]\nReceived: from localhost (localhost [127.0.0.1])\n\tby phobos.labs.netnoteinc.com (Postfix) with ESMTP id D8CB9440CC\n\tfor <jm@localhost>; Mon, 22 Jul 2002 13:39:18 -0400 (EDT)\nReceived: from dogma.slashnull.org [212.17.35.15]\n\tby localhost with IMAP (fetchmail-5.9.0)\n\tfor jm@localhost (single-drop); Mon, 22 Jul 2002 18:39:18 +0100 (IST)\nReceived: from webnote.net (mail.webnote.net [193.120.211.219]) by\n dogma.slashnull.org (8.11.6/8.11.6) with ESMTP id g6MG1PY16605 for\n <<EMAIL>>; Mon, 22 Jul 2002 17:01:25 +0100\nReceived: from mandark.labs.netnoteinc.com ([192.168.3.1140]) by\n webnote.net (8.9.3/8.9.3) with ESMTP id JAA26624 for <<EMAIL>>;\n Sun, 21 Jul 2002 09:15:26 +0100\nReceived: from 2172.16.17.32 ([211.251.139.129]) by\n mandark.labs.netnoteinc.com (8.11.6/8.11.6) with SMTP id g6L8FNp07161 for\n <<EMAIL>>; Sun, 21 Jul 2002 09:15:24 +0100\nMessage-Id: <<EMAIL>1<EMAIL>>\nFrom: ldneYour Buddy <<EMAIL>>\nTo: <EMAIL>.Friends<EMAIL>inc.com\nCc: \nSubject: Say \"Goodbye\" to the 9-5 yhe\nSender: ldneYour Buddy <<EMAIL>>\nMIME-Version: 1.0\nDate: Sun, 21 Jul 2002 01:19:02 -0700\nX-Mailer: AOL 7.0 for Windows US sub 118\nX-Priority: 1\nContent-Type: text/html; charset=\"iso-8859-1\"\n\n<html>\n<body>\n<p align=\"center\"><b><font size=\"5\" color=\"#FF0000\">Fire Your Boss...</font></b><font size=\"5\"><br>\n</font>Say "Goodbye" to the 9-5!</p>\n<font FACE=\"Times New Roman\" SIZE=\"3\">\n<p align=\"center\">Tired of working to make someone else wealthy?</p>\n<p align=\"center\">FREE tape teaches you how to make YOU wealthy!</p>\n<p align=\"center\"><a href=\"mailto:<EMAIL>?subject=free-tape\">Click here and \nsend your name and mailing address for a free copy</a></p>\n<p align=\"center\"> </p>\n</font><font FACE=\"Times New Roman\" size=\"2\">\n<p align=\"center\"><a href=\"mailto:<EMAIL>\">To unsubscribe click \nhere</a></p>\n</font>\n</body>\n</html> \n\nxgcqyahtsvdwhqnhjiuweimhfumiaiyawr\n\n\n"} | 986 |
850 | from ..utils import TranspileTestCase
class DocstringTests(TranspileTestCase):
def test_method_docstring(self):
self.assertCodeExecution("""
def test():
"This is the docstring"
return 3
print(test())
print(test.__doc__)
""")
def test_naked_string(self):
self.assertCodeExecution("""
def test():
x = 3
"This is a naked string"
return x
print(test())
print(test.__doc__)
""")
| 315 |
5,169 | <reponame>Gantios/Specs<gh_stars>1000+
{
"name": "HBHybridCollectionView",
"version": "1.0.6",
"summary": "Hybrid scroll collection view.",
"homepage": "https://github.com/Ban-Tang/HBHybridCollectionView",
"authors": {
"Roylee": "<EMAIL>"
},
"description": "A collection for hybrid scrolling, you can use a swipe list in a collection footer.",
"platforms": {
"ios": "8.0"
},
"requires_arc": true,
"license": {
"type": "MIT",
"file": "LICENSE"
},
"source": {
"git": "https://github.com/Ban-Tang/HBHybridCollectionView.git",
"tag": "1.0.6"
},
"source_files": "hybrid/Hybrid/**/*.{h,m}",
"private_header_files": [
"hybrid/Hybrid/HybridCollectionViewObserver.h",
"hybrid/Hybrid/HybridCollectionViewProxy.h"
]
}
| 312 |
1,695 | <reponame>gautamkmr/caffe2<gh_stars>1000+
import fft.complex_soa
arg_t = Argument(ptr(const_float_), name="t")
arg_f = Argument(ptr(float_), name="f")
with Function("nnp_fft16_soa__avx2",
(arg_t, arg_f),
target=uarch.default + isa.fma3 + isa.avx2):
reg_t = GeneralPurposeRegister64()
LOAD.ARGUMENT(reg_t, arg_t)
reg_f = GeneralPurposeRegister64()
LOAD.ARGUMENT(reg_f, arg_f)
ymm_real = YMMRegister(), YMMRegister()
ymm_imag = YMMRegister(), YMMRegister()
for i, ymm_data in enumerate(ymm_real + ymm_imag):
VMOVUPS(ymm_data, [reg_t + i * YMMRegister.size])
fft.complex_soa.fft16_within_rows(ymm_real, ymm_imag)
for i, ymm_data in enumerate(ymm_real + ymm_imag):
VMOVUPS([reg_f + i * YMMRegister.size], ymm_data)
RETURN()
with Function("nnp_fft8_soa__avx2",
(arg_t, arg_f),
target=uarch.default + isa.fma3 + isa.avx2):
reg_t = GeneralPurposeRegister64()
LOAD.ARGUMENT(reg_t, arg_t)
reg_f = GeneralPurposeRegister64()
LOAD.ARGUMENT(reg_f, arg_f)
ymm_real, ymm_imag = YMMRegister(), YMMRegister()
VMOVUPS(ymm_real, [reg_t])
VMOVUPS(ymm_imag, [reg_t + YMMRegister.size])
fft.complex_soa.fft8_within_rows(ymm_real, ymm_imag)
VMOVUPS([reg_f], ymm_real)
VMOVUPS([reg_f + YMMRegister.size], ymm_imag)
RETURN()
with Function("nnp_ifft8_soa__avx2",
(arg_t, arg_f),
target=uarch.default + isa.fma3 + isa.avx2):
reg_t = GeneralPurposeRegister64()
LOAD.ARGUMENT(reg_t, arg_t)
reg_f = GeneralPurposeRegister64()
LOAD.ARGUMENT(reg_f, arg_f)
ymm_real, ymm_imag = YMMRegister(), YMMRegister()
VMOVUPS(ymm_real, [reg_t])
VMOVUPS(ymm_imag, [reg_t + YMMRegister.size])
fft.complex_soa.fft8_within_rows(ymm_real, ymm_imag, transformation="inverse")
VMOVUPS([reg_f], ymm_real)
VMOVUPS([reg_f + YMMRegister.size], ymm_imag)
RETURN()
with Function("nnp_ifft16_soa__avx2",
(arg_f, arg_t),
target=uarch.default + isa.fma3 + isa.avx2):
reg_f = GeneralPurposeRegister64()
LOAD.ARGUMENT(reg_f, arg_f)
reg_t = GeneralPurposeRegister64()
LOAD.ARGUMENT(reg_t, arg_t)
ymm_real = YMMRegister(), YMMRegister()
ymm_imag = YMMRegister(), YMMRegister()
for i, ymm_data in enumerate(ymm_real + ymm_imag):
VMOVUPS(ymm_data, [reg_f + i * YMMRegister.size])
fft.complex_soa.ifft16_within_rows(ymm_real, ymm_imag)
for i, ymm_data in enumerate(ymm_real + ymm_imag):
VMOVUPS([reg_t + i * YMMRegister.size], ymm_data)
RETURN()
| 1,211 |
335 | <filename>U/Unintelligible_adjective.json
{
"word": "Unintelligible",
"definitions": [
"Impossible to understand."
],
"parts-of-speech": "Adjective"
} | 76 |
303 | <reponame>didindinn/database-as-a-service
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from django.utils.translation import ugettext_lazy as _
from django.contrib import admin
import logging
LOG = logging.getLogger(__name__)
class ConfigurationAdmin(admin.ModelAdmin):
list_display = ["name", "value", "description"]
search_fields = ("name",)
| 129 |
3,212 | /*
* 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.nifi.persistence;
import org.apache.nifi.util.NiFiProperties;
import org.junit.Before;
import org.junit.Test;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.StandardOpenOption;
import java.nio.file.attribute.BasicFileAttributes;
import java.nio.file.attribute.FileTime;
import java.text.SimpleDateFormat;
import java.util.Date;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.testng.Assert.assertNull;
public class TestFlowConfigurationArchiveManager {
private final File flowXmlFile = new File("./target/flow-archive/flow.xml.gz");
private final File archiveDir = new File("./target/flow-archive");
@Before
public void before() throws Exception {
// Clean up old files.
if (Files.isDirectory(archiveDir.toPath())) {
Files.walkFileTree(archiveDir.toPath(), new SimpleFileVisitor<Path>(){
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
Files.delete(file);
return FileVisitResult.CONTINUE;
}
});
}
// Create original flow.xml.gz
Files.createDirectories(flowXmlFile.getParentFile().toPath());
try (OutputStream os = Files.newOutputStream(flowXmlFile.toPath(),
StandardOpenOption.CREATE, StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING)) {
// 10 bytes.
os.write("0123456789".getBytes());
}
}
private Object getPrivateFieldValue(final FlowConfigurationArchiveManager archiveManager, final String fieldName)
throws NoSuchFieldException, IllegalAccessException {
final Field field = FlowConfigurationArchiveManager.class.getDeclaredField(fieldName);
field.setAccessible(true);
return field.get(archiveManager);
}
@Test
public void testNiFiPropertiesDefault() throws Exception {
final NiFiProperties defaultProperties = mock(NiFiProperties.class);
when(defaultProperties.getFlowConfigurationFile()).thenReturn(flowXmlFile);
when(defaultProperties.getFlowConfigurationArchiveMaxCount()).thenReturn(null);
when(defaultProperties.getFlowConfigurationArchiveMaxTime()).thenReturn(null);
when(defaultProperties.getFlowConfigurationArchiveMaxStorage()).thenReturn(null);
final FlowConfigurationArchiveManager archiveManager = new FlowConfigurationArchiveManager(defaultProperties);
assertNull(getPrivateFieldValue(archiveManager, "maxCount"));
assertEquals(60L * 60L * 24L * 30L * 1000L, getPrivateFieldValue(archiveManager, "maxTimeMillis"));
assertEquals(500L * 1024L * 1024L, getPrivateFieldValue(archiveManager, "maxStorageBytes"));
}
@Test
public void testNiFiPropertiesMaxTime() throws Exception {
final NiFiProperties withMaxTime = mock(NiFiProperties.class);
when(withMaxTime.getFlowConfigurationFile()).thenReturn(flowXmlFile);
when(withMaxTime.getFlowConfigurationArchiveMaxCount()).thenReturn(null);
when(withMaxTime.getFlowConfigurationArchiveMaxTime()).thenReturn("10 days");
when(withMaxTime.getFlowConfigurationArchiveMaxStorage()).thenReturn(null);
final FlowConfigurationArchiveManager archiveManager = new FlowConfigurationArchiveManager(withMaxTime);
assertNull(getPrivateFieldValue(archiveManager, "maxCount"));
assertEquals(60L * 60L * 24L * 10L * 1000L, getPrivateFieldValue(archiveManager, "maxTimeMillis"));
assertNull(getPrivateFieldValue(archiveManager, "maxStorageBytes"));
}
@Test
public void testNiFiPropertiesMaxStorage() throws Exception {
final NiFiProperties withMaxTime = mock(NiFiProperties.class);
when(withMaxTime.getFlowConfigurationFile()).thenReturn(flowXmlFile);
when(withMaxTime.getFlowConfigurationArchiveMaxCount()).thenReturn(null);
when(withMaxTime.getFlowConfigurationArchiveMaxTime()).thenReturn(null);
when(withMaxTime.getFlowConfigurationArchiveMaxStorage()).thenReturn("10 MB");
final FlowConfigurationArchiveManager archiveManager = new FlowConfigurationArchiveManager(withMaxTime);
assertNull(getPrivateFieldValue(archiveManager, "maxCount"));
assertNull(getPrivateFieldValue(archiveManager, "maxTimeMillis"));
assertEquals(10L * 1024L * 1024L, getPrivateFieldValue(archiveManager, "maxStorageBytes"));
}
@Test
public void testNiFiPropertiesCount() throws Exception {
final NiFiProperties onlyCount = mock(NiFiProperties.class);
when(onlyCount.getFlowConfigurationFile()).thenReturn(flowXmlFile);
when(onlyCount.getFlowConfigurationArchiveMaxCount()).thenReturn(10);
when(onlyCount.getFlowConfigurationArchiveMaxTime()).thenReturn(null);
when(onlyCount.getFlowConfigurationArchiveMaxStorage()).thenReturn(null);
final FlowConfigurationArchiveManager archiveManager = new FlowConfigurationArchiveManager(onlyCount);
assertEquals(10, getPrivateFieldValue(archiveManager, "maxCount"));
assertNull(getPrivateFieldValue(archiveManager, "maxTimeMillis"));
assertNull(getPrivateFieldValue(archiveManager, "maxStorageBytes"));
}
@Test(expected = NoSuchFileException.class)
public void testArchiveWithoutOriginalFile() throws Exception {
final NiFiProperties properties = mock(NiFiProperties.class);
when(properties.getFlowConfigurationArchiveDir()).thenReturn(archiveDir.getPath());
when(properties.getFlowConfigurationFile()).thenReturn(flowXmlFile);
final File flowXmlFile = new File("does-not-exist");
final FlowConfigurationArchiveManager archiveManager = new FlowConfigurationArchiveManager(properties);
archiveManager.archive(flowXmlFile);
}
private void createSimulatedOldArchives(final File[] oldArchives, final long intervalMillis) throws Exception {
// Create old archive files. Altering file name and last modified date to simulate existing files.
final long now = System.currentTimeMillis();
final SimpleDateFormat dateFormat = new SimpleDateFormat("HHmmss");
final FlowConfigurationArchiveManager archiveManager = createArchiveManager(null,null, null);
for (int i = oldArchives.length; i > 0; i--) {
final Date date = new Date(now - (intervalMillis * i));
final String hhmmss = dateFormat.format(date);
final File archiveFile = archiveManager.archive(flowXmlFile);
final String renamedArchiveName = archiveFile.getName().replaceFirst("T[\\d]{6}", "T" + hhmmss);
final File renamedArchive = archiveFile.getParentFile().toPath().resolve(renamedArchiveName).toFile();
archiveFile.renameTo(renamedArchive);
Files.setLastModifiedTime(renamedArchive.toPath(), FileTime.fromMillis(date.getTime()));
oldArchives[oldArchives.length - i] = renamedArchive;
}
}
private FlowConfigurationArchiveManager createArchiveManager(final Integer maxCount, final String maxTime, final String maxStorage) {
final NiFiProperties properties = mock(NiFiProperties.class);
when(properties.getFlowConfigurationArchiveDir()).thenReturn(archiveDir.getPath());
when(properties.getFlowConfigurationArchiveMaxCount()).thenReturn(maxCount);
when(properties.getFlowConfigurationArchiveMaxTime()).thenReturn(maxTime);
when(properties.getFlowConfigurationArchiveMaxStorage()).thenReturn(maxStorage);
when(properties.getFlowConfigurationFile()).thenReturn(flowXmlFile);
return new FlowConfigurationArchiveManager(properties);
}
@Test
public void testArchiveExpiration() throws Exception {
final long intervalMillis = 60_000;
File[] oldArchives = new File[5];
createSimulatedOldArchives(oldArchives, intervalMillis);
// Now, we will test expiration. There should be following old archives created above:
// -5 min, -4 min, -3min, -2min, -1min
final long maxTimeForExpirationTest = intervalMillis * 3 + (intervalMillis / 2);
final FlowConfigurationArchiveManager archiveManager = createArchiveManager(null, maxTimeForExpirationTest + "ms", null);
final File archive = archiveManager.archive(flowXmlFile);
assertTrue(!oldArchives[0].exists()); // -5 min
assertTrue(!oldArchives[1].exists()); // -4 min
assertTrue(oldArchives[2].isFile()); // -3 min
assertTrue(oldArchives[3].isFile()); // -2 min
assertTrue(oldArchives[4].isFile()); // -1 min
assertTrue(archive.exists()); // new archive
assertTrue("Original file should remain intact", flowXmlFile.isFile());
}
@Test
public void testArchiveStorageSizeLimit() throws Exception {
final long intervalMillis = 60_000;
File[] oldArchives = new File[5];
createSimulatedOldArchives(oldArchives, intervalMillis);
// Now, we will test storage size limit. There should be following old archives created above:
// -5 min, -4 min, -3min, -2min, -1min, each of those have 10 bytes.
final FlowConfigurationArchiveManager archiveManager = createArchiveManager(null,null, "20b");
final File archive = archiveManager.archive(flowXmlFile);
assertTrue(!oldArchives[0].exists()); // -5 min
assertTrue(!oldArchives[1].exists()); // -4 min
assertTrue(!oldArchives[2].exists()); // -3 min
assertTrue(!oldArchives[3].exists()); // -2 min
assertTrue(oldArchives[4].exists()); // -1 min
assertTrue(archive.exists()); // new archive
assertTrue("Original file should remain intact", flowXmlFile.isFile());
}
@Test
public void testArchiveStorageCountLimit() throws Exception {
final long intervalMillis = 60_000;
File[] oldArchives = new File[5];
createSimulatedOldArchives(oldArchives, intervalMillis);
// Now, we will test count limit. There should be following old archives created above:
// -5 min, -4 min, -3min, -2min, -1min, each of those have 10 bytes.
final FlowConfigurationArchiveManager archiveManager = createArchiveManager(2,null, null);
final File archive = archiveManager.archive(flowXmlFile);
assertTrue(!oldArchives[0].exists()); // -5 min
assertTrue(!oldArchives[1].exists()); // -4 min
assertTrue(!oldArchives[2].exists()); // -3 min
assertTrue(!oldArchives[3].exists()); // -2 min
assertTrue(oldArchives[4].exists()); // -1 min
assertTrue(archive.exists()); // new archive
assertTrue("Original file should remain intact", flowXmlFile.isFile());
}
@Test
public void testLargeConfigFile() throws Exception{
final long intervalMillis = 60_000;
File[] oldArchives = new File[5];
createSimulatedOldArchives(oldArchives, intervalMillis);
// Now, we will test storage size limit. There should be following old archives created above:
// -5 min, -4 min, -3min, -2min, -1min, each of those have 10 bytes.
final FlowConfigurationArchiveManager archiveManager = createArchiveManager(null,null, "3b");
final File archive = archiveManager.archive(flowXmlFile);
assertTrue(!oldArchives[0].exists()); // -5 min
assertTrue(!oldArchives[1].exists()); // -4 min
assertTrue(!oldArchives[2].exists()); // -3 min
assertTrue(!oldArchives[3].exists()); // -2 min
assertTrue(!oldArchives[4].exists()); // -1 min
assertTrue("Even if flow config file is larger than maxStorage file, it can be archived", archive.exists()); // new archive
assertTrue("Original file should remain intact", flowXmlFile.isFile());
}
}
| 4,525 |
14,668 | // Copyright 2021 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 "chromeos/services/bluetooth_config/public/cpp/cros_bluetooth_config_util.h"
#include "base/strings/utf_string_conversions.h"
namespace chromeos {
namespace bluetooth_config {
bool IsBluetoothEnabledOrEnabling(
const mojom::BluetoothSystemState system_state) {
return system_state == mojom::BluetoothSystemState::kEnabled ||
system_state == mojom::BluetoothSystemState::kEnabling;
}
std::u16string GetPairedDeviceName(
const mojom::PairedBluetoothDeviceProperties* paired_device_properties) {
if (paired_device_properties->nickname.has_value())
return base::ASCIIToUTF16(paired_device_properties->nickname.value());
return paired_device_properties->device_properties->public_name;
}
} // namespace bluetooth_config
} // namespace chromeos
| 300 |
368 | from typing import Iterable, Optional
from cutecharts.charts.basic import BasicChart
class Scatter(BasicChart):
CHART_TYPE = "XY"
def set_options(
self,
x_label: str = "",
y_label: str = "",
x_tick_count: int = 3,
y_tick_count: int = 3,
is_show_line: bool = False,
dot_size: int = 1,
time_format: Optional[str] = None,
legend_pos: str = "upLeft",
colors: Optional[Iterable] = None,
font_family: Optional[str] = None,
):
"""
:param x_label: X 坐标轴名称
:param y_label: Y 坐标轴名称
:param x_tick_count: X 轴刻度分割段数
:param y_tick_count: Y 轴刻度分割段数
:param is_show_line: 是否将散点连成线
:param dot_size: 散点大小
:param time_format: 日期格式
:param legend_pos: 图例位置,有 "upLeft", "upRight", "downLeft", "downRight" 可选
:param colors: label 颜色数组
:param font_family: CSS font-family
"""
self.opts.update({"xLabel": x_label, "yLabel": y_label})
self.opts["options"] = {
"xTickCount": x_tick_count,
"yTickCount": y_tick_count,
"legendPosition": self._switch_pos(legend_pos),
"dataColors": colors,
"fontFamily": font_family,
"showLine": is_show_line,
"dotSize": dot_size,
"timeFormat": time_format,
}
return self
def add_series(self, name: str, data: Iterable):
"""
:param name: series 名称
:param data: series 数据列表,[(x1, y1), (x2, y2)]
"""
pairs = [{"x": item[0], "y": item[1]} for item in data]
self.opts["data"]["datasets"].append({"label": name, "data": pairs})
return self
| 1,031 |
1,144 | /* SPDX-License-Identifier: GPL-2.0+ */
/*
* (C) Copyright 2015 Google, Inc
*
* (C) Copyright 2008-2014 Rockchip Electronics
*/
#ifndef __RC4_H
#define __RC4_H
/**
* rc4_encode() - encode a buf with the RC4 cipher
*
* @buf: Buffer to encode (it is overwrite in the process
* @len: Length of buffer in bytes
* @key: 16-byte key to use
*/
void rc4_encode(unsigned char *buf, unsigned int len, unsigned char key[16]);
#endif
| 154 |
1,486 | <filename>gsi_openssh/source/regress/unittests/hostkeys/tests.c
/* $OpenBSD: tests.c,v 1.1 2015/02/16 22:18:34 djm Exp $ */
/*
* Regress test for known_hosts-related API.
*
* Placed in the public domain
*/
void tests(void);
void test_iterate(void); /* test_iterate.c */
void
tests(void)
{
test_iterate();
}
| 127 |
348 | {"nom":"Couches","circ":"3ème circonscription","dpt":"Saône-et-Loire","inscrits":1003,"abs":563,"votants":440,"blancs":29,"nuls":10,"exp":401,"res":[{"nuance":"REM","nom":"M. <NAME>","voix":248},{"nuance":"LR","nom":"M. <NAME>","voix":153}]} | 99 |
2,338 | // RUN: rm -rf %t
// RUN: %clang_cc1 -fmodules -fmodules-cache-path=%t -fimplicit-module-maps -I%S/Inputs/suggest-include %s -verify
#include "empty.h" // import the module file
// [email protected]:2 {{here}}
// [email protected]:1 {{here}}
// [email protected]:1 {{here}}
// [email protected]:1 {{here}}
// [email protected]:1 {{here}}
// [email protected]:1 {{here}}
// [email protected]:1 {{here}}
// [email protected]:1 {{here}}
void f() {
(void)::usetextual1; // expected-error {{missing '#include "usetextual1.h"'}}
(void)::usetextual2; // expected-error {{missing '#include "usetextual2.h"'}}
(void)::textual3; // expected-error-re {{{{^}}missing '#include "usetextual3.h"'}}
// If the declaration is in an include-guarded header, make sure we suggest
// including that rather than importing a module. In this case, there could
// be more than one module, and the module name we picked is almost certainly
// wrong.
(void)::textual4; // expected-error {{missing '#include "usetextual4.h"'; 'textual4' must be declared before it is used}}
(void)::textual5; // expected-error {{missing '#include "usetextual5.h"'; 'textual5' must be declared before it is used}}
// Don't suggest #including a private header.
// FIXME: We could suggest including "useprivate1.h" here, as it's the only
// public way to get at this declaration.
(void)::private1; // expected-error-re {{{{^}}declaration of 'private1'}}
// FIXME: Should we be suggesting an import at all here? Should declarations
// in private headers be visible when the surrounding module is imported?
(void)::private2; // expected-error-re {{{{^}}declaration of 'private2'}}
// Even if we suggest an include for private1, we should not do so here.
(void)::private3; // expected-error-re {{{{^}}declaration of 'private3'}}
}
| 626 |
3,395 | import pytest
import polars as pl
def test_compare_series_value_mismatch() -> None:
srs1 = pl.Series([1, 2, 3])
srs2 = pl.Series([2, 3, 4])
with pytest.raises(AssertionError, match="Series are different\n\nValue mismatch"):
pl.testing.assert_series_equal(srs1, srs2)
def test_compare_series_nulls_are_equal() -> None:
srs1 = pl.Series([1, 2, None])
srs2 = pl.Series([1, 2, None])
pl.testing.assert_series_equal(srs1, srs2)
def test_compare_series_value_mismatch_string() -> None:
srs1 = pl.Series(["hello", "no"])
srs2 = pl.Series(["hello", "yes"])
with pytest.raises(
AssertionError, match="Series are different\n\nExact value mismatch"
):
pl.testing.assert_series_equal(srs1, srs2)
def test_compare_series_type_mismatch() -> None:
srs1 = pl.Series([1, 2, 3])
srs2 = pl.DataFrame({"col1": [2, 3, 4]})
with pytest.raises(AssertionError, match="Series are different\n\nType mismatch"):
pl.testing.assert_series_equal(srs1, srs2) # type: ignore
srs3 = pl.Series([1.0, 2.0, 3.0])
with pytest.raises(AssertionError, match="Series are different\n\nDtype mismatch"):
pl.testing.assert_series_equal(srs1, srs3)
def test_compare_series_name_mismatch() -> None:
srs1 = pl.Series(values=[1, 2, 3], name="srs1")
srs2 = pl.Series(values=[1, 2, 3], name="srs2")
with pytest.raises(AssertionError, match="Series are different\n\nName mismatch"):
pl.testing.assert_series_equal(srs1, srs2)
def test_compare_series_shape_mismatch() -> None:
srs1 = pl.Series(values=[1, 2, 3, 4], name="srs1")
srs2 = pl.Series(values=[1, 2, 3], name="srs2")
with pytest.raises(AssertionError, match="Series are different\n\nShape mismatch"):
pl.testing.assert_series_equal(srs1, srs2)
def test_compare_series_value_exact_mismatch() -> None:
srs1 = pl.Series([1.0, 2.0, 3.0])
srs2 = pl.Series([1.0, 2.0 + 1e-7, 3.0])
with pytest.raises(
AssertionError, match="Series are different\n\nExact value mismatch"
):
pl.testing.assert_series_equal(srs1, srs2, check_exact=True)
def test_assert_frame_equal_pass() -> None:
df1 = pl.DataFrame({"a": [1, 2]})
df2 = pl.DataFrame({"a": [1, 2]})
pl.testing.assert_frame_equal(df1, df2)
def test_assert_frame_equal_types() -> None:
df1 = pl.DataFrame({"a": [1, 2]})
srs1 = pl.Series(values=[1, 2], name="a")
with pytest.raises(AssertionError):
pl.testing.assert_frame_equal(df1, srs1) # type: ignore
def test_assert_frame_equal_length_mismatch() -> None:
df1 = pl.DataFrame({"a": [1, 2]})
df2 = pl.DataFrame({"a": [1, 2, 3]})
with pytest.raises(AssertionError):
pl.testing.assert_frame_equal(df1, df2)
def test_assert_frame_equal_column_mismatch() -> None:
df1 = pl.DataFrame({"a": [1, 2]})
df2 = pl.DataFrame({"b": [1, 2]})
with pytest.raises(AssertionError):
pl.testing.assert_frame_equal(df1, df2)
def test_assert_frame_equal_column_mismatch2() -> None:
df1 = pl.DataFrame({"a": [1, 2]})
df2 = pl.DataFrame({"a": [1, 2], "b": [3, 4]})
with pytest.raises(AssertionError):
pl.testing.assert_frame_equal(df1, df2)
def test_assert_frame_equal_column_mismatch_order() -> None:
df1 = pl.DataFrame({"b": [3, 4], "a": [1, 2]})
df2 = pl.DataFrame({"a": [1, 2], "b": [3, 4]})
with pytest.raises(AssertionError):
pl.testing.assert_frame_equal(df1, df2)
| 1,554 |
1,194 | package ca.uhn.fhir.parser;
import org.hl7.fhir.dstu3.model.Observation;
import ca.uhn.fhir.model.api.annotation.ResourceDef;
@ResourceDef(name = "Observation", profile = CustomObservation.PROFILE)
public class CustomObservation extends Observation {
public static final String PROFILE = "http://custom_Observation";
private static final long serialVersionUID = 1L;
} | 122 |
2,025 | #pragma once
#include <iod/sio_utils.hh>
#include <silicon/symbols.hh>
#include <silicon/optional.hh>
namespace sl
{
using namespace iod;
using namespace s;
template <typename P>
struct params_t
{
params_t(P p) : params(p) {}
P params;
};
template <typename... P>
auto parameters(P... p)
{
typedef decltype(D(std::declval<P>()...)) sio_type;
return post_params_t<sio_type>(D(p...));
}
}
| 188 |
958 | <filename>scripts/interpolation.py
#! /usr/bin/python
'''
Data Interpolation
'''
import os, sys
import pandas as pd
def interpolate(dataframe, cols_to_interpolate):
for col in cols_to_interpolate:
dataframe[col] = dataframe[col].interpolate('spline', order=2)
return dataframe
def main(dir_path):
files = os.listdir(dir_path)
for file_name in files:
dataframe = pd.read_csv(os.path.join(dir_path, file_name))
dataframe = interpolate(dataframe, \
['high', 'open', 'low', 'close', 'volume', 'adj_close'])
print dataframe
break
if __name__=="__main__":
main(sys.argv[1])
| 281 |
339 | /*
*Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
*WSO2 Inc. 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.wso2.ei.dataservice.integration.test.services;
import org.apache.axiom.om.OMAbstractFactory;
import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.OMFactory;
import org.apache.axiom.om.OMNamespace;
import org.apache.axis2.AxisFault;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import org.wso2.carbon.automation.test.utils.axis2client.AxisServiceClient;
import org.wso2.ei.dataservice.integration.test.DSSIntegrationTest;
import org.wso2.ei.dataservice.integration.test.odata.ODataTestUtils;
import javax.xml.xpath.XPathExpressionException;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.wso2.ei.dataservice.integration.test.odata.ODataTestUtils.sendGET;
public class NestedQueryTestCase extends DSSIntegrationTest {
private static final Log log = LogFactory.getLog(NestedQueryTestCase.class);
private final OMFactory fac = OMAbstractFactory.getOMFactory();
private final OMNamespace omNs = fac.createOMNamespace("http://ws.wso2.org/dataservice/samples", "ns1");
private final String serviceName = "NestedQueryTest";
@BeforeClass(alwaysRun = true)
public void serviceDeployment() throws Exception {
super.init();
List<File> sqlFileLis = new ArrayList<File>();
sqlFileLis.add(selectSqlFile("CreateTables.sql"));
sqlFileLis.add(selectSqlFile("Offices.sql"));
sqlFileLis.add(selectSqlFile("Customers.sql"));
sqlFileLis.add(selectSqlFile("Employees.sql"));
sqlFileLis.add(selectSqlFile("Orders.sql"));
sqlFileLis.add(selectSqlFile("NestedQueryEmptyResult.sql"));
deployService(serviceName,
createArtifact(getResourceLocation() + File.separator + "dbs" + File.separator
+ "rdbms" + File.separator + "MySql" + File.separator
+ "NestedQueryTest.dbs", sqlFileLis));
}
@AfterClass(alwaysRun = true)
public void destroy() throws Exception {
deleteService(serviceName);
cleanup();
}
@Test(groups = {"wso2.dss"})
public void getCustomerOrdersNestedQuery() throws AxisFault, XPathExpressionException {
for (int i = 1; i < 6; i++) {
getCustomerOrders();
}
log.info("Customer Orders Nested Query verified");
}
@Test(groups = {"wso2.dss"})
public void listOfficeNestedQueryOperation() throws AxisFault, XPathExpressionException {
for (int i = 1; i < 6; i++) {
getOffices();
}
log.info("List Office Nested Query verified");
}
@Test(groups = {"wso2.dss"}, description = "nested query empty result test")
public void testNestedQueryEmptyResultJson() throws Exception {
String endpoint = getServiceUrlHttp(serviceName) + "/listOffices";
Map<String, String> headers = new HashMap<>();
headers.put("Accept", "application/json");
Object[] response = sendGET(endpoint, headers);
Assert.assertEquals(response[0], ODataTestUtils.OK, "Invalid status received");
Assert.assertTrue(response[1].toString().contains("\"Employees\":{}"), "Invalid result received");
}
private void getCustomerName() throws AxisFault, XPathExpressionException {
OMElement payload = fac.createOMElement("customerName", omNs);
OMElement customerNumber = fac.createOMElement("customerNumber", omNs);
customerNumber.setText("103");
payload.addChild(customerNumber);
OMElement result = new AxisServiceClient().sendReceive(payload, getServiceUrlHttp(serviceName), "customerName");
Assert.assertNotNull(result, "Response message null ");
log.debug(result);
Assert.assertTrue(result.toString().contains("<Name>At<NAME></Name>"), "Expected not same");
}
private void getCustomerOrders() throws AxisFault, XPathExpressionException {
OMElement payload = fac.createOMElement("customerOrders", omNs);
OMElement result = new AxisServiceClient().sendReceive(payload, getServiceUrlHttp(serviceName), "customerOrders");
Assert.assertNotNull(result, "Response message null ");
log.debug(result);
Assert.assertTrue(result.toString().contains("<Order><Order-number>"), "Expected not same");
Assert.assertTrue(result.toString().contains("<Customer><Name>"), "Expected not same");
Assert.assertTrue(result.toString().contains("</Customer>"), "Expected not same");
}
private void getEmployeesInOffice() throws AxisFault, XPathExpressionException {
OMElement payload = fac.createOMElement("employeesInOffice", omNs);
OMElement officeCode = fac.createOMElement("officeCode", omNs);
officeCode.setText("1");
payload.addChild(officeCode);
OMElement result = new AxisServiceClient().sendReceive(payload, getServiceUrlHttp(serviceName), "employeesInOffice");
Assert.assertNotNull(result, "Response message null ");
log.debug(result);
Assert.assertNotNull(result.getFirstElement(), "First Chilled null ");
log.debug(result.getFirstElement());
Assert.assertTrue(result.getFirstElement().toString().contains("<employeeNumber>1002</employeeNumber>"), "Expected not same");
}
private void getOffices() throws AxisFault, XPathExpressionException {
OMElement payload = fac.createOMElement("listOffices", omNs);
OMElement result = new AxisServiceClient().sendReceive(payload, getServiceUrlHttp(serviceName), "listOffices");
Assert.assertNotNull(result, "Response message null ");
log.debug(result);
Assert.assertTrue(result.toString().contains("<Office><officeCode>1</officeCode>"), "Expected not same");
Assert.assertTrue(result.toString().contains("<Employees><Employee><employeeNumber>"), "Expected not same");
}
}
| 2,481 |
3,269 | // Time: O(nlogm), m is the max of quantities
// Space: O(1)
class Solution {
public:
int minimizedMaximum(int n, vector<int>& quantities) {
int left = 1, right = *max_element(cbegin(quantities), cend(quantities));
while (left <= right) {
const auto& mid = left + (right - left) / 2;
if (check(n, quantities, mid)) {
right = mid - 1;
} else {
left = mid + 1;
}
}
return left;
}
private:
bool check(int n, const vector<int>& quantities, int x) {
return accumulate(cbegin(quantities), cend(quantities), 0,
[this, &x](const auto& total, const auto& q) {
return total + ceil_divide(q, x);
}) <= n;
}
int ceil_divide(int a, int b) {
return (a + (b - 1)) / b;
}
};
| 463 |
369 | #define SOKOL_IMPL
#include "sokol_fetch.h"
void use_fetch_impl(void) {
sfetch_setup(&(sfetch_desc_t){0});
}
| 57 |
6,497 | <gh_stars>1000+
package com.sohu.cache.web.controller;
import com.sohu.cache.entity.AppAudit;
import com.sohu.cache.entity.AppUser;
import com.sohu.cache.entity.InstanceAlertValueResult;
import com.sohu.cache.entity.InstanceInfo;
import com.sohu.cache.redis.RedisCenter;
import com.sohu.cache.stats.instance.InstanceDeployCenter;
import com.sohu.cache.stats.instance.InstanceStatsCenter;
import com.sohu.cache.web.enums.SuccessEnum;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
/**
* 应用后台管理
*
* @author leifu
* @Time 2014年7月3日
*/
@Controller
@RequestMapping("manage/instance")
public class InstanceManageController extends BaseController {
private Logger logger = LoggerFactory.getLogger(InstanceManageController.class);
@Resource(name = "instanceDeployCenter")
private InstanceDeployCenter instanceDeployCenter;
@Resource(name = "redisCenter")
private RedisCenter redisCenter;
@Resource(name = "instanceStatsCenter")
private InstanceStatsCenter instanceStatsCenter;
/**
* 上线(和下线分开)
*
* @param instanceId
*/
@RequestMapping(value = "/startInstance")
public ModelAndView doStartInstance(HttpServletRequest request, HttpServletResponse response, Model model, long appId, int instanceId) {
AppUser appUser = getUserInfo(request);
logger.warn("user {} startInstance {} ", appUser.getName(), instanceId);
boolean result = false;
if (instanceId > 0) {
try {
result = instanceDeployCenter.startExistInstance(appId, instanceId);
} catch (Exception e) {
logger.error(e.getMessage(), e);
model.addAttribute("message", e.getMessage());
}
} else {
logger.error("doStartInstance instanceId:{}", instanceId);
model.addAttribute("message", "wrong param");
}
logger.warn("user {} startInstance {} result is {}", appUser.getName(), instanceId, result);
if (result) {
model.addAttribute("success", SuccessEnum.SUCCESS.value());
} else {
model.addAttribute("success", SuccessEnum.FAIL.value());
}
return new ModelAndView();
}
@RequestMapping(value = "/scrollStartInstance")
public ModelAndView scrollStartInstance(HttpServletRequest request, Model model, String machineIp) {
AppUser appUser = getUserInfo(request);
logger.warn("user {} scroll startInstance ip :{} ", appUser.getName(), machineIp);
try {
List<InstanceAlertValueResult> instanceAlertValueResults = instanceDeployCenter.checkAndStartExceptionInstance(machineIp, false);
if (!CollectionUtils.isEmpty(instanceAlertValueResults)) {
model.addAttribute("message", "滚动重启:恢复实例数量:" + instanceAlertValueResults.size());
} else {
model.addAttribute("message", "滚动重启:无实例需要启动!");
}
model.addAttribute("success", SuccessEnum.SUCCESS.value());
} catch (Exception e) {
logger.error("scrollStartInstance error message :{}", e.getMessage(), e);
model.addAttribute("success", SuccessEnum.FAIL.value());
model.addAttribute("message", "滚动重启异常:" + e.getMessage());
}
return new ModelAndView();
}
/**
* 下线实例
*
* @param instanceId
*/
@RequestMapping(value = "/shutdownInstance")
public ModelAndView doShutdownInstance(HttpServletRequest request, HttpServletResponse response, Model model, long appId, int instanceId) {
AppUser appUser = getUserInfo(request);
logger.warn("user {} shutdownInstance {} ", appUser.getName(), instanceId);
boolean result = false;
if (instanceId > 0) {
try {
result = instanceDeployCenter.shutdownExistInstance(appId, instanceId);
} catch (Exception e) {
logger.error(e.getMessage(), e);
model.addAttribute("message", e.getMessage());
}
} else {
logger.error("doShutdownInstance instanceId:{}", instanceId);
model.addAttribute("message", "wrong param");
}
logger.warn("user {} shutdownInstance {}, result is {}", appUser.getName(), instanceId, result);
if (result) {
model.addAttribute("success", SuccessEnum.SUCCESS.value());
} else {
model.addAttribute("success", SuccessEnum.FAIL.value());
}
return new ModelAndView();
}
/**
* cluster forget instance
*
* @param instanceId
*/
@RequestMapping(value = "/forgetInstance")
public ModelAndView forgetInstance(HttpServletRequest request, HttpServletResponse response, Model model, long appId, int instanceId) {
AppUser appUser = getUserInfo(request);
logger.warn("user {} forgetInstance {} ", appUser.getName(), instanceId);
boolean result = false;
if (instanceId > 0) {
try {
result = instanceDeployCenter.forgetInstance(appId, instanceId);
} catch (Exception e) {
logger.error(e.getMessage(), e);
model.addAttribute("message", e.getMessage());
}
} else {
logger.error("doForgetInstance instanceId:{}", instanceId);
model.addAttribute("message", "wrong param");
}
logger.warn("user {} forgetInstance {}, result is {}", appUser.getName(), instanceId, result);
if (result) {
model.addAttribute("success", SuccessEnum.SUCCESS.value());
} else {
model.addAttribute("success", SuccessEnum.FAIL.value());
model.addAttribute("message", "请查看日志");
}
return new ModelAndView();
}
/**
* 查看redis节点日志
*/
@RequestMapping("/log")
public ModelAndView doShowLog(HttpServletRequest request, HttpServletResponse response, Model model, int instanceId) {
int pageSize = NumberUtils.toInt(request.getParameter("pageSize"), 0);
if (pageSize == 0) {
pageSize = 100;
}
String instanceLogStr = instanceDeployCenter.showInstanceRecentLog(instanceId, pageSize);
model.addAttribute("instanceLogList", StringUtils.isBlank(instanceLogStr) ? Collections.emptyList() : Arrays.asList(instanceLogStr.split("\n")));
return new ModelAndView("manage/instance/log");
}
/**
* 处理实例配置修改
*
* @param appAuditId 审批id
*/
@RequestMapping(value = "/initInstanceConfigChange")
public ModelAndView doInitInstanceConfigChange(HttpServletRequest request,
HttpServletResponse response, Model model, Long appAuditId) {
// 申请原因
AppAudit appAudit = appService.getAppAuditById(appAuditId);
model.addAttribute("appAudit", appAudit);
// 用第一个参数存实例id
Long instanceId = NumberUtils.toLong(appAudit.getParam1());
Map<String, String> redisConfigList = redisCenter.getRedisConfigList(instanceId.intValue());
model.addAttribute("redisConfigList", redisConfigList);
// 实例
InstanceInfo instanceInfo = instanceStatsCenter.getInstanceInfo(instanceId);
model.addAttribute("instanceInfo", instanceInfo);
model.addAttribute("appId", appAudit.getAppId());
model.addAttribute("appAuditId", appAuditId);
// 修改配置的键值对
model.addAttribute("instanceConfigKey", appAudit.getParam2());
model.addAttribute("instanceConfigValue", appAudit.getParam3());
return new ModelAndView("manage/appAudit/initInstanceConfigChange");
}
/**
* @param appId 应用id
* @param host 实例ip
* @param port 实例端口
* @param instanceConfigKey 实例配置key
* @param instanceConfigValue 实例配置value
* @param appAuditId 审批id
* @return
*/
@RequestMapping(value = "/addInstanceConfigChange")
public ModelAndView doAddAppConfigChange(HttpServletRequest request,
HttpServletResponse response, Model model, Long appId, String host, int port,
String instanceConfigKey, String instanceConfigValue, Long appAuditId) {
AppUser appUser = getUserInfo(request);
logger.warn("user {} change instanceConfig:appId={},{}:{};key={};value={},appAuditId:{}", appUser.getName(), appId, host, port, instanceConfigKey, instanceConfigValue, appAuditId);
boolean isModify = false;
if (StringUtils.isNotBlank(host) && port > 0 && appAuditId != null && StringUtils.isNotBlank(instanceConfigKey) && StringUtils.isNotBlank(instanceConfigValue)) {
try {
appAuditDao.updateAppAuditOperateUser(appAuditId, appUser.getId());
isModify = instanceDeployCenter.modifyInstanceConfig(appId, appAuditId, host, port, instanceConfigKey, instanceConfigValue);
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
}
logger.warn("user {} change instanceConfig:appId={},{}:{};key={};value={},appAuditId:{},result is:{}", appUser.getName(), appId, host, port, instanceConfigKey, instanceConfigValue, appAuditId, isModify);
return new ModelAndView("redirect:/manage/app/auditList");
}
}
| 4,472 |
1,980 | #pragma once
#include <windows.h>
#include <string>
namespace pesieve {
namespace util {
bool make_minidump(DWORD pid, std::string out_file);
};
};
| 59 |
348 | <filename>docs/data/leg-t2/045/04506334.json
{"nom":"Vieilles-Maisons-sur-Joudry","circ":"6ème circonscription","dpt":"Loiret","inscrits":450,"abs":233,"votants":217,"blancs":15,"nuls":12,"exp":190,"res":[{"nuance":"MDM","nom":"<NAME>","voix":96},{"nuance":"UDI","nom":"<NAME>","voix":94}]} | 120 |
310 | {
"name": "<NAME> R1900",
"description": "An ink jet printer.",
"url": "https://www.amazon.com/Epson-Stylus-Format-Printer-C11C698201/dp/B0011G47PQ"
} | 66 |
1,323 | <filename>ZYChat-EaseMob/ZYChat/Square/BTActionSheetViewController/BTActionSheetSimpleTextCell.h<gh_stars>1000+
//
// BTActionSheetSimpleTextCell.h
// ZYChat
//
// Created by ZYVincent QQ:1003081775 on 15/9/2.
// Copyright (c) 2015年 ZYProSoft. QQ群:219357847 All rights reserved.
//
#import "BTActionSheetBaseCell.h"
@interface BTActionSheetSimpleTextCell : BTActionSheetBaseCell
@end
| 161 |
521 | /* $Id: BandwidthGroupImpl.cpp $ */
/** @file
*
* VirtualBox COM class implementation
*/
/*
* Copyright (C) 2006-2017 Oracle Corporation
*
* This file is part of VirtualBox Open Source Edition (OSE), as
* available from http://www.virtualbox.org. This file is free software;
* you can redistribute it and/or modify it under the terms of the GNU
* General Public License (GPL) as published by the Free Software
* Foundation, in version 2 as it comes in the "COPYING" file of the
* VirtualBox OSE distribution. VirtualBox OSE is distributed in the
* hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
*/
#include "BandwidthGroupImpl.h"
#include "MachineImpl.h"
#include "Global.h"
#include "AutoCaller.h"
#include "Logging.h"
#include <iprt/cpp/utils.h>
// constructor / destructor
/////////////////////////////////////////////////////////////////////////////
//
DEFINE_EMPTY_CTOR_DTOR(BandwidthGroup)
HRESULT BandwidthGroup::FinalConstruct()
{
return BaseFinalConstruct();
}
void BandwidthGroup::FinalRelease()
{
uninit();
BaseFinalRelease();
}
// public initializer/uninitializer for internal purposes only
/////////////////////////////////////////////////////////////////////////////
/**
* Initializes the bandwidth group object.
*
* @returns COM result indicator.
* @param aParent Pointer to our parent object.
* @param aName Name of the bandwidth group.
* @param aType Type of the bandwidth group (net, disk).
* @param aMaxBytesPerSec Maximum bandwidth for the bandwidth group.
*/
HRESULT BandwidthGroup::init(BandwidthControl *aParent,
const Utf8Str &aName,
BandwidthGroupType_T aType,
LONG64 aMaxBytesPerSec)
{
LogFlowThisFunc(("aParent=%p aName=\"%s\"\n",
aParent, aName.c_str()));
ComAssertRet(aParent && !aName.isEmpty(), E_INVALIDARG);
if ( (aType <= BandwidthGroupType_Null)
|| (aType > BandwidthGroupType_Network))
return setError(E_INVALIDARG,
tr("Invalid bandwidth group type type"));
/* Enclose the state transition NotReady->InInit->Ready */
AutoInitSpan autoInitSpan(this);
AssertReturn(autoInitSpan.isOk(), E_FAIL);
m = new Data(aParent);
/* m->pPeer is left null */
m->bd.allocate();
m->bd->mData.strName = aName;
m->bd->mData.enmType = aType;
m->bd->cReferences = 0;
m->bd->mData.cMaxBytesPerSec = aMaxBytesPerSec;
/* Confirm a successful initialization */
autoInitSpan.setSucceeded();
return S_OK;
}
/**
* Initializes the object given another object
* (a kind of copy constructor). This object shares data with
* the object passed as an argument.
*
* @param aParent Pointer to our parent object.
* @param aThat
* @param aReshare
* When false, the original object will remain a data owner.
* Otherwise, data ownership will be transferred from the original
* object to this one.
*
* @note This object must be destroyed before the original object
* it shares data with is destroyed.
*
* @note Locks @a aThat object for writing if @a aReshare is @c true, or for
* reading if @a aReshare is false.
*/
HRESULT BandwidthGroup::init(BandwidthControl *aParent,
BandwidthGroup *aThat,
bool aReshare /* = false */)
{
LogFlowThisFunc(("aParent=%p, aThat=%p, aReshare=%RTbool\n",
aParent, aThat, aReshare));
ComAssertRet(aParent && aThat, E_INVALIDARG);
/* Enclose the state transition NotReady->InInit->Ready */
AutoInitSpan autoInitSpan(this);
AssertReturn(autoInitSpan.isOk(), E_FAIL);
m = new Data(aParent);
/* sanity */
AutoCaller thatCaller(aThat);
AssertComRCReturnRC(thatCaller.rc());
if (aReshare)
{
AutoWriteLock thatLock(aThat COMMA_LOCKVAL_SRC_POS);
unconst(aThat->m->pPeer) = this;
m->bd.attach(aThat->m->bd);
}
else
{
unconst(m->pPeer) = aThat;
AutoReadLock thatLock(aThat COMMA_LOCKVAL_SRC_POS);
m->bd.share(aThat->m->bd);
}
/* Confirm successful initialization */
autoInitSpan.setSucceeded();
return S_OK;
}
/**
* Initializes the bandwidth group object given another guest object
* (a kind of copy constructor). This object makes a private copy of data
* of the original object passed as an argument.
*/
HRESULT BandwidthGroup::initCopy(BandwidthControl *aParent, BandwidthGroup *aThat)
{
LogFlowThisFunc(("aParent=%p, aThat=%p\n", aParent, aThat));
ComAssertRet(aParent && aThat, E_INVALIDARG);
/* Enclose the state transition NotReady->InInit->Ready */
AutoInitSpan autoInitSpan(this);
AssertReturn(autoInitSpan.isOk(), E_FAIL);
m = new Data(aParent);
/* m->pPeer is left null */
AutoCaller thatCaller(aThat);
AssertComRCReturnRC(thatCaller.rc());
AutoReadLock thatlock(aThat COMMA_LOCKVAL_SRC_POS);
m->bd.attachCopy(aThat->m->bd);
/* Confirm a successful initialization */
autoInitSpan.setSucceeded();
return S_OK;
}
/**
* Uninitializes the instance and sets the ready flag to FALSE.
* Called either from FinalRelease() or by the parent when it gets destroyed.
*/
void BandwidthGroup::uninit()
{
LogFlowThisFunc(("\n"));
/* Enclose the state transition Ready->InUninit->NotReady */
AutoUninitSpan autoUninitSpan(this);
if (autoUninitSpan.uninitDone())
return;
m->bd.free();
unconst(m->pPeer) = NULL;
unconst(m->pParent) = NULL;
delete m;
m = NULL;
}
HRESULT BandwidthGroup::getName(com::Utf8Str &aName)
{
/* mName is constant during life time, no need to lock */
aName = m->bd.data()->mData.strName;
return S_OK;
}
HRESULT BandwidthGroup::getType(BandwidthGroupType_T *aType)
{
/* type is constant during life time, no need to lock */
*aType = m->bd->mData.enmType;
return S_OK;
}
HRESULT BandwidthGroup::getReference(ULONG *aReferences)
{
AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
*aReferences = m->bd->cReferences;
return S_OK;
}
HRESULT BandwidthGroup::getMaxBytesPerSec(LONG64 *aMaxBytesPerSec)
{
AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
*aMaxBytesPerSec = m->bd->mData.cMaxBytesPerSec;
return S_OK;
}
HRESULT BandwidthGroup::setMaxBytesPerSec(LONG64 aMaxBytesPerSec)
{
if (aMaxBytesPerSec < 0)
return setError(E_INVALIDARG,
tr("Bandwidth group limit cannot be negative"));
AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
m->bd.backup();
m->bd->mData.cMaxBytesPerSec = aMaxBytesPerSec;
/* inform direct session if any. */
ComObjPtr<Machine> pMachine = m->pParent->i_getMachine();
alock.release();
pMachine->i_onBandwidthGroupChange(this);
return S_OK;
}
// public methods only for internal purposes
/////////////////////////////////////////////////////////////////////////////
/** @note Locks objects for writing! */
void BandwidthGroup::i_rollback()
{
AutoCaller autoCaller(this);
AssertComRCReturnVoid(autoCaller.rc());
AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
m->bd.rollback();
}
/**
* @note Locks this object for writing, together with the peer object (also
* for writing) if there is one.
*/
void BandwidthGroup::i_commit()
{
/* sanity */
AutoCaller autoCaller(this);
AssertComRCReturnVoid(autoCaller.rc());
/* sanity too */
AutoCaller peerCaller(m->pPeer);
AssertComRCReturnVoid(peerCaller.rc());
/* lock both for writing since we modify both (m->pPeer is "master" so locked
* first) */
AutoMultiWriteLock2 alock(m->pPeer, this COMMA_LOCKVAL_SRC_POS);
if (m->bd.isBackedUp())
{
m->bd.commit();
if (m->pPeer)
{
// attach new data to the peer and reshare it
m->pPeer->m->bd.attach(m->bd);
}
}
}
/**
* Cancels sharing (if any) by making an independent copy of data.
* This operation also resets this object's peer to NULL.
*
* @note Locks this object for writing, together with the peer object
* represented by @a aThat (locked for reading).
*/
void BandwidthGroup::i_unshare()
{
/* sanity */
AutoCaller autoCaller(this);
AssertComRCReturnVoid(autoCaller.rc());
/* sanity too */
AutoCaller peerCaller(m->pPeer);
AssertComRCReturnVoid(peerCaller.rc());
/* peer is not modified, lock it for reading (m->pPeer is "master" so locked
* first) */
AutoReadLock rl(m->pPeer COMMA_LOCKVAL_SRC_POS);
AutoWriteLock wl(this COMMA_LOCKVAL_SRC_POS);
if (m->bd.isShared())
{
if (!m->bd.isBackedUp())
m->bd.backup();
m->bd.commit();
}
unconst(m->pPeer) = NULL;
}
void BandwidthGroup::i_reference()
{
AutoWriteLock wl(this COMMA_LOCKVAL_SRC_POS);
m->bd.backup();
m->bd->cReferences++;
}
void BandwidthGroup::i_release()
{
AutoWriteLock wl(this COMMA_LOCKVAL_SRC_POS);
m->bd.backup();
m->bd->cReferences--;
}
| 3,531 |
1,934 | /*
* Copyright 2018-2019 the original author or 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
*
* https://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.springframework.cloud.config.server.config;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.cloud.config.server.environment.ConfigTokenProvider;
import org.springframework.cloud.config.server.environment.EnvironmentConfigTokenProvider;
import org.springframework.cloud.config.server.environment.vault.authentication.AppRoleClientAuthenticationProvider;
import org.springframework.cloud.config.server.environment.vault.authentication.AwsEc2ClientAuthenticationProvider;
import org.springframework.cloud.config.server.environment.vault.authentication.AwsIamClientAuthenticationProvider;
import org.springframework.cloud.config.server.environment.vault.authentication.AzureMsiClientAuthenticationProvider;
import org.springframework.cloud.config.server.environment.vault.authentication.CertificateClientAuthenticationProvider;
import org.springframework.cloud.config.server.environment.vault.authentication.CubbyholeClientAuthenticationProvider;
import org.springframework.cloud.config.server.environment.vault.authentication.GcpGceClientAuthenticationProvider;
import org.springframework.cloud.config.server.environment.vault.authentication.GcpIamClientAuthenticationProvider;
import org.springframework.cloud.config.server.environment.vault.authentication.KubernetesClientAuthenticationProvider;
import org.springframework.cloud.config.server.environment.vault.authentication.PcfClientAuthenticationProvider;
import org.springframework.cloud.config.server.environment.vault.authentication.TokenClientAuthenticationProvider;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.vault.core.VaultTemplate;
/**
* @author <NAME>
*/
@Configuration(proxyBeanMethods = false)
public class VaultConfiguration {
private static final String VAULT_TOKEN_PROPERTY_NAME = "spring.cloud.config.server.vault.token";
@Bean
@ConditionalOnProperty(VAULT_TOKEN_PROPERTY_NAME)
public ConfigTokenProvider vaultConfigTokenProvider(Environment environment) {
return new EnvironmentConfigTokenProvider(environment, VAULT_TOKEN_PROPERTY_NAME);
}
@Configuration(proxyBeanMethods = false)
@ConditionalOnClass(VaultTemplate.class)
public static class VaultClientAuthenticationProviderConfiguration {
@Bean
public AppRoleClientAuthenticationProvider appRoleClientAuthenticationProvider() {
return new AppRoleClientAuthenticationProvider();
}
@Bean
public AwsEc2ClientAuthenticationProvider awsEc2ClientAuthenticationProvider() {
return new AwsEc2ClientAuthenticationProvider();
}
@Bean
public AwsIamClientAuthenticationProvider awsIamClientAuthenticationProvider() {
return new AwsIamClientAuthenticationProvider();
}
@Bean
public AzureMsiClientAuthenticationProvider azureMsiClientAuthenticationProvider() {
return new AzureMsiClientAuthenticationProvider();
}
@Bean
public CertificateClientAuthenticationProvider certificateClientAuthenticationProvider() {
return new CertificateClientAuthenticationProvider();
}
@Bean
public CubbyholeClientAuthenticationProvider cubbyholeClientAuthenticationProvider() {
return new CubbyholeClientAuthenticationProvider();
}
@Bean
public GcpGceClientAuthenticationProvider gcpGceClientAuthenticationProvider() {
return new GcpGceClientAuthenticationProvider();
}
@Bean
public GcpIamClientAuthenticationProvider gcpIamClientAuthenticationProvider() {
return new GcpIamClientAuthenticationProvider();
}
@Bean
public KubernetesClientAuthenticationProvider kubernetesClientAuthenticationProvider() {
return new KubernetesClientAuthenticationProvider();
}
@Bean
public PcfClientAuthenticationProvider pcfClientAuthenticationProvider() {
return new PcfClientAuthenticationProvider();
}
@Bean
public TokenClientAuthenticationProvider tokenClientAuthenticationProvider() {
return new TokenClientAuthenticationProvider();
}
}
}
| 1,287 |
2,003 | <gh_stars>1000+
// Copyright (c) 2015, Baidu.com, Inc. All Rights Reserved
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "gflags/gflags.h"
#include "glog/logging.h"
#include "gtest/gtest.h"
#include "load_balancer/cost_functions.h"
#include "load_balancer/random.h"
namespace tera {
namespace load_balancer {
class CostFunctionTest : public ::testing::Test {
public:
virtual void SetUp() { move_cost_function_.reset(new MoveCountCostFunction(lb_options_)); }
virtual void TearDown() {}
private:
LBOptions lb_options_;
std::shared_ptr<MoveCountCostFunction> move_cost_function_;
};
class MoveCountCostFunctionTest : public ::testing::Test {
public:
virtual void SetUp() {
move_cost_function_.reset(new MoveCountCostFunction(lb_options_));
std::vector<std::shared_ptr<LBTabletNode>> empty_lb_nodes;
LBOptions options;
cluster_.reset(new Cluster(empty_lb_nodes, options, false));
move_cost_function_->Init(cluster_);
}
virtual void TearDown() {}
private:
LBOptions lb_options_;
std::shared_ptr<MoveCountCostFunction> move_cost_function_;
std::shared_ptr<Cluster> cluster_;
};
class TabletCountCostFunctionTest : public ::testing::Test {
public:
virtual void SetUp() {
tablet_count_cost_function_.reset(new TabletCountCostFunction(lb_options_));
std::vector<std::shared_ptr<LBTabletNode>> empty_lb_nodes;
LBOptions options;
cluster_.reset(new Cluster(empty_lb_nodes, options, false));
tablet_count_cost_function_->Init(cluster_);
}
virtual void TearDown() {}
private:
LBOptions lb_options_;
std::shared_ptr<TabletCountCostFunction> tablet_count_cost_function_;
std::shared_ptr<Cluster> cluster_;
};
class SizeCostFunctionTest : public ::testing::Test {
public:
virtual void SetUp() {
size_cost_function_.reset(new SizeCostFunction(lb_options_));
std::vector<std::shared_ptr<LBTabletNode>> empty_lb_nodes;
LBOptions options;
cluster_.reset(new Cluster(empty_lb_nodes, options, false));
size_cost_function_->Init(cluster_);
}
virtual void TearDown() {}
private:
LBOptions lb_options_;
std::shared_ptr<SizeCostFunction> size_cost_function_;
std::shared_ptr<Cluster> cluster_;
};
TEST_F(CostFunctionTest, WeightTest) {
double w = 3.14;
move_cost_function_->SetWeight(w);
ASSERT_DOUBLE_EQ(w, move_cost_function_->GetWeight());
}
TEST_F(CostFunctionTest, SumTest) {
std::vector<double> stats = {1, 2, 3};
ASSERT_DOUBLE_EQ(6, move_cost_function_->GetSum(stats));
}
TEST_F(CostFunctionTest, ScaleTest) {
// value <= min
ASSERT_DOUBLE_EQ(0, move_cost_function_->Scale(0, 10, -1));
ASSERT_DOUBLE_EQ(0, move_cost_function_->Scale(0, 10, 0));
// max <= min
ASSERT_DOUBLE_EQ(0, move_cost_function_->Scale(0, 0, 5));
ASSERT_DOUBLE_EQ(0, move_cost_function_->Scale(0, -1, 5));
// normal case
ASSERT_DOUBLE_EQ(0, move_cost_function_->Scale(0, 10, 0));
ASSERT_DOUBLE_EQ(0.5, move_cost_function_->Scale(0, 10, 5));
ASSERT_DOUBLE_EQ(1, move_cost_function_->Scale(0, 10, 10));
// random case
size_t times = 100;
int min = 0;
int max = 10;
for (size_t i = 0; i < times; ++i) {
int value = Random::Rand(min, max + 1);
ASSERT_TRUE(move_cost_function_->Scale(min, max, value) >= 0);
ASSERT_TRUE(move_cost_function_->Scale(min, max, value) <= 1);
}
}
TEST_F(CostFunctionTest, ScaleFromArrayTest) {
std::vector<double> stats_0 = {0, 0};
ASSERT_DOUBLE_EQ(0, move_cost_function_->ScaleFromArray(stats_0));
std::vector<double> stats_1 = {10, 10};
ASSERT_DOUBLE_EQ(0, move_cost_function_->ScaleFromArray(stats_0));
int begin = 0;
int end = 100;
size_t times = 100;
std::vector<double> stats_2;
for (size_t i = 0; i < times; ++i) {
stats_2.clear();
stats_2.emplace_back(Random::Rand(begin, end));
stats_2.emplace_back(Random::Rand(begin, end));
ASSERT_TRUE(move_cost_function_->ScaleFromArray(stats_2) >= 0);
ASSERT_TRUE(move_cost_function_->ScaleFromArray(stats_2) <= 1);
}
}
TEST_F(MoveCountCostFunctionTest, CostTest) {
move_cost_function_->tablet_max_move_num_ = 10;
cluster_->tablet_num_ = 10;
cluster_->tablet_moved_num_ = 1;
ASSERT_DOUBLE_EQ(0.1, move_cost_function_->Cost());
cluster_->tablet_moved_num_ = 6;
ASSERT_DOUBLE_EQ(0.6, move_cost_function_->Cost());
cluster_->tablet_moved_num_ = 10;
ASSERT_DOUBLE_EQ(1, move_cost_function_->Cost());
cluster_->tablet_moved_num_ = 11;
ASSERT_DOUBLE_EQ(move_cost_function_->kExpensiveCost, move_cost_function_->Cost());
}
TEST_F(TabletCountCostFunctionTest, CostTest) {}
TEST_F(SizeCostFunctionTest, CostTest) {}
} // namespace load_balancer
} // namespace tera
/* vim: set expandtab ts=4 sw=4 sts=4 tw=100: */
| 1,841 |
357 | /*
* Copyright (c) 2012-2015 VMware, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy
* of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, without
* warranties or conditions of any kind, EITHER EXPRESS OR IMPLIED. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.vmware.identity.wstrust.client.impl;
import com.vmware.identity.wstrust.client.Credential;
import com.vmware.identity.wstrust.client.GSSServerCredential;
import com.vmware.identity.wstrust.client.SecurityTokenServiceConfig;
import com.vmware.identity.wstrust.client.TokenSpec;
import com.vmware.identity.wstrust.client.ValidateUtil;
class AcquireRequestGSSParserFactoryTest extends RequestParserAbstractFactory<GssResult> {
private static final String WS_TRUST_ISSUE = "http://docs.oasis-open.org/ws-sx/ws-trust/200512/Issue";
private boolean immediateReturnToken = true;
private boolean throwException = false;
public AcquireRequestGSSParserFactoryTest(SecurityTokenServiceConfig config, boolean immediateReturnToken,
boolean throwException) {
super(config);
this.immediateReturnToken = immediateReturnToken;
this.throwException = throwException;
}
@Override
public RequestParametersValidator createRequestParametersValidator() {
return new DefaultRequestParametersValidator();
}
@Override
public RequestBuilder createRequestBuilder(Credential clientCredential, TokenSpec tokenSpec) {
return new RequestBuilderMock(((GSSServerCredential) clientCredential).getContextId(), WS_TRUST_ISSUE);
}
@Override
public ResponseHandler<GssResult> createResponseHandler() {
return new GssResultResponseHandlerMock(this.immediateReturnToken, this.throwException);
}
@Override
public WsSecuritySignature createWsSecuritySignature(Credential clientCredential, TokenSpec tokenSpec) {
GSSServerCredential cred = (GSSServerCredential) clientCredential;
String contextId = cred.getContextId();
boolean isInitial = ValidateUtil.isEmpty(contextId);
boolean isHokRequest = stsConfig.getHolderOfKeyConfig() != null;
return isInitial && isHokRequest ? WsSecuritySignatureFactory.createWsSecuritySignatureCertificate(stsConfig
.getHolderOfKeyConfig()) : WsSecuritySignatureFactory.createWsEmptySecuritySignature();
}
}
| 869 |
606 | package org.arend.module.scopeprovider;
import org.arend.ext.module.ModulePath;
import org.arend.naming.scope.CachingScope;
import org.arend.naming.scope.Scope;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.HashMap;
import java.util.Map;
public class CachingModuleScopeProvider implements ModuleScopeProvider {
private final ModuleScopeProvider myModuleScopeProvider;
private final Map<ModulePath, Scope> myScopes = new HashMap<>();
private final static Scope NULL_SCOPE = new Scope() {};
public CachingModuleScopeProvider(ModuleScopeProvider moduleScopeProvider) {
myModuleScopeProvider = moduleScopeProvider;
}
public void reset(ModulePath modulePath) {
myScopes.remove(modulePath);
}
public void reset() {
myScopes.clear();
}
@Nullable
@Override
public Scope forModule(@NotNull ModulePath module) {
Scope scope = myScopes.get(module);
if (scope == NULL_SCOPE) {
return null;
}
if (scope != null) {
return scope;
}
scope = myModuleScopeProvider.forModule(module);
if (scope != null) {
scope = CachingScope.make(scope);
}
myScopes.put(module, scope == null ? NULL_SCOPE : scope);
return scope;
}
}
| 425 |
539 | /*************************************************************************/
/* */
/* Language Technologies Institute */
/* Carnegie Mellon University */
/* Copyright (c) 2015 */
/* All Rights Reserved. */
/* */
/* Permission is hereby granted, free of charge, to use and distribute */
/* this software and its documentation without restriction, including */
/* without limitation the rights to use, copy, modify, merge, publish, */
/* distribute, sublicense, and/or sell copies of this work, and to */
/* permit persons to whom this work is furnished to do so, subject to */
/* the following conditions: */
/* 1. The code must retain the above copyright notice, this list of */
/* conditions and the following disclaimer. */
/* 2. Any modifications must be clearly marked as such. */
/* 3. Original authors' names are not deleted. */
/* 4. The authors' names are not used to endorse or promote products */
/* derived from this software without specific prior written */
/* permission. */
/* */
/* CARNEGIE MELLON UNIVERSITY AND THE CONTRIBUTORS TO THIS WORK */
/* DISCLAIM ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING */
/* ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT */
/* SHALL CARNEGIE MELLON UNIVERSITY NOR THE CONTRIBUTORS BE LIABLE */
/* FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES */
/* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN */
/* AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, */
/* ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF */
/* THIS SOFTWARE. */
/* */
/*************************************************************************/
/* Author: <NAME> (<EMAIL>) */
/* Date: February 2015 */
/*************************************************************************/
/* */
/* A minmal example test program */
/* */
/*************************************************************************/
#include <stdio.h>
#include <string.h>
#include "flite.h"
void usenglish_init(cst_voice *v);
cst_lexicon *cmulex_init(void);
int main(int argc, char **argv)
{
cst_voice *v;
cst_wave *w;
cst_utterance *u;
const char *voice_pathname;
const char *text;
const char *outfile;
if (argc != 4)
{
fprintf(stderr,"usage: VOICE.flitevox TEXT WAVEFILE\n");
return 1;
}
voice_pathname = argv[1]; /* pathname to .flitevox file */
text = argv[2]; /* text to be synthesized */
outfile = argv[3]; /* output file (or "play" or "none") */
/* Initialize Flite, and set up language and lexicon */
flite_init();
flite_add_lang("eng",usenglish_init,cmulex_init);
flite_add_lang("usenglish",usenglish_init,cmulex_init);
/* Load and select voice */
v = flite_voice_select(voice_pathname);
if (v == NULL)
{
fprintf(stderr,"failed to load voice: %s\n",voice_pathname);
return 1;
}
u = flite_synth_text(text,v);
w = utt_wave(u);
/* Play the resulting wave, save it to a filename, or do none of these */
if (cst_streq(outfile,"play"))
play_wave(w);
else if (!cst_streq(outfile,"none"))
cst_wave_save_riff(w,outfile);
delete_utterance(u); /* will delete w too */
return 0;
}
| 2,079 |
4,339 | <reponame>geertjanw/ignite<filename>modules/core/src/main/java/org/apache/ignite/internal/processors/resource/GridResourceMethod.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.ignite.internal.processors.resource;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.Collection;
import org.apache.ignite.internal.util.typedef.internal.S;
/**
* Wrapper for data where resource should be injected.
* Bean contains {@link Method} and {@link Annotation} for that method.
*/
class GridResourceMethod {
/** */
static final GridResourceMethod[] EMPTY_ARRAY = new GridResourceMethod[0];
/** Method which used to inject resource. */
private final Method mtd;
/** Resource annotation. */
private final Annotation ann;
/**
* Creates new bean.
*
* @param mtd Method which used to inject resource.
* @param ann Resource annotation.
*/
GridResourceMethod(Method mtd, Annotation ann) {
assert mtd != null;
assert ann != null;
this.mtd = mtd;
this.ann = ann;
mtd.setAccessible(true);
}
/**
* Gets class method object.
*
* @return Class method.
*/
public Method getMethod() {
return mtd;
}
/**
* Gets annotation for class method object.
*
* @return Method annotation.
*/
public Annotation getAnnotation() {
return ann;
}
/**
* @param c Closure.
*/
public static GridResourceMethod[] toArray(Collection<GridResourceMethod> c) {
if (c.isEmpty())
return EMPTY_ARRAY;
return c.toArray(new GridResourceMethod[c.size()]);
}
/** {@inheritDoc} */
@Override public String toString() {
return S.toString(GridResourceMethod.class, this);
}
}
| 871 |
327 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package de.fhpotsdam.unfolding.providers;
import java.net.URI;
import org.apache.log4j.Logger;
import de.fhpotsdam.unfolding.core.Coordinate;
import de.fhpotsdam.unfolding.geo.MercatorProjection;
import de.fhpotsdam.unfolding.geo.Transformation;
/**
*
* @author marcus
*/
public class CartoDBProvider extends AbstractMapTileUrlProvider {
private String subdomain = null;
private String table = null;
private String sql = null;
private String carto = null;
public static Logger log = Logger.getLogger(CartoDBProvider.class);
public AbstractMapProvider masterProvider = null;
public CartoDBProvider(String account, String dbTable) {
super(new MercatorProjection(26, new Transformation(1.068070779e7, 0.0f, 3.355443185e7, 0.0,
-1.068070890e7, 3.355443057e7)));
this.subdomain = account;
this.table = dbTable;
}
public String getZoomString(Coordinate coordinate) {
return (int) coordinate.zoom + "/" + (int) coordinate.column + "/" + (int) coordinate.row;
}
@Override
public int tileWidth() {
return 256;
}
@Override
public int tileHeight() {
return 256;
}
public String getStyle() {
return carto;
}
public void setStyle(String carto) {
this.carto = carto;
}
public String getSql() {
return sql;
}
public void setSql(String sql) {
this.sql = sql;
}
@Override
public String[] getTileUrls(Coordinate coordinate) {
/*
* CartoDB Url Template
* http://{account}.cartodb.com/tiles/{table_name}/{z}/{x}/{y}.png?sql={SQL
* statement}&style={Carto style}
*/
try {
// Build the query part of the URL
String query = "";
if (this.sql != null) {
query += "sql=" + this.sql;
}
if (this.carto != null) {
query += (this.sql != null ? "&" : "") + "style=" + this.carto;
}
// This should do proper URI encoding for the sql query and the carto css
URI uri = new URI(
"http",
this.subdomain + ".cartodb.com",
"/tiles/" + this.table + "/" + getZoomString(coordinate) + ".png",
query,
null);
String request = uri.toASCIIString();
// This should be our final url
log.debug("CartoDB-Tile: " + request);
// Now we can optionally blend the cartodb-tiles onto a basemap layer
if (this.masterProvider != null) {
// We use the internal mechanism of the Map-Class, so we just have to provide the additional urls in the String-Array
String[] url = this.masterProvider.getTileUrls(coordinate);
String[] blend = new String[url.length + 1];
for (int i = 0; i < url.length; i++) {
blend[i] = url[i];
}
blend[blend.length - 1] = request;
return blend;
} else {
// Return the plain url
return new String[]{request};
}
} catch (Exception e) {
// Problem with url encoding, how to crash properly?
log.error("Unable to create CartoDB Urls: " + e.getLocalizedMessage());
return new String[]{""};
}
}
} | 1,137 |
680 | <filename>skyeye-promote/skyeye-web/src/main/java/com/skyeye/eve/controller/SysEveUserController.java
/**
* Copyright 卫志强 QQ:<EMAIL> Inc. All rights reserved.
*/
package com.skyeye.eve.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.skyeye.common.object.InputObject;
import com.skyeye.common.object.OutputObject;
import com.skyeye.eve.service.SysEveUserService;
@Controller
public class SysEveUserController {
@Autowired
public SysEveUserService sysEveUserService;
/**
*
* @Title: querySysUserList
* @Description: 获取管理员用户列表
* @param @param inputObject
* @param @param outputObject
* @param @throws Exception 参数
* @return void 返回类型
* @throws
*/
@RequestMapping("/post/SysEveUserController/querySysUserList")
@ResponseBody
public void querySysUserList(InputObject inputObject, OutputObject outputObject) throws Exception{
sysEveUserService.querySysUserList(inputObject, outputObject);
}
/**
*
* @Title: editSysUserLockStateToLockById
* @Description: 锁定账号
* @param @param inputObject
* @param @param outputObject
* @param @throws Exception 参数
* @return void 返回类型
* @throws
*/
@RequestMapping("/post/SysEveUserController/editSysUserLockStateToLockById")
@ResponseBody
public void editSysUserLockStateToLockById(InputObject inputObject, OutputObject outputObject) throws Exception{
sysEveUserService.editSysUserLockStateToLockById(inputObject, outputObject);
}
/**
*
* @Title: editSysUserLockStateToUnLockById
* @Description: 解锁账号
* @param @param inputObject
* @param @param outputObject
* @param @throws Exception 参数
* @return void 返回类型
* @throws
*/
@RequestMapping("/post/SysEveUserController/editSysUserLockStateToUnLockById")
@ResponseBody
public void editSysUserLockStateToUnLockById(InputObject inputObject, OutputObject outputObject) throws Exception{
sysEveUserService.editSysUserLockStateToUnLockById(inputObject, outputObject);
}
/**
*
* @Title: querySysUserMationToEditById
* @Description: 编辑账号时获取账号信息
* @param @param inputObject
* @param @param outputObject
* @param @throws Exception 参数
* @return void 返回类型
* @throws
*/
@RequestMapping("/post/SysEveUserController/querySysUserMationToEditById")
@ResponseBody
public void querySysUserMationToEditById(InputObject inputObject, OutputObject outputObject) throws Exception{
sysEveUserService.querySysUserMationToEditById(inputObject, outputObject);
}
/**
*
* @Title: insertSysUserMationById
* @Description: 创建账号
* @param @param inputObject
* @param @param outputObject
* @param @throws Exception 参数
* @return void 返回类型
* @throws
*/
@RequestMapping("/post/SysEveUserController/insertSysUserMationById")
@ResponseBody
public void insertSysUserMationById(InputObject inputObject, OutputObject outputObject) throws Exception{
sysEveUserService.insertSysUserMationById(inputObject, outputObject);
}
/**
*
* @Title: editSysUserMationById
* @Description: 编辑账号
* @param @param inputObject
* @param @param outputObject
* @param @throws Exception 参数
* @return void 返回类型
* @throws
*/
@RequestMapping("/post/SysEveUserController/editSysUserMationById")
@ResponseBody
public void editSysUserMationById(InputObject inputObject, OutputObject outputObject) throws Exception{
sysEveUserService.editSysUserMationById(inputObject, outputObject);
}
/**
*
* @Title: queryUserToLogin
* @Description: 登录
* @param @param inputObject
* @param @param outputObject
* @param @throws Exception 参数
* @return void 返回类型
* @throws
*/
@RequestMapping("/post/SysEveUserController/queryUserToLogin")
@ResponseBody
public void queryUserToLogin(InputObject inputObject, OutputObject outputObject) throws Exception{
sysEveUserService.queryUserToLogin(inputObject, outputObject);
}
/**
*
* @Title: queryUserMationBySession
* @Description: 从session中获取用户信息
* @param @param inputObject
* @param @param outputObject
* @param @throws Exception 参数
* @return void 返回类型
* @throws
*/
@RequestMapping("/post/SysEveUserController/queryUserMationBySession")
@ResponseBody
public void queryUserMationBySession(InputObject inputObject, OutputObject outputObject) throws Exception{
sysEveUserService.queryUserMationBySession(inputObject, outputObject);
}
/**
*
* @Title: deleteUserMationBySession
* @Description: 退出
* @param @param inputObject
* @param @param outputObject
* @param @throws Exception 参数
* @return void 返回类型
* @throws
*/
@RequestMapping("/post/SysEveUserController/deleteUserMationBySession")
@ResponseBody
public void deleteUserMationBySession(InputObject inputObject, OutputObject outputObject) throws Exception{
sysEveUserService.deleteUserMationBySession(inputObject, outputObject);
}
/**
*
* @Title: queryRoleAndBindRoleByUserId
* @Description: 获取角色和当前已经绑定的角色信息
* @param @param inputObject
* @param @param outputObject
* @param @throws Exception 参数
* @return void 返回类型
* @throws
*/
@RequestMapping("/post/SysEveUserController/queryRoleAndBindRoleByUserId")
@ResponseBody
public void queryRoleAndBindRoleByUserId(InputObject inputObject, OutputObject outputObject) throws Exception{
sysEveUserService.queryRoleAndBindRoleByUserId(inputObject, outputObject);
}
/**
*
* @Title: editRoleIdsByUserId
* @Description: 编辑用户绑定的角色
* @param @param inputObject
* @param @param outputObject
* @param @throws Exception 参数
* @return void 返回类型
* @throws
*/
@RequestMapping("/post/SysEveUserController/editRoleIdsByUserId")
@ResponseBody
public void editRoleIdsByUserId(InputObject inputObject, OutputObject outputObject) throws Exception{
sysEveUserService.editRoleIdsByUserId(inputObject, outputObject);
}
/**
*
* @Title: queryDeskTopMenuBySession
* @Description: 获取桌面菜单列表
* @param @param inputObject
* @param @param outputObject
* @param @throws Exception 参数
* @return void 返回类型
* @throws
*/
@RequestMapping("/post/SysEveUserController/queryDeskTopMenuBySession")
@ResponseBody
public void queryDeskTopMenuBySession(InputObject inputObject, OutputObject outputObject) throws Exception{
sysEveUserService.queryDeskTopMenuBySession(inputObject, outputObject);
}
/**
*
* @Title: queryAllMenuBySession
* @Description: 获取全部菜单列表
* @param @param inputObject
* @param @param outputObject
* @param @throws Exception 参数
* @return void 返回类型
* @throws
*/
@RequestMapping("/post/SysEveUserController/queryAllMenuBySession")
@ResponseBody
public void queryAllMenuBySession(InputObject inputObject, OutputObject outputObject) throws Exception{
sysEveUserService.queryAllMenuBySession(inputObject, outputObject);
}
/**
*
* @Title: editUserInstallThemeColor
* @Description: 自定义设置主题颜色
* @param @param inputObject
* @param @param outputObject
* @param @throws Exception 参数
* @return void 返回类型
* @throws
*/
@RequestMapping("/post/SysEveUserController/editUserInstallThemeColor")
@ResponseBody
public void editUserInstallThemeColor(InputObject inputObject, OutputObject outputObject) throws Exception{
sysEveUserService.editUserInstallThemeColor(inputObject, outputObject);
}
/**
*
* @Title: editUserInstallWinBgPic
* @Description: 自定义设置win背景图片
* @param @param inputObject
* @param @param outputObject
* @param @throws Exception 参数
* @return void 返回类型
* @throws
*/
@RequestMapping("/post/SysEveUserController/editUserInstallWinBgPic")
@ResponseBody
public void editUserInstallWinBgPic(InputObject inputObject, OutputObject outputObject) throws Exception{
sysEveUserService.editUserInstallWinBgPic(inputObject, outputObject);
}
/**
*
* @Title: editUserInstallWinLockBgPic
* @Description: 自定义设置win锁屏背景图片
* @param @param inputObject
* @param @param outputObject
* @param @throws Exception 参数
* @return void 返回类型
* @throws
*/
@RequestMapping("/post/SysEveUserController/editUserInstallWinLockBgPic")
@ResponseBody
public void editUserInstallWinLockBgPic(InputObject inputObject, OutputObject outputObject) throws Exception{
sysEveUserService.editUserInstallWinLockBgPic(inputObject, outputObject);
}
/**
*
* @Title: editUserInstallWinStartMenuSize
* @Description: 自定义设置win开始菜单尺寸
* @param @param inputObject
* @param @param outputObject
* @param @throws Exception 参数
* @return void 返回类型
* @throws
*/
@RequestMapping("/post/SysEveUserController/editUserInstallWinStartMenuSize")
@ResponseBody
public void editUserInstallWinStartMenuSize(InputObject inputObject, OutputObject outputObject) throws Exception{
sysEveUserService.editUserInstallWinStartMenuSize(inputObject, outputObject);
}
/**
*
* @Title: editUserInstallWinTaskPosition
* @Description: 自定义设置win任务栏在屏幕的位置
* @param @param inputObject
* @param @param outputObject
* @param @throws Exception 参数
* @return void 返回类型
* @throws
*/
@RequestMapping("/post/SysEveUserController/editUserInstallWinTaskPosition")
@ResponseBody
public void editUserInstallWinTaskPosition(InputObject inputObject, OutputObject outputObject) throws Exception{
sysEveUserService.editUserInstallWinTaskPosition(inputObject, outputObject);
}
/**
*
* @Title: editUserPassword
* @Description: 修改密码
* @param @param inputObject
* @param @param outputObject
* @param @throws Exception 参数
* @return void 返回类型
* @throws
*/
@RequestMapping("/post/SysEveUserController/editUserPassword")
@ResponseBody
public void editUserPassword(InputObject inputObject, OutputObject outputObject) throws Exception{
sysEveUserService.editUserPassword(inputObject, outputObject);
}
/**
*
* @Title: editUserInstallVagueBgSrc
* @Description: 自定义设置win雾化
* @param @param inputObject
* @param @param outputObject
* @param @throws Exception 参数
* @return void 返回类型
* @throws
*/
@RequestMapping("/post/SysEveUserController/editUserInstallVagueBgSrc")
@ResponseBody
public void editUserInstallVagueBgSrc(InputObject inputObject, OutputObject outputObject) throws Exception{
sysEveUserService.editUserInstallVagueBgSrc(inputObject, outputObject);
}
}
| 4,568 |
6,181 | <reponame>emacslisp/python
/* System module interface */
#ifndef Py_SYSMODULE_H
#define Py_SYSMODULE_H
#ifdef __cplusplus
extern "C" {
#endif
PyAPI_FUNC(PyObject *) PySys_GetObject(const char *);
PyAPI_FUNC(int) PySys_SetObject(const char *, PyObject *);
#ifndef Py_LIMITED_API
PyAPI_FUNC(PyObject *) _PySys_GetObjectId(_Py_Identifier *key);
PyAPI_FUNC(int) _PySys_SetObjectId(_Py_Identifier *key, PyObject *);
#endif
PyAPI_FUNC(void) PySys_SetArgv(int, wchar_t **);
PyAPI_FUNC(void) PySys_SetArgvEx(int, wchar_t **, int);
PyAPI_FUNC(void) PySys_SetPath(const wchar_t *);
PyAPI_FUNC(void) PySys_WriteStdout(const char *format, ...)
Py_GCC_ATTRIBUTE((format(printf, 1, 2)));
PyAPI_FUNC(void) PySys_WriteStderr(const char *format, ...)
Py_GCC_ATTRIBUTE((format(printf, 1, 2)));
PyAPI_FUNC(void) PySys_FormatStdout(const char *format, ...);
PyAPI_FUNC(void) PySys_FormatStderr(const char *format, ...);
PyAPI_FUNC(void) PySys_ResetWarnOptions(void);
PyAPI_FUNC(void) PySys_AddWarnOption(const wchar_t *);
PyAPI_FUNC(void) PySys_AddWarnOptionUnicode(PyObject *);
PyAPI_FUNC(int) PySys_HasWarnOptions(void);
PyAPI_FUNC(void) PySys_AddXOption(const wchar_t *);
PyAPI_FUNC(PyObject *) PySys_GetXOptions(void);
#ifndef Py_LIMITED_API
PyAPI_FUNC(size_t) _PySys_GetSizeOf(PyObject *);
#endif
#ifdef __cplusplus
}
#endif
#endif /* !Py_SYSMODULE_H */
| 615 |
3,301 | <filename>core/src/test/java/com/alibaba/alink/operator/common/statistics/basicstatistic/VectorStatColTest.java
package com.alibaba.alink.operator.common.statistics.basicstatistic;
import com.alibaba.alink.testutil.AlinkTestBase;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class VectorStatColTest extends AlinkTestBase {
@Test
public void test() {
VectorStatCol stat = new VectorStatCol();
stat.visit(1.0);
stat.visit(-2.0);
stat.visit(Double.NaN);
stat = stat.copy();
assertEquals(1.0, stat.max, 10e-6);
assertEquals(-2.0, stat.min, 10e-6);
assertEquals(5.0, stat.squareSum, 10e-6);
assertEquals(3.0, stat.normL1, 10e-6);
assertEquals(2.0, stat.numNonZero, 10e-6);
assertEquals(-1.0, stat.sum, 10e-6);
assertEquals(-0.5, stat.mean(2), 10e-6);
assertEquals(4.5, stat.variance(2), 10e-6);
assertEquals(2.12132, stat.standardDeviation(2), 10e-6);
}
} | 386 |
7,057 | <gh_stars>1000+
// Copyright 2016 The RE2 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 <stddef.h>
#include <stdint.h>
#include <stdlib.h>
// Entry point for libFuzzer.
extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size);
int main(int argc, char** argv) {
uint8_t data[32];
for (int i = 0; i < 32; i++) {
for (int j = 0; j < 32; j++) {
data[j] = random() & 0xFF;
}
LLVMFuzzerTestOneInput(data, 32);
}
return 0;
}
| 228 |
3,102 | <reponame>medismailben/llvm-project
// Check that we pass -fcomment-block-commands to frontend.
//
// RUN: %clang -c %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-NO-ARG
// RUN: %clang -c %s -fcomment-block-commands=Foo -### 2>&1 | FileCheck %s --check-prefix=CHECK-ARG
//
// CHECK-ARG: -fcomment-block-commands=Foo
//
// CHECK-NO-ARG-NOT: -fcomment-block-commands=
| 154 |
468 | <gh_stars>100-1000
//
// C++ implementation of bucket sort.
//
//
// The All ▲lgorithms Project
//
// https://allalgorithms.com/
// https://github.com/allalgorithms/cpp
//
// Contributed by: <NAME>
// Github: @macmullen
//
#include <cmath>
#include <iostream>
#include <algorithm>
#include <vector>
// A utility function to print an array of size n.
// Implemented by <NAME> in bubble_sort.cpp
void print_array(int arr[], int n)
{
for (size_t i = 0; i < n; i++)
{
std::cout << arr[i] << " ";
}
std::cout << std::endl;
}
// Given an array "arr" of size "n", this function sorts its numbers
// using the algorithm of Bucket Sort.
void bucket_sort(int arr[], size_t n, int number_of_buckets)
{
// Find the maximum element of the array
int* max = std::max_element(arr, arr+n);
// Calculate the divider value dividing the maximum element and number of buckets.
int divider = std::ceil(float(*max + 1) / float(number_of_buckets) );
// Create the buckets array.
std::vector<std::vector<int>> buckets;
buckets.resize(number_of_buckets);
// Place every number into a corresponding bucket.
for (size_t i = 0; i < n; i++)
{
int j = floor(arr[i] / divider);
buckets[j].push_back(arr[i]);
}
// Sort every bucket.
int index = 0;
for (size_t i = 0; i < number_of_buckets; i++)
{
sort(buckets[i].begin(), buckets[i].end());
// Place the sorted numbers into the original array.
for(int number : buckets[i])
{
arr[index] = number;
index++;
}
}
}
int main()
{
int arr[] = {22, 45, 12, 8, 10, 6, 72, 81, 33, 18, 50, 14};
int n = sizeof(arr)/sizeof(arr[0]);
std::cout << "Unsorted array: ";
print_array(arr, n);
bucket_sort(arr, n, 10);
std::cout << "Sorted array: ";
print_array(arr, n);
return 0;
} | 781 |
5,169 | <filename>Specs/WZLSerializeKit/1.1/WZLSerializeKit.podspec.json
{
"name": "WZLSerializeKit",
"version": "1.1",
"summary": "A four-line tool to enable serialize and deserialize in iOS platform",
"description": "A four-line tool to enable serialize and deserialize in iOS platform. 4行代码完成iOS序列化与反序列化.",
"homepage": "https://github.com/weng1250/WZLSerializeKit",
"license": {
"type": "None",
"file": "LICENSE"
},
"authors": {
"<NAME>": "<EMAIL>"
},
"source": {
"git": "https://github.com/weng1250/WZLSerializeKit.git",
"tag": "1.1"
},
"platforms": {
"ios": "6.0"
},
"requires_arc": true,
"source_files": "WZLSerializeKit/*.{h,m}",
"public_header_files": "WZLSerializeKit/**/*.{h}"
}
| 332 |
341 | /* -*- Mode: C; tab-width: 4 -*-
*
* Copyright (c) 2003-2015 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of Apple Inc. ("Apple") 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 APPLE AND ITS 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 APPLE OR ITS 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 DNSSD_IPC_H
#define DNSSD_IPC_H
#include "dns_sd.h"
//
// Common cross platform services
//
#if defined(WIN32)
# include <winsock2.h>
# define dnssd_InvalidSocket INVALID_SOCKET
# define dnssd_SocketValid(s) ((s) != INVALID_SOCKET)
# define dnssd_EWOULDBLOCK WSAEWOULDBLOCK
# define dnssd_EINTR WSAEINTR
# define dnssd_ECONNRESET WSAECONNRESET
# define dnssd_socklen_t int
# define dnssd_close(sock) closesocket(sock)
# define dnssd_errno WSAGetLastError()
# define dnssd_strerror(X) win32_strerror(X)
# define ssize_t int
# define getpid _getpid
# define unlink _unlink
extern char *win32_strerror(int inErrorCode);
#else
# include <sys/types.h>
# include <unistd.h>
# include <sys/un.h>
# include <string.h>
# include <stdio.h>
# include <stdlib.h>
# include <sys/stat.h>
# include <sys/socket.h>
# include <netinet/in.h>
# include <arpa/inet.h>
# define dnssd_InvalidSocket -1
# define dnssd_SocketValid(s) ((s) >= 0)
# define dnssd_EWOULDBLOCK EWOULDBLOCK
# define dnssd_EINTR EINTR
# define dnssd_ECONNRESET ECONNRESET
# define dnssd_EPIPE EPIPE
# define dnssd_socklen_t unsigned int
# define dnssd_close(sock) close(sock)
# define dnssd_errno errno
# define dnssd_strerror(X) strerror(X)
#endif
#if defined(USE_TCP_LOOPBACK)
# define AF_DNSSD AF_INET
# define MDNS_TCP_SERVERADDR "127.0.0.1"
# define MDNS_TCP_SERVERPORT 5354
# define LISTENQ 5
# define dnssd_sockaddr_t struct sockaddr_in
#else
# define AF_DNSSD AF_LOCAL
# ifndef MDNS_UDS_SERVERPATH
# define MDNS_UDS_SERVERPATH "/var/run/mDNSResponder"
# endif
# define MDNS_UDS_SERVERPATH_ENVVAR "DNSSD_UDS_PATH"
# define LISTENQ 100
// longest legal control path length
# define MAX_CTLPATH (sizeof(((struct sockaddr_un*)0)->sun_path))
# define dnssd_sockaddr_t struct sockaddr_un
#endif
// Compatibility workaround
#ifndef AF_LOCAL
#define AF_LOCAL AF_UNIX
#endif
// General UDS constants
#define TXT_RECORD_INDEX ((uint32_t)(-1)) // record index for default text record
// IPC data encoding constants and types
#define VERSION 1
#define IPC_FLAGS_NOREPLY 1 // set flag if no asynchronous replies are to be sent to client
// Structure packing macro. If we're not using GNUC, it's not fatal. Most compilers naturally pack the on-the-wire
// structures correctly anyway, so a plain "struct" is usually fine. In the event that structures are not packed
// correctly, our compile-time assertion checks will catch it and prevent inadvertent generation of non-working code.
#ifndef packedstruct
#if ((__GNUC__ > 2) || ((__GNUC__ == 2) && (__GNUC_MINOR__ >= 9)))
#define packedstruct struct __attribute__((__packed__))
#define packedunion union __attribute__((__packed__))
#else
#define packedstruct struct
#define packedunion union
#endif
#endif
typedef enum
{
request_op_none = 0, // No request yet received on this connection
connection_request = 1, // connected socket via DNSServiceConnect()
reg_record_request, // reg/remove record only valid for connected sockets
remove_record_request,
enumeration_request,
reg_service_request,
browse_request,
resolve_request,
query_request,
reconfirm_record_request,
add_record_request,
update_record_request,
setdomain_request, // Up to here is in Tiger and B4W 1.0.3
getproperty_request, // New in B4W 1.0.4
port_mapping_request, // New in Leopard and B4W 2.0
addrinfo_request,
send_bpf, // New in SL
getpid_request,
release_request,
connection_delegate_request,
cancel_request = 63
} request_op_t;
typedef enum
{
enumeration_reply_op = 64,
reg_service_reply_op,
browse_reply_op,
resolve_reply_op,
query_reply_op,
reg_record_reply_op, // Up to here is in Tiger and B4W 1.0.3
getproperty_reply_op, // New in B4W 1.0.4
port_mapping_reply_op, // New in Leopard and B4W 2.0
addrinfo_reply_op
} reply_op_t;
#if defined(_WIN64)
# pragma pack(push,4)
#endif
// Define context object big enough to hold a 64-bit pointer,
// to accomodate 64-bit clients communicating with 32-bit daemon.
// There's no reason for the daemon to ever be a 64-bit process, but its clients might be
typedef packedunion
{
void *context;
uint32_t u32[2];
} client_context_t;
typedef packedstruct
{
uint32_t version;
uint32_t datalen;
uint32_t ipc_flags;
uint32_t op; // request_op_t or reply_op_t
client_context_t client_context; // context passed from client, returned by server in corresponding reply
uint32_t reg_index; // identifier for a record registered via DNSServiceRegisterRecord() on a
// socket connected by DNSServiceCreateConnection(). Must be unique in the scope of the connection, such that and
// index/socket pair uniquely identifies a record. (Used to select records for removal by DNSServiceRemoveRecord())
} ipc_msg_hdr;
#if defined(_WIN64)
# pragma pack(pop)
#endif
// routines to write to and extract data from message buffers.
// caller responsible for bounds checking.
// ptr is the address of the pointer to the start of the field.
// it is advanced to point to the next field, or the end of the message
void put_uint32(const uint32_t l, char **ptr);
uint32_t get_uint32(const char **ptr, const char *end);
void put_uint16(uint16_t s, char **ptr);
uint16_t get_uint16(const char **ptr, const char *end);
#define put_flags put_uint32
#define get_flags get_uint32
#define put_error_code put_uint32
#define get_error_code get_uint32
int put_string(const char *str, char **ptr);
int get_string(const char **ptr, const char *const end, char *buffer, int buflen);
void put_rdata(const int rdlen, const unsigned char *rdata, char **ptr);
const char *get_rdata(const char **ptr, const char *end, int rdlen); // return value is rdata pointed to by *ptr -
// rdata is not copied from buffer.
void ConvertHeaderBytes(ipc_msg_hdr *hdr);
struct CompileTimeAssertionChecks_dnssd_ipc
{
// Check that the compiler generated our on-the-wire packet format structure definitions
// properly packed, without adding padding bytes to align fields on 32-bit or 64-bit boundaries.
char assert0[(sizeof(client_context_t) == 8) ? 1 : -1];
char assert1[(sizeof(ipc_msg_hdr) == 28) ? 1 : -1];
};
#endif // DNSSD_IPC_H
| 3,074 |
3,062 | <reponame>kudlav/organicmaps
package com.mapswithme.maps.search;
import android.view.View;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.StringRes;
import com.mapswithme.maps.R;
import com.mapswithme.util.UiUtils;
public class SearchFilterController
{
@NonNull
private final View mFrame;
@NonNull
private final TextView mShowOnMap;
@NonNull
private final View mDivider;
@Nullable
private final FilterListener mFilterListener;
interface FilterListener
{
void onShowOnMapClick();
}
public SearchFilterController(@NonNull View frame, @Nullable FilterListener listener,
@StringRes int populateButtonText)
{
mFrame = frame;
mFilterListener = listener;
mShowOnMap = mFrame.findViewById(R.id.show_on_map);
mShowOnMap.setText(populateButtonText);
mDivider = mFrame.findViewById(R.id.divider);
initListeners();
}
public void show(boolean show)
{
UiUtils.showIf(show, mFrame);
showPopulateButton(true);
}
void showPopulateButton(boolean show)
{
UiUtils.showIf(show, mShowOnMap);
}
void showDivider(boolean show)
{
UiUtils.showIf(show, mDivider);
}
private void initListeners()
{
mShowOnMap.setOnClickListener(v ->
{
if (mFilterListener != null)
mFilterListener.onShowOnMapClick();
});
}
public static class DefaultFilterListener implements FilterListener
{
@Override
public void onShowOnMapClick()
{
}
}
}
| 706 |
995 | // Copyright 2015-2017 <NAME>
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt
// or copy at http://www.boost.org/LICENSE_1_0.txt)
#ifndef BOOST_HISTOGRAM_UNLIMTED_STORAGE_HPP
#define BOOST_HISTOGRAM_UNLIMTED_STORAGE_HPP
#include <algorithm>
#include <boost/assert.hpp>
#include <boost/config/workaround.hpp>
#include <boost/cstdint.hpp>
#include <boost/histogram/detail/meta.hpp>
#include <boost/histogram/fwd.hpp>
#include <boost/iterator/iterator_adaptor.hpp>
#include <boost/mp11/algorithm.hpp>
#include <boost/mp11/list.hpp>
#include <cmath>
#include <functional>
#include <limits>
#include <memory>
#include <type_traits>
namespace boost {
namespace histogram {
namespace detail {
// version of std::equal_to<> which handles comparison of signed and unsigned
struct equal {
template <class T, class U>
bool operator()(const T& t, const U& u) const noexcept {
return impl(std::is_signed<T>{}, std::is_signed<U>{}, t, u);
}
template <class T, class U>
bool impl(std::false_type, std::false_type, const T& t, const U& u) const noexcept {
return t == u;
}
template <class T, class U>
bool impl(std::false_type, std::true_type, const T& t, const U& u) const noexcept {
return u >= 0 && t == make_unsigned(u);
}
template <class T, class U>
bool impl(std::true_type, std::false_type, const T& t, const U& u) const noexcept {
return t >= 0 && make_unsigned(t) == u;
}
template <class T, class U>
bool impl(std::true_type, std::true_type, const T& t, const U& u) const noexcept {
return t == u;
}
};
// version of std::less<> which handles comparison of signed and unsigned
struct less {
template <class T, class U>
bool operator()(const T& t, const U& u) const noexcept {
return impl(std::is_signed<T>{}, std::is_signed<U>{}, t, u);
}
template <class T, class U>
bool impl(std::false_type, std::false_type, const T& t, const U& u) const noexcept {
return t < u;
}
template <class T, class U>
bool impl(std::false_type, std::true_type, const T& t, const U& u) const noexcept {
return u >= 0 && t < make_unsigned(u);
}
template <class T, class U>
bool impl(std::true_type, std::false_type, const T& t, const U& u) const noexcept {
return t < 0 || make_unsigned(t) < u;
}
template <class T, class U>
bool impl(std::true_type, std::true_type, const T& t, const U& u) const noexcept {
return t < u;
}
};
// version of std::greater<> which handles comparison of signed and unsigned
struct greater {
template <class T, class U>
bool operator()(const T& t, const U& u) const noexcept {
return impl(std::is_signed<T>{}, std::is_signed<U>{}, t, u);
}
template <class T, class U>
bool impl(std::false_type, std::false_type, const T& t, const U& u) const noexcept {
return t > u;
}
template <class T, class U>
bool impl(std::false_type, std::true_type, const T& t, const U& u) const noexcept {
return u < 0 || t > make_unsigned(u);
}
template <class T, class U>
bool impl(std::true_type, std::false_type, const T& t, const U& u) const noexcept {
return t >= 0 && make_unsigned(t) > u;
}
template <class T, class U>
bool impl(std::true_type, std::true_type, const T& t, const U& u) const noexcept {
return t > u;
}
};
template <class Allocator>
struct mp_int;
template <class T>
struct is_unsigned_integral : mp11::mp_and<std::is_integral<T>, std::is_unsigned<T>> {};
template <class T>
bool safe_increment(T& t) {
if (t < std::numeric_limits<T>::max()) {
++t;
return true;
}
return false;
}
template <class T, class U>
bool safe_radd(T& t, const U& u) {
static_assert(is_unsigned_integral<T>::value, "T must be unsigned integral type");
static_assert(is_unsigned_integral<U>::value, "T must be unsigned integral type");
if (static_cast<T>(std::numeric_limits<T>::max() - t) >= u) {
t += static_cast<T>(u); // static_cast to suppress conversion warning
return true;
}
return false;
}
// use boost.multiprecision.cpp_int in your own code, it is much more sophisticated
// than this implementation; we use it here to reduce coupling between boost libs
template <class Allocator>
struct mp_int {
explicit mp_int(Allocator a = {}) : data(1, 0, std::move(a)) {}
explicit mp_int(uint64_t v, Allocator a = {}) : data(1, v, std::move(a)) {}
mp_int(const mp_int&) = default;
mp_int& operator=(const mp_int&) = default;
mp_int(mp_int&&) = default;
mp_int& operator=(mp_int&&) = default;
mp_int& operator=(uint64_t o) {
data = decltype(data)(1, o);
return *this;
}
mp_int& operator++() {
BOOST_ASSERT(data.size() > 0u);
std::size_t i = 0;
while (!safe_increment(data[i])) {
data[i] = 0;
++i;
if (i == data.size()) {
data.push_back(1);
break;
}
}
return *this;
}
mp_int& operator+=(const mp_int& o) {
if (this == &o) {
auto tmp{o};
return operator+=(tmp);
}
bool carry = false;
std::size_t i = 0;
for (uint64_t oi : o.data) {
auto& di = maybe_extend(i);
if (carry) {
if (safe_increment(oi))
carry = false;
else {
++i;
continue;
}
}
if (!safe_radd(di, oi)) {
add_remainder(di, oi);
carry = true;
}
++i;
}
while (carry) {
auto& di = maybe_extend(i);
if (safe_increment(di)) break;
di = 0;
++i;
}
return *this;
}
mp_int& operator+=(uint64_t o) {
BOOST_ASSERT(data.size() > 0u);
if (safe_radd(data[0], o)) return *this;
add_remainder(data[0], o);
// carry the one, data may grow several times
std::size_t i = 1;
while (true) {
auto& di = maybe_extend(i);
if (safe_increment(di)) break;
di = 0;
++i;
}
return *this;
}
operator double() const noexcept {
BOOST_ASSERT(data.size() > 0u);
double result = static_cast<double>(data[0]);
std::size_t i = 0;
while (++i < data.size())
result += static_cast<double>(data[i]) * std::pow(2.0, i * 64);
return result;
}
// total ordering for mp_int, mp_int
bool operator<(const mp_int& o) const noexcept {
BOOST_ASSERT(data.size() > 0u);
BOOST_ASSERT(o.data.size() > 0u);
// no leading zeros allowed
BOOST_ASSERT(data.size() == 1 || data.back() > 0u);
BOOST_ASSERT(o.data.size() == 1 || o.data.back() > 0u);
if (data.size() < o.data.size()) return true;
if (data.size() > o.data.size()) return false;
auto s = data.size();
while (s > 0u) {
--s;
if (data[s] < o.data[s]) return true;
if (data[s] > o.data[s]) return false;
}
return false; // args are equal
}
bool operator==(const mp_int& o) const noexcept {
BOOST_ASSERT(data.size() > 0u);
BOOST_ASSERT(o.data.size() > 0u);
// no leading zeros allowed
BOOST_ASSERT(data.size() == 1 || data.back() > 0u);
BOOST_ASSERT(o.data.size() == 1 || o.data.back() > 0u);
if (data.size() != o.data.size()) return false;
return std::equal(data.begin(), data.end(), o.data.begin());
}
// copied from boost/operators.hpp
friend bool operator>(const mp_int& x, const mp_int& y) { return y < x; }
friend bool operator<=(const mp_int& x, const mp_int& y) { return !(y < x); }
friend bool operator>=(const mp_int& x, const mp_int& y) { return !(x < y); }
friend bool operator!=(const mp_int& x, const mp_int& y) { return !(x == y); }
// total ordering for mp_int, uint64; partial ordering for mp_int, double
template <class U>
bool operator<(const U& o) const noexcept {
BOOST_ASSERT(data.size() > 0u);
return static_if<is_unsigned_integral<U>>(
[this](uint64_t o) { return data.size() == 1 && data[0] < o; },
[this](double o) { return operator double() < o; }, o);
}
template <class U>
bool operator>(const U& o) const noexcept {
BOOST_ASSERT(data.size() > 0u);
BOOST_ASSERT(data.back() > 0u); // no leading zeros allowed
return static_if<is_unsigned_integral<U>>(
[this](uint64_t o) { return data.size() > 1 || data[0] > o; },
[this](double o) { return operator double() > o; }, o);
}
template <class U>
bool operator==(const U& o) const noexcept {
BOOST_ASSERT(data.size() > 0u);
return static_if<is_unsigned_integral<U>>(
[this](uint64_t o) { return data.size() == 1 && data[0] == o; },
[this](double o) { return operator double() == o; }, o);
}
// adapted copy from boost/operators.hpp
template <class U>
friend bool operator<=(const mp_int& x, const U& y) {
if (is_unsigned_integral<U>::value) return !(x > y);
return (x < y) || (x == y);
}
template <class U>
friend bool operator>=(const mp_int& x, const U& y) {
if (is_unsigned_integral<U>::value) return !(x < y);
return (x > y) || (x == y);
}
template <class U>
friend bool operator>(const U& x, const mp_int& y) {
if (is_unsigned_integral<U>::value) return y < x;
return y < x;
}
template <class U>
friend bool operator<(const U& x, const mp_int& y) {
if (is_unsigned_integral<U>::value) return y > x;
return y > x;
}
template <class U>
friend bool operator<=(const U& x, const mp_int& y) {
if (is_unsigned_integral<U>::value) return !(y < x);
return (y > x) || (y == x);
}
template <class U>
friend bool operator>=(const U& x, const mp_int& y) {
if (is_unsigned_integral<U>::value) return !(y > x);
return (y < x) || (y == x);
}
template <class U>
friend bool operator==(const U& y, const mp_int& x) {
return x == y;
}
template <class U>
friend bool operator!=(const U& y, const mp_int& x) {
return !(x == y);
}
template <class U>
friend bool operator!=(const mp_int& y, const U& x) {
return !(y == x);
}
uint64_t& maybe_extend(std::size_t i) {
while (i >= data.size()) data.push_back(0);
return data[i];
}
static void add_remainder(uint64_t& d, const uint64_t o) noexcept {
BOOST_ASSERT(d > 0u);
// in decimal system it would look like this:
// 8 + 8 = 6 = 8 - (9 - 8) - 1
// 9 + 1 = 0 = 9 - (9 - 1) - 1
auto tmp = std::numeric_limits<uint64_t>::max();
tmp -= o;
--d -= tmp;
}
std::vector<uint64_t, Allocator> data;
};
template <class Allocator>
auto create_buffer(Allocator& a, std::size_t n) {
using AT = std::allocator_traits<Allocator>;
auto ptr = AT::allocate(a, n); // may throw
static_assert(std::is_trivially_copyable<decltype(ptr)>::value,
"ptr must be trivially copyable");
auto it = ptr;
const auto end = ptr + n;
try {
// this loop may throw
while (it != end) AT::construct(a, it++, typename AT::value_type{});
} catch (...) {
// release resources that were already acquired before rethrowing
while (it != ptr) AT::destroy(a, --it);
AT::deallocate(a, ptr, n);
throw;
}
return ptr;
}
template <class Allocator, class Iterator>
auto create_buffer(Allocator& a, std::size_t n, Iterator iter) {
BOOST_ASSERT(n > 0u);
using AT = std::allocator_traits<Allocator>;
auto ptr = AT::allocate(a, n); // may throw
static_assert(std::is_trivially_copyable<decltype(ptr)>::value,
"ptr must be trivially copyable");
auto it = ptr;
const auto end = ptr + n;
try {
// this loop may throw
while (it != end) AT::construct(a, it++, *iter++);
} catch (...) {
// release resources that were already acquired before rethrowing
while (it != ptr) AT::destroy(a, --it);
AT::deallocate(a, ptr, n);
throw;
}
return ptr;
}
template <class Allocator>
void destroy_buffer(Allocator& a, typename std::allocator_traits<Allocator>::pointer p,
std::size_t n) {
BOOST_ASSERT(p);
BOOST_ASSERT(n > 0u);
using AT = std::allocator_traits<Allocator>;
auto it = p + n;
while (it != p) AT::destroy(a, --it);
AT::deallocate(a, p, n);
}
} // namespace detail
/**
Memory-efficient storage for integral counters which cannot overflow.
This storage provides a no-overflow-guarantee if it is filled with integral weights
only. This storage implementation keeps a contiguous array of elemental counters, one
for each cell. If an operation is requested, which would overflow a counter, the whole
array is replaced with another of a wider integral type, then the operation is executed.
The storage uses integers of 8, 16, 32, 64 bits, and then switches to a multiprecision
integral type, similar to those in
[Boost.Multiprecision](https://www.boost.org/doc/libs/develop/libs/multiprecision/doc/html/index.html).
A scaling operation or adding a floating point number turns the elements into doubles,
which voids the no-overflow-guarantee.
*/
template <class Allocator>
class unlimited_storage {
static_assert(
std::is_same<typename std::allocator_traits<Allocator>::pointer,
typename std::allocator_traits<Allocator>::value_type*>::value,
"unlimited_storage requires allocator with trivial pointer type");
public:
using allocator_type = Allocator;
using value_type = double;
using mp_int = detail::mp_int<
typename std::allocator_traits<allocator_type>::template rebind_alloc<uint64_t>>;
private:
using types = mp11::mp_list<uint8_t, uint16_t, uint32_t, uint64_t, mp_int, double>;
template <class T>
static constexpr char type_index() noexcept {
return static_cast<char>(mp11::mp_find<types, T>::value);
}
struct buffer_type {
allocator_type alloc;
std::size_t size = 0;
char type = 0;
void* ptr = nullptr;
template <class F, class... Ts>
decltype(auto) apply(F&& f, Ts&&... ts) const {
// this is intentionally not a switch, the if-chain is faster in benchmarks
if (type == type_index<uint8_t>())
return f(static_cast<uint8_t*>(ptr), std::forward<Ts>(ts)...);
if (type == type_index<uint16_t>())
return f(static_cast<uint16_t*>(ptr), std::forward<Ts>(ts)...);
if (type == type_index<uint32_t>())
return f(static_cast<uint32_t*>(ptr), std::forward<Ts>(ts)...);
if (type == type_index<uint64_t>())
return f(static_cast<uint64_t*>(ptr), std::forward<Ts>(ts)...);
if (type == type_index<mp_int>())
return f(static_cast<mp_int*>(ptr), std::forward<Ts>(ts)...);
return f(static_cast<double*>(ptr), std::forward<Ts>(ts)...);
}
buffer_type(allocator_type a = {}) : alloc(std::move(a)) {}
buffer_type(buffer_type&& o) noexcept
: alloc(std::move(o.alloc)), size(o.size), type(o.type), ptr(o.ptr) {
o.size = 0;
o.type = 0;
o.ptr = nullptr;
}
buffer_type& operator=(buffer_type&& o) noexcept {
if (this != &o) {
using std::swap;
swap(alloc, o.alloc);
swap(size, o.size);
swap(type, o.type);
swap(ptr, o.ptr);
}
return *this;
}
buffer_type(const buffer_type& o) : alloc(o.alloc) {
o.apply([this, &o](auto* otp) {
using T = detail::remove_cvref_t<decltype(*otp)>;
this->template make<T>(o.size, otp);
});
}
buffer_type& operator=(const buffer_type& o) {
*this = buffer_type(o);
return *this;
}
~buffer_type() noexcept { destroy(); }
void destroy() noexcept {
BOOST_ASSERT((ptr == nullptr) == (size == 0));
if (ptr == nullptr) return;
apply([this](auto* tp) {
using T = detail::remove_cvref_t<decltype(*tp)>;
using alloc_type =
typename std::allocator_traits<allocator_type>::template rebind_alloc<T>;
alloc_type a(alloc); // rebind allocator
detail::destroy_buffer(a, tp, size);
});
size = 0;
type = 0;
ptr = nullptr;
}
#if defined(_MSC_VER)
#pragma warning(push)
#pragma warning(disable : 4244) // possible loss of data
#endif
template <class T>
void make(std::size_t n) {
// note: order of commands is to not leave buffer in invalid state upon throw
destroy();
if (n > 0) {
// rebind allocator
using alloc_type =
typename std::allocator_traits<allocator_type>::template rebind_alloc<T>;
alloc_type a(alloc);
ptr = detail::create_buffer(a, n); // may throw
}
size = n;
type = type_index<T>();
}
template <class T, class U>
void make(std::size_t n, U iter) {
// note: iter may be current ptr, so create new buffer before deleting old buffer
T* new_ptr = nullptr;
const auto new_type = type_index<T>();
if (n > 0) {
// rebind allocator
using alloc_type =
typename std::allocator_traits<allocator_type>::template rebind_alloc<T>;
alloc_type a(alloc);
new_ptr = detail::create_buffer(a, n, iter); // may throw
}
destroy();
size = n;
type = new_type;
ptr = new_ptr;
}
#if defined(_MSC_VER)
#pragma warning(pop)
#endif
};
template <class Buffer>
class reference_t {
public:
reference_t(Buffer* b, std::size_t i) : buffer_(b), idx_(i) {}
reference_t(const reference_t&) = default;
reference_t& operator=(const reference_t&) = delete; // references do not rebind
reference_t& operator=(reference_t&&) = delete; // references do not rebind
// minimal operators for partial ordering
bool operator<(reference_t rhs) const { return op<detail::less>(rhs); }
bool operator>(reference_t rhs) const { return op<detail::greater>(rhs); }
bool operator==(reference_t rhs) const { return op<detail::equal>(rhs); }
// adapted copy from boost/operators.hpp for partial ordering
friend bool operator<=(reference_t x, reference_t y) { return !(y < x); }
friend bool operator>=(reference_t x, reference_t y) { return !(y > x); }
friend bool operator!=(reference_t y, reference_t x) { return !(x == y); }
template <class U>
bool operator<(const U& rhs) const {
return op<detail::less>(rhs);
}
template <class U>
bool operator>(const U& rhs) const {
return op<detail::greater>(rhs);
}
template <class U>
bool operator==(const U& rhs) const {
return op<detail::equal>(rhs);
}
// adapted copy from boost/operators.hpp
template <class U>
friend bool operator<=(reference_t x, const U& y) {
if (detail::is_unsigned_integral<U>::value) return !(x > y);
return (x < y) || (x == y);
}
template <class U>
friend bool operator>=(reference_t x, const U& y) {
if (detail::is_unsigned_integral<U>::value) return !(x < y);
return (x > y) || (x == y);
}
template <class U>
friend bool operator>(const U& x, reference_t y) {
return y < x;
}
template <class U>
friend bool operator<(const U& x, reference_t y) {
return y > x;
}
template <class U>
friend bool operator<=(const U& x, reference_t y) {
if (detail::is_unsigned_integral<U>::value) return !(y < x);
return (y > x) || (y == x);
}
template <class U>
friend bool operator>=(const U& x, reference_t y) {
if (detail::is_unsigned_integral<U>::value) return !(y > x);
return (y < x) || (y == x);
}
template <class U>
friend bool operator==(const U& y, reference_t x) {
return x == y;
}
template <class U>
friend bool operator!=(const U& y, reference_t x) {
return !(x == y);
}
template <class U>
friend bool operator!=(reference_t y, const U& x) {
return !(y == x);
}
operator double() const {
return buffer_->apply(
[this](const auto* tp) { return static_cast<double>(tp[idx_]); });
}
protected:
template <class Binary, class U>
bool op(const reference_t<U>& rhs) const {
const auto i = idx_;
const auto j = rhs.idx_;
return buffer_->apply([i, j, &rhs](const auto* ptr) {
const auto& pi = ptr[i];
return rhs.buffer_->apply([&pi, j](const auto* q) { return Binary()(pi, q[j]); });
});
}
template <class Binary, class U>
bool op(const U& rhs) const {
const auto i = idx_;
return buffer_->apply([i, &rhs](const auto* tp) { return Binary()(tp[i], rhs); });
}
template <class U>
friend class reference_t;
Buffer* buffer_;
std::size_t idx_;
};
public:
using const_reference = reference_t<const buffer_type>;
class reference : public reference_t<buffer_type> {
using base_type = reference_t<buffer_type>;
public:
using base_type::base_type;
reference operator=(reference t) {
t.buffer_->apply([this, &t](const auto* otp) { *this = otp[t.idx_]; });
return *this;
}
reference operator=(const_reference t) {
t.buffer_->apply([this, &t](const auto* otp) { *this = otp[t.idx_]; });
return *this;
}
template <class U>
reference operator=(const U& t) {
base_type::buffer_->apply([this, &t](auto* tp) {
tp[this->idx_] = 0;
adder()(tp, *(this->buffer_), this->idx_, t);
});
return *this;
}
template <class U>
reference operator+=(const U& t) {
base_type::buffer_->apply(adder(), *base_type::buffer_, base_type::idx_, t);
return *this;
}
template <class U>
reference operator*=(const U& t) {
base_type::buffer_->apply(multiplier(), *base_type::buffer_, base_type::idx_, t);
return *this;
}
template <class U>
reference operator-=(const U& t) {
return operator+=(-t);
}
template <class U>
reference operator/=(const U& t) {
return operator*=(1.0 / static_cast<double>(t));
}
reference operator++() {
base_type::buffer_->apply(incrementor(), *base_type::buffer_, base_type::idx_);
return *this;
}
// minimal operators for partial ordering
bool operator<(reference rhs) const { return base_type::operator<(rhs); }
bool operator>(reference rhs) const { return base_type::operator>(rhs); }
bool operator==(reference rhs) const { return base_type::operator==(rhs); }
// adapted copy from boost/operators.hpp for partial ordering
friend bool operator<=(reference x, reference y) { return !(y < x); }
friend bool operator>=(reference x, reference y) { return !(y > x); }
friend bool operator!=(reference y, reference x) { return !(x == y); }
};
private:
template <class Value, class Reference, class Buffer>
class iterator_t
: public boost::iterator_adaptor<iterator_t<Value, Reference, Buffer>, std::size_t,
Value, std::random_access_iterator_tag, Reference,
std::ptrdiff_t> {
public:
iterator_t() = default;
template <class V, class R, class B>
iterator_t(const iterator_t<V, R, B>& it)
: iterator_t::iterator_adaptor_(it.base()), buffer_(it.buffer_) {}
iterator_t(Buffer* b, std::size_t i) noexcept
: iterator_t::iterator_adaptor_(i), buffer_(b) {}
protected:
template <class V, class R, class B>
bool equal(const iterator_t<V, R, B>& rhs) const noexcept {
return buffer_ == rhs.buffer_ && this->base() == rhs.base();
}
Reference dereference() const { return {buffer_, this->base()}; }
friend class ::boost::iterator_core_access;
template <class V, class R, class B>
friend class iterator_t;
private:
Buffer* buffer_ = nullptr;
};
public:
using const_iterator = iterator_t<const value_type, const_reference, const buffer_type>;
using iterator = iterator_t<value_type, reference, buffer_type>;
explicit unlimited_storage(allocator_type a = {}) : buffer(std::move(a)) {}
unlimited_storage(const unlimited_storage&) = default;
unlimited_storage& operator=(const unlimited_storage&) = default;
unlimited_storage(unlimited_storage&&) = default;
unlimited_storage& operator=(unlimited_storage&&) = default;
template <class T>
unlimited_storage(const storage_adaptor<T>& s) {
using V = detail::remove_cvref_t<decltype(s[0])>;
constexpr auto ti = type_index<V>();
detail::static_if_c<(ti < mp11::mp_size<types>::value)>(
[&](auto) { buffer.template make<V>(s.size(), s.begin()); },
[&](auto) { buffer.template make<double>(s.size(), s.begin()); }, 0);
}
template <class Iterable, class = detail::requires_iterable<Iterable>>
unlimited_storage& operator=(const Iterable& s) {
*this = unlimited_storage(s);
return *this;
}
allocator_type get_allocator() const { return buffer.alloc; }
void reset(std::size_t s) { buffer.template make<uint8_t>(s); }
std::size_t size() const noexcept { return buffer.size; }
reference operator[](std::size_t i) noexcept { return {&buffer, i}; }
const_reference operator[](std::size_t i) const noexcept { return {&buffer, i}; }
bool operator==(const unlimited_storage& o) const noexcept {
if (size() != o.size()) return false;
return buffer.apply([&o](const auto* ptr) {
return o.buffer.apply([ptr, &o](const auto* optr) {
return std::equal(ptr, ptr + o.size(), optr, detail::equal{});
});
});
}
template <class T>
bool operator==(const T& o) const {
if (size() != o.size()) return false;
return buffer.apply([&o](const auto* ptr) {
return std::equal(ptr, ptr + o.size(), std::begin(o), detail::equal{});
});
}
unlimited_storage& operator*=(const double x) {
buffer.apply(multiplier(), buffer, x);
return *this;
}
iterator begin() noexcept { return {&buffer, 0}; }
iterator end() noexcept { return {&buffer, size()}; }
const_iterator begin() const noexcept { return {&buffer, 0}; }
const_iterator end() const noexcept { return {&buffer, size()}; }
/// @private used by unit tests, not part of generic storage interface
template <class T>
unlimited_storage(std::size_t s, const T* p, allocator_type a = {})
: buffer(std::move(a)) {
buffer.template make<T>(s, p);
}
template <class Archive>
void serialize(Archive&, unsigned);
private:
struct incrementor {
template <class T, class Buffer>
void operator()(T* tp, Buffer& b, std::size_t i) {
if (!detail::safe_increment(tp[i])) {
using U = mp11::mp_at_c<types, (type_index<T>() + 1)>;
b.template make<U>(b.size, tp);
++static_cast<U*>(b.ptr)[i];
}
}
template <class Buffer>
void operator()(mp_int* tp, Buffer&, std::size_t i) {
++tp[i];
}
template <class Buffer>
void operator()(double* tp, Buffer&, std::size_t i) {
++tp[i];
}
};
struct adder {
template <class Buffer, class U>
void operator()(double* tp, Buffer&, std::size_t i, const U& x) {
tp[i] += static_cast<double>(x);
}
template <class T, class Buffer, class U>
void operator()(T* tp, Buffer& b, std::size_t i, const U& x) {
U_is_integral(std::is_integral<U>{}, tp, b, i, x);
}
template <class T, class Buffer, class U>
void U_is_integral(std::false_type, T* tp, Buffer& b, std::size_t i, const U& x) {
b.template make<double>(b.size, tp);
operator()(static_cast<double*>(b.ptr), b, i, x);
}
template <class T, class Buffer, class U>
void U_is_integral(std::true_type, T* tp, Buffer& b, std::size_t i, const U& x) {
U_is_unsigned_integral(std::is_unsigned<U>{}, tp, b, i, x);
}
template <class T, class Buffer, class U>
void U_is_unsigned_integral(std::false_type, T* tp, Buffer& b, std::size_t i,
const U& x) {
if (x >= 0)
U_is_unsigned_integral(std::true_type{}, tp, b, i, detail::make_unsigned(x));
else
U_is_integral(std::false_type{}, tp, b, i, static_cast<double>(x));
}
template <class Buffer, class U>
void U_is_unsigned_integral(std::true_type, mp_int* tp, Buffer&, std::size_t i,
const U& x) {
tp[i] += x;
}
template <class T, class Buffer, class U>
void U_is_unsigned_integral(std::true_type, T* tp, Buffer& b, std::size_t i,
const U& x) {
if (detail::safe_radd(tp[i], x)) return;
using V = mp11::mp_at_c<types, (type_index<T>() + 1)>;
b.template make<V>(b.size, tp);
U_is_unsigned_integral(std::true_type{}, static_cast<V*>(b.ptr), b, i, x);
}
};
struct multiplier {
template <class T, class Buffer>
void operator()(T* tp, Buffer& b, const double x) {
// potential lossy conversion that cannot be avoided
b.template make<double>(b.size, tp);
operator()(static_cast<double*>(b.ptr), b, x);
}
template <class Buffer>
void operator()(double* tp, Buffer& b, const double x) {
for (auto end = tp + b.size; tp != end; ++tp) *tp *= x;
}
template <class T, class Buffer, class U>
void operator()(T* tp, Buffer& b, std::size_t i, const U& x) {
b.template make<double>(b.size, tp);
operator()(static_cast<double*>(b.ptr), b, i, x);
}
template <class Buffer, class U>
void operator()(double* tp, Buffer&, std::size_t i, const U& x) {
tp[i] *= static_cast<double>(x);
}
};
buffer_type buffer;
};
} // namespace histogram
} // namespace boost
#endif
| 12,967 |
776 | <filename>src/main/java/com/hivemq/security/ssl/NonSslHandler.java
/*
* Copyright 2019-present HiveMQ GmbH
*
* 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.hivemq.security.ssl;
import com.google.inject.Inject;
import com.hivemq.extension.sdk.api.annotations.NotNull;
import com.hivemq.mqtt.handler.disconnect.MqttServerDisconnector;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import io.netty.handler.ssl.SslHandler;
import java.util.List;
/**
* @author <NAME>
*/
public class NonSslHandler extends ByteToMessageDecoder {
private final @NotNull MqttServerDisconnector mqttServerDisconnector;
@Inject
public NonSslHandler(final @NotNull MqttServerDisconnector mqttServerDisconnector) {
this.mqttServerDisconnector = mqttServerDisconnector;
}
@Override
protected void decode(final @NotNull ChannelHandlerContext ctx, final @NotNull ByteBuf in, final @NotNull List<Object> out) throws Exception {
//Needs minimum 5 bytes to be able to tell what it is.
if (in.readableBytes() < 11) {
return;
}
//Check for SSL bytes
final boolean encrypted = SslHandler.isEncrypted(in);
//With MQTT5 it is possible to craft a valid CONNECT packet, that matches an SSLv2 packet
final boolean isConnectPacket = in.getUnsignedByte(0) == 16;
final boolean isMqttPacket = in.getUnsignedByte(7) == 'M' &&
in.getUnsignedByte(8) == 'Q' &&
in.getUnsignedByte(9) == 'T' &&
in.getUnsignedByte(10) == 'T';
if (encrypted && !(isConnectPacket && isMqttPacket)) {
mqttServerDisconnector.logAndClose(ctx.channel(),
"SSL connection on non-SSL listener, dropping connection for client with IP '{}'",
"SSL connection to non-SSL listener");
in.clear();
return;
}
ctx.pipeline().remove(this);
}
}
| 960 |
1,838 | <reponame>RussellM2020/maml_gps
import numpy as np
from nose2 import tools
from rllab.envs.box2d.car_parking_env import CarParkingEnv
from rllab.envs.box2d.cartpole_env import CartpoleEnv
from rllab.envs.box2d.cartpole_swingup_env import CartpoleSwingupEnv
from rllab.envs.box2d.double_pendulum_env import DoublePendulumEnv
from rllab.envs.box2d.mountain_car_env import MountainCarEnv
from rllab.envs.grid_world_env import GridWorldEnv
from rllab.envs.identification_env import IdentificationEnv
import os
MUJOCO_ENABLED = True
try:
import rllab.mujoco_py
from rllab.envs.mujoco.half_cheetah_env import HalfCheetahEnv
from rllab.envs.mujoco.hopper_env import HopperEnv
from rllab.envs.mujoco.inverted_double_pendulum_env import InvertedDoublePendulumEnv
from rllab.envs.mujoco.point_env import PointEnv
from rllab.envs.mujoco.simple_humanoid_env import SimpleHumanoidEnv
from rllab.envs.mujoco.swimmer_env import SwimmerEnv
from rllab.envs.mujoco.walker2d_env import Walker2DEnv
from rllab.envs.mujoco.gather.point_gather_env import PointGatherEnv
from rllab.envs.mujoco.gather.swimmer_gather_env import SwimmerGatherEnv
from rllab.envs.mujoco.gather.ant_gather_env import AntGatherEnv
from rllab.envs.mujoco.maze.point_maze_env import PointMazeEnv
from rllab.envs.mujoco.maze.swimmer_maze_env import SwimmerMazeEnv
from rllab.envs.mujoco.maze.ant_maze_env import AntMazeEnv
except OSError:
print("Warning: Mujoco not installed. Skipping mujoco-related tests")
MUJOCO_ENABLED = False
from rllab.envs.noisy_env import NoisyObservationEnv, DelayedActionEnv
from rllab.envs.normalized_env import NormalizedEnv
from rllab.envs.proxy_env import ProxyEnv
from rllab.envs.gym_env import GymEnv
simple_env_classes = [
GridWorldEnv,
CartpoleEnv,
CarParkingEnv,
CartpoleSwingupEnv,
DoublePendulumEnv,
MountainCarEnv,
]
if MUJOCO_ENABLED:
simple_env_classes.extend([
PointEnv,
Walker2DEnv,
SwimmerEnv,
SimpleHumanoidEnv,
InvertedDoublePendulumEnv,
HopperEnv,
HalfCheetahEnv,
PointGatherEnv,
SwimmerGatherEnv,
AntGatherEnv,
PointMazeEnv,
SwimmerMazeEnv,
AntMazeEnv,
])
envs = [cls() for cls in simple_env_classes]
envs.append(
ProxyEnv(envs[0])
)
envs.append(
IdentificationEnv(CartpoleEnv, {})
)
envs.append(
NoisyObservationEnv(CartpoleEnv())
)
envs.append(
DelayedActionEnv(CartpoleEnv())
)
envs.append(
NormalizedEnv(CartpoleEnv())
)
envs.append(
GymEnv('CartPole-v0')
)
@tools.params(*envs)
def test_env(env):
print("Testing", env.__class__)
ob_space = env.observation_space
act_space = env.action_space
ob = env.reset()
assert ob_space.contains(ob)
a = act_space.sample()
assert act_space.contains(a)
res = env.step(a)
assert ob_space.contains(res.observation)
assert np.isscalar(res.reward)
if 'CIRCLECI' in os.environ:
print("Skipping rendering test")
else:
env.render()
env.terminate()
| 1,382 |
3,631 | <reponame>AnilKumarBejjanki/drools
/*
* Copyright 2017 Red Hat, Inc. and/or its affiliates.
*
* 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.kie.dmn.feel.runtime.functions.twovaluelogic;
import org.junit.Before;
import org.junit.Test;
import org.kie.dmn.feel.runtime.functions.FunctionTestUtil;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class CountFunctionTest {
private NNCountFunction countFunction;
@Before
public void setUp() {
countFunction = new NNCountFunction();
}
@Test
public void invokeParamListNull() {
FunctionTestUtil.assertResult(countFunction.invoke((List) null), BigDecimal.ZERO);
}
@Test
public void invokeParamListEmpty() {
FunctionTestUtil.assertResult(countFunction.invoke(Collections.emptyList()), BigDecimal.ZERO);
}
@Test
public void invokeParamListNonEmpty() {
FunctionTestUtil.assertResult(countFunction.invoke(Arrays.asList(1, 2, "test")), BigDecimal.valueOf(3));
}
@Test
public void invokeParamArrayNull() {
FunctionTestUtil.assertResult(countFunction.invoke((Object[]) null), BigDecimal.ZERO);
}
@Test
public void invokeParamArrayEmpty() {
FunctionTestUtil.assertResult(countFunction.invoke(new Object[]{}), BigDecimal.ZERO);
}
@Test
public void invokeParamArrayNonEmpty() {
FunctionTestUtil.assertResult(countFunction.invoke(new Object[]{1, 2, "test"}), BigDecimal.valueOf(3));
}
} | 700 |
343 | <filename>mayan/apps/duplicates/tests/mixins.py<gh_stars>100-1000
from ..tasks import task_duplicates_scan_all, task_duplicates_scan_for
class DuplicatedDocumentAPIViewTestMixin:
def _request_test_duplicated_document_list_api_view(self):
return self.get(viewname='rest_api:duplicateddocument-list')
def _request_test_document_duplicates_list_api_view(self):
return self.get(
viewname='rest_api:documentduplicate-list', kwargs={
'document_id': self.test_documents[0].pk
}
)
class DuplicatedDocumentTaskTestMixin:
def _execute_task_duplicates_scan_all(self):
task_duplicates_scan_all.apply_async().get()
def _execute_task_duplicates_scan_for(self):
task_duplicates_scan_for.apply_async(
kwargs={
'document_id': self.test_document.pk
}
).get()
class DuplicatedDocumentTestMixin:
def _upload_duplicate_document(self):
self._upload_test_document(label='duplicated document label')
class DuplicatedDocumentToolViewTestMixin:
def _request_duplicated_document_scan_view(self):
return self.post(viewname='duplicates:duplicated_document_scan')
class DuplicatedDocumentViewTestMixin:
def _request_test_document_duplicates_list_view(self):
return self.get(
viewname='duplicates:document_duplicates_list', kwargs={
'document_id': self.test_documents[0].pk
}
)
def _request_test_duplicated_document_list_view(self):
return self.get(viewname='duplicates:duplicated_document_list')
| 696 |
5,937 | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
//+----------------------------------------------------------------------------
//
//
// Abstract:
// Templatized class for delay loading a module
//
// Notes:
// Implementation is thread safe.
//
// Once loaded the module will not be unloaded until the class is
// destroyed.
//
//-----------------------------------------------------------------------------
#pragma once
//+----------------------------------------------------------------------------
//
// Class:
// CDelayLoadedModule
//
// Synopsis:
// Loads a module specified by template information, when requested by a
// caller, but does not unload module until respective instance of class
// is destroyed.
//
// Template type should be a struct with a static constant member named
// sc_szFileName which is a string of the module to load:
// struct SomeModuleInfo {
// static const TCHAR sc_szFileName[];
// };
// const TCHAR sc_szFileName[] = _T("foo");
//
// Optionally the template struct may contain a static method named
// CheckLoadAvailability which CDelayLoadedModule will call before
// attempting to actually load specified module. If caller allows
// multiple threads to attempt module load simultaneously, then
// CheckLoadAvailability must be prepared to also handle this call pattern
// and must return the same result for all calls. Example declaration:
// static HRESULT CheckLoadAvailability();
//
//-----------------------------------------------------------------------------
template<typename ModuleInfo>
class CDelayLoadedModule
{
public:
CDelayLoadedModule()
: m_hrLoad(WGXERR_NOTINITIALIZED),
m_hModule(NULL)
{
}
~CDelayLoadedModule()
{
if (m_hModule)
{
FreeLibrary(m_hModule);
}
}
HRESULT Load()
{
HRESULT hr = m_hrLoad;
if (hr == WGXERR_NOTINITIALIZED)
{
__if_exists (ModuleInfo::CheckLoadAvailability)
{
hr = ModuleInfo::CheckLoadAvailability();
}
// else
__if_not_exists (ModuleInfo::CheckLoadAvailability)
{
hr = S_OK;
}
if (SUCCEEDED(hr))
{
HMODULE hNew;
MIL_TW32_NOSLE(hNew = LoadLibrary(ModuleInfo::sc_szFileName));
if (SUCCEEDED(hr))
{
Assert(hNew != NULL);
HMODULE hCurrent = reinterpret_cast<HMODULE>(
InterlockedCompareExchangePointer(
(PVOID volatile *)&m_hModule,
hNew,
NULL));
// If m_hModule was already updated then release this
// unneeded load reference.
if (hCurrent != NULL)
{
// LoadLibrary should always return the same HMODULE
Assert(hCurrent == hNew);
FreeLibrary(hNew);
}
// At this point we need to be sure result is written
// before result status is set. We rely on
// InterlockecdCompareExchangePointer to have committed
// results by now.
}
else
{
// No need to update m_hModule when load fails. No one
// else should have udpated it to a non-zero value either.
Assert(m_hModule == NULL);
}
}
// Note for future users - the assert can be removed if
// CheckLoadAvailabity wants to delay loading until certain
// conditions, but in that case other logic depending on a
// deterministic result will need to be checked. For example
// threading module/protection may need to change and callers that
// use a single function pointer to intialially point to a "load"
// function routine will have to expect this case as well.
Assert(hr != WGXERR_NOTINITIALIZED);
// Save results
m_hrLoad = hr;
}
RRETURN(hr);
}
__out HMODULE Handle() const
{
Assert(SUCCEEDED(m_hrLoad));
return m_hModule;
}
FARPROC
GetProcAddress(
__in PCSTR pProcName
) const
{
Assert(SUCCEEDED(m_hrLoad));
return ::GetProcAddress(m_hModule, pProcName);
}
FARPROC
LoadProcAddress(
__in PCSTR pProcName
)
{
return SUCCEEDED(Load()) ? ::GetProcAddress(m_hModule, pProcName) : NULL;
}
private:
HRESULT volatile m_hrLoad;
HMODULE volatile m_hModule;
};
| 2,293 |
335 | <filename>A/Anal_adjective.json
{
"word": "Anal",
"definitions": [
"Relating to or situated near the anus.",
"(in Freudian theory) relating to or denoting a stage of infantile psychosexual development in which defecation is the major source of sensuous pleasure and the anus forms the centre of self-awareness.",
"Anal-retentive."
],
"parts-of-speech": "Adjective"
} | 143 |
601 | <reponame>Harshagracy/sp-dev-fx-webparts<filename>samples/react-side-panel/config/package-solution.json<gh_stars>100-1000
{
"solution": {
"name": "react-side-panel-client-side-solution",
"id": "e9f0eff5-4e0f-492d-a5c8-d16568d2bfc3",
"version": "1.0.0.0"
},
"paths": {
"zippedPackage": "solution/react-side-panel.sppkg"
}
}
| 169 |
535 | /*
* 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.
*/
#ifndef NET_INSTAWEB_REWRITER_PUBLIC_JS_INLINE_FILTER_H_
#define NET_INSTAWEB_REWRITER_PUBLIC_JS_INLINE_FILTER_H_
#include <cstddef>
#include "net/instaweb/rewriter/public/common_filter.h"
#include "net/instaweb/rewriter/public/resource.h"
#include "net/instaweb/rewriter/public/rewrite_driver.h"
#include "net/instaweb/rewriter/public/rewrite_options.h"
#include "net/instaweb/rewriter/public/script_tag_scanner.h"
#include "pagespeed/kernel/base/basictypes.h"
#include "pagespeed/kernel/base/string.h"
#include "pagespeed/kernel/base/string_util.h"
#include "pagespeed/kernel/html/html_element.h"
#include "pagespeed/kernel/html/html_filter.h"
#include "pagespeed/kernel/html/html_node.h"
#include "pagespeed/kernel/http/semantic_type.h"
namespace net_instaweb {
class Statistics;
class Variable;
// Inline small Javascript files.
class JsInlineFilter : public CommonFilter {
public:
static const char kNumJsInlined[];
explicit JsInlineFilter(RewriteDriver* driver);
~JsInlineFilter() override;
void StartDocumentImpl() override;
void EndDocument() override;
void StartElementImpl(HtmlElement* element) override;
void EndElementImpl(HtmlElement* element) override;
void Characters(HtmlCharactersNode* characters) override;
const char* Name() const override { return "InlineJs"; }
// Inlining javascript from unauthorized domains into HTML is considered
// safe because it does not cause any new content to be executed compared
// to the unoptimized page.
RewriteDriver::InlineAuthorizationPolicy AllowUnauthorizedDomain()
const override {
return driver()->options()->HasInlineUnauthorizedResourceType(
semantic_type::kScript)
? RewriteDriver::kInlineUnauthorizedResources
: RewriteDriver::kInlineOnlyAuthorizedResources;
}
bool IntendedForInlining() const override { return true; }
ScriptUsage GetScriptUsage() const override { return kWillInjectScripts; }
static void InitStats(Statistics* statistics);
private:
class Context;
friend class Context;
bool ShouldInline(const ResourcePtr& resource, GoogleString* reason) const;
void RenderInline(const ResourcePtr& resource, const StringPiece& text,
HtmlElement* element);
const size_t size_threshold_bytes_;
ScriptTagScanner script_tag_scanner_;
// This is set to true during StartElement() for a <script> tag that we
// should maybe inline, but may be set back to false by Characters(). If it
// is still true when we hit the corresponding EndElement(), then we'll
// inline the script (and set it back to false). It should never be true
// outside of <script> and </script>.
bool should_inline_;
Variable* num_js_inlined_;
DISALLOW_COPY_AND_ASSIGN(JsInlineFilter);
};
} // namespace net_instaweb
#endif // NET_INSTAWEB_REWRITER_PUBLIC_JS_INLINE_FILTER_H_
| 1,147 |
724 | # -*- coding=utf-8 -*-
# Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the MIT License.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# MIT License for more details.
"""Default configs."""
from .base import BaseConfig
from vega.common import ConfigSerializable
class SpatiotemporalConfig(BaseConfig):
"""Default Dataset config for SpatiotemporalConfig."""
n_his = 12
n_pred = 4
batch_size = 32
test_portion = 0.2
train_portion = 0.9
is_spatiotemporal = True
@classmethod
def rules(cls):
"""Return rules for checking."""
rules_Base = {"data_path": {"type": (str)},
"n_his": {"type": int},
"n_pred": {"type": bool},
"train_portion": {"type": float},
"is_spatiotemporal": {"type": bool},
}
return rules_Base
class SpatiotemporalDatasetConfig(ConfigSerializable):
"""Dummy dataset config."""
common = SpatiotemporalConfig
train = SpatiotemporalConfig
val = SpatiotemporalConfig
test = SpatiotemporalConfig
| 535 |
2,151 | <gh_stars>1000+
// Copyright 2019 The Dawn 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.
#include "tests/DawnTest.h"
#include "utils/ComboRenderPipelineDescriptor.h"
#include "utils/WGPUHelpers.h"
constexpr uint32_t kRTSize = 16;
constexpr wgpu::TextureFormat kFormat = wgpu::TextureFormat::RGBA8Unorm;
class RenderPassTest : public DawnTest {
protected:
void SetUp() override {
DawnTest::SetUp();
// Shaders to draw a bottom-left triangle in blue.
mVSModule = utils::CreateShaderModule(device, utils::SingleShaderStage::Vertex, R"(
#version 450
void main() {
const vec2 pos[3] = vec2[3](
vec2(-1.f, 1.f), vec2(1.f, -1.f), vec2(-1.f, -1.f));
gl_Position = vec4(pos[gl_VertexIndex], 0.f, 1.f);
})");
wgpu::ShaderModule fsModule =
utils::CreateShaderModule(device, utils::SingleShaderStage::Fragment, R"(
#version 450
layout(location = 0) out vec4 fragColor;
void main() {
fragColor = vec4(0.0, 0.0, 1.0, 1.0);
})");
utils::ComboRenderPipelineDescriptor descriptor(device);
descriptor.vertexStage.module = mVSModule;
descriptor.cFragmentStage.module = fsModule;
descriptor.primitiveTopology = wgpu::PrimitiveTopology::TriangleStrip;
descriptor.cColorStates[0].format = kFormat;
pipeline = device.CreateRenderPipeline(&descriptor);
}
wgpu::Texture CreateDefault2DTexture() {
wgpu::TextureDescriptor descriptor;
descriptor.dimension = wgpu::TextureDimension::e2D;
descriptor.size.width = kRTSize;
descriptor.size.height = kRTSize;
descriptor.size.depth = 1;
descriptor.sampleCount = 1;
descriptor.format = kFormat;
descriptor.mipLevelCount = 1;
descriptor.usage = wgpu::TextureUsage::OutputAttachment | wgpu::TextureUsage::CopySrc;
return device.CreateTexture(&descriptor);
}
wgpu::ShaderModule mVSModule;
wgpu::RenderPipeline pipeline;
};
// Test using two different render passes in one commandBuffer works correctly.
TEST_P(RenderPassTest, TwoRenderPassesInOneCommandBuffer) {
if (IsOpenGL() || IsMetal()) {
// crbug.com/950768
// This test is consistently failing on OpenGL and flaky on Metal.
return;
}
wgpu::Texture renderTarget1 = CreateDefault2DTexture();
wgpu::Texture renderTarget2 = CreateDefault2DTexture();
wgpu::CommandEncoder encoder = device.CreateCommandEncoder();
{
// In the first render pass we clear renderTarget1 to red and draw a blue triangle in the
// bottom left of renderTarget1.
utils::ComboRenderPassDescriptor renderPass({renderTarget1.CreateView()});
renderPass.cColorAttachments[0].clearColor = {1.0f, 0.0f, 0.0f, 1.0f};
wgpu::RenderPassEncoder pass = encoder.BeginRenderPass(&renderPass);
pass.SetPipeline(pipeline);
pass.Draw(3);
pass.EndPass();
}
{
// In the second render pass we clear renderTarget2 to green and draw a blue triangle in the
// bottom left of renderTarget2.
utils::ComboRenderPassDescriptor renderPass({renderTarget2.CreateView()});
renderPass.cColorAttachments[0].clearColor = {0.0f, 1.0f, 0.0f, 1.0f};
wgpu::RenderPassEncoder pass = encoder.BeginRenderPass(&renderPass);
pass.SetPipeline(pipeline);
pass.Draw(3);
pass.EndPass();
}
wgpu::CommandBuffer commands = encoder.Finish();
queue.Submit(1, &commands);
EXPECT_PIXEL_RGBA8_EQ(RGBA8::kBlue, renderTarget1, 1, kRTSize - 1);
EXPECT_PIXEL_RGBA8_EQ(RGBA8::kRed, renderTarget1, kRTSize - 1, 1);
EXPECT_PIXEL_RGBA8_EQ(RGBA8::kBlue, renderTarget2, 1, kRTSize - 1);
EXPECT_PIXEL_RGBA8_EQ(RGBA8::kGreen, renderTarget2, kRTSize - 1, 1);
}
// Verify that the content in the color attachment will not be changed if there is no corresponding
// fragment shader outputs in the render pipeline, the load operation is LoadOp::Load and the store
// operation is StoreOp::Store.
TEST_P(RenderPassTest, NoCorrespondingFragmentShaderOutputs) {
wgpu::Texture renderTarget = CreateDefault2DTexture();
wgpu::CommandEncoder encoder = device.CreateCommandEncoder();
wgpu::TextureView renderTargetView = renderTarget.CreateView();
utils::ComboRenderPassDescriptor renderPass({renderTargetView});
renderPass.cColorAttachments[0].clearColor = {1.0f, 0.0f, 0.0f, 1.0f};
renderPass.cColorAttachments[0].loadOp = wgpu::LoadOp::Clear;
renderPass.cColorAttachments[0].storeOp = wgpu::StoreOp::Store;
wgpu::RenderPassEncoder pass = encoder.BeginRenderPass(&renderPass);
{
// First we draw a blue triangle in the bottom left of renderTarget.
pass.SetPipeline(pipeline);
pass.Draw(3);
}
{
// Next we use a pipeline whose fragment shader has no outputs.
wgpu::ShaderModule fsModule =
utils::CreateShaderModule(device, utils::SingleShaderStage::Fragment, R"(
#version 450
void main() {
})");
utils::ComboRenderPipelineDescriptor descriptor(device);
descriptor.vertexStage.module = mVSModule;
descriptor.cFragmentStage.module = fsModule;
descriptor.primitiveTopology = wgpu::PrimitiveTopology::TriangleStrip;
descriptor.cColorStates[0].format = kFormat;
wgpu::RenderPipeline pipelineWithNoFragmentOutput =
device.CreateRenderPipeline(&descriptor);
pass.SetPipeline(pipelineWithNoFragmentOutput);
pass.Draw(3);
}
pass.EndPass();
wgpu::CommandBuffer commands = encoder.Finish();
queue.Submit(1, &commands);
EXPECT_PIXEL_RGBA8_EQ(RGBA8::kBlue, renderTarget, 2, kRTSize - 1);
EXPECT_PIXEL_RGBA8_EQ(RGBA8::kRed, renderTarget, kRTSize - 1, 1);
}
DAWN_INSTANTIATE_TEST(RenderPassTest,
D3D12Backend(),
D3D12Backend({}, {"use_d3d12_render_pass"}),
MetalBackend(),
OpenGLBackend(),
VulkanBackend());
| 2,770 |
2,208 | <reponame>sveilleux1/pybrain<gh_stars>1000+
#!/usr/bin/env python
#########################################################################
# Reinforcement Learning with PGPE on the Acrobot Environment
#
# The Acrobot Environment is a 1 DoF system.
# The goal is to swing up the pole and balance it.
# The motor is underpowered so that the pole can not go directly to the upright position.
# It has to swing several times to gain enough momentum.
#
# Control/Actions:
# The agent can control 1 joint.
#
# Requirements: pylab (for plotting only). If not available, comment the
# last 3 lines out
# Author: <NAME>, <EMAIL>
#########################################################################
__author__ = "<NAME>, <NAME>"
__version__ = '$Id$'
from pybrain.tools.example_tools import ExTools
from pybrain.rl.environments.ode import AcrobotEnvironment
from pybrain.rl.environments.ode.tasks import GradualRewardTask
from pybrain.structure.modules.tanhlayer import TanhLayer
from pybrain.tools.shortcuts import buildNetwork
from pybrain.rl.agents import OptimizationAgent
from pybrain.optimization import FiniteDifferences
from pybrain.rl.experiments import EpisodicExperiment
batch=2 #number of samples per learning step
prnts=1 #number of learning steps after results are printed
epis=4000/batch/prnts #number of roleouts
numbExp=10 #number of experiments
et = ExTools(batch, prnts) #tool for printing and plotting
for runs in range(numbExp):
# create environment
#Options: Bool(OpenGL), Bool(Realtime simu. while client is connected), ServerIP(default:localhost), Port(default:21560)
env = AcrobotEnvironment()
# create task
task = GradualRewardTask(env)
# create controller network
net = buildNetwork(len(task.getObservation()), env.actLen, outclass=TanhLayer)
# create agent with controller and learner (and its options)
agent = OptimizationAgent(net, FiniteDifferences(storeAllEvaluations = True))
et.agent = agent
# create the experiment
experiment = EpisodicExperiment(task, agent)
#Do the experiment
for updates in range(epis):
for i in range(prnts):
experiment.doEpisodes(batch)
et.printResults((agent.learner._allEvaluations)[-50:-1], runs, updates)
et.addExps()
et.showExps()
#To view what the simulation is doing at the moment, go to pybrain/rl/environments/ode/ and start viewer.py (python-openGL musst be installed, see PyBrain documentation)
| 743 |
1,144 | <reponame>yodaos-project/yodaos
/*
* Copyright (C) 2008 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.
*/
#ifndef ANDROID_UTILS_SYSTEMCLOCK_H
#define ANDROID_UTILS_SYSTEMCLOCK_H
#include <stdint.h>
#include <sys/types.h>
enum android_alarm_type {
/* return code bit numbers or set alarm arg */
ANDROID_ALARM_RTC_WAKEUP,
ANDROID_ALARM_RTC,
ANDROID_ALARM_ELAPSED_REALTIME_WAKEUP,
ANDROID_ALARM_ELAPSED_REALTIME,
ANDROID_ALARM_SYSTEMTIME,
ANDROID_ALARM_TYPE_COUNT,
/* return code bit numbers */
/* ANDROID_ALARM_TIME_CHANGE = 16 */
};
enum android_alarm_return_flags {
ANDROID_ALARM_RTC_WAKEUP_MASK = 1U << ANDROID_ALARM_RTC_WAKEUP,
ANDROID_ALARM_RTC_MASK = 1U << ANDROID_ALARM_RTC,
ANDROID_ALARM_ELAPSED_REALTIME_WAKEUP_MASK =
1U << ANDROID_ALARM_ELAPSED_REALTIME_WAKEUP,
ANDROID_ALARM_ELAPSED_REALTIME_MASK =
1U << ANDROID_ALARM_ELAPSED_REALTIME,
ANDROID_ALARM_SYSTEMTIME_MASK = 1U << ANDROID_ALARM_SYSTEMTIME,
ANDROID_ALARM_TIME_CHANGE_MASK = 1U << 16
};
/* Disable alarm */
#define ANDROID_ALARM_CLEAR(type) _IO('a', 0 | ((type) << 4))
/* Ack last alarm and wait for next */
#define ANDROID_ALARM_WAIT _IO('a', 1)
#define ALARM_IOW(c, type, size) _IOW('a', (c) | ((type) << 4), size)
/* Set alarm */
#define ANDROID_ALARM_SET(type) ALARM_IOW(2, type, struct timespec)
#define ANDROID_ALARM_SET_AND_WAIT(type) ALARM_IOW(3, type, struct timespec)
#define ANDROID_ALARM_GET_TIME(type) ALARM_IOW(4, type, struct timespec)
#define ANDROID_ALARM_SET_RTC _IOW('a', 5, struct timespec)
#define ANDROID_ALARM_BASE_CMD(cmd) (cmd & ~(_IOC(0, 0, 0xf0, 0)))
#define ANDROID_ALARM_IOCTL_TO_TYPE(cmd) (_IOC_NR(cmd) >> 4)
#define CLOCK_BOOTTIME 7
namespace android {
int64_t uptimeMillis();
int64_t elapsedRealtime();
int64_t elapsedRealtimeNano();
}; // namespace android
#endif // ANDROID_UTILS_SYSTEMCLOCK_H
| 1,051 |
510 | <reponame>cmars/cakeshop
package com.jpmorgan.cakeshop.test;
import static org.testng.Assert.*;
import com.jpmorgan.cakeshop.model.Node;
import com.jpmorgan.cakeshop.service.NodeService;
import java.io.IOException;
import org.springframework.beans.factory.annotation.Autowired;
import org.testng.annotations.Test;
public class NodeServiceTest extends BaseGethRpcTest {
@Autowired
private NodeService nodeService;
@Test
public void testGet() throws IOException {
Node node = nodeService.get();
assertNotNull(node);
assertEquals(node.getStatus(), "running");
}
}
| 202 |
685 | #include <Logging.h>
#include <APIC.h>
#include <CString.h>
#include <IDT.h>
#include <Panic.h>
#include <Serial.h>
#include <StackTrace.h>
extern "C" {
[[noreturn]] void KernelAssertionFailed(const char* msg, const char* file, int line) {
asm("cli");
APIC::Local::SendIPI(0, ICR_DSH_OTHER /* Send to all other processors except us */, ICR_MESSAGE_TYPE_FIXED,
IPI_HALT);
Log::Error("Kernel Assertion Failed (%s) - file: %s, line: %d", msg, file, line);
uint64_t rbp = 0;
asm("mov %%rbp, %0" : "=r"(rbp));
PrintStackTrace(rbp);
char buf[16];
itoa(line, buf, 10);
const char* panic[] = {"Kernel Assertion Failed", msg, "File: ", file, "Line:", buf};
KernelPanic(panic, 6);
asm("hlt");
}
} | 348 |
765 | /*
* Copyright 2018 Google, Inc.
*
* 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 holders 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 __SYSTEMC_CORE_EVENT_HH__
#define __SYSTEMC_CORE_EVENT_HH__
#include <list>
#include <string>
#include <vector>
#include "sim/eventq.hh"
#include "systemc/core/list.hh"
#include "systemc/core/object.hh"
#include "systemc/core/process.hh"
#include "systemc/core/sched_event.hh"
#include "systemc/core/sensitivity.hh"
#include "systemc/ext/core/sc_prim.hh"
#include "systemc/ext/core/sc_time.hh"
namespace sc_core
{
class sc_event;
} // namespace sc_core
namespace sc_gem5
{
typedef std::vector<sc_core::sc_event *> Events;
class Sensitivity;
class Event
{
public:
Event(sc_core::sc_event *_sc_event, bool internal=false);
Event(sc_core::sc_event *_sc_event, const char *_basename,
bool internal=false);
~Event();
sc_core::sc_event *sc_event() { return _sc_event; }
const std::string &name() const;
const std::string &basename() const;
bool inHierarchy() const;
sc_core::sc_object *getParentObject() const;
void notify(StaticSensitivities &senses);
void notify(DynamicSensitivities &senses);
void notify();
void notify(const sc_core::sc_time &t);
void
notify(double d, sc_core::sc_time_unit &u)
{
notify(sc_core::sc_time(d, u));
}
void notifyDelayed(const sc_core::sc_time &t);
void cancel();
bool triggered() const;
uint64_t triggeredStamp() const { return _triggeredStamp; }
static Event *
getFromScEvent(sc_core::sc_event *e)
{
return e->_gem5_event;
}
static const Event *
getFromScEvent(const sc_core::sc_event *e)
{
return e->_gem5_event;
}
void
addSensitivity(StaticSensitivity *s) const
{
// Insert static sensitivities in reverse order to match Accellera's
// implementation.
auto &senses = s->ofMethod() ? staticSenseMethod : staticSenseThread;
senses.insert(senses.begin(), s);
}
void
delSensitivity(StaticSensitivity *s) const
{
auto &senses = s->ofMethod() ? staticSenseMethod : staticSenseThread;
for (auto &t: senses) {
if (t == s) {
t = senses.back();
senses.pop_back();
break;
}
}
}
void
addSensitivity(DynamicSensitivity *s) const
{
auto &senses = s->ofMethod() ? dynamicSenseMethod : dynamicSenseThread;
senses.push_back(s);
}
void
delSensitivity(DynamicSensitivity *s) const
{
auto &senses = s->ofMethod() ? dynamicSenseMethod : dynamicSenseThread;
for (auto &t: senses) {
if (t == s) {
t = senses.back();
senses.pop_back();
break;
}
}
}
void clearParent();
private:
sc_core::sc_event *_sc_event;
std::string _basename;
std::string _name;
bool _inHierarchy;
sc_core::sc_object *parent;
ScEvent delayedNotify;
mutable uint64_t _triggeredStamp;
mutable StaticSensitivities staticSenseMethod;
mutable StaticSensitivities staticSenseThread;
mutable DynamicSensitivities dynamicSenseMethod;
mutable DynamicSensitivities dynamicSenseThread;
};
extern Events topLevelEvents;
extern Events allEvents;
EventsIt findEvent(const std::string &name);
} // namespace sc_gem5
#endif //__SYSTEMC_CORE_EVENT_HH__
| 1,834 |
2,151 | <reponame>terrajobst/linux-packaging-skiasharp
package com.google.typography.font.sfntly.table.opentype.chaincontextsubst;
import com.google.typography.font.sfntly.data.ReadableFontData;
import com.google.typography.font.sfntly.table.opentype.component.OffsetRecordTable;
public abstract class ChainSubGenericRuleSet<T extends ChainSubGenericRule>
extends OffsetRecordTable<T> {
protected ChainSubGenericRuleSet(ReadableFontData data, int base, boolean dataIsCanonical) {
super(data, base, dataIsCanonical);
}
@Override
public int fieldCount() {
return 0;
}
static abstract class Builder<
T extends ChainSubGenericRuleSet<S>, S extends ChainSubGenericRule>
extends OffsetRecordTable.Builder<T, S> {
protected Builder(ReadableFontData data, boolean dataIsCanonical) {
super(data, dataIsCanonical);
}
protected Builder() {
super();
}
protected Builder(T table) {
super(table);
}
@Override
protected void initFields() {
}
@Override
public int fieldCount() {
return 0;
}
}
}
| 388 |
348 | {"nom":"Marnay","circ":"1ère circonscription","dpt":"Haute-Saône","inscrits":1100,"abs":571,"votants":529,"blancs":50,"nuls":22,"exp":457,"res":[{"nuance":"REM","nom":"Mme <NAME>","voix":251},{"nuance":"FN","nom":"Mme <NAME>","voix":206}]} | 95 |
374 | import unittest
import numpy as np
try:
import Levenshtein
except ImportError:
Levenshtein = False
from dirty_cat import string_distances
def _random_string_pairs(n_pairs=50, seed=1):
rng = np.random.RandomState(seed)
characters = list(map(chr, range(10000)))
pairs = []
for n in range(n_pairs):
s1_len = rng.randint(50)
s2_len = rng.randint(50)
s1 = ''.join(rng.choice(characters, s1_len))
s2 = ''.join(rng.choice(characters, s2_len))
pairs.append((s1, s2))
return pairs
def _random_common_char_pairs(n_pairs=50, seed=1):
"""
Return string pairs with a common char at random positions, in order to
distinguish different thresholds for matching chararacters in Jaro
distance.
"""
# Make strings with random length and common char at index 0
rng = np.random.RandomState(seed=seed)
list1 = ['a' + 'b' * rng.randint(2, 20) for k in range(n_pairs)]
list2 = ['a' + 'c' * rng.randint(2, 20) for k in range(n_pairs)]
# Shuffle strings
list1 = [''.join(rng.choice(
list(s), size=len(s), replace=False)) for s in list1]
list2 = [''.join(rng.choice(
list(s), size=len(s), replace=False)) for s in list2]
pairs = zip(list1, list2)
return pairs
# TODO: some factorization of what is common for distances;
# check results for same examples on all distances
def _check_levenshtein_example_results(levenshtein_dist):
assert levenshtein_dist('', '') == 0
assert levenshtein_dist('', 'abc') == 3
assert levenshtein_dist('abc', '') == 3
assert levenshtein_dist('abc', 'abc') == 0
assert levenshtein_dist('abcd', 'abc') == 1
assert levenshtein_dist('abc', 'abcd') == 1
assert levenshtein_dist('xbcd', 'abcd') == 1
assert levenshtein_dist('axcd', 'abcd') == 1
assert levenshtein_dist('abxd', 'abcd') == 1
assert levenshtein_dist('abcx', 'abcd') == 1
assert levenshtein_dist('axcx', 'abcd') == 2
assert levenshtein_dist('axcx', 'abcde') == 3
def _check_symmetry(dist_func, *args, **kwargs):
for (a, b) in _random_string_pairs():
assert dist_func(
a, b, *args, **kwargs) == dist_func(b, a, *args, **kwargs)
def _check_levenshtein_distances():
for levenshtein_dist in [
string_distances.levenshtein_seq]:
_check_levenshtein_example_results(levenshtein_dist)
_check_symmetry(levenshtein_dist)
for (a, b) in _random_string_pairs():
assert string_distances.levenshtein_array(
a, b) == string_distances.levenshtein_seq(a, b)
assert string_distances.levenshtein_seq(
a, b) == string_distances.levenshtein(a, b)
if Levenshtein is not False:
assert string_distances.levenshtein_seq(
a, b) == Levenshtein.distance(a, b)
def test_levenshtein_ratio():
# TODO
# assert string_distances.levenshtein_ratio('', '') == 1
# assert string_distances.levenshtein_ratio('', 'abc') == 3
# assert string_distances.levenshtein_ratio('abc', '') == 3
# assert string_distances.levenshtein_ratio('abc', 'abc') == 0
# assert string_distances.levenshtein_ratio('abcd', 'abc') == 1
# assert string_distances.levenshtein_ratio('abc', 'abcd') == 1
# assert string_distances.levenshtein_ratio('xbcd', 'abcd') == 1
# assert string_distances.levenshtein_ratio('axcd', 'abcd') == 1
# assert string_distances.levenshtein_ratio('abxd', 'abcd') == 1
# assert string_distances.levenshtein_ratio('abcx', 'abcd') == 1
# assert string_distances.levenshtein_ratio('axcx', 'abcd') == 2
# assert string_distances.levenshtein_ratio('axcx', 'abcde') == 3
pass
# Tests for jaro
def test_jaro():
# If no character in common: similarity is 0
assert string_distances.jaro('Brian', 'Jesus') == 0
assert string_distances.jaro_winkler('Brian', 'Jesus') == 0
def test_identical_strings():
# Test that if 2 strings are the same, the similarity
for string1, _ in _random_string_pairs(n_pairs=10):
assert string_distances.jaro(string1, string1) == 1
assert string_distances.jaro_winkler(string1, string1) == 1
assert string_distances.levenshtein_ratio(string1, string1) == 1
def test_compare_implementations():
# Compare the implementations of python-Levenshtein to our
# pure-Python implementations
if Levenshtein is False:
raise unittest.SkipTest
# Test on strings with randomly placed common char
for string1, string2 in _random_common_char_pairs(n_pairs=50):
assert (string_distances._jaro_winkler(string1, string2,
winkler=False)
== Levenshtein.jaro(string1, string2)
)
assert (string_distances._jaro_winkler(string1, string2,
winkler=True)
== Levenshtein.jaro_winkler(string1, string2))
assert (string_distances.levenshtein_ratio(string1, string2)
== Levenshtein.ratio(string1, string2))
# Test on random strings
for string1, string2 in _random_string_pairs(n_pairs=50):
assert (string_distances._jaro_winkler(string1, string2,
winkler=False)
== Levenshtein.jaro(string1, string2))
assert (string_distances._jaro_winkler(string1, string2,
winkler=True)
== Levenshtein.jaro_winkler(string1, string2))
assert (string_distances.levenshtein_ratio(string1, string2)
== Levenshtein.ratio(string1, string2))
def test_ngram_similarity():
# TODO
# assert ...
for n in range(1, 4):
_check_symmetry(string_distances.ngram_similarity, n)
| 2,572 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.