max_stars_count
int64 301
224k
| text
stringlengths 6
1.05M
| token_count
int64 3
727k
|
---|---|---|
16,989 |
<reponame>jobechoi/bazel
// Copyright 2017 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.devtools.build.android.desugar.testdata.java8;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;
/** An interface with default methods, lambdas, and generics */
public interface GenericDefaultInterfaceWithLambda<T> {
T getBaseValue();
T increment(T value);
String toString(T value);
public default ArrayList<T> toList(int bound) {
ArrayList<T> result = new ArrayList<>();
if (bound == 0) {
return result;
}
result.add(getBaseValue());
for (int i = 1; i < bound; ++i) {
result.add(increment(result.get(i - 1)));
}
return result;
}
public default List<String> convertToStringList(List<T> list) {
return list.stream().map(this::toString).collect(Collectors.toList());
}
public default Function<Integer, ArrayList<T>> toListSupplier() {
return this::toList;
}
/** The type parameter is concretized to {@link Number} */
interface LevelOne<T extends Number> extends GenericDefaultInterfaceWithLambda<T> {}
/** The type parameter is instantiated to {@link Integer} */
interface LevelTwo extends LevelOne<Integer> {
@Override
default Integer getBaseValue() {
return 0;
}
}
/** An abstract class with no implementing methods. */
abstract static class ClassOne implements LevelTwo {}
/** A class for {@link Integer} */
class ClassTwo extends ClassOne {
@Override
public Integer increment(Integer value) {
return value + 1;
}
@Override
public String toString(Integer value) {
return value.toString();
}
}
/** A class fo {@link Long} */
class ClassThree implements LevelOne<Long> {
@Override
public Long getBaseValue() {
return Long.valueOf(0);
}
@Override
public Long increment(Long value) {
return value + 1;
}
@Override
public String toString(Long value) {
return value.toString();
}
}
}
| 840 |
32,544 |
<filename>core-java-modules/core-java-collections-maps-4/src/test/java/com/baeldung/maps/CoordinateKeyUnitTest.java
package com.baeldung.maps;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import java.awt.*;
import java.util.HashMap;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
public class CoordinateKeyUnitTest {
private Map<CoordinateKey, Color> pixels = new HashMap<>();
@Test
void testOptimalKey() {
// setup
CoordinateKey coord = new CoordinateKey(1, 2);
pixels.put(coord, Color.CYAN);
// read out color correctly
assertEquals(Color.CYAN, pixels.get(coord));
}
@Test
void testSlowKey() {
// setup
CoordinateKey coord = new CoordinateSlowKey(1, 2);
pixels.put(coord, Color.CYAN);
// read out color correctly
assertEquals(Color.CYAN, pixels.get(coord));
}
// Performance Test Parameters - change here
private static final int MAX_X = 100;
private static final int MAX_Y = 100;
private static final int COUNT_OF_QUERIES = 1000;
private static final int QUERY_X = 1;
private static final int QUERY_Y = 1;
@Tag("performance")
@Test
void testKeyPerformance() {
// generate some sample keys and values
for (int x = 0; x < MAX_X; x++) {
for (int y = 0; y < MAX_Y; y++) {
pixels.put(new CoordinateKey(x, y), new Color(x % 255, y % 255, (x + y) % 255));
}
}
// read out multiple times and measure time
CoordinateKey coord = new CoordinateKey(QUERY_X, QUERY_Y);
long t1 = System.currentTimeMillis();
for (int i = 0; i < COUNT_OF_QUERIES; i++) {
assertNotNull(pixels.get(coord));
}
long t2 = System.currentTimeMillis();
System.out.printf("Optimal key performance: %d ms%n", t2 - t1);
}
@Tag("performance")
@Test
void testSlowKeyPerformance() {
// generate some sample keys and values
for (int x = 0; x < MAX_X; x++) {
for (int y = 0; y < MAX_Y; y++) {
pixels.put(new CoordinateSlowKey(x, y), new Color(x % 255, y % 255, (x + y) % 255));
}
}
// read out multiple times and measure time
CoordinateKey coord = new CoordinateSlowKey(QUERY_X, QUERY_Y);
long t1 = System.currentTimeMillis();
for (int i = 0; i < COUNT_OF_QUERIES; i++) {
assertNotNull(pixels.get(coord));
}
long t2 = System.currentTimeMillis();
System.out.printf("Slow key performance: %d ms%n", t2 - t1);
}
}
| 1,180 |
533 |
<filename>saber/funcs/impl/x86/mkldnn_helper.cpp
#include "anakin_config.h"
#ifndef USE_SGX
#include "saber/funcs/impl/x86/mkldnn_helper.h"
namespace anakin{
namespace saber{
mkldnn_mem_format get_mkldnn_format(LayoutType layout){
switch (layout){
case Layout_NCHW:
return mkldnn_mem_format::nchw;
case Layout_NCHW_C8R:
return mkldnn_mem_format::nChw8c;
default :
return mkldnn_mem_format::nchw;
}
}
mkldnn_mem_format get_mkldnn_format(LayoutType in_layout, LayoutType out_layout){
if (in_layout == Layout_NCHW){
switch (out_layout){
case Layout_NCHW:
return mkldnn_mem_format::oihw;
case Layout_NCHW_C8R:
return mkldnn_mem_format::Oihw8o;
default:
return mkldnn_mem_format::format_undef;
}
}
if (in_layout == Layout_NCHW_C8R){
switch (out_layout){
case Layout_NCHW:
return mkldnn_mem_format::oIhw8i;
case Layout_NCHW_C8R:
return mkldnn_mem_format::OIhw8i8o;
default:
return mkldnn_mem_format::format_undef;
}
}
return mkldnn_mem_format::format_undef;
}
mkldnn_mem_dtype get_mkldnn_dtype(DataType dtype){
switch (dtype){
case AK_FLOAT:
return mkldnn_mem_dtype::f32;
case AK_INT8:
return mkldnn_mem_dtype::u8;
default:
return mkldnn_mem_dtype::f32;
}
}
desc<mkldnn_mem> create_mkldnn_memory_desc(
const std::vector<int>& dims,
mkldnn_mem_dtype dtype,
mkldnn_mem_format layout){
mkldnn_mem_dim tz = dims;
return desc<mkldnn_mem>({tz}, dtype, layout);
}
mkldnn_mem_ptr create_mkldnn_memory(Tensor<X86>* tensor, mkldnn::engine e){
mkldnn_mem_format mft = get_mkldnn_format(tensor -> get_layout());
mkldnn_mem_dtype dt = get_mkldnn_dtype(tensor -> get_dtype());
mkldnn_mem_dim dim = tensor -> shape();
return mkldnn_mem_ptr(new mkldnn_mem({ { {dim}, dt, mft}, e}, tensor->mutable_data()));
}
mkldnn_mem_ptr create_mkldnn_memory_no_data(const Tensor<X86>* tensor, mkldnn::engine e){
mkldnn_mem_format mft = get_mkldnn_format(tensor -> get_layout());
mkldnn_mem_dtype dt = get_mkldnn_dtype(tensor -> get_dtype());
mkldnn_mem_dim dim = tensor -> shape();
return mkldnn_mem_ptr(new mkldnn_mem({ { {dim}, dt, mft}, e}));
}
mkldnn_mem_ptr create_mkldnn_memory(Tensor<X86>* tensor, const std::vector<int>& sh, mkldnn::engine e){
mkldnn_mem_format mft = get_mkldnn_format(tensor -> get_layout());
mkldnn_mem_dtype dt = get_mkldnn_dtype(tensor -> get_dtype());
mkldnn_mem_dim dim = sh;
return mkldnn_mem_ptr(new mkldnn_mem({ { {dim}, dt, mft}, e}, tensor->mutable_data()));
}
mkldnn_mem_ptr create_mkldnn_memory(Tensor<X86>* tensor,const std::vector<int>& sh,
mkldnn_mem_format mft, mkldnn_mem_dtype dt, mkldnn::engine e){
mkldnn_mem_dim dim = sh;
return mkldnn_mem_ptr(new mkldnn_mem({ { {dim}, dt, mft}, e}, tensor->mutable_data()));
}
}
}
#endif
| 1,585 |
1,756 |
<filename>mailcore2/src/java/native/com_libmailcore_IMAPMessagePart.h
/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class com_libmailcore_IMAPMessagePart */
#ifndef _Included_com_libmailcore_IMAPMessagePart
#define _Included_com_libmailcore_IMAPMessagePart
#ifdef __cplusplus
extern "C" {
#endif
#undef com_libmailcore_IMAPMessagePart_serialVersionUID
#define com_libmailcore_IMAPMessagePart_serialVersionUID 1LL
#undef com_libmailcore_IMAPMessagePart_serialVersionUID
#define com_libmailcore_IMAPMessagePart_serialVersionUID 1LL
/*
* Class: com_libmailcore_IMAPMessagePart
* Method: setPartID
* Signature: (Ljava/lang/String;)V
*/
JNIEXPORT void JNICALL Java_com_libmailcore_IMAPMessagePart_setPartID
(JNIEnv *, jobject, jstring);
/*
* Class: com_libmailcore_IMAPMessagePart
* Method: partID
* Signature: ()Ljava/lang/String;
*/
JNIEXPORT jstring JNICALL Java_com_libmailcore_IMAPMessagePart_partID
(JNIEnv *, jobject);
#ifdef __cplusplus
}
#endif
#endif
| 379 |
410 |
package de.codewhite.jmet.exceptions;
/**
* Created by kaimatt.
*/
public class InitException extends Exception {
public InitException() {
super();
}
public InitException(String message) {
super(message);
}
public InitException(String message, Throwable cause) {
super(message, cause);
}
public InitException(Throwable cause) {
super(cause);
}
protected InitException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
}
| 213 |
721 |
package crazypants.enderio.base.item.darksteel.upgrade.anvil;
import java.util.List;
import javax.annotation.Nonnull;
import com.enderio.core.common.util.NNList;
import com.enderio.core.common.util.NullHelper;
import crazypants.enderio.api.upgrades.IDarkSteelUpgrade;
import crazypants.enderio.api.upgrades.IRule;
import crazypants.enderio.base.EnderIO;
import crazypants.enderio.base.config.config.DarkSteelConfig;
import crazypants.enderio.base.handler.darksteel.AbstractUpgrade;
import crazypants.enderio.base.handler.darksteel.Rules;
import crazypants.enderio.base.lang.Lang;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.EntityEquipmentSlot;
import net.minecraft.item.ItemStack;
import net.minecraftforge.event.RegistryEvent;
import net.minecraftforge.fml.common.Mod.EventBusSubscriber;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
@EventBusSubscriber(modid = EnderIO.MODID)
public class AnvilUpgrade extends AbstractUpgrade {
private static final @Nonnull String UPGRADE_NAME = "anvil";
public static final @Nonnull NNList<AnvilUpgrade> INSTANCES = new NNList<>(new AnvilUpgrade(0), new AnvilUpgrade(1), new AnvilUpgrade(2));
@SubscribeEvent
public static void registerDarkSteelUpgrades(@Nonnull RegistryEvent.Register<IDarkSteelUpgrade> event) {
INSTANCES.apply(instance -> {
event.getRegistry().register(instance);
});
}
public static AnvilUpgrade loadAnyFromItem(@Nonnull ItemStack stack) {
int level = INSTANCES.get(0).getUpgradeVariantLevel(stack);
return level < 0 ? null : INSTANCES.get(level);
}
public static AnvilUpgrade getHighestEquippedUpgrade(@Nonnull EntityPlayer player) {
int level = -1;
for (EntityEquipmentSlot slot : EntityEquipmentSlot.values()) {
level = Math.max(level, INSTANCES.get(0).getUpgradeVariantLevel(player.getItemStackFromSlot(NullHelper.notnullJ(slot, "Enum.values()"))));
}
return level < 0 ? null : INSTANCES.get(level);
}
public AnvilUpgrade(int level) {
super(UPGRADE_NAME, level, "enderio.darksteel.upgrade." + UPGRADE_NAME + "." + level, DarkSteelConfig.anvilUpgradeCost.get(level));
}
@Override
@Nonnull
public List<IRule> getRules() {
return new NNList<>(Rules.withLevels(variant, INSTANCES), Rules.itemTypeTooltip(Lang.DSU_CLASS_EVERYTHING),
Rules.staticCheck(item -> !(item instanceof INoAnvilUpgrade)));
}
public boolean allowsEditingOtherEquippedItems() {
return variant >= 1;
}
public boolean allowsEditingSlotItems() {
return variant >= 2;
}
public boolean allowsAnvilRecipes() {
return variant >= 2;
}
public interface INoAnvilUpgrade {
}
}
| 895 |
1,006 |
/****************************************************************************
* net/devif/devif_iobsend.c
*
* 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.
*
****************************************************************************/
/****************************************************************************
* Included Files
****************************************************************************/
#include <nuttx/config.h>
#include <string.h>
#include <assert.h>
#include <debug.h>
#include <nuttx/mm/iob.h>
#include <nuttx/net/netdev.h>
#ifdef CONFIG_MM_IOB
/****************************************************************************
* Public Functions
****************************************************************************/
/****************************************************************************
* Name: devif_iob_send
*
* Description:
* Called from socket logic in response to a xmit or poll request from the
* the network interface driver.
*
* This is identical to calling devif_send() except that the data is
* in an I/O buffer chain, rather than a flat buffer.
*
* Assumptions:
* Called with the network locked.
*
****************************************************************************/
void devif_iob_send(FAR struct net_driver_s *dev, FAR struct iob_s *iob,
unsigned int len, unsigned int offset)
{
DEBUGASSERT(dev && len > 0 && len < NETDEV_PKTSIZE(dev));
/* Copy the data from the I/O buffer chain to the device buffer */
iob_copyout(dev->d_appdata, iob, len, offset);
dev->d_sndlen = len;
#ifdef CONFIG_NET_TCP_WRBUFFER_DUMP
/* Dump the outgoing device buffer */
lib_dumpbuffer("devif_iob_send", dev->d_appdata, len);
#endif
}
#endif /* CONFIG_MM_IOB */
| 645 |
2,921 |
<gh_stars>1000+
{
"name": "BankSocial",
"website": "https://www.banksocial.io",
"description": "BankSocial is your gateway to a full range of banking services using blockchain technology available globally.",
"explorer": "https://etherscan.io/token/0x0AF55d5fF28A3269d69B98680Fd034f115dd53Ac",
"type": "ERC20",
"symbol": "BSL",
"decimals": 8,
"status": "active",
"id": "0x0AF55d5fF28A3269d69B98680Fd034f115dd53Ac",
"links": [
{
"name": "twitter",
"url": "https://twitter.com/banksocialio"
},
{
"name": "coinmarketcap",
"url": "https://coinmarketcap.com/currencies/banksocial/"
}
]
}
| 333 |
351 |
import numpy as np
from ..pakbase import Package
from ..utils import Util2d, Util3d
class ModflowBct(Package):
"""
Block centered transport package class for MODFLOW-USG
"""
def __init__(
self,
model,
itrnsp=1,
ibctcb=0,
mcomp=1,
ic_ibound_flg=1,
itvd=1,
iadsorb=0,
ict=0,
cinact=-999.0,
ciclose=1.0e-6,
idisp=1,
ixdisp=0,
diffnc=0.0,
izod=0,
ifod=0,
icbund=1,
porosity=0.1,
bulkd=1.0,
arad=0.0,
dlh=0.0,
dlv=0.0,
dth=0.0,
dtv=0.0,
sconc=0.0,
extension="bct",
unitnumber=None,
):
# set default unit number of one is not specified
if unitnumber is None:
unitnumber = ModflowBct._defaultunit()
# call base package constructor
super().__init__(model, extension, self._ftype(), unitnumber)
self.url = "bct.htm"
nrow, ncol, nlay, nper = self.parent.nrow_ncol_nlay_nper
self.itrnsp = itrnsp
self.ibctcb = ibctcb
self.mcomp = mcomp
self.ic_ibound_flg = ic_ibound_flg
self.itvd = itvd
self.iadsorb = iadsorb
self.ict = ict
self.cinact = cinact
self.ciclose = ciclose
self.idisp = idisp
self.ixdisp = ixdisp
self.diffnc = diffnc
self.izod = izod
self.ifod = ifod
self.icbund = Util3d(
model,
(nlay, nrow, ncol),
np.float32,
icbund,
"icbund",
)
self.porosity = Util3d(
model, (nlay, nrow, ncol), np.float32, porosity, "porosity"
)
# self.arad = Util2d(model, (1, nja), np.float32,
# arad, 'arad')
self.dlh = Util3d(model, (nlay, nrow, ncol), np.float32, dlh, "dlh")
self.dlv = Util3d(model, (nlay, nrow, ncol), np.float32, dlv, "dlv")
self.dth = Util3d(model, (nlay, nrow, ncol), np.float32, dth, "dth")
self.dtv = Util3d(model, (nlay, nrow, ncol), np.float32, dth, "dtv")
self.sconc = Util3d(
model,
(nlay, nrow, ncol),
np.float32,
sconc,
"sconc",
)
self.parent.add_package(self)
return
def write_file(self):
"""
Write the package file.
Returns
-------
None
"""
nrow, ncol, nlay, nper = self.parent.nrow_ncol_nlay_nper
# Open file for writing
f_bct = open(self.fn_path, "w")
# Item 1: ITRNSP, IBCTCB, MCOMP, IC_IBOUND_FLG, ITVD, IADSORB,
# ICT, CINACT, CICLOSE, IDISP, IXDISP, DIFFNC, IZOD, IFOD
s = "{0} {1} {2} {3} {4} {5} {6} {7} {8} {9} {10} {11} {12} {13}"
s = s.format(
self.itrnsp,
self.ibctcb,
self.mcomp,
self.ic_ibound_flg,
self.itvd,
self.iadsorb,
self.ict,
self.cinact,
self.ciclose,
self.idisp,
self.ixdisp,
self.diffnc,
self.izod,
self.ifod,
)
f_bct.write(s + "\n")
#
# ibound
if self.ic_ibound_flg == 0:
for k in range(nlay):
f_bct.write(self.icbund[k].get_file_entry())
#
# porosity
for k in range(nlay):
f_bct.write(self.porosity[k].get_file_entry())
#
# bulkd
if self.iadsorb != 0:
for k in range(nlay):
f_bct.write(self.bulkd[k].get_file_entry())
#
# arad
if self.idisp != 0:
f_bct.write("open/close arad.dat 1.0 (free) -1\n")
#
# dlh
if self.idisp == 1:
for k in range(nlay):
f_bct.write(self.dlh[k].get_file_entry())
#
# dlv
if self.idisp == 2:
for k in range(nlay):
f_bct.write(self.dlv[k].get_file_entry())
#
# dth
if self.idisp == 1:
for k in range(nlay):
f_bct.write(self.dth[k].get_file_entry())
#
# dtv
if self.idisp == 2:
for k in range(nlay):
f_bct.write(self.dtv[k].get_file_entry())
#
# sconc
for k in range(nlay):
f_bct.write(self.sconc[k].get_file_entry())
return
@staticmethod
def _ftype():
return "BCT"
@staticmethod
def _defaultunit():
return 35
| 2,812 |
634 |
<gh_stars>100-1000
/*
* Copyright 2000-2013 JetBrains s.r.o.
*
* 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.intellij.openapi.components;
import com.intellij.util.ReflectionUtil;
import com.intellij.util.xmlb.XmlSerializer;
import org.jdom.Element;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.lang.reflect.TypeVariable;
/**
* @author nik
*/
public class ComponentSerializationUtil {
@SuppressWarnings("unchecked")
public static <T> Class<T> getStateClass(final Class<? extends PersistentStateComponent> aClass) {
TypeVariable<Class<PersistentStateComponent>> variable = PersistentStateComponent.class.getTypeParameters()[0];
return (Class<T>)ReflectionUtil.getRawType(ReflectionUtil.resolveVariableInHierarchy(variable, aClass));
}
public static <S> void loadComponentState(@Nonnull PersistentStateComponent<S> configuration, @Nullable Element element) {
if (element != null) {
Class<S> stateClass = getStateClass(configuration.getClass());
configuration.loadState(XmlSerializer.deserialize(element, stateClass));
}
}
}
| 489 |
312 |
/*******************************************************************************
* Copyright (c) 2020 Eclipse RDF4J contributors.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Distribution License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*******************************************************************************/
package org.eclipse.rdf4j.rio.hdt;
import java.util.zip.Checksum;
/**
* CRC16-ANSI checksum
*
* @author <NAME>
*/
class CRC16 implements Checksum {
// note that Java considers short to be signed, hence the need to cast values larger than 32767
private final static short[] TABLE = new short[] {
(short) 0x0000, (short) 0xC0C1, (short) 0xC181, (short) 0x0140, (short) 0xC301, (short) 0x03C0,
(short) 0x0280, (short) 0xC241,
(short) 0xC601, (short) 0x06C0, (short) 0x0780, (short) 0xC741, (short) 0x0500, (short) 0xC5C1,
(short) 0xC481, (short) 0x0440,
(short) 0xCC01, (short) 0x0CC0, (short) 0x0D80, (short) 0xCD41, (short) 0x0F00, (short) 0xCFC1,
(short) 0xCE81, (short) 0x0E40,
(short) 0x0A00, (short) 0xCAC1, (short) 0xCB81, (short) 0x0B40, (short) 0xC901, (short) 0x09C0,
(short) 0x0880, (short) 0xC841,
(short) 0xD801, (short) 0x18C0, (short) 0x1980, (short) 0xD941, (short) 0x1B00, (short) 0xDBC1,
(short) 0xDA81, (short) 0x1A40,
(short) 0x1E00, (short) 0xDEC1, (short) 0xDF81, (short) 0x1F40, (short) 0xDD01, (short) 0x1DC0,
(short) 0x1C80, (short) 0xDC41,
(short) 0x1400, (short) 0xD4C1, (short) 0xD581, (short) 0x1540, (short) 0xD701, (short) 0x17C0,
(short) 0x1680, (short) 0xD641,
(short) 0xD201, (short) 0x12C0, (short) 0x1380, (short) 0xD341, (short) 0x1100, (short) 0xD1C1,
(short) 0xD081, (short) 0x1040,
(short) 0xF001, (short) 0x30C0, (short) 0x3180, (short) 0xF141, (short) 0x3300, (short) 0xF3C1,
(short) 0xF281, (short) 0x3240,
(short) 0x3600, (short) 0xF6C1, (short) 0xF781, (short) 0x3740, (short) 0xF501, (short) 0x35C0,
(short) 0x3480, (short) 0xF441,
(short) 0x3C00, (short) 0xFCC1, (short) 0xFD81, (short) 0x3D40, (short) 0xFF01, (short) 0x3FC0,
(short) 0x3E80, (short) 0xFE41,
(short) 0xFA01, (short) 0x3AC0, (short) 0x3B80, (short) 0xFB41, (short) 0x3900, (short) 0xF9C1,
(short) 0xF881, (short) 0x3840,
(short) 0x2800, (short) 0xE8C1, (short) 0xE981, (short) 0x2940, (short) 0xEB01, (short) 0x2BC0,
(short) 0x2A80, (short) 0xEA41,
(short) 0xEE01, (short) 0x2EC0, (short) 0x2F80, (short) 0xEF41, (short) 0x2D00, (short) 0xEDC1,
(short) 0xEC81, (short) 0x2C40,
(short) 0xE401, (short) 0x24C0, (short) 0x2580, (short) 0xE541, (short) 0x2700, (short) 0xE7C1,
(short) 0xE681, (short) 0x2640,
(short) 0x2200, (short) 0xE2C1, (short) 0xE381, (short) 0x2340, (short) 0xE101, (short) 0x21C0,
(short) 0x2080, (short) 0xE041,
(short) 0xA001, (short) 0x60C0, (short) 0x6180, (short) 0xA141, (short) 0x6300, (short) 0xA3C1,
(short) 0xA281, (short) 0x6240,
(short) 0x6600, (short) 0xA6C1, (short) 0xA781, (short) 0x6740, (short) 0xA501, (short) 0x65C0,
(short) 0x6480, (short) 0xA441,
(short) 0x6C00, (short) 0xACC1, (short) 0xAD81, (short) 0x6D40, (short) 0xAF01, (short) 0x6FC0,
(short) 0x6E80, (short) 0xAE41,
(short) 0xAA01, (short) 0x6AC0, (short) 0x6B80, (short) 0xAB41, (short) 0x6900, (short) 0xA9C1,
(short) 0xA881, (short) 0x6840,
(short) 0x7800, (short) 0xB8C1, (short) 0xB981, (short) 0x7940, (short) 0xBB01, (short) 0x7BC0,
(short) 0x7A80, (short) 0xBA41,
(short) 0xBE01, (short) 0x7EC0, (short) 0x7F80, (short) 0xBF41, (short) 0x7D00, (short) 0xBDC1,
(short) 0xBC81, (short) 0x7C40,
(short) 0xB401, (short) 0x74C0, (short) 0x7580, (short) 0xB541, (short) 0x7700, (short) 0xB7C1,
(short) 0xB681, (short) 0x7640,
(short) 0x7200, (short) 0xB2C1, (short) 0xB381, (short) 0x7340, (short) 0xB101, (short) 0x71C0,
(short) 0x7080, (short) 0xB041,
(short) 0x5000, (short) 0x90C1, (short) 0x9181, (short) 0x5140, (short) 0x9301, (short) 0x53C0,
(short) 0x5280, (short) 0x9241,
(short) 0x9601, (short) 0x56C0, (short) 0x5780, (short) 0x9741, (short) 0x5500, (short) 0x95C1,
(short) 0x9481, (short) 0x5440,
(short) 0x9C01, (short) 0x5CC0, (short) 0x5D80, (short) 0x9D41, (short) 0x5F00, (short) 0x9FC1,
(short) 0x9E81, (short) 0x5E40,
(short) 0x5A00, (short) 0x9AC1, (short) 0x9B81, (short) 0x5B40, (short) 0x9901, (short) 0x59C0,
(short) 0x5880, (short) 0x9841,
(short) 0x8801, (short) 0x48C0, (short) 0x4980, (short) 0x8941, (short) 0x4B00, (short) 0x8BC1,
(short) 0x8A81, (short) 0x4A40,
(short) 0x4E00, (short) 0x8EC1, (short) 0x8F81, (short) 0x4F40, (short) 0x8D01, (short) 0x4DC0,
(short) 0x4C80, (short) 0x8C41,
(short) 0x4400, (short) 0x84C1, (short) 0x8581, (short) 0x4540, (short) 0x8701, (short) 0x47C0,
(short) 0x4680, (short) 0x8641,
(short) 0x8201, (short) 0x42C0, (short) 0x4380, (short) 0x8341, (short) 0x4100, (short) 0x81C1,
(short) 0x8081, (short) 0x4040
};
private long value = 0;
@Override
public void update(int b) {
int j = (int) (value ^ b) & 0xFF;
value = ((value >>> 8) ^ TABLE[j]) & 0xFFFF;
}
@Override
public void update(byte[] b, int off, int len) {
while (len-- > 0) {
int j = (int) (value ^ b[off++]) & 0xFF;
value = (TABLE[j] ^ value >>> 8) & 0xFFFF;
}
}
@Override
public long getValue() {
return value & 0xFFFF;
}
@Override
public void reset() {
value = 0;
}
}
| 2,814 |
3,655 |
<filename>paddlex/paddleseg/models/backbones/resnet_vd.py<gh_stars>1000+
# copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve.
#
# 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.
import paddle
import paddle.nn as nn
import paddle.nn.functional as F
from paddlex.paddleseg.cvlibs import manager
from paddlex.paddleseg.models import layers
from paddlex.paddleseg.utils import utils
__all__ = [
"ResNet18_vd", "ResNet34_vd", "ResNet50_vd", "ResNet101_vd", "ResNet152_vd"
]
class ConvBNLayer(nn.Layer):
def __init__(
self,
in_channels,
out_channels,
kernel_size,
stride=1,
dilation=1,
groups=1,
is_vd_mode=False,
act=None, ):
super(ConvBNLayer, self).__init__()
self.is_vd_mode = is_vd_mode
self._pool2d_avg = nn.AvgPool2D(
kernel_size=2, stride=2, padding=0, ceil_mode=True)
self._conv = nn.Conv2D(
in_channels=in_channels,
out_channels=out_channels,
kernel_size=kernel_size,
stride=stride,
padding=(kernel_size - 1) // 2 if dilation == 1 else 0,
dilation=dilation,
groups=groups,
bias_attr=False)
self._batch_norm = layers.SyncBatchNorm(out_channels)
self._act_op = layers.Activation(act=act)
def forward(self, inputs):
if self.is_vd_mode:
inputs = self._pool2d_avg(inputs)
y = self._conv(inputs)
y = self._batch_norm(y)
y = self._act_op(y)
return y
class BottleneckBlock(nn.Layer):
def __init__(self,
in_channels,
out_channels,
stride,
shortcut=True,
if_first=False,
dilation=1):
super(BottleneckBlock, self).__init__()
self.conv0 = ConvBNLayer(
in_channels=in_channels,
out_channels=out_channels,
kernel_size=1,
act='relu')
self.dilation = dilation
self.conv1 = ConvBNLayer(
in_channels=out_channels,
out_channels=out_channels,
kernel_size=3,
stride=stride,
act='relu',
dilation=dilation)
self.conv2 = ConvBNLayer(
in_channels=out_channels,
out_channels=out_channels * 4,
kernel_size=1,
act=None)
if not shortcut:
self.short = ConvBNLayer(
in_channels=in_channels,
out_channels=out_channels * 4,
kernel_size=1,
stride=1,
is_vd_mode=False if if_first or stride == 1 else True)
self.shortcut = shortcut
def forward(self, inputs):
y = self.conv0(inputs)
####################################################################
# If given dilation rate > 1, using corresponding padding.
# The performance drops down without the follow padding.
if self.dilation > 1:
padding = self.dilation
y = F.pad(y, [padding, padding, padding, padding])
#####################################################################
conv1 = self.conv1(y)
conv2 = self.conv2(conv1)
if self.shortcut:
short = inputs
else:
short = self.short(inputs)
y = paddle.add(x=short, y=conv2)
y = F.relu(y)
return y
class BasicBlock(nn.Layer):
def __init__(self,
in_channels,
out_channels,
stride,
shortcut=True,
if_first=False):
super(BasicBlock, self).__init__()
self.stride = stride
self.conv0 = ConvBNLayer(
in_channels=in_channels,
out_channels=out_channels,
kernel_size=3,
stride=stride,
act='relu')
self.conv1 = ConvBNLayer(
in_channels=out_channels,
out_channels=out_channels,
kernel_size=3,
act=None)
if not shortcut:
self.short = ConvBNLayer(
in_channels=in_channels,
out_channels=out_channels,
kernel_size=1,
stride=1,
is_vd_mode=False if if_first else True)
self.shortcut = shortcut
def forward(self, inputs):
y = self.conv0(inputs)
conv1 = self.conv1(y)
if self.shortcut:
short = inputs
else:
short = self.short(inputs)
y = paddle.add(x=short, y=conv1)
y = F.relu(y)
return y
class ResNet_vd(nn.Layer):
"""
The ResNet_vd implementation based on PaddlePaddle.
The original article refers to <NAME>, et, al. "Bag of Tricks for Image Classification with Convolutional Neural Networks"
(https://arxiv.org/pdf/1812.01187.pdf).
Args:
layers (int, optional): The layers of ResNet_vd. The supported layers are (18, 34, 50, 101, 152, 200). Default: 50.
output_stride (int, optional): The stride of output features compared to input images. It is 8 or 16. Default: 8.
multi_grid (tuple|list, optional): The grid of stage4. Defult: (1, 1, 1).
pretrained (str, optional): The path of pretrained model.
"""
def __init__(self,
layers=50,
output_stride=8,
multi_grid=(1, 1, 1),
pretrained=None):
super(ResNet_vd, self).__init__()
self.conv1_logit = None # for gscnn shape stream
self.layers = layers
supported_layers = [18, 34, 50, 101, 152, 200]
assert layers in supported_layers, \
"supported layers are {} but input layer is {}".format(
supported_layers, layers)
if layers == 18:
depth = [2, 2, 2, 2]
elif layers == 34 or layers == 50:
depth = [3, 4, 6, 3]
elif layers == 101:
depth = [3, 4, 23, 3]
elif layers == 152:
depth = [3, 8, 36, 3]
elif layers == 200:
depth = [3, 12, 48, 3]
num_channels = [64, 256, 512,
1024] if layers >= 50 else [64, 64, 128, 256]
num_filters = [64, 128, 256, 512]
# for channels of four returned stages
self.feat_channels = [c * 4 for c in
num_filters] if layers >= 50 else num_filters
dilation_dict = None
if output_stride == 8:
dilation_dict = {2: 2, 3: 4}
elif output_stride == 16:
dilation_dict = {3: 2}
self.conv1_1 = ConvBNLayer(
in_channels=3,
out_channels=32,
kernel_size=3,
stride=2,
act='relu')
self.conv1_2 = ConvBNLayer(
in_channels=32,
out_channels=32,
kernel_size=3,
stride=1,
act='relu')
self.conv1_3 = ConvBNLayer(
in_channels=32,
out_channels=64,
kernel_size=3,
stride=1,
act='relu')
self.pool2d_max = nn.MaxPool2D(kernel_size=3, stride=2, padding=1)
# self.block_list = []
self.stage_list = []
if layers >= 50:
for block in range(len(depth)):
shortcut = False
block_list = []
for i in range(depth[block]):
if layers in [101, 152] and block == 2:
if i == 0:
conv_name = "res" + str(block + 2) + "a"
else:
conv_name = "res" + str(block + 2) + "b" + str(i)
else:
conv_name = "res" + str(block + 2) + chr(97 + i)
###############################################################################
# Add dilation rate for some segmentation tasks, if dilation_dict is not None.
dilation_rate = dilation_dict[
block] if dilation_dict and block in dilation_dict else 1
# Actually block here is 'stage', and i is 'block' in 'stage'
# At the stage 4, expand the the dilation_rate if given multi_grid
if block == 3:
dilation_rate = dilation_rate * multi_grid[i]
###############################################################################
bottleneck_block = self.add_sublayer(
'bb_%d_%d' % (block, i),
BottleneckBlock(
in_channels=num_channels[block]
if i == 0 else num_filters[block] * 4,
out_channels=num_filters[block],
stride=2 if i == 0 and block != 0 and
dilation_rate == 1 else 1,
shortcut=shortcut,
if_first=block == i == 0,
dilation=dilation_rate))
block_list.append(bottleneck_block)
shortcut = True
self.stage_list.append(block_list)
else:
for block in range(len(depth)):
shortcut = False
block_list = []
for i in range(depth[block]):
conv_name = "res" + str(block + 2) + chr(97 + i)
basic_block = self.add_sublayer(
'bb_%d_%d' % (block, i),
BasicBlock(
in_channels=num_channels[block]
if i == 0 else num_filters[block],
out_channels=num_filters[block],
stride=2 if i == 0 and block != 0 else 1,
shortcut=shortcut,
if_first=block == i == 0))
block_list.append(basic_block)
shortcut = True
self.stage_list.append(block_list)
self.pretrained = pretrained
self.init_weight()
def forward(self, inputs):
y = self.conv1_1(inputs)
y = self.conv1_2(y)
y = self.conv1_3(y)
self.conv1_logit = y.clone()
y = self.pool2d_max(y)
# A feature list saves the output feature map of each stage.
feat_list = []
for stage in self.stage_list:
for block in stage:
y = block(y)
feat_list.append(y)
return feat_list
def init_weight(self):
utils.load_pretrained_model(self, self.pretrained)
@manager.BACKBONES.add_component
def ResNet18_vd(**args):
model = ResNet_vd(layers=18, **args)
return model
def ResNet34_vd(**args):
model = ResNet_vd(layers=34, **args)
return model
@manager.BACKBONES.add_component
def ResNet50_vd(**args):
model = ResNet_vd(layers=50, **args)
return model
@manager.BACKBONES.add_component
def ResNet101_vd(**args):
model = ResNet_vd(layers=101, **args)
return model
def ResNet152_vd(**args):
model = ResNet_vd(layers=152, **args)
return model
def ResNet200_vd(**args):
model = ResNet_vd(layers=200, **args)
return model
| 6,183 |
604 |
# Copyright 2011 Google 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.
#
"""Cisco IOS-XR filter renderer."""
from capirca.lib import cisco
class CiscoXR(cisco.Cisco):
"""A cisco policy object."""
_PLATFORM = 'ciscoxr'
_DEFAULT_PROTOCOL = 'ip'
SUFFIX = '.xacl'
_PROTO_INT = False
def _AppendTargetByFilterType(self, filter_name, filter_type):
"""Takes in the filter name and type and appends headers.
Args:
filter_name: Name of the current filter
filter_type: Type of current filter
Returns:
list of strings
"""
target = []
if filter_type == 'inet6':
target.append('no ipv6 access-list %s' % filter_name)
target.append('ipv6 access-list %s' % filter_name)
else:
target.append('no ipv4 access-list %s' % filter_name)
target.append('ipv4 access-list %s' % filter_name)
return target
def _BuildTokens(self):
"""Build supported tokens for platform.
Returns:
tuple containing both supported tokens and sub tokens
"""
supported_tokens, supported_sub_tokens = super()._BuildTokens()
supported_tokens |= {'next_ip'}
return supported_tokens, supported_sub_tokens
def _GetObjectGroupTerm(self, term, filter_name, verbose=True):
"""Returns an ObjectGroupTerm object."""
return CiscoXRObjectGroupTerm(term, filter_name,
platform=self._PLATFORM, verbose=verbose)
class CiscoXRObjectGroupTerm(cisco.ObjectGroupTerm):
ALLOWED_PROTO_STRINGS = cisco.Term.ALLOWED_PROTO_STRINGS + ['pcp', 'esp']
| 732 |
2,297 |
<gh_stars>1000+
// Created by <NAME> on 26/02/2017.
// Copyright wuxudong
//
#ifndef RNBarLineChartManagerBridge_h
#define RNBarLineChartManagerBridge_h
#define EXPORT_BAR_LINE_CHART_BASE_PROPERTIES \
EXPORT_Y_AXIS_CHART_BASE_PROPERTIES \
RCT_EXPORT_VIEW_PROPERTY(drawGridBackground, BOOL) \
RCT_EXPORT_VIEW_PROPERTY(maxHighlightDistance, CGFloat) \
RCT_EXPORT_VIEW_PROPERTY(gridBackgroundColor, NSInteger) \
RCT_EXPORT_VIEW_PROPERTY(drawBorders, BOOL) \
RCT_EXPORT_VIEW_PROPERTY(borderColor, NSInteger) \
RCT_EXPORT_VIEW_PROPERTY(borderWidth, CGFloat) \
RCT_EXPORT_VIEW_PROPERTY(maxVisibleValueCount, NSInteger) \
RCT_EXPORT_VIEW_PROPERTY(visibleRange, NSDictionary) \
RCT_EXPORT_VIEW_PROPERTY(autoScaleMinMaxEnabled, BOOL) \
RCT_EXPORT_VIEW_PROPERTY(keepPositionOnRotation, BOOL) \
RCT_EXPORT_VIEW_PROPERTY(scaleEnabled, BOOL) \
RCT_EXPORT_VIEW_PROPERTY(dragEnabled, BOOL) \
RCT_EXPORT_VIEW_PROPERTY(scaleXEnabled, BOOL) \
RCT_EXPORT_VIEW_PROPERTY(scaleYEnabled, BOOL) \
RCT_EXPORT_VIEW_PROPERTY(pinchZoom, BOOL) \
RCT_EXPORT_VIEW_PROPERTY(highlightPerDragEnabled, BOOL) \
RCT_EXPORT_VIEW_PROPERTY(doubleTapToZoomEnabled, BOOL) \
RCT_EXPORT_VIEW_PROPERTY(zoom, NSDictionary) \
RCT_EXPORT_VIEW_PROPERTY(viewPortOffsets, NSDictionary) \
RCT_EXPORT_VIEW_PROPERTY(extraOffsets, NSDictionary) \
RCT_EXPORT_VIEW_PROPERTY(onYaxisMinMaxChange, RCTBubblingEventBlock) \
RCT_EXTERN_METHOD(moveViewToX:(nonnull NSNumber *)node xValue:(nonnull NSNumber *)xValue) \
RCT_EXTERN_METHOD(moveViewTo:(nonnull NSNumber *)node xValue:(nonnull NSNumber *)xValue yValue:(nonnull NSNumber *)yValue axisDependency:(nonnull NSString *)axisDependency) \
RCT_EXTERN_METHOD(moveViewToAnimated:(nonnull NSNumber *)node xValue:(nonnull NSNumber *)xValue yValue:(nonnull NSNumber *)yValue axisDependency:(nonnull NSString *)axisDependency duration:(nonnull NSNumber *)duration) \
RCT_EXTERN_METHOD(centerViewTo:(nonnull NSNumber *)node xValue:(nonnull NSNumber *)xValue yValue:(nonnull NSNumber *)yValue axisDependency:(nonnull NSString *)axisDependency) \
RCT_EXTERN_METHOD(centerViewToAnimated:(nonnull NSNumber *)node xValue:(nonnull NSNumber *)xValue yValue:(nonnull NSNumber *)yValue axisDependency:(nonnull NSString *)axisDependency duration:(nonnull NSNumber *)duration) \
RCT_EXTERN_METHOD(highlights:(nonnull NSNumber *)node config:(nonnull NSArray *)config) \
RCT_EXTERN_METHOD(fitScreen:(nonnull NSNumber *)node) \
RCT_EXTERN_METHOD(setDataAndLockIndex:(nonnull NSNumber *)node data:(nonnull NSDictionary *)data)
#endif /* RNBarLineChartManagerBridge_h */
| 931 |
14,668 |
<filename>src/base/containers/span_rust.h
// 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.
#ifndef BASE_CONTAINERS_SPAN_RUST_H_
#define BASE_CONTAINERS_SPAN_RUST_H_
#include <stdint.h>
#include "base/containers/span.h"
#include "third_party/rust/cxx/v1/crate/include/cxx.h"
namespace base {
// Create a Rust slice from a base::span.
inline rust::Slice<const uint8_t> SpanToRustSlice(span<const uint8_t> span) {
return rust::Slice<const uint8_t>(span.data(), span.size());
}
} // namespace base
#endif // BASE_CONTAINERS_SPAN_RUST_H_
| 244 |
460 |
<filename>norminette/tests/lexer/files/ok_test_18.c
struct bitfield {
unsigned x: 3;
};
void foo() {
int a[2];
int i;
const int j;
struct bitfield bf;
a;
i;
j;
bf.x;
foo;
i = 4;
bf.x = 4;
&a;
&i;
&j;
&foo;
}
| 130 |
879 |
package org.zstack.test.kvm;
import org.junit.Before;
import org.junit.Test;
import org.zstack.core.cloudbus.CloudBus;
import org.zstack.core.componentloader.ComponentLoader;
import org.zstack.core.db.DatabaseFacade;
import org.zstack.header.configuration.InstanceOfferingInventory;
import org.zstack.header.identity.SessionInventory;
import org.zstack.header.image.ImageInventory;
import org.zstack.header.network.l3.L3NetworkInventory;
import org.zstack.header.storage.primary.PrimaryStorageInventory;
import org.zstack.simulator.storage.backup.sftp.SftpBackupStorageSimulatorConfig;
import org.zstack.simulator.storage.primary.nfs.NfsPrimaryStorageSimulatorConfig;
import org.zstack.test.*;
import org.zstack.test.deployer.Deployer;
import org.zstack.test.storage.backup.sftp.TestSftpBackupStorageDeleteImage2;
import org.zstack.utils.Utils;
import org.zstack.utils.logging.CLogger;
public class TestCreateVmOnKvmSpecifiedPrimaryStorageForRootVolume {
CLogger logger = Utils.getLogger(TestSftpBackupStorageDeleteImage2.class);
Deployer deployer;
Api api;
ComponentLoader loader;
CloudBus bus;
DatabaseFacade dbf;
SessionInventory session;
SftpBackupStorageSimulatorConfig config;
NfsPrimaryStorageSimulatorConfig nconfig;
@Before
public void setUp() throws Exception {
DBUtil.reDeployDB();
WebBeanConstructor con = new WebBeanConstructor();
deployer = new Deployer("deployerXml/kvm/TestCreateVmOnKvmSpeicfiedPrimaryStorageForRootVolume.xml", con);
deployer.addSpringConfig("KVMRelated.xml");
deployer.build();
api = deployer.getApi();
loader = deployer.getComponentLoader();
bus = loader.getComponent(CloudBus.class);
dbf = loader.getComponent(DatabaseFacade.class);
config = loader.getComponent(SftpBackupStorageSimulatorConfig.class);
nconfig = loader.getComponent(NfsPrimaryStorageSimulatorConfig.class);
session = api.loginAsAdmin();
}
@Test
public void test() throws ApiSenderException {
PrimaryStorageInventory nfsPS = deployer.primaryStorages.get("nfs");
L3NetworkInventory l3nInv1 = deployer.l3Networks.get("TestL3Network1");
L3NetworkInventory l3nInv2 = deployer.l3Networks.get("TestL3Network2");
L3NetworkInventory l3nInv3 = deployer.l3Networks.get("TestL3Network3");
L3NetworkInventory l3nInv4 = deployer.l3Networks.get("TestL3Network4");
InstanceOfferingInventory ioinv = deployer.instanceOfferings.get("TestInstanceOffering");
ImageInventory img = deployer.images.get("TestImage");
nconfig.downloadFromSftpCmds.clear();
VmCreator creator = new VmCreator(api);
creator.addL3Network(l3nInv1.getUuid());
creator.addL3Network(l3nInv2.getUuid());
creator.addL3Network(l3nInv3.getUuid());
creator.addL3Network(l3nInv4.getUuid());
creator.name = "vm";
creator.imageUuid = img.getUuid();
creator.instanceOfferingUuid = ioinv.getUuid();
creator.primaryStorageUuidForRootVolume = nfsPS.getUuid();
creator.create();
}
}
| 1,206 |
450 |
/*
* Copyright 2016-2020 chronicle.software
*
* https://chronicle.software
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.openhft.chronicle.core.time;
import net.openhft.chronicle.core.Jvm;
import java.util.concurrent.atomic.AtomicLong;
/**
* Timestamps are unique across threads for a single process.
*/
public class UniqueMicroTimeProvider implements TimeProvider {
public static final UniqueMicroTimeProvider INSTANCE = new UniqueMicroTimeProvider();
private final AtomicLong lastTime = new AtomicLong();
private TimeProvider provider = SystemTimeProvider.INSTANCE;
/**
* Create new instances for testing purposes as it is stateful
*/
public UniqueMicroTimeProvider() {
}
public UniqueMicroTimeProvider provider(TimeProvider provider) throws IllegalStateException {
this.provider = provider;
lastTime.set(provider.currentTimeMicros());
return this;
}
@Override
public long currentTimeMillis() {
return provider.currentTimeMillis();
}
@Override
public long currentTimeMicros() throws IllegalStateException {
long time = provider.currentTimeMicros();
while (true) {
long time0 = lastTime.get();
if (time0 >= time) {
assertTime(time, time0);
time = time0 + 1;
}
if (lastTime.compareAndSet(time0, time))
return time;
Jvm.nanoPause();
}
}
@Override
public long currentTimeNanos() throws IllegalStateException {
long time = provider.currentTimeNanos();
long timeUS = time / 1000;
while (true) {
long time0 = lastTime.get();
if (time0 >= time / 1000) {
assertTime(timeUS, time0);
timeUS = time0 + 1;
time = timeUS * 1000;
}
if (lastTime.compareAndSet(time0, timeUS))
return time;
Jvm.nanoPause();
}
}
private void assertTime(long realTimeUS, long timeUS) {
assert (timeUS - realTimeUS) < 1 * 1e6 : "if you call this more than 1 million times a second it will make time go forward";
}
}
| 1,031 |
520 |
<filename>wrappers/Modelica/src/solvermap.cpp
#include "solvermap.h"
#include "basesolver.h"
#include "testsolver.h"
#if (FLUIDPROP == 1)
#include "fluidpropsolver.h"
#endif // FLUIDPROP == 1
#if (COOLPROP == 1)
#include "coolpropsolver.h"
#endif // COOLPROP == 1
//! Get a specific solver
/*!
This function returns the solver for the specified library name, substance name
and possibly medium name. It creates a new solver if the solver does not already
exist. When implementing new solvers, one has to add the newly created solvers to
this function. An error message is generated if the specific library is not supported
by the interface library.
@param mediumName Medium name
@param libraryName Library name
@param substanceName Substance name
*/
BaseSolver *SolverMap::getSolver(const string &mediumName, const string &libraryName, const string &substanceName){
// Get solver key from library and substance name
string solverKeyString(solverKey(libraryName, substanceName));
// Check whether solver already exists
if (_solvers.find(solverKeyString) != _solvers.end())
return _solvers[solverKeyString];
// Create new solver if it doesn't exist
// Test solver for compiler setup debugging
if (libraryName.compare("TestMedium") == 0)
_solvers[solverKeyString] = new TestSolver(mediumName, libraryName, substanceName);
#if (FLUIDPROP == 1)
// FluidProp solver
else if (libraryName.find("FluidProp") == 0)
_solvers[solverKeyString] = new FluidPropSolver(mediumName, libraryName, substanceName);
#endif // FLUIDPROP == 1
#if (COOLPROP == 1)
// CoolProp solver
else if (libraryName.find("CoolProp") == 0)
_solvers[solverKeyString] = new CoolPropSolver(mediumName, libraryName, substanceName);
#endif // COOLPROP == 1
else {
// Generate error message
char error[100];
sprintf(error, "Error: libraryName = %s is not supported by any external solver\n", libraryName.c_str());
errorMessage(error);
}
// Return pointer to solver
return _solvers[solverKeyString];
};
//! Generate a unique solver key
/*!
This function generates a unique solver key based on the library name and
substance name.
*/
string SolverMap::solverKey(const string &libraryName, const string &substanceName){
// This function returns the solver key and may be changed by advanced users
return libraryName + "." + substanceName;
}
map<string, BaseSolver*> SolverMap::_solvers;
| 752 |
14,668 |
<filename>components/safe_browsing/core/browser/db/fake_database_manager.cc
// 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 "components/safe_browsing/core/browser/db/fake_database_manager.h"
namespace safe_browsing {
FakeSafeBrowsingDatabaseManager::FakeSafeBrowsingDatabaseManager(
scoped_refptr<base::SequencedTaskRunner> ui_task_runner,
scoped_refptr<base::SequencedTaskRunner> io_task_runner)
: TestSafeBrowsingDatabaseManager(std::move(ui_task_runner),
std::move(io_task_runner)) {}
FakeSafeBrowsingDatabaseManager::~FakeSafeBrowsingDatabaseManager() = default;
void FakeSafeBrowsingDatabaseManager::AddDangerousUrl(
const GURL& dangerous_url,
SBThreatType threat_type) {
dangerous_urls_[dangerous_url] = threat_type;
}
void FakeSafeBrowsingDatabaseManager::ClearDangerousUrl(
const GURL& dangerous_url) {
dangerous_urls_.erase(dangerous_url);
}
bool FakeSafeBrowsingDatabaseManager::CanCheckRequestDestination(
network::mojom::RequestDestination request_destination) const {
return true;
}
bool FakeSafeBrowsingDatabaseManager::ChecksAreAlwaysAsync() const {
return false;
}
bool FakeSafeBrowsingDatabaseManager::CheckBrowseUrl(
const GURL& url,
const SBThreatTypeSet& threat_types,
Client* client) {
const auto it = dangerous_urls_.find(url);
if (it == dangerous_urls_.end())
return true;
const SBThreatType result_threat_type = it->second;
if (result_threat_type == SB_THREAT_TYPE_SAFE)
return true;
io_task_runner()->PostTask(
FROM_HERE,
base::BindOnce(&FakeSafeBrowsingDatabaseManager::CheckBrowseURLAsync, url,
result_threat_type, client));
return false;
}
bool FakeSafeBrowsingDatabaseManager::CheckDownloadUrl(
const std::vector<GURL>& url_chain,
Client* client) {
for (size_t i = 0; i < url_chain.size(); i++) {
GURL url = url_chain[i];
const auto it = dangerous_urls_.find(url);
if (it == dangerous_urls_.end())
continue;
const SBThreatType result_threat_type = it->second;
if (result_threat_type == SB_THREAT_TYPE_SAFE)
continue;
io_task_runner()->PostTask(
FROM_HERE,
base::BindOnce(&FakeSafeBrowsingDatabaseManager::CheckDownloadURLAsync,
url_chain, result_threat_type, client));
return false;
}
return true;
}
bool FakeSafeBrowsingDatabaseManager::CheckExtensionIDs(
const std::set<std::string>& extension_ids,
Client* client) {
return true;
}
bool FakeSafeBrowsingDatabaseManager::CheckUrlForSubresourceFilter(
const GURL& url,
Client* client) {
return true;
}
safe_browsing::ThreatSource FakeSafeBrowsingDatabaseManager::GetThreatSource()
const {
return safe_browsing::ThreatSource::LOCAL_PVER4;
}
bool FakeSafeBrowsingDatabaseManager::IsSupported() const {
return true;
}
// static
void FakeSafeBrowsingDatabaseManager::CheckBrowseURLAsync(
GURL url,
SBThreatType result_threat_type,
Client* client) {
client->OnCheckBrowseUrlResult(url, result_threat_type,
safe_browsing::ThreatMetadata());
}
// static
void FakeSafeBrowsingDatabaseManager::CheckDownloadURLAsync(
const std::vector<GURL>& url_chain,
SBThreatType result_threat_type,
Client* client) {
client->OnCheckDownloadUrlResult(url_chain, result_threat_type);
}
} // namespace safe_browsing
| 1,308 |
2,996 |
// Copyright 2021 The Terasology Foundation
// SPDX-License-Identifier: Apache-2.0
package org.terasology.engine.core;
/**
* An interface for subscribers to engine state changes
*/
@FunctionalInterface
public interface StateChangeSubscriber {
void onStateChange();
}
| 76 |
348 |
<reponame>chamberone/Leaflet.PixiOverlay
{"nom":"Vorly","circ":"3ème circonscription","dpt":"Cher","inscrits":195,"abs":118,"votants":77,"blancs":2,"nuls":6,"exp":69,"res":[{"nuance":"SOC","nom":"M. <NAME>","voix":36},{"nuance":"REM","nom":"M. <NAME>","voix":33}]}
| 112 |
1,540 |
# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# Modified from espnet(https://github.com/espnet/espnet)
"""Positional Encoding Module."""
import math
import paddle
from paddle import nn
class PositionalEncoding(nn.Layer):
"""Positional encoding.
Parameters
----------
d_model : int
Embedding dimension.
dropout_rate : float
Dropout rate.
max_len : int
Maximum input length.
reverse : bool
Whether to reverse the input position.
type : str
dtype of param
"""
def __init__(self,
d_model,
dropout_rate,
max_len=5000,
dtype="float32",
reverse=False):
"""Construct an PositionalEncoding object."""
super().__init__()
self.d_model = d_model
self.reverse = reverse
self.xscale = math.sqrt(self.d_model)
self.dropout = nn.Dropout(p=dropout_rate)
self.pe = None
self.dtype = dtype
self.extend_pe(paddle.expand(paddle.zeros([1]), (1, max_len)))
def extend_pe(self, x):
"""Reset the positional encodings."""
x_shape = paddle.shape(x)
pe = paddle.zeros([x_shape[1], self.d_model])
if self.reverse:
position = paddle.arange(
x_shape[1] - 1, -1, -1.0, dtype=self.dtype).unsqueeze(1)
else:
position = paddle.arange(
0, x_shape[1], dtype=self.dtype).unsqueeze(1)
div_term = paddle.exp(
paddle.arange(0, self.d_model, 2, dtype=self.dtype) *
-(math.log(10000.0) / self.d_model))
pe[:, 0::2] = paddle.sin(position * div_term)
pe[:, 1::2] = paddle.cos(position * div_term)
pe = pe.unsqueeze(0)
self.pe = pe
def forward(self, x: paddle.Tensor):
"""Add positional encoding.
Parameters
----------
x : paddle.Tensor
Input tensor (batch, time, `*`).
Returns
----------
paddle.Tensor
Encoded tensor (batch, time, `*`).
"""
self.extend_pe(x)
T = paddle.shape(x)[1]
x = x * self.xscale + self.pe[:, :T]
return self.dropout(x)
class ScaledPositionalEncoding(PositionalEncoding):
"""Scaled positional encoding module.
See Sec. 3.2 https://arxiv.org/abs/1809.08895
Parameters
----------
d_model : int
Embedding dimension.
dropout_rate : float
Dropout rate.
max_len : int
Maximum input length.
dtype : str
dtype of param
"""
def __init__(self, d_model, dropout_rate, max_len=5000, dtype="float32"):
"""Initialize class."""
super().__init__(
d_model=d_model,
dropout_rate=dropout_rate,
max_len=max_len,
dtype=dtype)
x = paddle.ones([1], dtype=self.dtype)
self.alpha = paddle.create_parameter(
shape=x.shape,
dtype=self.dtype,
default_initializer=nn.initializer.Assign(x))
def reset_parameters(self):
"""Reset parameters."""
self.alpha = paddle.ones([1])
def forward(self, x):
"""Add positional encoding.
Parameters
----------
x : paddle.Tensor
Input tensor (batch, time, `*`).
Returns
----------
paddle.Tensor
Encoded tensor (batch, time, `*`).
"""
self.extend_pe(x)
T = paddle.shape(x)[1]
x = x + self.alpha * self.pe[:, :T]
return self.dropout(x)
class RelPositionalEncoding(nn.Layer):
"""Relative positional encoding module (new implementation).
Details can be found in https://github.com/espnet/espnet/pull/2816.
See : Appendix B in https://arxiv.org/abs/1901.02860
Parameters
----------
d_model : int
Embedding dimension.
dropout_rate : float
Dropout rate.
max_len : int
Maximum input length.
"""
def __init__(self, d_model, dropout_rate, max_len=5000, dtype="float32"):
"""Construct an PositionalEncoding object."""
super().__init__()
self.d_model = d_model
self.xscale = math.sqrt(self.d_model)
self.dropout = nn.Dropout(p=dropout_rate)
self.pe = None
self.dtype = dtype
self.extend_pe(paddle.expand(paddle.zeros([1]), (1, max_len)))
def extend_pe(self, x):
"""Reset the positional encodings."""
if self.pe is not None:
# self.pe contains both positive and negative parts
# the length of self.pe is 2 * input_len - 1
if paddle.shape(self.pe)[1] >= paddle.shape(x)[1] * 2 - 1:
return
# Suppose `i` means to the position of query vecotr and `j` means the
# position of key vector. We use position relative positions when keys
# are to the left (i>j) and negative relative positions otherwise (i<j).
x_shape = paddle.shape(x)
pe_positive = paddle.zeros([x_shape[1], self.d_model])
pe_negative = paddle.zeros([x_shape[1], self.d_model])
position = paddle.arange(0, x_shape[1], dtype=self.dtype).unsqueeze(1)
div_term = paddle.exp(
paddle.arange(0, self.d_model, 2, dtype=self.dtype) *
-(math.log(10000.0) / self.d_model))
pe_positive[:, 0::2] = paddle.sin(position * div_term)
pe_positive[:, 1::2] = paddle.cos(position * div_term)
pe_negative[:, 0::2] = paddle.sin(-1 * position * div_term)
pe_negative[:, 1::2] = paddle.cos(-1 * position * div_term)
# Reserve the order of positive indices and concat both positive and
# negative indices. This is used to support the shifting trick
# as in https://arxiv.org/abs/1901.02860
pe_positive = paddle.flip(pe_positive, [0]).unsqueeze(0)
pe_negative = pe_negative[1:].unsqueeze(0)
pe = paddle.concat([pe_positive, pe_negative], axis=1)
self.pe = pe
def forward(self, x: paddle.Tensor):
"""Add positional encoding.
Parameters
----------
x : paddle.Tensor
Input tensor (batch, time, `*`).
Returns
----------
paddle.Tensor
Encoded tensor (batch, time, `*`).
"""
self.extend_pe(x)
x = x * self.xscale
T = paddle.shape(x)[1]
pe_size = paddle.shape(self.pe)
pos_emb = self.pe[:, pe_size[1] // 2 - T + 1:pe_size[1] // 2 + T, ]
return self.dropout(x), self.dropout(pos_emb)
| 3,268 |
726 |
package org.landy.delegate.leader;
/**
* Created by Tom on 2018/3/14.
*/
public interface ITarget {
public void doing(String command);
}
| 49 |
14,668 |
<reponame>zealoussnow/chromium
// Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_VIEWS_ACCESSIBILITY_VIEWS_UTILITIES_AURA_H_
#define UI_VIEWS_ACCESSIBILITY_VIEWS_UTILITIES_AURA_H_
namespace aura {
class Window;
}
namespace views {
// Return the parent of |window|, first checking to see if it has a
// transient parent. This allows us to walk up the aura::Window
// hierarchy when it spans multiple window tree hosts, each with
// their own native window.
aura::Window* GetWindowParentIncludingTransient(aura::Window* window);
} // namespace views
#endif // UI_VIEWS_ACCESSIBILITY_VIEWS_UTILITIES_AURA_H_
| 233 |
348 |
<reponame>chamberone/Leaflet.PixiOverlay<gh_stars>100-1000
{"nom":"Sandillon","circ":"3ème circonscription","dpt":"Loiret","inscrits":3153,"abs":1411,"votants":1742,"blancs":25,"nuls":14,"exp":1703,"res":[{"nuance":"REM","nom":"Mme <NAME>","voix":748},{"nuance":"LR","nom":"M. <NAME>","voix":348},{"nuance":"FN","nom":"M. <NAME>","voix":223},{"nuance":"FI","nom":"M. <NAME>","voix":180},{"nuance":"ECO","nom":"<NAME>","voix":119},{"nuance":"COM","nom":"Mme <NAME>","voix":36},{"nuance":"DIV","nom":"Mme <NAME>","voix":14},{"nuance":"EXG","nom":"M. <NAME>","voix":12},{"nuance":"DVD","nom":"M. <NAME>","voix":12},{"nuance":"DIV","nom":"M. <NAME>","voix":9},{"nuance":"DVD","nom":"M. <NAME>","voix":2}]}
| 285 |
777 |
<gh_stars>100-1000
/*
* Copyright (C) 2013 Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef WebDOMFileSystem_h
#define WebDOMFileSystem_h
#include "../platform/WebCommon.h"
#include "../platform/WebFileSystem.h"
#include "../platform/WebPrivatePtr.h"
#include "../platform/WebString.h"
#include "../platform/WebURL.h"
#include "WebFrame.h"
#if BLINK_IMPLEMENTATION
#include "platform/heap/Handle.h"
#endif
namespace v8 {
class Isolate;
class Object;
class Value;
template <class T>
class Local;
}
namespace blink {
class DOMFileSystem;
class WebDOMFileSystem {
public:
enum SerializableType {
SerializableTypeSerializable,
SerializableTypeNotSerializable,
};
enum EntryType {
EntryTypeFile,
EntryTypeDirectory,
};
~WebDOMFileSystem() { reset(); }
WebDOMFileSystem() {}
WebDOMFileSystem(const WebDOMFileSystem& d) { assign(d); }
WebDOMFileSystem& operator=(const WebDOMFileSystem& d) {
assign(d);
return *this;
}
BLINK_EXPORT static WebDOMFileSystem fromV8Value(v8::Local<v8::Value>);
// Create file system URL from the given entry.
BLINK_EXPORT static WebURL createFileSystemURL(v8::Local<v8::Value> entry);
// FIXME: Deprecate the last argument when all filesystems become
// serializable.
BLINK_EXPORT static WebDOMFileSystem create(
WebLocalFrame*,
WebFileSystemType,
const WebString& name,
const WebURL& rootURL,
SerializableType = SerializableTypeNotSerializable);
BLINK_EXPORT void reset();
BLINK_EXPORT void assign(const WebDOMFileSystem&);
BLINK_EXPORT WebString name() const;
BLINK_EXPORT WebFileSystem::Type type() const;
BLINK_EXPORT WebURL rootURL() const;
BLINK_EXPORT v8::Local<v8::Value> toV8Value(
v8::Local<v8::Object> creationContext,
v8::Isolate*);
BLINK_EXPORT v8::Local<v8::Value> createV8Entry(
const WebString& path,
EntryType,
v8::Local<v8::Object> creationContext,
v8::Isolate*);
bool isNull() const { return m_private.isNull(); }
#if BLINK_IMPLEMENTATION
WebDOMFileSystem(DOMFileSystem*);
WebDOMFileSystem& operator=(DOMFileSystem*);
#endif
private:
WebPrivatePtr<DOMFileSystem> m_private;
};
} // namespace blink
#endif // WebDOMFileSystem_h
| 1,208 |
311 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (c) 2012-2019 Snowflake Computing Inc. All rights reserved.
#
from logging import getLogger
from snowflake.connector.converter_snowsql import SnowflakeConverterSnowSQL
logger = getLogger(__name__)
ConverterSnowSQL = SnowflakeConverterSnowSQL
def test_benchmark_date_converter():
conv = ConverterSnowSQL(support_negative_year=True)
conv.set_parameter("DATE_OUTPUT_FORMAT", "YY-MM-DD")
m = conv.to_python_method("DATE", {"scale": 0})
current_date_counter = 12345
for _ in range(2000000):
m(current_date_counter)
def test_benchmark_date_without_negative_converter():
conv = ConverterSnowSQL(support_negative_year=False)
conv.set_parameter("DATE_OUTPUT_FORMAT", "YY-MM-DD")
m = conv.to_python_method("DATE", {"scale": 0})
current_date_counter = 12345
for _ in range(2000000):
m(current_date_counter)
def test_benchmark_timestamp_converter():
conv = ConverterSnowSQL(support_negative_year=True)
conv.set_parameter("TIMESTAMP_NTZ_OUTPUT_FORMAT", "YYYY-MM-DD HH24:MI:SS.FF9")
m = conv.to_python_method("TIMESTAMP_NTZ", {"scale": 9})
current_timestamp = "2208943503.876543211"
for _ in range(2000000):
m(current_timestamp)
def test_benchmark_timestamp_without_negative_converter():
conv = ConverterSnowSQL(support_negative_year=False)
conv.set_parameter("TIMESTAMP_NTZ_OUTPUT_FORMAT", "YYYY-MM-DD HH24:MI:SS.FF9")
m = conv.to_python_method("TIMESTAMP_NTZ", {"scale": 9})
current_timestamp = "2208943503.876543211"
for _ in range(2000000):
m(current_timestamp)
| 660 |
425 |
<reponame>AdityaKane2001/MaskTextSpotter<filename>maskrcnn_benchmark/utils/logging.py<gh_stars>100-1000
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
# modified by <NAME>
import logging
import os
import sys
from tensorboardX import SummaryWriter
def setup_logger(name, save_dir, distributed_rank=0):
logger = logging.getLogger(name)
logger.setLevel(logging.DEBUG)
# don't log results for the non-master process
if distributed_rank > 0:
return logger
ch = logging.StreamHandler(stream=sys.stdout)
ch.setLevel(logging.DEBUG)
formatter = logging.Formatter("%(asctime)s %(name)s %(levelname)s: %(message)s")
ch.setFormatter(formatter)
logger.addHandler(ch)
if save_dir:
fh = logging.FileHandler(os.path.join(save_dir, "log.txt"))
fh.setLevel(logging.DEBUG)
fh.setFormatter(formatter)
logger.addHandler(fh)
return logger
class Logger(object):
def __init__(self, log_dir, distributed_rank=0):
"""Create a summary writer logging to log_dir."""
self.distributed_rank = distributed_rank
if distributed_rank == 0:
self.writer = SummaryWriter(log_dir)
def scalar_summary(self, tag, value, step):
"""Log a scalar variable."""
if self.distributed_rank == 0:
self.writer.add_scalar(tag, value, step)
| 547 |
763 |
<reponame>zabrewer/batfish
/*
* Note: We obtained permission from the author of Javabdd, <NAME>, to use
* the library with Batfish under the MIT license. The email exchange is included
* in LICENSE.email file.
*
* MIT License
*
* Copyright (c) 2013-2017 <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
package net.sf.javabdd.regression;
import net.sf.javabdd.BDD;
import net.sf.javabdd.BDDFactory;
import net.sf.javabdd.bdd.BDDTestCase;
import org.junit.internal.runners.JUnit38ClassRunner;
import org.junit.runner.RunWith;
/**
* unique() and applyUni() bug
*
* @author <NAME>
* @version $Id: R3.java,v 1.2 2005/04/18 12:00:00 joewhaley Exp $
*/
@RunWith(JUnit38ClassRunner.class)
public class R3 extends BDDTestCase {
public static void main(String[] args) {
junit.textui.TestRunner.run(R3.class);
}
public void testR3() {
assertTrue(hasNext());
while (hasNext()) {
BDDFactory bdd = next();
BDD x0, x1, y0, y1, z0, z1, t, or, one;
bdd.setVarNum(5);
x0 = bdd.ithVar(0);
x1 = bdd.ithVar(1);
one = bdd.one();
or = x0.or(x1);
z0 = or.unique(x0);
t = x1.not();
assertEquals(z0.toString(), z0, t);
t.free();
z1 = or.unique(x1);
t = x0.not();
assertEquals(z1.toString(), z1, t);
t.free();
t = one.unique(x0);
assertTrue(t.toString(), t.isZero());
t.free();
y0 = x0.applyUni(x1, BDDFactory.or, x0);
t = x1.not();
assertEquals(y0.toString(), y0, t);
t.free();
y1 = x0.applyUni(x1, BDDFactory.or, x1);
t = x0.not();
assertEquals(y1.toString(), y1, t);
t.free();
x0.free();
x1.free();
y0.free();
y1.free();
z0.free();
z1.free();
or.free();
one.free();
}
}
}
| 1,121 |
2,144 |
/**
* 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.pinot.broker.requesthandler;
import com.google.common.collect.ImmutableSet;
import java.util.Arrays;
import org.apache.pinot.common.request.PinotQuery;
import org.apache.pinot.common.utils.request.RequestUtils;
import org.apache.pinot.sql.parsers.CalciteSqlParser;
import org.testng.annotations.Test;
import static org.testng.Assert.assertEquals;
public class QueryOverrideTest {
private static final int QUERY_LIMIT = 1000;
@Test
public void testLimitOverride() {
// Selections
testLimitOverride("SELECT * FROM vegetables LIMIT 999", 999);
testLimitOverride("select * from vegetables limit 1000", 1000);
testLimitOverride("SeLeCt * FrOm vegetables LiMit 1001", 1000);
testLimitOverride("sElEcT * fRoM vegetables lImIt 10000", 1000);
// Group-bys
testLimitOverride("SELECT COUNT(*) FROM vegetables GROUP BY a LIMIT 999", 999);
testLimitOverride("select count(*) from vegetables group by a limit 1000", 1000);
testLimitOverride("SeLeCt CoUnT(*) FrOm vegetables GrOuP By a LiMit 1001", 1000);
testLimitOverride("sElEcT cOuNt(*) fRoM vegetables gRoUp bY a lImIt 10000", 1000);
}
private void testLimitOverride(String query, int expectedLimit) {
PinotQuery pinotQuery = CalciteSqlParser.compileToPinotQuery(query);
BaseBrokerRequestHandler.handleQueryLimitOverride(pinotQuery, QUERY_LIMIT);
assertEquals(pinotQuery.getLimit(), expectedLimit);
}
@Test
public void testDistinctCountOverride() {
String query = "SELECT DISTINCT_COUNT(col1) FROM myTable";
PinotQuery pinotQuery = CalciteSqlParser.compileToPinotQuery(query);
BaseBrokerRequestHandler.handleSegmentPartitionedDistinctCountOverride(pinotQuery, ImmutableSet.of("col2", "col3"));
assertEquals(pinotQuery.getSelectList().get(0).getFunctionCall().getOperator(), "distinctcount");
BaseBrokerRequestHandler.handleSegmentPartitionedDistinctCountOverride(pinotQuery,
ImmutableSet.of("col1", "col2", "col3"));
assertEquals(pinotQuery.getSelectList().get(0).getFunctionCall().getOperator(), "segmentpartitioneddistinctcount");
}
@Test
public void testApproximateFunctionOverride() {
{
String query = "SELECT DISTINCT_COUNT(col1) FROM myTable GROUP BY col2 HAVING DISTINCT_COUNT(col1) > 10 "
+ "ORDER BY DISTINCT_COUNT(col1) DESC";
PinotQuery pinotQuery = CalciteSqlParser.compileToPinotQuery(query);
BaseBrokerRequestHandler.handleApproximateFunctionOverride(pinotQuery);
assertEquals(pinotQuery.getSelectList().get(0).getFunctionCall().getOperator(), "distinctcountsmarthll");
assertEquals(
pinotQuery.getOrderByList().get(0).getFunctionCall().getOperands().get(0).getFunctionCall().getOperator(),
"distinctcountsmarthll");
assertEquals(
pinotQuery.getHavingExpression().getFunctionCall().getOperands().get(0).getFunctionCall().getOperator(),
"distinctcountsmarthll");
query = "SELECT DISTINCT_COUNT_MV(col1) FROM myTable";
pinotQuery = CalciteSqlParser.compileToPinotQuery(query);
BaseBrokerRequestHandler.handleApproximateFunctionOverride(pinotQuery);
assertEquals(pinotQuery.getSelectList().get(0).getFunctionCall().getOperator(), "distinctcountsmarthll");
query = "SELECT DISTINCT col1 FROM myTable";
pinotQuery = CalciteSqlParser.compileToPinotQuery(query);
BaseBrokerRequestHandler.handleApproximateFunctionOverride(pinotQuery);
assertEquals(pinotQuery.getSelectList().get(0).getFunctionCall().getOperator(), "distinct");
query = "SELECT DISTINCT_COUNT_HLL(col1) FROM myTable";
pinotQuery = CalciteSqlParser.compileToPinotQuery(query);
BaseBrokerRequestHandler.handleApproximateFunctionOverride(pinotQuery);
assertEquals(pinotQuery.getSelectList().get(0).getFunctionCall().getOperator(), "distinctcounthll");
query = "SELECT DISTINCT_COUNT_BITMAP(col1) FROM myTable";
pinotQuery = CalciteSqlParser.compileToPinotQuery(query);
BaseBrokerRequestHandler.handleApproximateFunctionOverride(pinotQuery);
assertEquals(pinotQuery.getSelectList().get(0).getFunctionCall().getOperator(), "distinctcountbitmap");
}
for (String query : Arrays.asList("SELECT PERCENTILE(col1, 95) FROM myTable",
"SELECT PERCENTILE_MV(col1, 95) FROM myTable", "SELECT PERCENTILE95(col1) FROM myTable",
"SELECT PERCENTILE95MV(col1) FROM myTable")) {
PinotQuery pinotQuery = CalciteSqlParser.compileToPinotQuery(query);
BaseBrokerRequestHandler.handleApproximateFunctionOverride(pinotQuery);
assertEquals(pinotQuery.getSelectList().get(0).getFunctionCall().getOperator(), "percentilesmarttdigest");
assertEquals(pinotQuery.getSelectList().get(0).getFunctionCall().getOperands().get(1),
RequestUtils.getLiteralExpression(95));
}
{
String query = "SELECT PERCENTILE_TDIGEST(col1, 95) FROM myTable";
PinotQuery pinotQuery = CalciteSqlParser.compileToPinotQuery(query);
BaseBrokerRequestHandler.handleApproximateFunctionOverride(pinotQuery);
assertEquals(pinotQuery.getSelectList().get(0).getFunctionCall().getOperator(), "percentiletdigest");
query = "SELECT PERCENTILE_EST(col1, 95) FROM myTable";
pinotQuery = CalciteSqlParser.compileToPinotQuery(query);
BaseBrokerRequestHandler.handleApproximateFunctionOverride(pinotQuery);
assertEquals(pinotQuery.getSelectList().get(0).getFunctionCall().getOperator(), "percentileest");
}
}
}
| 2,159 |
3,589 |
package picocli;
import org.junit.Ignore;
import org.junit.Rule;
import org.junit.Test;
import org.junit.contrib.java.lang.system.ProvideSystemProperty;
import org.junit.contrib.java.lang.system.RestoreSystemProperties;
import org.junit.rules.TestRule;
import picocli.CommandLine.Command;
import picocli.CommandLine.MissingParameterException;
import picocli.CommandLine.Option;
import picocli.CommandLine.OverwrittenOptionException;
import picocli.CommandLine.Parameters;
import picocli.CommandLine.ParseResult;
import picocli.CommandLine.UnmatchedArgumentException;
import java.util.Arrays;
import java.util.List;
import static org.junit.Assert.*;
/**
* Tests for
* <ul>
* <li>https://github.com/remkop/picocli/issues/1015</li>>
* <li>https://github.com/remkop/picocli/issues/1055</li>>
* <li>https://github.com/remkop/picocli/issues/639</li>>
* </ul>
*/
public class UnmatchedOptionTest {
// allows tests to set any kind of properties they like, without having to individually roll them back
@Rule
public final TestRule restoreSystemProperties = new RestoreSystemProperties();
@Rule
public final ProvideSystemProperty ansiOFF = new ProvideSystemProperty("picocli.ansi", "false");
static void expect(Object userObject, String errorMessage, Class<? extends Exception> cls, String... args) {
expect(new CommandLine(userObject), errorMessage, cls, args);
}
static void expect(CommandLine cmd, String errorMessage, Class<? extends Exception> cls, String... args) {
try {
cmd.parseArgs(args);
fail("Expected exception");
} catch (Exception ex) {
assertTrue("Wrong exception: " + ex + ", expected " + cls.getName(), cls.isAssignableFrom(ex.getClass()));
assertEquals(errorMessage, ex.getMessage());
}
}
@Test
public void testSingleValuePositionalDoesNotConsumeActualOption() {
class App {
@Option(names = "-x") int x;
@Parameters String y;
}
expect(new App(), "Missing required parameter for option '-x' (<x>)", MissingParameterException.class, "-x", "3", "-x");
expect(new App(), "option '-x' (<x>) should be specified only once", OverwrittenOptionException.class, "-x", "3", "-x", "4");
App app = new App();
new CommandLine(app).parseArgs("-x", "3", "4");
assertEquals(3, app.x);
assertEquals("4", app.y);
}
@Test
public void testMultiValuePositionalDoesNotConsumeActualOption() {
class App {
@Option(names = "-x") int x;
@Parameters String[] y;
}
expect(new App(), "Missing required parameter for option '-x' (<x>)", MissingParameterException.class, "-x", "3", "-x");
expect(new App(), "option '-x' (<x>) should be specified only once", OverwrittenOptionException.class, "-x", "3", "-x", "4");
expect(new App(), "Missing required parameter for option '-x' (<x>)", MissingParameterException.class, "-x", "3", "4", "-x");
App app = new App();
new CommandLine(app).parseArgs("-x", "3", "4");
assertEquals(3, app.x);
assertArrayEquals(new String[]{"4"}, app.y);
}
@Test
public void testMultiValueVarArgPositionalDoesNotConsumeActualOption() {
class App {
@Option(names = "-x") int x;
@Parameters(arity = "*") String[] y;
}
expect(new App(), "Missing required parameter for option '-x' (<x>)", MissingParameterException.class, "-x", "3", "-x");
expect(new App(), "option '-x' (<x>) should be specified only once", OverwrittenOptionException.class, "-x", "3", "-x", "4");
expect(new App(), "Missing required parameter for option '-x' (<x>)", MissingParameterException.class, "-x", "3", "4", "-x");
App app = new App();
new CommandLine(app).parseArgs("-x", "3", "4");
assertEquals(3, app.x);
assertArrayEquals(new String[]{"4"}, app.y);
}
@Test
public void testMultiValuePositionalArity2_NDoesNotConsumeActualOption() {
class App {
@Option(names = "-x") int x;
@Parameters(arity = "2..*") String[] y;
}
expect(new App(), "Missing required parameter for option '-x' (<x>)", MissingParameterException.class, "-x", "3", "-x");
expect(new App(), "option '-x' (<x>) should be specified only once", OverwrittenOptionException.class, "-x", "3", "-x", "4");
expect(new App(), "Expected parameter 2 (of 2 mandatory parameters) for positional parameter at index 0..* (<y>) but found '-x'",
MissingParameterException.class, "-x", "3", "4", "-x");
App app = new App();
new CommandLine(app).parseArgs("-x", "3", "4", "5");
assertEquals(3, app.x);
assertArrayEquals(new String[]{"4", "5"}, app.y);
}
@Test
public void testSingleValueOptionDoesNotConsumeActualOptionSimple() {
class App {
@Option(names = "-x") String x;
}
expect(new App(), "Expected parameter for option '-x' but found '-x'", MissingParameterException.class, "-x", "-x");
}
@Test
public void testSingleValueOptionDoesNotConsumeActualOption() {
class App {
@Option(names = "-x") int x;
@Option(names = "-y") String y;
}
expect(new App(), "Expected parameter for option '-y' but found '-x'", MissingParameterException.class, "-y", "-x");
}
@Test
public void testSingleValueOptionDoesNotConsumeNegatedActualOption() {
class App {
@Option(names = "--x", negatable = true) boolean x;
@Option(names = "-y") String y;
}
expect(new App(), "Expected parameter for option '-y' but found '--no-x'", MissingParameterException.class, "-y", "--no-x");
}
@Test
public void testSingleValueOptionCanConsumeQuotedActualOption() {
class App {
@Option(names = "-x") int x;
@Option(names = "-y") String y;
}
App app = new App();
new CommandLine(app).parseArgs("-y", "\"-x\"");
assertEquals("\"-x\"", app.y);
new CommandLine(app).setTrimQuotes(true).parseArgs("-y", "\"-x\"");
assertEquals("-x", app.y);
}
@Test
public void testMultiValueOptionDoesNotConsumeActualOption() {
class App {
@Option(names = "-x") int x;
@Option(names = "-y") String[] y;
}
expect(new App(), "Expected parameter for option '-y' but found '-x'", MissingParameterException.class, "-y", "-x");
expect(new App(), "Missing required parameter for option '-x' (<x>)", MissingParameterException.class, "-y", "3", "-x");
}
@Test
public void testMultiValueOptionArity2DoesNotConsumeActualOption() {
class App {
@Option(names = "-x") int x;
@Option(names = "-y", arity = "2") String[] y;
}
expect(new App(), "option '-y' at index 0 (<y>) requires at least 2 values, but only 1 were specified: [-x]",
MissingParameterException.class, "-y", "-x");
expect(new App(), "Expected parameter 2 (of 2 mandatory parameters) for option '-y' but found '-x'",
MissingParameterException.class, "-y", "3", "-x");
}
@Test
public void testMultiValueOptionArity2_NDoesNotConsumeActualOption() {
class App {
@Option(names = "-x") int x;
@Option(names = "-y", arity = "2..N") String[] y;
}
expect(new App(), "option '-y' at index 0 (<y>) requires at least 2 values, but only 1 were specified: [-x]",
MissingParameterException.class, "-y", "-x");
expect(new App(), "Expected parameter 2 (of 2 mandatory parameters) for option '-y' but found '-x'",
MissingParameterException.class, "-y", "1", "-x");
expect(new App(), "Missing required parameter for option '-x' (<x>)", MissingParameterException.class, "-y", "1", "2", "-x");
}
@Test
public void testMultiValueVarArgOptionDoesNotConsumeActualOption() {
class App {
@Option(names = "-x") int x;
@Option(names = "-y", arity = "*") String[] y;
}
expect(new App(), "Missing required parameter for option '-x' (<x>)", MissingParameterException.class, "-y", "-x");
expect(new App(), "Missing required parameter for option '-x' (<x>)", MissingParameterException.class, "-y", "3", "-x");
}
// -----------------------------------
@Test
public void testSingleValuePositionalDoesNotConsumeUnknownOption() {
class App {
@Option(names = "-x") int x;
@Parameters String y;
}
expect(new App(), "Missing required parameter: '<y>'", MissingParameterException.class, "-x", "3", "-z");
expect(new App(), "Unknown option: '-z'", UnmatchedArgumentException.class, "-x", "3", "-z", "4");
}
@Test
public void testSingleValuePositionalCanBeConfiguredToConsumeUnknownOption() {
class App {
@Option(names = "-x") int x;
@Parameters String y;
}
App app = new App();
new CommandLine(app).setUnmatchedOptionsArePositionalParams(true).parseArgs("-x", "3", "-z");
assertEquals(3, app.x);
assertEquals("-z", app.y);
CommandLine cmd = new CommandLine(new App()).setUnmatchedOptionsArePositionalParams(true);
expect(cmd, "Unmatched argument at index 3: '4'", UnmatchedArgumentException.class, "-x", "3", "-z", "4");
}
@Test
public void testMultiValuePositionalDoesNotConsumeUnknownOption() {
class App {
@Option(names = "-x") int x;
@Parameters String[] y;
}
expect(new App(), "Unknown option: '-z'", UnmatchedArgumentException.class, "-x", "3", "-z");
expect(new App(), "Unknown option: '-z'", UnmatchedArgumentException.class, "-x", "3", "-z", "4");
expect(new App(), "Unknown option: '-z'", UnmatchedArgumentException.class, "-x", "3", "4", "-z");
}
@Test
public void testMultiValuePositionalCanBeConfiguredToConsumeUnknownOption() {
class App {
@Option(names = "-x") int x;
@Parameters String[] y;
}
App app = new App();
new CommandLine(app).setUnmatchedOptionsArePositionalParams(true).parseArgs("-x", "3", "-z");
assertEquals(3, app.x);
assertArrayEquals(new String[]{"-z"}, app.y);
app = new App();
new CommandLine(app).setUnmatchedOptionsArePositionalParams(true).parseArgs("-x", "3", "-z", "4");
assertEquals(3, app.x);
assertArrayEquals(new String[]{"-z", "4"}, app.y);
app = new App();
new CommandLine(app).setUnmatchedOptionsArePositionalParams(true).parseArgs("-x", "3", "4", "-z");
assertEquals(3, app.x);
assertArrayEquals(new String[]{"4", "-z"}, app.y);
}
@Test
public void testMultiValueVarArgPositionalDoesNotConsumeUnknownOptionSimple() {
class App {
@Parameters(arity = "*") String[] y;
}
expect(new App(), "Unknown option: '-z'", UnmatchedArgumentException.class, "-z", "4");
expect(new App(), "Unknown option: '-z'", UnmatchedArgumentException.class, "4", "-z");
}
@Test
public void testMultiValueVarArgPositionalDoesNotConsumeUnknownOption() {
class App {
@Option(names = "-x") int x;
@Parameters(arity = "*") String[] y;
}
expect(new App(), "Unknown option: '-z'", UnmatchedArgumentException.class, "-x", "3", "-z");
expect(new App(), "Unknown option: '-z'", UnmatchedArgumentException.class, "-x", "3", "-z", "4");
expect(new App(), "Unknown option: '-z'", UnmatchedArgumentException.class, "-x", "3", "4", "-z");
}
@Test
public void testMultiValueVarArgPositionalCanBeConfiguredToConsumeUnknownOption() {
class App {
@Option(names = "-x") int x;
@Parameters(arity = "*") String[] y;
}
App app = new App();
new CommandLine(app).setUnmatchedOptionsArePositionalParams(true).parseArgs("-x", "3", "-z");
assertEquals(3, app.x);
assertArrayEquals(new String[]{"-z"}, app.y);
app = new App();
new CommandLine(app).setUnmatchedOptionsArePositionalParams(true).parseArgs("-x", "3", "-z", "4");
assertEquals(3, app.x);
assertArrayEquals(new String[]{"-z", "4"}, app.y);
app = new App();
new CommandLine(app).setUnmatchedOptionsArePositionalParams(true).parseArgs("-x", "3", "4", "-z");
assertEquals(3, app.x);
assertArrayEquals(new String[]{"4", "-z"}, app.y);
}
@Test
public void testMultiValuePositionalArity2_NDoesNotConsumeUnknownOption() {
class App {
@Option(names = "-x") int x;
@Parameters(arity = "2..*") String[] y;
}
expect(new App(), "positional parameter at index 0..* (<y>) requires at least 2 values, but none were specified.",
MissingParameterException.class, "-x", "3", "-z");
expect(new App(), "positional parameter at index 0..* (<y>) requires at least 2 values, but only 1 were specified: [4]",
MissingParameterException.class, "-x", "3", "-z", "4");
expect(new App(), "Unknown option: '-z'", UnmatchedArgumentException.class, "-x", "3", "4", "-z");
}
@Test
public void testMultiValuePositionalArity2_NCanBeConfiguredToConsumeUnknownOption() {
class App {
@Option(names = "-x") int x;
@Parameters(arity = "2..*") String[] y;
}
expect(new App(), "positional parameter at index 0..* (<y>) requires at least 2 values, but none were specified.",
MissingParameterException.class, "-x", "3", "-z");
App app = new App();
new CommandLine(app).setUnmatchedOptionsArePositionalParams(true).parseArgs("-x", "3", "-z", "4");
assertEquals(3, app.x);
assertArrayEquals(new String[]{"-z", "4"}, app.y);
app = new App();
new CommandLine(app).setUnmatchedOptionsArePositionalParams(true).parseArgs("-x", "3", "4", "-z");
assertEquals(3, app.x);
assertArrayEquals(new String[]{"4", "-z"}, app.y);
}
@Test
public void testSingleValueOptionDoesNotConsumeUnknownOptionByDefault() {
class App {
@Option(names = "-x") int x;
@Option(names = "-y") String y;
}
CommandLine cmd = new CommandLine(new App());
cmd.setUnmatchedOptionsAllowedAsOptionParameters(false);
expect(cmd, "Unknown option: '-z'; Expected parameter for option '-y' but found '-z'", UnmatchedArgumentException.class, "-y", "-z");
}
@Test
public void testSingleValueOptionCanBeConfiguredToConsumeUnknownOption() {
class App {
@Option(names = "-x") int x;
@Option(names = "-y") String y;
}
App app = new App();
new CommandLine(app).setUnmatchedOptionsAllowedAsOptionParameters(true).parseArgs("-y", "-z");
assertEquals("-z", app.y);
}
@Test
public void testMultiValueOptionDoesNotConsumeUnknownOptionByDefault() {
class App {
@Option(names = "-x") int x;
@Option(names = "-y") String[] y;
}
CommandLine cmd = new CommandLine(new App());
cmd.setUnmatchedOptionsAllowedAsOptionParameters(false);
expect(cmd, "Unknown option: '-z'; Expected parameter for option '-y' but found '-z'", UnmatchedArgumentException.class, "-y", "-z");
expect(cmd, "Unknown option: '-z'", UnmatchedArgumentException.class, "-y", "3", "-z");
}
@Test
public void testMultiValueOptionCanBeConfiguredToConsumeUnknownOption() {
class App {
@Option(names = "-x") int x;
@Option(names = "-y") String[] y;
}
App app = new App();
new CommandLine(app).setUnmatchedOptionsAllowedAsOptionParameters(true).parseArgs("-y", "-z");
assertArrayEquals(new String[]{"-z"}, app.y);
// arity=1 for multi-value options
CommandLine cmd = new CommandLine(new App()).setUnmatchedOptionsAllowedAsOptionParameters(true);
expect(cmd, "Unknown option: '-z'", UnmatchedArgumentException.class, "-y", "3", "-z");
}
@Test
public void testMultiValueOptionArity2DoesNotConsumeUnknownOptionByDefault() {
class App {
@Option(names = "-x") int x;
@Option(names = "-y", arity = "2") String[] y;
}
CommandLine cmd = new CommandLine(new App());
expect(cmd, "option '-y' at index 0 (<y>) requires at least 2 values, but only 1 were specified: [-z]",
MissingParameterException.class, "-y", "-z");
cmd.setUnmatchedOptionsAllowedAsOptionParameters(false);
expect(cmd, "Unknown option: '-z'; Expected parameter 2 (of 2 mandatory parameters) for option '-y' but found '-z'",
UnmatchedArgumentException.class, "-y", "3", "-z");
}
@Test
public void testMultiValueOptionArity2CanBeConfiguredToConsumeUnknownOptions() {
class App {
@Option(names = "-x") int x;
@Option(names = "-y", arity = "2") String[] y;
}
CommandLine cmd = new CommandLine(new App()).setUnmatchedOptionsAllowedAsOptionParameters(true);
expect(cmd, "option '-y' at index 0 (<y>) requires at least 2 values, but only 1 were specified: [-z]",
MissingParameterException.class, "-y", "-z");
App app = new App();
new CommandLine(app).setUnmatchedOptionsAllowedAsOptionParameters(true).parseArgs("-y", "3", "-z");
assertArrayEquals(new String[]{"3", "-z"}, app.y);
}
@Test
public void testMultiValueOptionArity2_NDoesNotConsumeUnknownOptionsByDefault() {
class App {
@Option(names = "-x") int x;
@Option(names = "-y", arity = "2..N") String[] y;
}
CommandLine cmd = new CommandLine(new App());
cmd.setUnmatchedOptionsAllowedAsOptionParameters(false);
expect(cmd, "option '-y' at index 0 (<y>) requires at least 2 values, but only 1 were specified: [-z]",
MissingParameterException.class, "-y", "-z");
expect(cmd, "Unknown option: '-z'; Expected parameter 2 (of 2 mandatory parameters) for option '-y' but found '-z'",
UnmatchedArgumentException.class, "-y", "1", "-z");
expect(cmd, "Unknown option: '-z'; Expected parameter 3 (of 2 mandatory parameters) for option '-y' but found '-z'",
UnmatchedArgumentException.class, "-y", "1", "2", "-z");
}
@Test
public void testMultiValueOptionArity2_NCanBeConfiguredToConsumeUnknownOption() {
class App {
@Option(names = "-x") int x;
@Option(names = "-y", arity = "2..N") String[] y;
}
CommandLine cmd = new CommandLine(new App()).setUnmatchedOptionsAllowedAsOptionParameters(true);
expect(cmd, "option '-y' at index 0 (<y>) requires at least 2 values, but only 1 were specified: [-z]",
MissingParameterException.class, "-y", "-z");
App app = new App();
new CommandLine(app).setUnmatchedOptionsAllowedAsOptionParameters(true).parseArgs("-y", "1", "-z");
assertArrayEquals(new String[]{"1", "-z"}, app.y);
app = new App();
new CommandLine(app).setUnmatchedOptionsAllowedAsOptionParameters(true).parseArgs("-y", "1", "2", "-z");
assertArrayEquals(new String[]{"1", "2", "-z"}, app.y);
}
@Test
public void testMultiValueVarArgOptionDoesNotConsumeUnknownOptionsByDefault() {
class App {
@Option(names = "-x") int x;
@Option(names = "-y", arity = "*") String[] y;
}
CommandLine cmd = new CommandLine(new App());
cmd.setUnmatchedOptionsAllowedAsOptionParameters(false);
expect(cmd, "Unknown option: '-z'; Expected parameter for option '-y' but found '-z'", UnmatchedArgumentException.class, "-y", "-z");
expect(cmd, "Unknown option: '-z'; Expected parameter for option '-y' but found '-z'", UnmatchedArgumentException.class, "-y", "3", "-z");
}
@Test
public void testMultiValueVarArgOptionCanBeConfiguredToConsumeUnknownOption() {
class App {
@Option(names = "-x") int x;
@Option(names = "-y", arity = "*") String[] y;
}
App app = new App();
new CommandLine(app).setUnmatchedOptionsAllowedAsOptionParameters(true).parseArgs("-y", "-z");
assertArrayEquals(new String[]{"-z"}, app.y);
app = new App();
new CommandLine(app).setUnmatchedOptionsAllowedAsOptionParameters(true).parseArgs("-y", "3", "-z");
assertArrayEquals(new String[]{"3", "-z"}, app.y);
}
@Test //#639
public void testUnknownOptionAsOptionValue() {
class App {
@Option(names = {"-x", "--xvalue"})
String x;
@Option(names = {"-y", "--yvalues"}, arity = "1")
List<String> y;
}
App app = new App();
CommandLine cmd = new CommandLine(app).setUnmatchedOptionsAllowedAsOptionParameters(true);
cmd.parseArgs("-x", "-unknown");
assertEquals("-unknown", app.x);
cmd.parseArgs("-y", "-unknown");
assertEquals(Arrays.asList("-unknown"), app.y);
cmd = new CommandLine(new App());
cmd.setUnmatchedOptionsAllowedAsOptionParameters(false);
expect(cmd, "Unknown option: '-unknown'; Expected parameter for option '--xvalue' but found '-unknown'", UnmatchedArgumentException.class, "-x", "-unknown");
expect(cmd, "Unknown option: '-unknown'; Expected parameter for option '--yvalues' but found '-unknown'", UnmatchedArgumentException.class, "-y", "-unknown");
}
static class LenientShortConverter implements CommandLine.ITypeConverter<Short> {
public Short convert(String value) {
return Short.decode(value); // allow octal values "-#123"
}
}
static class LenientLongConverter implements CommandLine.ITypeConverter<Long> {
public Long convert(String value) {
return Long.decode(value); // allow hex values "-0xABCDEF"
}
}
@Test //#639
public void testNegativeNumbersAreNotUnknownOption() {
class App {
@Option(names = {"-i", "--int"})
int i;
@Option(names = {"-s", "--short"}, converter = LenientShortConverter.class)
short s;
@Option(names = {"-L", "--long"}, converter = LenientLongConverter.class)
long L;
@Option(names = {"-d", "--double"})
double d;
@Option(names = {"-f", "--float"})
float f;
@Option(names = {"-x", "--xvalue"})
String x;
@Option(names = {"-y", "--yvalues"}, arity = "1")
List<String> y;
}
App app = new App();
CommandLine cmd = new CommandLine(app).setUnmatchedOptionsAllowedAsOptionParameters(true);
String[] args = {"-i", "-1", "-s", "-#55", "-L", "-0xCAFEBABE", "-d", "-Infinity", "-f", "-NaN", "-x", "-2", "-y", "-3", "-y", "-0", "-y", "-0.0", "-y", "-NaN"};
cmd.parseArgs(args);
assertEquals(-1, app.i);
assertEquals(-0x55, app.s);
assertEquals(-0xCAFEBABEL, app.L);
assertEquals(Double.NEGATIVE_INFINITY, app.d, 0);
assertEquals(Float.NaN, app.f, 0);
assertEquals("-2", app.x);
assertEquals(Arrays.asList("-3", "-0", "-0.0", "-NaN"), app.y);
cmd = new CommandLine(new App());
cmd.setUnmatchedOptionsAllowedAsOptionParameters(false);
cmd.parseArgs(args);
assertEquals(-1, app.i);
assertEquals(-0x55, app.s);
assertEquals(-0xCAFEBABEL, app.L);
assertEquals(Double.NEGATIVE_INFINITY, app.d, 0);
assertEquals(Float.NaN, app.f, 0);
assertEquals("-2", app.x);
assertEquals(Arrays.asList("-3", "-0", "-0.0", "-NaN"), app.y);
}
@Ignore("#1125")
@Test // https://github.com/remkop/picocli/issues/1125
public void testSubcommandAsOptionValue() {
@Command(name = "app")
class App {
@Option(names = "-x") String x;
@Command
public int search() {
return 123;
}
}
ParseResult parseResult = new CommandLine(new App()).parseArgs("-x", "search", "search");
assertEquals("search", parseResult.matchedOptionValue("-x", null));
assertTrue(parseResult.hasSubcommand());
}
}
| 10,262 |
852 |
<gh_stars>100-1000
#include "TGLViewer.h"
#include "TEveManager.h"
#include "Fireworks/Core/interface/FWEventAnnotation.h"
#include "Fireworks/Core/interface/FWGUIManager.h"
#include "Fireworks/Core/interface/BuilderUtils.h"
#include "Fireworks/Core/interface/FWConfiguration.h"
#include "DataFormats/FWLite/interface/Event.h"
FWEventAnnotation::FWEventAnnotation(TGLViewerBase* view) : TGLAnnotation(view, "Event Info", 0.05, 0.95), m_level(1) {
SetRole(TGLOverlayElement::kViewer);
SetUseColorSet(true);
fAllowClose = false;
}
FWEventAnnotation::~FWEventAnnotation() {}
//______________________________________________________________________________
void FWEventAnnotation::setLevel(long x) {
if (x != m_level) {
m_level = x;
fParent->Changed();
gEve->Redraw3D();
}
updateOverlayText();
}
void FWEventAnnotation::setEvent() { updateOverlayText(); }
void FWEventAnnotation::updateOverlayText() {
fText = "CMS Experiment at LHC, CERN";
const edm::EventBase* event = FWGUIManager::getGUIManager()->getCurrentEvent();
if (event && m_level) {
fText += "\nData recorded: ";
fText += fireworks::getLocalTime(*event);
fText += "\nRun/Event: ";
fText += event->id().run();
fText += " / ";
fText += event->id().event();
if (m_level > 1) {
fText += "\nLumi section: ";
fText += event->luminosityBlock();
}
if (m_level > 2) {
fText += "\nOrbit/Crossing: ";
fText += event->orbitNumber();
fText += " / ";
fText += event->bunchCrossing();
}
}
if (m_level) {
fParent->Changed();
gEve->Redraw3D();
}
}
void FWEventAnnotation::Render(TGLRnrCtx& rnrCtx) {
if (m_level)
TGLAnnotation::Render(rnrCtx);
}
//______________________________________________________________________________
void FWEventAnnotation::addTo(FWConfiguration& iTo) const {
std::stringstream s;
s << fTextSize;
iTo.addKeyValue("EventInfoTextSize", FWConfiguration(s.str()));
std::stringstream x;
x << fPosX;
iTo.addKeyValue("EventInfoPosX", FWConfiguration(x.str()));
std::stringstream y;
y << fPosY;
iTo.addKeyValue("EventInfoPosY", FWConfiguration(y.str()));
}
void FWEventAnnotation::setFrom(const FWConfiguration& iFrom) {
const FWConfiguration* value;
value = iFrom.valueForKey("EventInfoTextSize");
if (value)
fTextSize = atof(value->value().c_str());
value = iFrom.valueForKey("EventInfoPosX");
if (value)
fPosX = atof(value->value().c_str());
value = iFrom.valueForKey("EventInfoPosY");
if (value)
fPosY = atof(value->value().c_str());
}
| 982 |
1,172 |
// Copyright (C) 2008 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.caja.util;
import java.util.Locale;
import javax.annotation.Nullable;
import javax.annotation.ParametersAreNonnullByDefault;
/**
* Locale independent versions of String case-insensitive operations.
* <p>
* The normal case insensitive operators {@link String#toLowerCase}
* and {@link String#equalsIgnoreCase} depend upon the current locale.
* In the Turkish locale, uppercasing "i" yields a dotted I "\u0130",
* and lowercasing "I" yields a dotless i "\u0131".
* <p>
* These are convenience methods for avoiding that problem.
* <p>
* Note, regex matching does not have this problem, because
* Pattern.CASE_INSENSITIVE is ascii-only case folding unless you
* also ask for Pattern.UNICODE_CASE.
* <p>
* @author <EMAIL>, <EMAIL>
*/
@ParametersAreNonnullByDefault
public final class Strings {
/* Avoids Turkish 'i' problem. */
public static boolean eqIgnoreCase(@Nullable String a, @Nullable String b) {
if (a == null) { return b == null; }
if (b == null) { return false; }
return lower(a).equals(lower(b));
}
/** Avoids Turkish 'i' problem. */
public static String lower(String s) {
return s.toLowerCase(Locale.ENGLISH);
}
/** Avoids Turkish 'i' problem. */
public static String upper(String s) {
return s.toUpperCase(Locale.ENGLISH);
}
private Strings() { /* uninstantiable */ }
}
| 597 |
352 |
<reponame>sivanag1974/t-vault
package com.tmobile.cso.vault.api.model;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.io.Serializable;
public class SSLCertMetadataResponse implements Serializable {
private static final long serialVersionUID = -3967795703312263611L;
@JsonProperty("data")
private SSLCertificateMetadataDetails sslCertificateMetadataDetails;
public SSLCertMetadataResponse() {
super();
}
public SSLCertMetadataResponse(SSLCertificateMetadataDetails sslCertificateMetadataDetails) {
this.sslCertificateMetadataDetails = sslCertificateMetadataDetails;
}
public SSLCertificateMetadataDetails getSslCertificateMetadataDetails() {
return sslCertificateMetadataDetails;
}
public void setSslCertificateMetadataDetails(SSLCertificateMetadataDetails sslCertificateMetadataDetails) {
this.sslCertificateMetadataDetails = sslCertificateMetadataDetails;
}
@Override
public String toString() {
return "SSLCertMetadataResponse{" +
"sslCertificateMetadataDetails=" + sslCertificateMetadataDetails +
'}';
}
}
| 415 |
365 |
<reponame>groupon/grox<filename>grox-core-rx2/src/main/java/com/groupon/grox/rxjava2/StoreOnSubscribe.java
/*
* Copyright (c) 2017, Groupon, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.groupon.grox.rxjava2;
import com.groupon.grox.Store;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Cancellable;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* Internal subscriber to a store's observable. It basically allows to unsubscribe from the store
* when the observable is disposed.
*
* @param <STATE> the class of the the state of the store.
*/
final class StoreOnSubscribe<STATE> implements ObservableOnSubscribe<STATE> {
private final Store<STATE> store;
StoreOnSubscribe(Store<STATE> store) {
this.store = store;
}
@Override
public void subscribe(ObservableEmitter<STATE> emitter) throws Exception {
//the internal listener to the store.
Store.StateChangeListener<STATE> listener =
emitter::onNext;
emitter.setCancellable(() -> store.unsubscribe(listener));
store.subscribe(listener);
}
}
| 513 |
2,783 |
<filename>website/i18n/en.json
{
"_comment": "This file is auto-generated by write-translations.js",
"localized-strings": {
"next": "Next",
"previous": "Previous",
"tagline": "A minimal WebAssembly virtual DOM to build C++ SPA",
"boolean-attributes": "Boolean Attributes",
"cpp": "cpp",
"children": "Children",
"comments": "Comments",
"elements": "Elements",
"cpx-fragments": "Fragments",
"introduction": "Introduction",
"tag-attributes": "Tag Attributes",
"deleteVNode": "deleteVNode",
"examples": "Examples",
"fragments": "Fragments",
"h": "h",
"init": "init",
"inline-example": "Inline example",
"installation": "Installation",
"js": "js",
"memory-management": "Memory Management",
"motivation": "Motivation",
"patch": "patch",
"ref": "Ref",
"server-side-rendering": "Server Side Rendering",
"string-encoding": "String Encoding",
"structuring-applications": "Structuring Applications",
"svg": "SVG",
"toHTML": "toHTML",
"toVNode": "toVNode",
"webcomponents": "Web Components",
"Docs": "Docs",
"API": "API",
"GitHub": "GitHub",
"Introduction": "Introduction",
"Guides": "Guides",
"API Reference": "API Reference",
"CPX syntax": "CPX syntax"
},
"pages-strings": {
"Help Translate|recruit community translators for your project": "Help Translate",
"Edit this Doc|recruitment message asking to edit the doc source": "Edit",
"Translate this Doc|recruitment message asking to translate the docs": "Translate"
}
}
| 596 |
338 |
<gh_stars>100-1000
package io.grpc.grpcswagger.store;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import com.google.common.collect.ImmutableMap;
/**
* @author <NAME>
* @date 2019-08-24
*/
public class MapStorage<K, V> implements BaseStorage<K, V> {
private final Map<K, V> map = new ConcurrentHashMap<>();
@Override
public void put(K key, V value) {
map.put(key, value);
}
@Override
public V get(K key) {
return map.get(key);
}
@Override
public void remove(K key) {
map.remove(key);
}
@Override
public boolean exists(K key) {
return map.containsKey(key);
}
@Override
public ImmutableMap<K, V> getAll() {
return ImmutableMap.copyOf(map);
}
}
| 353 |
2,706 |
<reponame>MatPoliquin/retro
/* 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/. */
#pragma once
#include "Override.h"
#include <QMap>
#include <QObject>
#include <QSettings>
#include <QVariant>
#include <functional>
#include <mgba/core/config.h>
#include <mgba-util/configuration.h>
#include <mgba/feature/commandline.h>
class QAction;
class QMenu;
struct mArguments;
struct GBACartridgeOverride;
namespace QGBA {
class ConfigOption : public QObject {
Q_OBJECT
public:
ConfigOption(QObject* parent = nullptr);
void connect(std::function<void(const QVariant&)>, QObject* parent = nullptr);
QAction* addValue(const QString& text, const QVariant& value, QMenu* parent = nullptr);
QAction* addValue(const QString& text, const char* value, QMenu* parent = nullptr);
QAction* addBoolean(const QString& text, QMenu* parent = nullptr);
public slots:
void setValue(bool value);
void setValue(int value);
void setValue(unsigned value);
void setValue(const char* value);
void setValue(const QVariant& value);
signals:
void valueChanged(const QVariant& value);
private:
QMap<QObject*, std::function<void(const QVariant&)>> m_slots;
QList<QPair<QAction*, QVariant>> m_actions;
};
class ConfigController : public QObject {
Q_OBJECT
public:
constexpr static const char* const PORT = "qt";
static const int MRU_LIST_SIZE = 10;
ConfigController(QObject* parent = nullptr);
~ConfigController();
const mCoreOptions* options() const { return &m_opts; }
bool parseArguments(mArguments* args, int argc, char* argv[], mSubParser* subparser = nullptr);
ConfigOption* addOption(const char* key);
void updateOption(const char* key);
QString getOption(const char* key, const QVariant& defaultVal = QVariant()) const;
QString getOption(const QString& key, const QVariant& defaultVal = QVariant()) const;
QVariant getQtOption(const QString& key, const QString& group = QString()) const;
QList<QString> getMRU() const;
void setMRU(const QList<QString>& mru);
Configuration* overrides() { return mCoreConfigGetOverrides(&m_config); }
void saveOverride(const Override&);
Configuration* input() { return mCoreConfigGetInput(&m_config); }
const mCoreConfig* config() { return &m_config; }
static const QString& configDir();
public slots:
void setOption(const char* key, bool value);
void setOption(const char* key, int value);
void setOption(const char* key, unsigned value);
void setOption(const char* key, const char* value);
void setOption(const char* key, const QVariant& value);
void setQtOption(const QString& key, const QVariant& value, const QString& group = QString());
void makePortable();
void write();
private:
Configuration* defaults() { return &m_config.defaultsTable; }
mCoreConfig m_config;
mCoreOptions m_opts{};
QMap<QString, ConfigOption*> m_optionSet;
QSettings* m_settings;
static QString s_configDir;
};
}
| 1,019 |
575 |
<filename>chrome/android/javatests/src/org/chromium/chrome/browser/multiwindow/MultiWindowTestHelper.java
// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.chrome.browser.multiwindow;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import androidx.annotation.Nullable;
import org.hamcrest.Matchers;
import org.junit.Assert;
import org.chromium.base.ActivityState;
import org.chromium.base.ApplicationStatus;
import org.chromium.base.ContextUtils;
import org.chromium.base.test.util.Criteria;
import org.chromium.base.test.util.CriteriaHelper;
import org.chromium.base.test.util.CriteriaNotSatisfiedException;
import org.chromium.chrome.browser.ChromeTabbedActivity;
import org.chromium.chrome.browser.ChromeTabbedActivity2;
import org.chromium.chrome.browser.tab.Tab;
import org.chromium.content_public.browser.LoadUrlParams;
import org.chromium.content_public.browser.test.util.TestThreadUtils;
import java.util.concurrent.atomic.AtomicReference;
/**
* Utilities helper class for multi-window tests.
*/
public class MultiWindowTestHelper {
/**
* Creates a new {@link ChromeTabbedActivity2} with no {@link LoadUrlParams}.
* @param activity A current running activity that will handle the intent to start another
* activity.
* @return The new {@link ChromeTabbedActivity2}.
*/
public static ChromeTabbedActivity2 createSecondChromeTabbedActivity(Activity activity) {
return createSecondChromeTabbedActivity(activity, null);
}
/**
* Creates a new {@link ChromeTabbedActivity2}.
* @param activity A current running activity that will handle the intent to start another
* activity.
* @param params {@link LoadUrlParams} used to create the launch intent. May be null if no
* params should be used when creating the activity.
* @return The new {@link ChromeTabbedActivity2}.
*/
public static ChromeTabbedActivity2 createSecondChromeTabbedActivity(
Activity activity, @Nullable LoadUrlParams params) {
// TODO(twellington): after there is test support for putting an activity into multi-window
// mode, this should be changed to use the menu item for opening a new window.
// Number of expected activities after the second ChromeTabbedActivity is created.
int numExpectedActivities = ApplicationStatus.getRunningActivities().size() + 1;
// Get the class name to use for the second ChromeTabbedActivity. This step is important
// for initializing things in MultiWindowUtils.java.
Class<? extends Activity> secondActivityClass =
MultiWindowUtils.getInstance().getOpenInOtherWindowActivity(activity);
Assert.assertEquals(
"ChromeTabbedActivity2 should be used as the 'open in other window' activity.",
ChromeTabbedActivity2.class, secondActivityClass);
// Create an intent and start the second ChromeTabbedActivity.
Intent intent;
if (params != null) {
intent = new Intent(Intent.ACTION_VIEW, Uri.parse(params.getUrl()));
} else {
intent = new Intent();
}
MultiWindowUtils.setOpenInOtherWindowIntentExtras(intent, activity, secondActivityClass);
MultiInstanceManager.onMultiInstanceModeStarted();
activity.startActivity(intent);
// Wait for ChromeTabbedActivity2 to be created.
CriteriaHelper.pollUiThread(() -> {
Criteria.checkThat(ApplicationStatus.getRunningActivities().size(),
Matchers.is(numExpectedActivities));
});
return waitForSecondChromeTabbedActivity();
}
/**
* Waits for an instance of ChromeTabbedActivity2, and then waits until it's resumed.
*/
public static ChromeTabbedActivity2 waitForSecondChromeTabbedActivity() {
AtomicReference<ChromeTabbedActivity2> returnActivity = new AtomicReference<>();
CriteriaHelper.pollUiThread(() -> {
for (Activity runningActivity : ApplicationStatus.getRunningActivities()) {
if (runningActivity.getClass().equals(ChromeTabbedActivity2.class)) {
returnActivity.set((ChromeTabbedActivity2) runningActivity);
return;
}
}
throw new CriteriaNotSatisfiedException(
"Couldn't find instance of ChromeTabbedActivity2");
});
waitUntilActivityResumed(returnActivity.get());
return returnActivity.get();
}
private static void waitUntilActivityResumed(final Activity activity) {
CriteriaHelper.pollUiThread(() -> {
Criteria.checkThat(ApplicationStatus.getStateForActivity(activity),
Matchers.is(ActivityState.RESUMED));
});
}
/**
* Moves the given activity to the foreground so it can receive user input.
*/
@TargetApi(Build.VERSION_CODES.N)
public static void moveActivityToFront(final Activity activity) {
TestThreadUtils.runOnUiThreadBlocking(() -> {
Context context = ContextUtils.getApplicationContext();
ActivityManager activityManager =
(ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
for (ActivityManager.AppTask task : activityManager.getAppTasks()) {
if (activity.getTaskId() == task.getTaskInfo().id) {
task.moveToFront();
break;
}
}
});
waitUntilActivityResumed(activity);
}
/**
* Waits until 'activity' has 'expectedTotalTabCount' total tabs, and its active tab has
* 'expectedActiveTabId' ID. 'expectedActiveTabId' is optional and can be Tab.INVALID_TAB_ID.
* 'tag' is an arbitrary string that is prepended to failure reasons.
*/
public static void waitForTabs(final String tag, final ChromeTabbedActivity activity,
final int expectedTotalTabCount, final int expectedActiveTabId) {
CriteriaHelper.pollUiThread(() -> {
int actualTotalTabCount = activity.getTabModelSelector().getTotalTabCount();
Criteria.checkThat(actualTotalTabCount, Matchers.is(expectedTotalTabCount));
});
if (expectedActiveTabId == Tab.INVALID_TAB_ID) return;
CriteriaHelper.pollUiThread(() -> {
int actualActiveTabId = activity.getActivityTab().getId();
Criteria.checkThat(actualActiveTabId, Matchers.is(expectedActiveTabId));
});
}
}
| 2,528 |
6,717 |
// $Id: QuadDemo.java,v 1.8 1999/12/16 02:10:05 gjb Exp $
//
// Cassowary Incremental Constraint Solver
// Original Smalltalk Implementation by <NAME>
// This Java Implementation by <NAME>, <<EMAIL>>
// http://www.cs.washington.edu/homes/gjb
// (c) 1998, 1999 <NAME>, <NAME>, and <NAME>.
// See ../../LICENSE for legal details regarding this software
//
// Implementation of the QuadDemo
// By <NAME>, 8 Feb 1998
// Port of QuadDemo made more like the C++ version -- gjb, 13 Feb 1998
//
// QuadDemo.java
package EDU.Washington.grad.gjb.cassowary_demos;
import java.awt.*;
import java.applet.*;
import java.util.Vector;
import EDU.Washington.grad.gjb.cassowary.*;
public class QuadDemo extends Applet {
DraggableBox db[]; // Line endpoints
DraggableBox mp[]; // Midpoints
int dbDragging; // Which db is being dragged? -1 for none
ClSimplexSolver solver;
public void init() {
solver = new ClSimplexSolver();
dbDragging = -1;
db = new DraggableBox[8];
mp = new DraggableBox[4];
int a;
for ( a = 0; a < 8; a++ )
db[a] = new DraggableBox(a);
for ( a = 0; a < 4; a++ )
mp[a] = db[a+4];
db[0].SetCenter(5, 5);
db[1].SetCenter(5, 200);
db[2].SetCenter(200, 200);
db[3].SetCenter(200, 5);
// Add constraints
try {
// Add stay constraints on line endpoints
solver.addPointStay(db[0].CenterPt(), 1.0);
solver.addPointStay(db[1].CenterPt(), 2.0);
solver.addPointStay(db[2].CenterPt(), 4.0);
solver.addPointStay(db[3].CenterPt(), 8.0);
ClLinearExpression cle;
ClLinearEquation cleq;
// Add constraints to keep midpoints at line midpoints
cle = new ClLinearExpression(db[0].X());
cle = (cle.plus(db[1].X())).divide(2);
cleq = new ClLinearEquation(mp[0].X(), cle);
// System.out.println("Adding " + cleq);
solver.addConstraint(cleq);
cle = new ClLinearExpression(db[0].Y());
cle = (cle.plus(db[1].Y())).divide(2);
cleq = new ClLinearEquation(mp[0].Y(), cle);
// System.out.println("Adding " + cleq);
solver.addConstraint(cleq);
cle = new ClLinearExpression(db[1].X());
cle = (cle.plus(db[2].X())).divide(2);
cleq = new ClLinearEquation(mp[1].X(), cle);
// System.out.println("Adding " + cleq);
solver.addConstraint(cleq);
cle = new ClLinearExpression(db[1].Y());
cle = (cle.plus(db[2].Y())).divide(2);
cleq = new ClLinearEquation(mp[1].Y(), cle);
// System.out.println("Adding " + cleq);
solver.addConstraint(cleq);
cle = new ClLinearExpression(db[2].X());
cle = (cle.plus(db[3].X())).divide(2);
cleq = new ClLinearEquation(mp[2].X(), cle);
// System.out.println("Adding " + cleq);
solver.addConstraint(cleq);
cle = new ClLinearExpression(db[2].Y());
cle = (cle.plus(db[3].Y())).divide(2);
cleq = new ClLinearEquation(mp[2].Y(), cle);
// System.out.println("Adding " + cleq);
solver.addConstraint(cleq);
cle = new ClLinearExpression(db[3].X());
cle = (cle.plus(db[0].X())).divide(2);
cleq = new ClLinearEquation(mp[3].X(), cle);
// System.out.println("Adding " + cleq);
solver.addConstraint(cleq);
cle = new ClLinearExpression(db[3].Y());
cle = (cle.plus(db[0].Y())).divide(2);
cleq = new ClLinearEquation(mp[3].Y(), cle);
// System.out.println("Adding " + cleq);
solver.addConstraint(cleq);
cle = CL.Plus(db[0].X(),10);
solver
.addConstraint(new ClLinearInequality(cle,CL.LEQ,db[2].X()))
.addConstraint(new ClLinearInequality(cle,CL.LEQ,db[3].X()));
cle = CL.Plus(db[1].X(),10);
solver
.addConstraint(new ClLinearInequality(cle,CL.LEQ,db[2].X()))
.addConstraint(new ClLinearInequality(cle,CL.LEQ,db[3].X()));
cle = CL.Plus(db[0].Y(),10);
solver
.addConstraint(new ClLinearInequality(cle,CL.LEQ,db[1].Y()))
.addConstraint(new ClLinearInequality(cle,CL.LEQ,db[2].Y()));
cle = CL.Plus(db[3].Y(),10);
solver
.addConstraint(new ClLinearInequality(cle,CL.LEQ,db[1].Y()))
.addConstraint(new ClLinearInequality(cle,CL.LEQ,db[2].Y()));
int width = getSize().width;
int height = getSize().height;
// Add constraints to keep points inside window
solver.addConstraint(new ClLinearInequality(db[0].X(), CL.GEQ, 0.0));
solver.addConstraint(new ClLinearInequality(db[0].Y(), CL.GEQ, 0.0));
solver.addConstraint(new ClLinearInequality(db[1].X(), CL.GEQ, 0.0));
solver.addConstraint(new ClLinearInequality(db[1].Y(), CL.GEQ, 0.0));
solver.addConstraint(new ClLinearInequality(db[2].X(), CL.GEQ, 0.0));
solver.addConstraint(new ClLinearInequality(db[2].Y(), CL.GEQ, 0.0));
solver.addConstraint(new ClLinearInequality(db[3].X(), CL.GEQ, 0.0));
solver.addConstraint(new ClLinearInequality(db[3].Y(), CL.GEQ, 0.0));
solver.addConstraint(new ClLinearInequality(db[0].X(), CL.LEQ, width));
solver.addConstraint(new ClLinearInequality(db[0].Y(), CL.LEQ, height));
solver.addConstraint(new ClLinearInequality(db[1].X(), CL.LEQ, width));
solver.addConstraint(new ClLinearInequality(db[1].Y(), CL.LEQ, height));
solver.addConstraint(new ClLinearInequality(db[2].X(), CL.LEQ, width));
solver.addConstraint(new ClLinearInequality(db[2].Y(), CL.LEQ, height));
solver.addConstraint(new ClLinearInequality(db[3].X(), CL.LEQ, width));
solver.addConstraint(new ClLinearInequality(db[3].Y(), CL.LEQ, height));
} catch (ExCLInternalError e) {
System.out.println("constructor: CLInternalError!");
} catch (ExCLRequiredFailure e) {
System.out.println("constructor: CLRequiredFailure!");
} catch (ExCLNonlinearExpression e) {
System.out.println("constructor: CLNonlinearExpression!");
}
}
public QuadDemo() {
super();
}
// Event handlers
public boolean mouseDown(Event e, int x, int y) {
for ( int a = 0; a < db.length; a++ ) {
if ( db[a].Contains(x, y) ) {
dbDragging = a;
// System.err.println("dragging " + a);
break;
}
}
repaint();
if ( dbDragging != -1 ) {
try {
solver
.addEditVar(db[dbDragging].X())
.addEditVar(db[dbDragging].Y())
.beginEdit();
} catch (ExCLInternalError ex) {
System.err.println("mouseDown: CLInternalError!");
System.err.println(ex.description());
}
}
return true;
}
public boolean mouseUp(Event e, int x, int y) {
if ( dbDragging != -1 ) {
try {
dbDragging = -1;
solver.endEdit();
repaint();
} catch (ExCLInternalError ex) {
System.err.println("mouseUp: CLInternalError!");
System.err.println(ex.description());
}
}
return true;
}
public boolean mouseDrag(Event e, int x, int y) {
if ( dbDragging != -1 ) {
try {
solver
.suggestValue(db[dbDragging].X(),x)
.suggestValue(db[dbDragging].Y(),y)
.resolve();
} catch (ExCLInternalError ex) {
System.out.println("mouseDrag: CLInternalError!");
} catch (ExCLError ex) {
System.out.println("mouseDrag: CLError!");
}
repaint();
}
return true;
}
// Paint the display
public void paint(Graphics g) {
g.drawLine((int) db[0].CenterX(), (int) db[0].CenterY(),
(int) db[1].CenterX(), (int) db[1].CenterY());
g.drawLine((int) db[1].CenterX(), (int) db[1].CenterY(),
(int) db[2].CenterX(), (int) db[2].CenterY());
g.drawLine((int) db[2].CenterX(), (int) db[2].CenterY(),
(int) db[3].CenterX(), (int) db[3].CenterY());
g.drawLine((int) db[3].CenterX(), (int) db[3].CenterY(),
(int) db[0].CenterX(), (int) db[0].CenterY());
// Connecting lines
g.drawLine((int) mp[0].CenterX(), (int) mp[0].CenterY(),
(int) mp[1].CenterX(), (int) mp[1].CenterY());
g.drawLine((int) mp[1].CenterX(), (int) mp[1].CenterY(),
(int) mp[2].CenterX(), (int) mp[2].CenterY());
g.drawLine((int) mp[2].CenterX(), (int) mp[2].CenterY(),
(int) mp[3].CenterX(), (int) mp[3].CenterY());
g.drawLine((int) mp[3].CenterX(), (int) mp[3].CenterY(),
(int) mp[0].CenterX(), (int) mp[0].CenterY());
// Control points
for ( int a = 0; a < 8; a++ )
db[a].draw(g);
if ( dbDragging != -1 ) {
g.setColor(Color.blue);
db[dbDragging].draw(g);
g.setColor(Color.black);
}
g.setColor(Color.black);
}
public static void main(String[] argv) {
System.err.println("Run using `appletviewer quaddemo.htm'");
}
}
| 4,015 |
632 |
<filename>app/src/test/java/me/vickychijwani/spectre/testing/EventBusRule.java<gh_stars>100-1000
package me.vickychijwani.spectre.testing;
import org.junit.rules.TestRule;
import org.junit.runner.Description;
import org.junit.runners.model.Statement;
import me.vickychijwani.spectre.event.BusProvider;
public class EventBusRule implements TestRule {
@Override
public Statement apply(Statement base, Description description) {
return new Statement() {
@Override
public void evaluate() throws Throwable {
BusProvider.setupForTesting();
base.evaluate();
}
};
}
}
| 264 |
1,085 |
/*
* Copyright (C) 2017-2019 Dremio Corporation
*
* 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.dremio.service.nessie;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyString;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.InOrder;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.projectnessie.error.NessieConflictException;
import org.projectnessie.error.NessieNotFoundException;
import org.projectnessie.model.Contents;
import org.projectnessie.model.IcebergTable;
import org.projectnessie.model.ImmutableIcebergTable;
import org.projectnessie.services.rest.ContentsResource;
import com.dremio.service.nessieapi.ContentsKey;
import com.dremio.service.nessieapi.GetContentsRequest;
import com.dremio.service.nessieapi.SetContentsRequest;
import com.google.common.collect.Lists;
import io.grpc.Status;
import io.grpc.StatusRuntimeException;
import io.grpc.stub.StreamObserver;
/**
* Unit tests for the ContentsApiService
*/
@RunWith(MockitoJUnitRunner.class)
public class TestContentsApiService {
private ContentsApiService contentsApiService;
@Mock private ContentsResource contentsResource;
@Before
public void setup() {
contentsApiService = new ContentsApiService(() -> contentsResource);
}
@Test
public void getContentsFound() throws Exception {
final ContentsKey contentsKey = ContentsKey.newBuilder().addElements("a").addElements("b").build();
final org.projectnessie.model.ContentsKey nessieContentsKey = org.projectnessie.model.ContentsKey.of("a", "b");
final GetContentsRequest request = GetContentsRequest
.newBuilder()
.setContentsKey(contentsKey)
.setRef("foo")
.build();
final Contents contents = ImmutableIcebergTable.builder().metadataLocation("here").build();
when(contentsResource.getContents(nessieContentsKey, "foo")).thenReturn(contents);
StreamObserver responseObserver = mock(StreamObserver.class);
contentsApiService.getContents(request, responseObserver);
final InOrder inOrder = inOrder(responseObserver);
final ArgumentCaptor<com.dremio.service.nessieapi.Contents> contentsCaptor =
ArgumentCaptor.forClass(com.dremio.service.nessieapi.Contents.class);
inOrder.verify(responseObserver).onNext(contentsCaptor.capture());
final com.dremio.service.nessieapi.Contents actualContents = contentsCaptor.getValue();
assertEquals(com.dremio.service.nessieapi.Contents.Type.ICEBERG_TABLE, actualContents.getType());
assertEquals("here", actualContents.getIcebergTable().getMetadataLocation());
inOrder.verify(responseObserver).onCompleted();
}
@Test
public void getContentsNotFound() throws NessieNotFoundException {
final ContentsKey contentsKey = ContentsKey.newBuilder().addElements("a").addElements("b").build();
final org.projectnessie.model.ContentsKey nessieContentsKey = org.projectnessie.model.ContentsKey.of("a", "b");
final GetContentsRequest request = GetContentsRequest
.newBuilder()
.setContentsKey(contentsKey)
.setRef("foo")
.build();
when(contentsResource.getContents(nessieContentsKey, "foo")).thenThrow(new NessieNotFoundException("Not found"));
final StreamObserver responseObserver = mock(StreamObserver.class);
contentsApiService.getContents(request, responseObserver);
final ArgumentCaptor<Throwable> errorCaptor = ArgumentCaptor.forClass(Throwable.class);
verify(responseObserver).onError(errorCaptor.capture());
final StatusRuntimeException status = (StatusRuntimeException) errorCaptor.getValue();
assertEquals(Status.NOT_FOUND.getCode(), status.getStatus().getCode());
}
@Test
public void getContentsUnexpectedException() throws NessieNotFoundException {
final ContentsKey contentsKey = ContentsKey.newBuilder().addElements("a").addElements("b").build();
final org.projectnessie.model.ContentsKey nessieContentsKey = org.projectnessie.model.ContentsKey.of("a", "b");
final GetContentsRequest request = GetContentsRequest
.newBuilder()
.setContentsKey(contentsKey)
.setRef("foo")
.build();
when(contentsResource.getContents(nessieContentsKey, "foo")).thenThrow(new RuntimeException("Not found"));
final StreamObserver responseObserver = mock(StreamObserver.class);
contentsApiService.getContents(request, responseObserver);
final ArgumentCaptor<Throwable> errorCaptor = ArgumentCaptor.forClass(Throwable.class);
verify(responseObserver).onError(errorCaptor.capture());
final StatusRuntimeException status = (StatusRuntimeException) errorCaptor.getValue();
assertEquals(Status.UNKNOWN.getCode(), status.getStatus().getCode());
}
@Test
public void setContents() throws Exception {
final SetContentsRequest request = SetContentsRequest
.newBuilder()
.setBranch("foo")
.setHash("0011223344556677")
.setMessage("bar")
.setContentsKey(ContentsKey.newBuilder().addElements("a").addElements("b"))
.setContents(com.dremio.service.nessieapi.Contents
.newBuilder()
.setType(com.dremio.service.nessieapi.Contents.Type.ICEBERG_TABLE)
.setIcebergTable(com.dremio.service.nessieapi.Contents.IcebergTable.newBuilder().setMetadataLocation("here")))
.build();
StreamObserver responseObserver = mock(StreamObserver.class);
contentsApiService.setContents(request, responseObserver);
final ArgumentCaptor<org.projectnessie.model.ContentsKey> contentsKeyCaptor =
ArgumentCaptor.forClass(org.projectnessie.model.ContentsKey.class);
final ArgumentCaptor<Contents> contentsCaptor = ArgumentCaptor.forClass(Contents.class);
verify(contentsResource).setContents(
contentsKeyCaptor.capture(),
eq("foo"),
eq("0011223344556677"),
eq("bar"),
contentsCaptor.capture()
);
final org.projectnessie.model.ContentsKey actualContentsKey = contentsKeyCaptor.getValue();
assertEquals(Lists.newArrayList("a", "b"), actualContentsKey.getElements());
assertTrue(contentsCaptor.getValue() instanceof IcebergTable);
final IcebergTable icebergTable = (IcebergTable) contentsCaptor.getValue();
assertEquals("here", icebergTable.getMetadataLocation());
}
@Test
public void setContentsConflict() throws Exception {
final SetContentsRequest request = SetContentsRequest
.newBuilder()
.setBranch("foo")
.setHash("0011223344556677")
.setMessage("bar")
.setContentsKey(ContentsKey.newBuilder().addElements("a").addElements("b"))
.setContents(com.dremio.service.nessieapi.Contents
.newBuilder()
.setType(com.dremio.service.nessieapi.Contents.Type.ICEBERG_TABLE)
.setIcebergTable(com.dremio.service.nessieapi.Contents.IcebergTable.newBuilder().setMetadataLocation("here")))
.build();
doThrow(new NessieConflictException("foo")).when(contentsResource).setContents(
any(org.projectnessie.model.ContentsKey.class), anyString(), anyString(), anyString(), any(Contents.class));
final StreamObserver streamObserver = mock(StreamObserver.class);
contentsApiService.setContents(request, streamObserver);
final ArgumentCaptor<Throwable> errorCaptor = ArgumentCaptor.forClass(Throwable.class);
verify(streamObserver).onError(errorCaptor.capture());
StatusRuntimeException status = (StatusRuntimeException) errorCaptor.getValue();
assertEquals(Status.ABORTED.getCode(), status.getStatus().getCode());
}
@Test
public void setContentsUnexpectedException() throws Exception {
final SetContentsRequest request = SetContentsRequest
.newBuilder()
.setBranch("foo")
.setHash("0011223344556677")
.setMessage("bar")
.setContentsKey(ContentsKey.newBuilder().addElements("a").addElements("b"))
.setContents(com.dremio.service.nessieapi.Contents
.newBuilder()
.setType(com.dremio.service.nessieapi.Contents.Type.ICEBERG_TABLE)
.setIcebergTable(com.dremio.service.nessieapi.Contents.IcebergTable.newBuilder().setMetadataLocation("here")))
.build();
doThrow(new RuntimeException("foo")).when(contentsResource).setContents(
any(org.projectnessie.model.ContentsKey.class), anyString(), anyString(), anyString(), any(Contents.class));
final StreamObserver streamObserver = mock(StreamObserver.class);
contentsApiService.setContents(request, streamObserver);
final ArgumentCaptor<Throwable> errorCaptor = ArgumentCaptor.forClass(Throwable.class);
verify(streamObserver).onError(errorCaptor.capture());
StatusRuntimeException status = (StatusRuntimeException) errorCaptor.getValue();
assertEquals(Status.UNKNOWN.getCode(), status.getStatus().getCode());
}
}
| 3,215 |
665 |
<filename>testing/serial_procedure_test.py<gh_stars>100-1000
#
# serial_procedure_test.py
# mldb.ai inc, 2015
# this file is part of mldb. copyright 2015 mldb.ai inc. all rights reserved.
#
import time
from functools import reduce
from mldb import mldb, MldbUnitTest, ResponseException
class SerialProcedureTest(MldbUnitTest): # noqa
def test_deadloack(self):
# MLDB-621
try:
mldb.perform("PUT", "/v1/procedures/q", [], {
"type": "serial",
"params": {"steps": [{"id": "q", "type": "null"}]}
})
except Exception:
pass
def test_progress(self):
proc = {
'type' : 'mock',
'params' : {
'durationMs' : 900,
'refreshRateMs' : 100
}
}
res = mldb.post_async('/v1/procedures', {
'type' : "serial",
'params' : {
'steps' : [proc, proc, proc, proc, proc]
}
}).json()
proc_id = res['id']
run_id = res['status']['firstRun']['id']
time.sleep(0.5)
url = '/v1/procedures/{}/runs/{}'.format(proc_id, run_id)
res = mldb.get(url).json()
self.assertEqual(res['state'], 'executing')
self.assertTrue('subProgress' in res['progress'])
self.assertEqual(len(res['progress']['steps']), 5)
def reducer(x, y):
return x + y['value']
total1 = reduce(reducer, res['progress']['steps'], 0)
time.sleep(1)
res = mldb.get(url).json()
total2 = reduce(reducer, res['progress']['steps'], 0)
self.assertGreater(total2, total1)
if __name__ == '__main__':
mldb.run_tests()
| 886 |
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.openidconnect.protocol;
import org.apache.commons.lang3.Validate;
import com.vmware.identity.openidconnect.common.ParseException;
import com.vmware.identity.openidconnect.common.StatusCode;
/**
* @author <NAME>
*/
public abstract class TokenResponse extends ProtocolResponse {
public static TokenResponse parse(HttpResponse httpResponse) throws ParseException {
Validate.notNull(httpResponse, "httpResponse");
return (httpResponse.getStatusCode() == StatusCode.OK) ?
TokenSuccessResponse.parse(httpResponse) :
TokenErrorResponse.parse(httpResponse);
}
}
| 386 |
1,210 |
/*
Copyright 2005-2007 Adobe Systems Incorporated
Use, modification and distribution are subject to 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).
See http://opensource.adobe.com/gil for most recent version including documentation.
*/
/*************************************************************************************************/
#ifndef GIL_DEPRECATED_HPP
#define GIL_DEPRECATED_HPP
////////////////////////////////////////////////////////////////////////////////////////
/// \file
/// \brief Deprecated names
/// This file is provided as a courtesy to ease upgrading GIL client code.
/// Please make sure your code compiles when this file is not included.
///
/// \author <NAME> and <NAME> \n
/// Adobe Systems Incorporated
/// \date 2005-2007 \n Last updated on February 12, 2007
///
////////////////////////////////////////////////////////////////////////////////////////
#include <cstddef>
#define planar_ptr planar_pixel_iterator
#define planar_ref planar_pixel_reference
#define membased_2d_locator memory_based_2d_locator
#define pixel_step_iterator memory_based_step_iterator
#define pixel_image_iterator iterator_from_2d
#define equal_channels static_equal
#define copy_channels static_copy
#define fill_channels static_fill
#define generate_channels static_generate
#define for_each_channel static_for_each
#define transform_channels static_transform
#define max_channel static_max
#define min_channel static_min
#define semantic_channel semantic_at_c
template <typename Img>
void resize_clobber_image(Img& img, const typename Img::point_t& new_dims) {
img.recreate(new_dims);
}
template <typename Img>
void resize_clobber_image(Img& img, const typename Img::x_coord_t& width, const typename Img::y_coord_t& height) {
img.recreate(width,height);
}
template <typename T> typename T::x_coord_t get_width(const T& a) { return a.width(); }
template <typename T> typename T::y_coord_t get_height(const T& a) { return a.height(); }
template <typename T> typename T::point_t get_dimensions(const T& a) { return a.dimensions(); }
template <typename T> std::size_t get_num_channels(const T& a) { return a.num_channels(); }
#define GIL boost::gil
#define ADOBE_GIL_NAMESPACE_BEGIN namespace boost { namespace gil {
#define ADOBE_GIL_NAMESPACE_END } }
#define ByteAdvancableIteratorConcept MemoryBasedIteratorConcept
#define byte_advance memunit_advance
#define byte_advanced memunit_advanced
#define byte_step memunit_step
#define byte_distance memunit_distance
#define byte_addressable_step_iterator memory_based_step_iterator
#define byte_addressable_2d_locator memory_based_2d_locator
// These are members of memory-based locators
//#define row_bytes row_size // commented out because row_bytes is commonly used
#define pix_bytestep pixel_size
#endif
| 1,068 |
1,056 |
<filename>enterprise/j2ee.dd/test/unit/src/org/netbeans/modules/j2ee/dd/api/web/DDApiTest.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.netbeans.modules.j2ee.dd.api.web;
import org.netbeans.modules.j2ee.dd.api.common.InitParam;
import org.netbeans.modules.j2ee.dd.api.common.VersionNotSupportedException;
import org.netbeans.modules.j2ee.dd.api.common.NameAlreadyUsedException;
import java.io.*;
import junit.framework.*;
import org.netbeans.junit.*;
import org.openide.filesystems.*;
import java.util.*;
public class DDApiTest extends NbTestCase {
private static final String VERSION="3.0";
private static final int TIMEOUT=30;
private static final int WF_NUMBER=3;
private static final String SERVLET_NAME = "FordServlet";
private static final String SERVLET_CLASS = "org.package.mypackage.CarServlet";
private static final String SERVLET_NAME1 = "VolvoServlet";
private static final String[] URL_PATTERN = new String[]{"/ford"};
private static final String URL_PATTERN1 = "/volvo";
private static final java.math.BigInteger LOAD_ON_STARTUP = java.math.BigInteger.valueOf(10);
private static final java.math.BigInteger LOAD_ON_STARTUP1 = java.math.BigInteger.valueOf(25);
private static final String PARAM1 = "car";
private static final String VALUE1 = "Ford";
private static final String VALUE11 = "Volvo";
private static final String PARAM2 = "color";
private static final String VALUE2 = "red";
private static final String PARAM3 = "type";
private static final String VALUE3 = "Puma";
private static final String DESCRIPTION = "the color of the car";
private static final String DESCRIPTION_EN = "the colour of the car";
private static final String DESCRIPTION_DE = "die automobile farbe";
private static final String DESCRIPTION_CZ = "barva automobilu";
private static final String DESCRIPTION_SK = "farba automobilu";
private static final String URL_PATTERN_JSP = "*.jsp";
private static final String PRELUDE = "/jsp/prelude.jsp";
private static final String CODA = "/jsp/coda.jsp";
private static final String LARGE_ICON = "/img/icon32x32.gif";
private static final String SMALL_ICON = "/img/icon16x16.gif";
private WebApp webApp;
public DDApiTest(java.lang.String testName) {
super(testName);
}
public static void main(java.lang.String[] args) {
junit.textui.TestRunner.run(suite());
}
public static Test suite() {
TestSuite suite = new NbTestSuite(DDApiTest.class);
return suite;
}
/** Test of greeting method, of class HelloWorld. */
public void test_InitDataChecking () {
System.out.println("Init Data Checking");
String version = webApp.getVersion();
assertEquals("Incorrect servlet spec.version :",VERSION,version);
assertEquals("Incorrect number of servlets :",0,webApp.sizeServlet());
assertEquals("Incorrect Session Timeout :",TIMEOUT,webApp.getSingleSessionConfig().getSessionTimeout().intValue());
assertEquals("Incorrect number of welcome files : ",WF_NUMBER,webApp.getSingleWelcomeFileList().sizeWelcomeFile());
}
public void test_Servlet() {
System.out.println("Testing servlet, servlet-mapping");
try {
Servlet servlet = (Servlet) webApp.createBean("Servlet");
servlet.setServletName(SERVLET_NAME);
servlet.setServletClass(SERVLET_CLASS);
servlet.setLoadOnStartup(LOAD_ON_STARTUP);
webApp.addServlet(servlet);
ServletMapping25 mapping = (ServletMapping25) webApp.createBean("ServletMapping");
mapping.setServletName(SERVLET_NAME);
mapping.setUrlPatterns(URL_PATTERN);
webApp.addServletMapping(mapping);
webApp.write(fo);
} catch (ClassNotFoundException ex) {
throw new AssertionFailedErrorException("createBean() method failed",ex);
} catch (java.io.IOException ex) {
throw new AssertionFailedErrorException("write method failed",ex);
}
assertEquals("Incorrect number of servlets :",1,webApp.sizeServlet());
Servlet s = (Servlet)webApp.findBeanByName("Servlet","ServletName",SERVLET_NAME);
assertTrue("Servlet "+SERVLET_NAME+" not found", null != s);
assertEquals("Wrong Servlet Name :",SERVLET_NAME,s.getServletName());
assertEquals("Wrong Servlet Class :",SERVLET_CLASS,s.getServletClass());
assertEquals("Wrong load-on-startup :",LOAD_ON_STARTUP,s.getLoadOnStartup());
}
public void test_InitParams() {
// unfortunately the test depends on actions made by other tests
test_Servlet();
System.out.println("Testing init-params, context-params");
Servlet s = (Servlet)webApp.findBeanByName("Servlet","ServletName",SERVLET_NAME);
assertTrue("Servlet "+SERVLET_NAME+" not found", null != s);
try {
InitParam param = (InitParam) s.createBean("InitParam");
param.setParamName(PARAM1);
param.setParamValue(VALUE1);
s.addInitParam(param);
InitParam clonnedParam1 = (InitParam)param.clone();
param = (InitParam) s.createBean("InitParam");
param.setParamName(PARAM2);
param.setParamValue(VALUE2);
s.addInitParam(param);
InitParam clonnedParam2 = (InitParam)param.clone();
webApp.setContextParam(new InitParam[]{clonnedParam1, clonnedParam2});
webApp.write(fo);
} catch (ClassNotFoundException ex) {
throw new AssertionFailedErrorException("createBean() method failed",ex);
} catch (java.io.IOException ex) {
throw new AssertionFailedErrorException("write method failed",ex);
}
s = (Servlet)webApp.findBeanByName("Servlet","ServletName",SERVLET_NAME);
assertTrue("Servlet "+SERVLET_NAME+" not found", null != s);
assertEquals("Incorrect number of context-params :",2,webApp.sizeContextParam());
assertEquals("Incorrect number of init-params in servlet:",2,s.sizeInitParam());
// context-param test
InitParam[] params = webApp.getContextParam();
assertEquals("Incorrect context-param name :",PARAM1,params[0].getParamName());
assertEquals("Incorrect context-param name :",PARAM2,params[1].getParamName());
assertEquals("Incorrect context-param value :",VALUE1,params[0].getParamValue());
assertEquals("Incorrect context-param value :",VALUE2,params[1].getParamValue());
// init-param test
assertEquals("Incorrect servlet's init-param name :",PARAM1,s.getInitParam(0).getParamName());
assertEquals("Incorrect servlet's init-param name :",PARAM2,s.getInitParam(1).getParamName());
assertEquals("Incorrect servlet's init-param value :",VALUE1,s.getInitParam(0).getParamValue());
assertEquals("Incorrect servlet's init-param value :",VALUE2,s.getInitParam(1).getParamValue());
// init-param/context-param, searching
InitParam p = (InitParam)s.findBeanByName("InitParam","ParamName",PARAM2);
assertTrue("InitParam "+PARAM2+" not found", null != p);
p = (InitParam)webApp.findBeanByName("InitParam","ParamName",PARAM1);
assertTrue("Context Param "+PARAM1+" not found", null != p);
}
public void test_Description() {
// unfortunately the test depends on actions made by other tests
test_InitParams();
System.out.println("Testing description, description for locales");
Servlet s = (Servlet)webApp.findBeanByName("Servlet","ServletName",SERVLET_NAME);
assertTrue("Servlet "+SERVLET_NAME+" not found", null != s);
InitParam p = (InitParam)s.findBeanByName("InitParam","ParamName",PARAM2);
assertTrue("InitParam "+PARAM2+" not found", null != p);
p.setDescription(DESCRIPTION);
try {
p.setDescription("en",DESCRIPTION_EN);
p.setDescription("de",DESCRIPTION);
p.setDescription("cz",DESCRIPTION_CZ);
p.setDescription("sk",DESCRIPTION_SK);
p.setDescription("de",DESCRIPTION_DE); // correction
} catch (VersionNotSupportedException ex) {
throw new AssertionFailedErrorException("setDescription() method failed",ex);
}
java.util.Map map = p.getAllDescriptions();
assertEquals("Incorrect size of description :",5,map.size());
assertEquals("Incorrect default description :",DESCRIPTION,map.get(null));
assertEquals("Incorrect english description :",DESCRIPTION_EN,map.get("en"));
assertEquals("Incorrect german description :",DESCRIPTION_DE,map.get("de"));
assertEquals("Incorrect czech description :",DESCRIPTION_CZ,map.get("cz"));
assertEquals("Incorrect slovak description :",DESCRIPTION_SK,map.get("sk"));
try {
p.removeDescriptionForLocale("de");
} catch (VersionNotSupportedException ex) {
throw new AssertionFailedErrorException("removeDescription() method failed",ex);
}
assertEquals("Incorrect size of description :",4,p.getAllDescriptions().size());
assertEquals("Incorrect default description :",DESCRIPTION,p.getDefaultDescription());
try {
assertEquals("Incorrect default description :",DESCRIPTION,p.getDescription(null));
assertEquals("Incorrect english description :",DESCRIPTION_EN,p.getDescription("en"));
assertEquals("German description was removed :",null,p.getDescription("de"));
assertEquals("Incorrect czech description :",DESCRIPTION_CZ,p.getDescription("cz"));
assertEquals("Incorrect slovak description :",DESCRIPTION_SK,p.getDescription("sk"));
} catch (VersionNotSupportedException ex) {
throw new AssertionFailedErrorException("getDescription(String locale) method failed",ex);
}
try {
webApp.write(fo);
} catch (java.io.IOException ex) {
throw new AssertionFailedErrorException("write method failed",ex);
}
}
public void test_addBean() {
System.out.println("Testing addBean method");
try {
InitParam context = (InitParam)webApp.addBean("InitParam",null,null, null);
context.setParamName(PARAM3);
context.setParamValue(VALUE3);
JspConfig jspConfig = (JspConfig)webApp.addBean("JspConfig", null, null, null);
jspConfig.addBean("JspPropertyGroup",new String[]{"UrlPattern","IncludePrelude","IncludeCoda"},
new String[]{URL_PATTERN_JSP,PRELUDE,CODA},null);
webApp.addBean("Icon",new String[]{"LargeIcon","SmallIcon"},new String[]{LARGE_ICON,SMALL_ICON},null);
} catch (Exception ex){
throw new AssertionFailedErrorException("addBean() method failed for ContextParam,JspConfig or Icon",ex);
}
// addinng new Servlet
try {
Servlet servlet = (Servlet)webApp.addBean("Servlet", new String[]{"ServletName","ServletClass","LoadOnStartup"},
new Object[]{SERVLET_NAME1,SERVLET_CLASS,LOAD_ON_STARTUP1}, "ServletName");
servlet.addBean("InitParam", new String[]{"ParamName","ParamValue"}, new String[]{PARAM1,VALUE11},null);
webApp.addBean("ServletMapping", new String[]{"ServletName","UrlPattern"},new String[]{SERVLET_NAME1,URL_PATTERN1},"UrlPattern");
} catch (Exception ex){
new AssertionFailedErrorException("addBean() method failed for Servlet",ex);
}
// attempt to add servlet with the same name
try {
Servlet servlet = (Servlet)webApp.addBean("Servlet", new String[]{"ServletName","ServletClass"},
new Object[]{SERVLET_NAME1,SERVLET_CLASS}, "ServletName");
throw new AssertionFailedError("Servlet shouldn't have been added because of the same name");
} catch (NameAlreadyUsedException ex){
System.out.println("Expected exception : "+ex);
} catch (ClassNotFoundException ex) {
new AssertionFailedErrorException("addBean() method failed for Servlet",ex);
}
try {
webApp.write(fo);
} catch (java.io.IOException ex) {
throw new AssertionFailedErrorException("write method failed",ex);
}
}
public void test_Result() {
// unfortunately the test depends on actions made by other tests
test_Description();
test_addBean();
System.out.println("Comparing result with golden file");
String testDataDirS = System.getProperty("test.data.dir");
java.io.File pass = new File(getDataDir(),"/web.pass");
File test = FileUtil.toFile(fo);
try {
BufferedReader reader1 = new BufferedReader(new FileReader(test));
BufferedReader reader2 = new BufferedReader(new FileReader(pass));
String line1=null;
Set set1 = new HashSet();
Set set2 = new HashSet();
while((line1=reader1.readLine())!=null) {
line1 = line1.trim();
String line2 = reader2.readLine();
if (line2==null) {
assertFile("Result different than golden file " + pass.getAbsolutePath() + " " + test.getAbsolutePath(), pass, test, test.getParentFile());
}
line2=line2.trim();
// description order can be changed so it must be compared differently
if (line1.startsWith("<description")) {
set1.add(line1);
set2.add(line2);
} else if (!line1.equals(line2)) {
assertFile("Result different than golden file " + pass.getAbsolutePath() + " " + test.getAbsolutePath(), pass, test, test.getParentFile());
}
}
reader1.close();reader2.close();
if (!set1.equals(set2)) {
assertFile("Problem with descriotion elements", pass, test, test.getParentFile());
}
} catch (IOException ex) {
throw new AssertionFailedErrorException("Comparing to golden file failed",ex);
}
}
private static DDProvider ddProvider;
private static FileObject fo;
private static boolean initialized;
@Override
protected void setUp() throws Exception {
super.setUp();
System.out.println("setUp() .......................");
if (ddProvider==null) ddProvider = DDProvider.getDefault();
assertTrue("DDProvider object not found",null != ddProvider);
FileObject dataFolder = FileUtil.toFileObject(getDataDir());
if (!initialized){
FileObject old = dataFolder.getFileObject("web", "xml");
if (old != null){
old.delete();
}
initialized = true;
}
if (fo==null) {
fo = FileUtil.copyFile(dataFolder.getFileObject("web_org","xml"), dataFolder, "web");
}
assertTrue("FileObject web.xml not found",null != fo);
try {
webApp = ddProvider.getDDRoot(fo);
} catch (Exception ex) {
ex.printStackTrace();
}
assertTrue("WebApp object not found", null != webApp);
}
@Override
protected void tearDown() throws Exception {
if (initialized && fo != null) {
fo.delete();
fo = null;
webApp = null;
}
super.tearDown();
}
}
| 6,684 |
311 |
<filename>dd-java-agent/instrumentation/spring-rabbit/src/test/java/rabbit/Receiver.java
package rabbit;
import datadog.trace.api.Trace;
import datadog.trace.bootstrap.instrumentation.api.AgentTracer;
import java.util.concurrent.CountDownLatch;
import org.springframework.stereotype.Component;
@Component
public class Receiver {
public final CountDownLatch latch = new CountDownLatch(1);
@Trace(operationName = "receive")
public void receiveMessage(String message) {
assert null != AgentTracer.activeSpan() : "no active span during message receipt";
latch.countDown();
}
}
| 187 |
2,341 |
#
# Copyright 2016 Cluster Labs, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
from datetime import datetime
from datetime import timedelta
from django.core.cache import cache
from backend.lk.models import User
from backend.lk.models import OAuthAccessToken
CACHE_KEY_FORMAT = 'lk_oauthaccesstoken:%s'
def create_token_for_user_client_scope(user, client_id, scope):
access_tokens = OAuthAccessToken.objects.filter(user=user, client_id=client_id, scope=scope,
expire_time__isnull=True).order_by('-create_time')[:1]
if access_tokens:
access_token = access_tokens[0]
else:
access_token = OAuthAccessToken(user=user, client_id=client_id, scope=scope)
access_token.save()
return access_token.token
def user_scope_for_token(raw_token):
if not raw_token:
return None
token_cache_key = CACHE_KEY_FORMAT % raw_token
token = cache.get(token_cache_key)
if not token:
try:
token = OAuthAccessToken.objects.get(token=raw_token, expire_time__isnull=True)
except OAuthAccessToken.DoesNotExist:
token = None
if token:
cache.set(token_cache_key, token)
if token:
if token.last_used_time < datetime.now() - timedelta(hours=1):
OAuthAccessToken.objects.filter(id=token.id).update(last_used_time=datetime.now())
cache.delete(token_cache_key)
user = User.get_cached(token.user_id)
if not user:
# User account was deleted.
token.invalidate_cache()
return None, None
return user, token.scope
return None, None
def invalidate_client_token(client_id, raw_token):
access_tokens = OAuthAccessToken.objects.filter(client_id=client_id, token=raw_token,
expire_time__isnull=True).order_by('-create_time')[:1]
if access_tokens:
OAuthAccessToken.objects.filter(id=access_tokens[0].id).update(expire_time=datetime.now())
token_cache_key = CACHE_KEY_FORMAT % raw_token
cache.delete(token_cache_key)
return True
return False
def invalidate_tokens_for_user(user):
access_tokens = OAuthAccessToken.objects.filter(user=user,
expire_time__isnull=True).order_by('-create_time')
for access_token in access_tokens:
OAuthAccessToken.objects.filter(id=access_token.id).update(expire_time=datetime.now())
token_cache_key = CACHE_KEY_FORMAT % access_token.token
cache.delete(token_cache_key)
| 1,020 |
373 |
package com.xxx.zookeeper;
import java.io.IOException;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.ZooKeeper;
/**
* Created by W510 on 2015/12/3.
*/
public class ZookeeperTest {
/**
* 主方法.
*/
public static void main(String[] args) throws IOException, KeeperException, InterruptedException {
Watcher watcher = new Watcher() {
@Override
public void process(WatchedEvent event) {
System.out.println(event.toString());
}
};
ZooKeeper zooKeeper = new ZooKeeper("127.0.0.1:2181", 3000, watcher);
zooKeeper.create("/temp", "hahaha".getBytes(),
ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
while (true) {
String value = new String(zooKeeper.getData("/temp", false, null));
System.out.println("value = " + value.toString());
Thread.sleep(3000);
}
}
}
| 407 |
497 |
package com.tubb.smrv.demo.normal;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import com.tubb.smrv.demo.R;
import com.tubb.smrv.demo.rv.RvMainActivity;
public class NormalMainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_normal_main);
}
public void onClick(View v){
if (v.getId() == R.id.button1) {
startActivity(new Intent(this, SimpleActivity.class));
}else if(v.getId() == R.id.button2){
startActivity(new Intent(this, SimpleVerticalActivity.class));
}
}
}
| 296 |
3,897 |
/* mbed Microcontroller Library
* Copyright (c) 2006-2020 ARM Limited
* SPDX-License-Identifier: Apache-2.0
*
* 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 "PeripheralPins.h"
#include "mbed_error.h"
#include "gpio_addrdefine.h"
#include "mbed_drv_cfg.h"
PinName gpio_multi_guard = (PinName)NC; /* If set pin name here, setting of the "pin" is just one time */
void pin_function(PinName pin, int function)
{
uint32_t reg_group = PINGROUP(pin);
uint32_t bitmask = (1 << PINNO(pin));
if (reg_group > GPIO_GROUP_MAX) {
return;
}
if (gpio_multi_guard == pin) {
gpio_multi_guard = (PinName)NC;
return;
}
if (function == 0) {
*PMR(reg_group) &= ~bitmask;
} else {
GPIO.PWPR.BIT.B0WI = 0;
GPIO.PWPR.BIT.PFSWE = 1;
*PFS(reg_group, PINNO(pin)) = function;
GPIO.PWPR.BIT.PFSWE = 0;
GPIO.PWPR.BIT.B0WI = 1;
*PMR(reg_group) |= bitmask;
}
}
void pin_mode(PinName pin, PinMode mode)
{
// if (pin == (PinName)NC) { return; }
}
| 619 |
5,169 |
{
"name": "PusherSwiftC",
"version": "8.0.3",
"summary": "A Pusher client library in Swift",
"homepage": "https://github.com/SuaMusica/pusher-websocket-swift",
"license": "MIT",
"authors": {
"<NAME>": "<EMAIL>"
},
"source": {
"git": "https://github.com/SuaMusica/pusher-websocket-swift.git",
"tag": "8.0.3"
},
"social_media_url": "https://twitter.com/pusher",
"swift_versions": "5.0",
"requires_arc": true,
"source_files": [
"Sources/*.swift",
"Sources/PusherSwift-Only/*.swift"
],
"dependencies": {
"Starscream": [
"~> 3.1"
]
},
"platforms": {
"ios": "8.0"
},
"swift_version": "5.0"
}
| 306 |
575 |
<filename>remoting/host/desktop_resizer_ozone.cc
// Copyright 2015 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 "remoting/host/desktop_resizer_ozone.h"
#include "build/build_config.h"
namespace remoting {
DesktopResizerOzone::DesktopResizerOzone() = default;
DesktopResizerOzone::~DesktopResizerOzone() = default;
ScreenResolution DesktopResizerOzone::GetCurrentResolution() {
NOTIMPLEMENTED();
return ScreenResolution();
}
std::list<ScreenResolution> DesktopResizerOzone::GetSupportedResolutions(
const ScreenResolution& preferred) {
NOTIMPLEMENTED();
return std::list<ScreenResolution>();
}
void DesktopResizerOzone::SetResolution(const ScreenResolution& resolution) {
NOTIMPLEMENTED();
}
void DesktopResizerOzone::RestoreResolution(const ScreenResolution& original) {}
// To avoid multiple definitions when use_x11 && use_ozone is true, disable this
// factory method for OS_LINUX as Linux has a factory method that decides what
// desktopresizer to use based on IsUsingOzonePlatform feature flag.
#if !defined(OS_LINUX) && !defined(OS_CHROMEOS)
std::unique_ptr<DesktopResizer> DesktopResizer::Create() {
return base::WrapUnique(new DesktopResizerOzone);
}
#endif
} // namespace remoting
| 401 |
1,209 |
/*
graphics_test.c
>>> PLEASE UNCOMMENT DISPLAY TYPE IN THE MAIN PROCEDURE <<<
ARM U8glib Example
Universal 8bit Graphics Library
Copyright (c) 2013, <EMAIL>
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this list
of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this
list of conditions and the following disclaimer in the documentation and/or other
materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "u8g_arm.h"
/*========================================================================*/
/* SystemInit & SysTick Interrupt */
#define SYS_TICK_PERIOD_IN_MS 10
void SystemInit()
{
init_system_clock(); /* SystemCoreClock will be set here */
/* SysTick is defined in core_cm0.h */
SysTick->LOAD = (SystemCoreClock/1000UL*(unsigned long)SYS_TICK_PERIOD_IN_MS) - 1;
SysTick->VAL = 0;
SysTick->CTRL = 7; /* enable, generate interrupt (SysTick_Handler), do not divide by 2 */
}
void __attribute__ ((interrupt)) SysTick_Handler(void)
{
}
/*========================================================================*/
/* main */
u8g_t u8g;
void u8g_prepare(void) {
u8g_SetFont(&u8g, u8g_font_6x10);
u8g_SetFontRefHeightExtendedText(&u8g);
u8g_SetDefaultForegroundColor(&u8g);
u8g_SetFontPosTop(&u8g);
}
void u8g_box_frame(uint8_t a) {
u8g_DrawStr(&u8g, 0, 0, "drawBox");
u8g_DrawBox(&u8g, 5,10,20,10);
u8g_DrawBox(&u8g, 10+a,15,30,7);
u8g_DrawStr(&u8g, 0, 30, "drawFrame");
u8g_DrawFrame(&u8g, 5,10+30,20,10);
u8g_DrawFrame(&u8g, 10+a,15+30,30,7);
}
void u8g_string(uint8_t a) {
u8g_DrawStr(&u8g, 30+a,31, " 0");
u8g_DrawStr90(&u8g, 30,31+a, " 90");
u8g_DrawStr180(&u8g, 30-a,31, " 180");
u8g_DrawStr270(&u8g, 30,31-a, " 270");
}
void u8g_line(uint8_t a) {
u8g_DrawStr(&u8g, 0, 0, "drawLine");
u8g_DrawLine(&u8g, 7+a, 10, 40, 55);
u8g_DrawLine(&u8g, 7+a*2, 10, 60, 55);
u8g_DrawLine(&u8g, 7+a*3, 10, 80, 55);
u8g_DrawLine(&u8g, 7+a*4, 10, 100, 55);
}
void u8g_ascii_1(void) {
char s[2] = " ";
uint8_t x, y;
u8g_DrawStr(&u8g, 0, 0, "ASCII page 1");
for( y = 0; y < 6; y++ ) {
for( x = 0; x < 16; x++ ) {
s[0] = y*16 + x + 32;
u8g_DrawStr(&u8g, x*7, y*10+10, s);
}
}
}
void u8g_ascii_2(void) {
char s[2] = " ";
uint8_t x, y;
u8g_DrawStr(&u8g, 0, 0, "ASCII page 2");
for( y = 0; y < 6; y++ ) {
for( x = 0; x < 16; x++ ) {
s[0] = y*16 + x + 160;
u8g_DrawStr(&u8g, x*7, y*10+10, s);
}
}
}
uint8_t draw_state = 0;
void draw(void) {
u8g_prepare();
switch(draw_state >> 3) {
case 0: u8g_box_frame(draw_state&7); break;
case 1: u8g_string(draw_state&7); break;
case 2: u8g_line(draw_state&7); break;
case 3: u8g_ascii_1(); break;
case 4: u8g_ascii_2(); break;
}
}
void main()
{
/*
Please uncomment one of the displays below
Notes:
- "2x", "4x": high speed version, which uses more RAM
- "hw_spi": All hardware SPI devices can be used with software SPI also.
Access type is defined by u8g_com_hw_spi_fn
*/
// u8g_InitComFn(&u8g, &u8g_dev_uc1701_dogs102_hw_spi, u8g_com_hw_spi_fn);
// u8g_InitComFn(&u8g, &u8g_dev_uc1701_dogs102_2x_hw_spi, u8g_com_hw_spi_fn);
// u8g_InitComFn(&u8g, &u8g_dev_uc1701_mini12864_hw_spi, u8g_com_hw_spi_fn);
// u8g_InitComFn(&u8g, &u8g_dev_uc1701_mini12864_2x_hw_spi, u8g_com_hw_spi_fn);
// u8g_InitComFn(&u8g, &u8g_dev_st7565_dogm132_hw_spi, u8g_com_hw_spi_fn);
// u8g_InitComFn(&u8g, &u8g_dev_st7565_dogm128_hw_spi, u8g_com_hw_spi_fn);
// u8g_InitComFn(&u8g, &u8g_dev_st7565_dogm128_2x_hw_spi, u8g_com_hw_spi_fn);
// u8g_InitComFn(&u8g, &u8g_dev_st7565_lm6059_hw_spi, u8g_com_hw_spi_fn);
// u8g_InitComFn(&u8g, &u8g_dev_st7565_lm6059_2x_hw_spi, u8g_com_hw_spi_fn);
// u8g_InitComFn(&u8g, &u8g_dev_st7565_lm6063_hw_spi, u8g_com_hw_spi_fn);
// u8g_InitComFn(&u8g, &u8g_dev_st7565_lm6063_2x_hw_spi, u8g_com_hw_spi_fn);
// u8g_InitComFn(&u8g, &u8g_dev_st7565_nhd_c12864_hw_spi, u8g_com_hw_spi_fn);
// u8g_InitComFn(&u8g, &u8g_dev_st7565_nhd_c12864_2x_hw_spi, u8g_com_hw_spi_fn);
// u8g_InitComFn(&u8g, &u8g_dev_st7565_nhd_c12832_hw_spi, u8g_com_hw_spi_fn);
// u8g_InitComFn(&u8g, &u8g_dev_st7565_64128n_hw_spi, u8g_com_hw_spi_fn);
// u8g_InitComFn(&u8g, &u8g_dev_st7565_64128n_2x_hw_spi, u8g_com_hw_spi_fn);
// u8g_InitComFn(&u8g, &u8g_dev_uc1601_c128032_hw_spi, u8g_com_hw_spi_fn);
// u8g_InitComFn(&u8g, &u8g_dev_uc1601_c128032_2x_hw_spi, u8g_com_hw_spi_fn);
// u8g_InitComFn(&u8g, &u8g_dev_uc1610_dogxl160_bw_hw_spi, u8g_com_hw_spi_fn);
// u8g_InitComFn(&u8g, &u8g_dev_uc1610_dogxl160_gr_hw_spi, u8g_com_hw_spi_fn);
// u8g_InitComFn(&u8g, &u8g_dev_uc1610_dogxl160_2x_bw_hw_spi, u8g_com_hw_spi_fn);
// u8g_InitComFn(&u8g, &u8g_dev_uc1610_dogxl160_2x_gr_hw_spi, u8g_com_hw_spi_fn);
// u8g_InitComFn(&u8g, &u8g_dev_pcd8544_84x48_hw_spi, u8g_com_hw_spi_fn);
// u8g_InitComFn(&u8g, &u8g_dev_pcf8812_96x65_hw_spi, u8g_com_hw_spi_fn);
// u8g_InitComFn(&u8g, &u8g_dev_ssd1325_nhd27oled_bw_hw_spi, u8g_com_hw_spi_fn);
// u8g_InitComFn(&u8g, &u8g_dev_ssd1325_nhd27oled_gr_hw_spi, u8g_com_hw_spi_fn);
// u8g_InitComFn(&u8g, &u8g_dev_ssd1325_nhd27oled_2x_bw_hw_spi, u8g_com_hw_spi_fn);
// u8g_InitComFn(&u8g, &u8g_dev_ssd1325_nhd27oled_2x_gr_hw_spi, u8g_com_hw_spi_fn);
// u8g_InitComFn(&u8g, &u8g_dev_ssd1327_96x96_gr_hw_spi, u8g_com_hw_spi_fn);
// u8g_InitComFn(&u8g, &u8g_dev_ssd1327_96x96_2x_gr_hw_spi, u8g_com_hw_spi_fn);
// u8g_InitComFn(&u8g, &u8g_dev_ssd1322_nhd31oled_bw_hw_spi, u8g_com_hw_spi_fn);
// u8g_InitComFn(&u8g, &u8g_dev_ssd1322_nhd31oled_2x_bw_hw_spi, u8g_com_hw_spi_fn);
// u8g_InitComFn(&u8g, &u8g_dev_ssd1322_nhd31oled_gr_hw_spi, u8g_com_hw_spi_fn);
// u8g_InitComFn(&u8g, &u8g_dev_ssd1322_nhd31oled_2x_gr_hw_spi, u8g_com_hw_spi_fn);
// u8g_InitComFn(&u8g, &u8g_dev_ssd1306_128x64_hw_spi, u8g_com_hw_spi_fn);
// u8g_InitComFn(&u8g, &u8g_dev_ssd1306_128x64_2x_hw_spi, u8g_com_hw_spi_fn);
// u8g_InitComFn(&u8g, &u8g_dev_ssd1309_128x64_hw_spi, u8g_com_hw_spi_fn);
// u8g_InitComFn(&u8g, &u8g_dev_ssd1306_128x32_hw_spi, u8g_com_hw_spi_fn);
// u8g_InitComFn(&u8g, &u8g_dev_ssd1306_128x32_2x_hw_spi, u8g_com_hw_spi_fn);
// u8g_InitComFn(&u8g, &u8g_dev_ssd1351_128x128_332_hw_spi, u8g_com_hw_spi_fn);
// u8g_InitComFn(&u8g, &u8g_dev_ssd1351_128x128_4x_332_hw_spi, u8g_com_hw_spi_fn);
// u8g_InitComFn(&u8g, &u8g_dev_ssd1351_128x128_hicolor_hw_spi, u8g_com_hw_spi_fn);
// u8g_InitComFn(&u8g, &u8g_dev_ssd1351_128x128_4x_hicolor_hw_spi, u8g_com_hw_spi_fn);
/* flip screen, if required */
u8g_SetRot180(&u8g);
for(;;)
{
/* picture loop */
u8g_FirstPage(&u8g);
do
{
draw();
} while ( u8g_NextPage(&u8g) );
draw_state++;
if ( draw_state >= 5*8 )
draw_state = 0;
/* refresh screen after some delay */
u8g_Delay(100);
}
}
| 4,150 |
1,587 |
package io.reflectoring.resilience4j.retry.services.failures;
import java.util.Random;
public class FailHalfTheTime implements PotentialFailure {
Random random = new Random();
int times;
int failedCount;
public FailHalfTheTime(int times) {
this.times = times;
}
@Override
public void occur() {
if (failedCount++ < times && random.nextInt() % 2 == 0) {
throw new RuntimeException("Operation failed");
}
}
public static void main(String[] args) {
PotentialFailure failure = new FailHalfTheTime(4);
failure.occur();
}
}
| 229 |
2,663 |
<filename>Projects/Foundations/Schemas/Docs-Nodes/T/Trading/Trading-Engine/trading-engine.json
{
"type": "Trading Engine",
"definition": {
"text": "The trading engine hierarchy is the data structure used by the trading bot to keep runtime information highly accessible and exposed to others.",
"translations": [
{
"language": "ES",
"text": "La jerarquia trading engine es la estructura de datos utilizada por el robot comercial para mantener la información en tiempo de ejecución altamente accesible y expuesta a otros.",
"updated": 1624452474129
}
]
},
"paragraphs": [
{
"style": "Block",
"text": "Content"
},
{
"style": "Text",
"text": "You will use this hierarchy for two main purposes:"
},
{
"style": "List",
"text": "To let your trading systems access the information processed by the trading bot. This allows strategies to keep track of and react to current and past events—including those involving the exchange, such as orders placed or filled—as the bot is running."
},
{
"style": "List",
"text": "To keep track of the actions of the trading bot via the design space visual environment and panels over the charts. By analyzing runtime information, you may gain a detailed understanding of what happens, when, and why, throughout a trading session."
},
{
"style": "Title",
"text": "Frequently Asked Questions"
},
{
"style": "Subtitle",
"text": "Can a Trading Engine be shared between two Trading Bots?"
},
{
"style": "Text",
"text": "The same trading engine can be used from multiple trading sessions, because it is just a node-based representation of a data structure.",
"updated": 1621987910896
},
{
"style": "Text",
"text": "Every time a Task is ran, a snapshot of that data structure, together with a snapshot of the Network and the Bots definitions at their Data Mine is sent from the UI to the Task Server, and from there is consumed by the running Bot. That means that a second Bot can receive the same Trading Engine snapshot and it will never know if other bots were fed with the same information or not.",
"updated": 1621987965915
},
{
"style": "Subtitle",
"text": "Do I need to change something at the Trading Engine?"
},
{
"style": "Text",
"text": "You don't need to physically change anything inside trading engine via the UI. The trading engine is a visual representation of the data structure that the trading system uses to store its values, so to speak."
},
{
"style": "Subtitle",
"text": "Can I change the values inside the Trading Engine?"
},
{
"style": "Text",
"text": "You access the Trading Engine from within your trading system if there is something in there you would like to change. This is the whole purpose of the User Defined Code node.",
"updated": 1621988418300
}
]
}
| 1,300 |
3,645 |
<reponame>huyu0415/FFmpeg<filename>ffmpeg-3.2.5/libavutil/tests/aes.c
/*
* This file is part of FFmpeg.
*
* FFmpeg is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* FFmpeg is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with FFmpeg; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
// LCOV_EXCL_START
#include <string.h>
#include "libavutil/aes.h"
#include "libavutil/lfg.h"
#include "libavutil/log.h"
#include "libavutil/mem.h"
int main(int argc, char **argv)
{
int i, j;
struct AVAES *b;
static const uint8_t rkey[2][16] = {
{ 0 },
{ 0x10, 0xa5, 0x88, 0x69, 0xd7, 0x4b, 0xe5, 0xa3,
0x74, 0xcf, 0x86, 0x7c, 0xfb, 0x47, 0x38, 0x59 }
};
static const uint8_t rpt[2][16] = {
{ 0x6a, 0x84, 0x86, 0x7c, 0xd7, 0x7e, 0x12, 0xad,
0x07, 0xea, 0x1b, 0xe8, 0x95, 0xc5, 0x3f, 0xa3 },
{ 0 }
};
static const uint8_t rct[2][16] = {
{ 0x73, 0x22, 0x81, 0xc0, 0xa0, 0xaa, 0xb8, 0xf7,
0xa5, 0x4a, 0x0c, 0x67, 0xa0, 0xc4, 0x5e, 0xcf },
{ 0x6d, 0x25, 0x1e, 0x69, 0x44, 0xb0, 0x51, 0xe0,
0x4e, 0xaa, 0x6f, 0xb4, 0xdb, 0xf7, 0x84, 0x65 }
};
uint8_t pt[32];
uint8_t temp[32];
uint8_t iv[2][16];
int err = 0;
b = av_aes_alloc();
if (!b)
return 1;
av_log_set_level(AV_LOG_DEBUG);
for (i = 0; i < 2; i++) {
av_aes_init(b, rkey[i], 128, 1);
av_aes_crypt(b, temp, rct[i], 1, NULL, 1);
for (j = 0; j < 16; j++) {
if (rpt[i][j] != temp[j]) {
av_log(NULL, AV_LOG_ERROR, "%d %02X %02X\n",
j, rpt[i][j], temp[j]);
err = 1;
}
}
}
av_free(b);
if (argc > 1 && !strcmp(argv[1], "-t")) {
struct AVAES *ae, *ad;
AVLFG prng;
ae = av_aes_alloc();
ad = av_aes_alloc();
if (!ae || !ad) {
av_free(ae);
av_free(ad);
return 1;
}
av_aes_init(ae, (const uint8_t*)"PI=3.141592654..", 128, 0);
av_aes_init(ad, (const uint8_t*)"PI=3.141592654..", 128, 1);
av_lfg_init(&prng, 1);
for (i = 0; i < 10000; i++) {
for (j = 0; j < 32; j++)
pt[j] = av_lfg_get(&prng);
for (j = 0; j < 16; j++)
iv[0][j] = iv[1][j] = av_lfg_get(&prng);
{
START_TIMER;
av_aes_crypt(ae, temp, pt, 2, iv[0], 0);
if (!(i & (i - 1)))
av_log(NULL, AV_LOG_ERROR, "%02X %02X %02X %02X\n",
temp[0], temp[5], temp[10], temp[15]);
av_aes_crypt(ad, temp, temp, 2, iv[1], 1);
av_aes_crypt(ae, temp, pt, 2, NULL, 0);
if (!(i & (i - 1)))
av_log(NULL, AV_LOG_ERROR, "%02X %02X %02X %02X\n",
temp[0], temp[5], temp[10], temp[15]);
av_aes_crypt(ad, temp, temp, 2, NULL, 1);
STOP_TIMER("aes");
}
for (j = 0; j < 16; j++) {
if (pt[j] != temp[j]) {
av_log(NULL, AV_LOG_ERROR, "%d %d %02X %02X\n",
i, j, pt[j], temp[j]);
}
}
}
av_free(ae);
av_free(ad);
}
return err;
}
// LCOV_EXCL_STOP
| 2,214 |
397 |
#ifndef _AVL_H
#define _AVL_H
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#define max(a,b) (a>b?a:b)
typedef struct treenode* ptn;
typedef ptn AVL;
struct treenode {
int h;
int data;
ptn Left;
ptn Right;
};
int height(AVL a);
void update(AVL a);
AVL CreateAVL(int x);
AVL balance(AVL a);
AVL insert(int x, AVL a);
AVL delete(int x,AVL a);
int find(AVL a, int x);
void printAVL(AVL a,int space);
#endif
| 246 |
506 |
#pragma once
#include <iostream>
enum egc_result_t
{
k_EGCResultOK = 0,
k_EGCResultNoMessage = 1, // There is no message in the queue
k_EGCResultBufferTooSmall = 2, // The buffer is too small for the requested message
k_EGCResultNotLoggedOn = 3, // The client is not logged onto Steam
k_EGCResultInvalidMessage = 4, // Something was wrong with the message being sent with SendMessage
};
class i_steam_game_coordinator
{
public:
virtual egc_result_t gc_send_message(int unMsgType, const void *pubData, int cubData) = 0;
virtual bool is_message_available(int *pcubMsgSize) = 0;
virtual egc_result_t gc_retrieve_message(int *punMsgType, void *pubDest, int cubDest, int *pcubMsgSize) = 0;
};
class c_steam_id
{
public:
c_steam_id()
{
m_steamid.m_comp.m_account_id = 0;
m_steamid.m_comp.m_account_type = 0;
m_steamid.m_comp.m_universe = 0;
m_steamid.m_comp.m_account_instance = 0;
}
uint32_t get_account_id() const { return m_steamid.m_comp.m_account_id; }
private:
union steam_id_t
{
struct steam_id_component_t
{
uint32_t m_account_id : 32; // unique account identifier
unsigned int m_account_instance : 20; // dynamic instance ID (used for multiseat type accounts only)
unsigned int m_account_type : 4; // type of account - can't show as EAccountType, due to signed / unsigned difference
int m_universe : 8; // universe this account belongs to
} m_comp;
uint64_t all64_bits;
} m_steamid;
};
class i_steam_user
{
public:
virtual uint32_t get_steam_user() = 0;
virtual bool logged_on() = 0;
virtual c_steam_id get_steam_id() = 0;
};
class i_steam_client
{
public:
i_steam_user *get_steam_user(void* hSteamUser, void* hSteamPipe, const char *pchVersion)
{
typedef i_steam_user*(__stdcall* func)(void*, void*, const char *);
return util::misc::vfunc<func>(this, 5)(hSteamUser, hSteamPipe, pchVersion);
}
i_steam_game_coordinator* get_steam_generic_interface(void* hSteamUser, void* hSteamPipe, const char *pchVersion)
{
typedef i_steam_game_coordinator*(__stdcall* func)(void*, void*, const char *);
return util::misc::vfunc<func>(this, 12)(hSteamUser, hSteamPipe, pchVersion);
}
};
| 861 |
713 |
package org.infinispan.stream;
import org.infinispan.CacheCollection;
import org.infinispan.CacheStream;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.test.fwk.InCacheMode;
import org.testng.annotations.Test;
/**
* Verifies stream tests work when stream is parallel with parallel distribution
*/
@Test(groups = "functional", testName = "streams.DistributedParallelStreamTest")
@InCacheMode({ CacheMode.DIST_SYNC, CacheMode.SCATTERED_SYNC })
public class DistributedParallelStreamTest extends DistributedStreamTest {
@Override
protected <E> CacheStream<E> createStream(CacheCollection<E> entries) {
return entries.parallelStream().parallelDistribution();
}
}
| 213 |
357 |
<filename>vmidentity/rest/core/client/src/main/java/com/vmware/identity/rest/core/client/exceptions/GeneralRequestException.java<gh_stars>100-1000
/*
* 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.rest.core.client.exceptions;
import org.apache.http.HttpException;
/**
* The {@code GeneralRequestException} exception class represents a generic set
* of HTTP exceptions, similar to those of the {@link WebApplicationException}.
* However, this class is used when the exception did not originate from the REST
* web application (e.g. a 404 error from accessing a server not running the REST
* web application).
*/
public class GeneralRequestException extends HttpException {
private static final long serialVersionUID = -1772702113396511240L;
private final int statusCode;
private final String serverResponse;
/**
* Construct a {@code GeneralRequestException} with a status code, an error message, the
* full response from the web server, and the cause.
*
* @param statusCode the status code of the exception.
* @param error the exception detail message.
* @param serverResponse the full contents of the response from the web server.
* @param e the {@code Throwable} that caused this exception, or {@code null}
* if the cause is unavailable, unknown, or not a {@code Throwable}.
*/
public GeneralRequestException(int statusCode, String error, String serverResponse, Throwable e) {
super(error, e);
this.statusCode = statusCode;
this.serverResponse = serverResponse;
}
/**
* Get the status code associated with this exception.
*
* @return the status code.
*/
public int getStatusCode() {
return statusCode;
}
/**
* Get the contents of the server's response.
*
* @return the contents of the server's response.
*/
public String getServerResponse() {
return serverResponse;
}
}
| 772 |
504 |
import asyncio
from time import time
import pytest
from slack_sdk.signature import SignatureVerifier
from slack_sdk.web.async_client import AsyncWebClient
from slack_bolt.app.async_app import AsyncApp
from slack_bolt.request.async_request import AsyncBoltRequest
from tests.mock_web_api_server import (
setup_mock_web_api_server,
cleanup_mock_web_api_server,
)
from tests.utils import remove_os_env_temporarily, restore_os_env
class TestAsyncSSLCheck:
signing_secret = "secret"
valid_token = "x<PASSWORD>"
mock_api_server_base_url = "http://localhost:8888"
signature_verifier = SignatureVerifier(signing_secret)
web_client = AsyncWebClient(
token=valid_token,
base_url=mock_api_server_base_url,
)
@pytest.fixture
def event_loop(self):
old_os_env = remove_os_env_temporarily()
try:
setup_mock_web_api_server(self)
loop = asyncio.get_event_loop()
yield loop
loop.close()
cleanup_mock_web_api_server(self)
finally:
restore_os_env(old_os_env)
def generate_signature(self, body: str, timestamp: str):
return self.signature_verifier.generate_signature(
body=body,
timestamp=timestamp,
)
@pytest.mark.asyncio
async def test_mock_server_is_running(self):
resp = await self.web_client.api_test()
assert resp != None
@pytest.mark.asyncio
async def test_ssl_check(self):
app = AsyncApp(client=self.web_client, signing_secret=self.signing_secret)
timestamp, body = str(int(time())), "token=random&ssl_check=1"
request: AsyncBoltRequest = AsyncBoltRequest(
body=body,
query={},
headers={
"content-type": ["application/x-www-form-urlencoded"],
"x-slack-signature": [self.generate_signature(body, timestamp)],
"x-slack-request-timestamp": [timestamp],
},
)
response = await app.async_dispatch(request)
assert response.status == 200
assert response.body == ""
| 952 |
1,139 |
<filename>CoreJavaProjects/CoreJavaExamples/src/com/journaldev/design/Shape.java
package com.journaldev.design;
public interface Shape{
//only public, static and final modifiers
//implicitly final
String LABLE="Shape";
//interface methods are implicitly abstract and public
void draw();
double getArea();
}
| 96 |
1,183 |
<reponame>liux-pro/blinker-js
{
"name": "example",
"version": "1.0.0",
"lockfileVersion": 1,
"requires": true,
"dependencies": {
"@dropb/diskinfo": {
"version": "2.0.0",
"resolved": "https://registry.npm.taobao.org/@dropb/diskinfo/download/@dropb/diskinfo-2.0.0.tgz",
"integrity": "sha1-uV3vxwQptbkH5ErAl8eeBhFTkGs="
},
"os-utils": {
"version": "0.0.14",
"resolved": "https://registry.npm.taobao.org/os-utils/download/os-utils-0.0.14.tgz",
"integrity": "sha1-KeURaXsZgrjGJ3Ihdf45eX72QVY="
}
}
}
| 295 |
407 |
<reponame>iuskye/SREWorks
package com.alibaba.sreworks.other.server.params;
import lombok.Data;
@Data
public class SreworksFileCreateRequestParam {
private String category;
private String name;
private String alias;
private String fileId;
private String type;
private String description;
public String fileId() {
String sreworksFilePrefix = System.getenv("SREWORKS_FILE_PREFIX");
if(fileId.startsWith(sreworksFilePrefix)) {
String[] words = fileId.split("/");
return words[words.length - 1];
}else{
return fileId;
}
}
}
| 258 |
2,494 |
<filename>deps/mozjs/src/gdb/mozilla/jsval.py
# Pretty-printers for SpiderMonkey jsvals.
import gdb
import gdb.types
import mozilla.prettyprinters
from mozilla.prettyprinters import pretty_printer, ptr_pretty_printer
# Forget any printers from previous loads of this module.
mozilla.prettyprinters.clear_module_printers(__name__)
# Summary of the JS::Value (also known as jsval) type:
#
# Viewed abstractly, JS::Value is a 64-bit discriminated union, with
# JSString *, JSObject *, IEEE 64-bit floating-point, and 32-bit integer
# branches (and a few others). (It is not actually a C++ union;
# 'discriminated union' just describes the overall effect.) Note that
# JS::Value is always 64 bits long, even on 32-bit architectures.
#
# The ECMAScript standard specifies that ECMAScript numbers are IEEE 64-bit
# floating-point values. A JS::Value can represent any JavaScript number
# value directly, without referring to additional storage, or represent an
# object, string, or other ECMAScript value, and remember which type it is.
# This may seem surprising: how can a 64-bit type hold all the 64-bit IEEE
# values, and still distinguish them from objects, strings, and so on,
# which have 64-bit addresses?
#
# This is possible for two reasons:
#
# - First, ECMAScript implementations aren't required to distinguish all
# the values the IEEE 64-bit format can represent. The IEEE format
# specifies many bitstrings representing NaN values, while ECMAScript
# requires only a single NaN value. This means we can use one IEEE NaN to
# represent ECMAScript's NaN, and use all the other IEEE NaNs to
# represent the other ECMAScript values.
#
# (IEEE says that any floating-point value whose 11-bit exponent field is
# 0x7ff (all ones) and whose 52-bit fraction field is non-zero is a NaN.
# So as long as we ensure the fraction field is non-zero, and save a NaN
# for ECMAScript, we have 2^52 values to play with.)
#
# - Second, on the only 64-bit architecture we support, x86_64, only the
# lower 48 bits of an address are significant. The upper sixteen bits are
# required to be the sign-extension of bit 48. Furthermore, user code
# always runs in "positive addresses": those in which bit 48 is zero. So
# we only actually need 47 bits to store all possible object or string
# addresses, even on 64-bit platforms.
#
# With a 52-bit fraction field, and 47 bits needed for the 'payload', we
# have up to five bits left to store a 'tag' value, to indicate which
# branch of our discriminated union is live.
#
# Thus, we define JS::Value representations in terms of the IEEE 64-bit
# floating-point format:
#
# - Any bitstring that IEEE calls a number or an infinity represents that
# ECMAScript number.
#
# - Any bitstring that IEEE calls a NaN represents either an ECMAScript NaN
# or a non-number ECMAScript value, as determined by a tag field stored
# towards the most significant end of the fraction field (exactly where
# depends on the address size). If the tag field indicates that this
# JS::Value is an object, the fraction field's least significant end
# holds the address of a JSObject; if a string, the address of a
# JSString; and so on.
#
# On the only 64-bit platform we support, x86_64, only the lower 48 bits of
# an address are significant, and only those values whose top bit is zero
# are used for user-space addresses. This means that x86_64 addresses are
# effectively 47 bits long, and thus fit nicely in the available portion of
# the fraction field.
#
#
# In detail:
#
# - jsval (Value.h) is a typedef for JS::Value.
#
# - JS::Value (Value.h) is a class with a lot of methods and a single data
# member, of type jsval_layout.
#
# - jsval_layout (Value.h) is a helper type for picking apart values. This
# is always 64 bits long, with a variant for each address size (32 bits
# or 64 bits) and endianness (little- or big-endian).
#
# jsval_layout is a union with 'asBits', 'asDouble', and 'asPtr'
# branches, and an 's' branch, which is a struct that tries to break out
# the bitfields a little for the non-double types. On 64-bit machines,
# jsval_layout also has an 'asUIntPtr' branch.
#
# On 32-bit platforms, the 's' structure has a 'tag' member at the
# exponent end of the 's' struct, and a 'payload' union at the mantissa
# end. The 'payload' union's branches are things like JSString *,
# JSObject *, and so on: the natural representations of the tags.
#
# On 64-bit platforms, the payload is 47 bits long; since C++ doesn't let
# us declare bitfields that hold unions, we can't break it down so
# neatly. In this case, we apply bit-shifting tricks to the 'asBits'
# branch of the union to extract the tag.
class Box(object):
def __init__(self, asBits, jtc):
self.asBits = asBits
self.jtc = jtc
# jsval_layout::asBits is uint64, but somebody botches the sign bit, even
# though Python integers are arbitrary precision.
if self.asBits < 0:
self.asBits = self.asBits + (1 << 64)
# Return this value's type tag.
def tag(self): raise NotImplementedError
# Return this value as a 32-bit integer, double, or address.
def as_uint32(self): raise NotImplementedError
def as_double(self): raise NotImplementedError
def as_address(self): raise NotImplementedError
# Packed non-number boxing --- the format used on x86_64. It would be nice to simply
# call JSVAL_TO_INT, etc. here, but the debugger is likely to see many jsvals, and
# doing several inferior calls for each one seems like a bad idea.
class Punbox(Box):
FULL_WIDTH = 64
TAG_SHIFT = 47
PAYLOAD_MASK = (1 << TAG_SHIFT) - 1
TAG_MASK = (1 << (FULL_WIDTH - TAG_SHIFT)) - 1
TAG_MAX_DOUBLE = 0x1fff0
TAG_TYPE_MASK = 0x0000f
def tag(self):
tag = self.asBits >> Punbox.TAG_SHIFT
if tag <= Punbox.TAG_MAX_DOUBLE:
return self.jtc.DOUBLE
else:
return tag & Punbox.TAG_TYPE_MASK
def as_uint32(self): return int(self.asBits & ((1 << 32) - 1))
def as_address(self): return gdb.Value(self.asBits & Punbox.PAYLOAD_MASK)
class Nunbox(Box):
TAG_SHIFT = 32
TAG_CLEAR = 0xffff0000
PAYLOAD_MASK = 0xffffffff
TAG_TYPE_MASK = 0x0000000f
def tag(self):
tag = self.asBits >> Nunbox.TAG_SHIFT
if tag < Nunbox.TAG_CLEAR:
return self.jtc.DOUBLE
return tag & Nunbox.TAG_TYPE_MASK
def as_uint32(self): return int(self.asBits & Nunbox.PAYLOAD_MASK)
def as_address(self): return gdb.Value(self.asBits & Nunbox.PAYLOAD_MASK)
# Cache information about the jsval type for this objfile.
class jsvalTypeCache(object):
def __init__(self, cache):
# Capture the tag values.
d = gdb.types.make_enum_dict(gdb.lookup_type('JSValueType'))
self.DOUBLE = d['JSVAL_TYPE_DOUBLE']
self.INT32 = d['JSVAL_TYPE_INT32']
self.UNDEFINED = d['JSVAL_TYPE_UNDEFINED']
self.BOOLEAN = d['JSVAL_TYPE_BOOLEAN']
self.MAGIC = d['JSVAL_TYPE_MAGIC']
self.STRING = d['JSVAL_TYPE_STRING']
self.SYMBOL = d['JSVAL_TYPE_SYMBOL']
self.NULL = d['JSVAL_TYPE_NULL']
self.OBJECT = d['JSVAL_TYPE_OBJECT']
# Let self.magic_names be an array whose i'th element is the name of
# the i'th magic value.
d = gdb.types.make_enum_dict(gdb.lookup_type('JSWhyMagic'))
self.magic_names = list(range(max(d.values()) + 1))
for (k,v) in d.items(): self.magic_names[v] = k
# Choose an unboxing scheme for this architecture.
self.boxer = Punbox if cache.void_ptr_t.sizeof == 8 else Nunbox
@pretty_printer('jsval_layout')
class jsval_layout(object):
def __init__(self, value, cache):
# Save the generic typecache, and create our own, if we haven't already.
self.cache = cache
if not cache.mod_jsval:
cache.mod_jsval = jsvalTypeCache(cache)
self.jtc = cache.mod_jsval
self.value = value
self.box = self.jtc.boxer(value['asBits'], self.jtc)
def to_string(self):
tag = self.box.tag()
if tag == self.jtc.INT32:
value = self.box.as_uint32()
signbit = 1 << 31
value = (value ^ signbit) - signbit
elif tag == self.jtc.UNDEFINED:
return 'JSVAL_VOID'
elif tag == self.jtc.BOOLEAN:
return 'JSVAL_TRUE' if self.box.as_uint32() else 'JSVAL_FALSE'
elif tag == self.jtc.MAGIC:
value = self.box.as_uint32()
if 0 <= value and value < len(self.jtc.magic_names):
return '$jsmagic(%s)' % (self.jtc.magic_names[value],)
else:
return '$jsmagic(%d)' % (value,)
elif tag == self.jtc.STRING:
value = self.box.as_address().cast(self.cache.JSString_ptr_t)
elif tag == self.jtc.SYMBOL:
value = self.box.as_address().cast(self.cache.JSSymbol_ptr_t)
elif tag == self.jtc.NULL:
return 'JSVAL_NULL'
elif tag == self.jtc.OBJECT:
value = self.box.as_address().cast(self.cache.JSObject_ptr_t)
elif tag == self.jtc.DOUBLE:
value = self.value['asDouble']
else:
return '$jsval(unrecognized!)'
return '$jsval(%s)' % (value,)
@pretty_printer('JS::Value')
class JSValue(object):
def __new__(cls, value, cache):
return jsval_layout(value['data'], cache)
| 3,630 |
575 |
<reponame>iridium-browser/iridium-browser<gh_stars>100-1000
// Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "weblayer/browser/download_callback_proxy.h"
#include "base/android/jni_string.h"
#include "url/android/gurl_android.h"
#include "url/gurl.h"
#include "weblayer/browser/download_impl.h"
#include "weblayer/browser/java/jni/DownloadCallbackProxy_jni.h"
#include "weblayer/browser/profile_impl.h"
#include "weblayer/browser/tab_impl.h"
using base::android::AttachCurrentThread;
using base::android::ConvertUTF8ToJavaString;
using base::android::ScopedJavaLocalRef;
namespace weblayer {
DownloadCallbackProxy::DownloadCallbackProxy(JNIEnv* env,
jobject obj,
Profile* profile)
: profile_(profile), java_delegate_(env, obj) {
profile_->SetDownloadDelegate(this);
}
DownloadCallbackProxy::~DownloadCallbackProxy() {
profile_->SetDownloadDelegate(nullptr);
}
bool DownloadCallbackProxy::InterceptDownload(
const GURL& url,
const std::string& user_agent,
const std::string& content_disposition,
const std::string& mime_type,
int64_t content_length) {
JNIEnv* env = AttachCurrentThread();
ScopedJavaLocalRef<jstring> jstring_url(
ConvertUTF8ToJavaString(env, url.spec()));
ScopedJavaLocalRef<jstring> jstring_user_agent(
ConvertUTF8ToJavaString(env, user_agent));
ScopedJavaLocalRef<jstring> jstring_content_disposition(
ConvertUTF8ToJavaString(env, content_disposition));
ScopedJavaLocalRef<jstring> jstring_mime_type(
ConvertUTF8ToJavaString(env, mime_type));
TRACE_EVENT0("weblayer", "Java_DownloadCallbackProxy_interceptDownload");
return Java_DownloadCallbackProxy_interceptDownload(
env, java_delegate_, jstring_url, jstring_user_agent,
jstring_content_disposition, jstring_mime_type, content_length);
}
void DownloadCallbackProxy::AllowDownload(
Tab* tab,
const GURL& url,
const std::string& request_method,
base::Optional<url::Origin> request_initiator,
AllowDownloadCallback callback) {
JNIEnv* env = AttachCurrentThread();
ScopedJavaLocalRef<jstring> jstring_url(
ConvertUTF8ToJavaString(env, url.spec()));
ScopedJavaLocalRef<jstring> jstring_method(
ConvertUTF8ToJavaString(env, request_method));
ScopedJavaLocalRef<jstring> jstring_request_initator;
if (request_initiator)
jstring_request_initator =
ConvertUTF8ToJavaString(env, request_initiator->Serialize());
// Make copy on the heap so we can pass the pointer through JNI. This will be
// deleted when it's run.
intptr_t callback_id = reinterpret_cast<intptr_t>(
new AllowDownloadCallback(std::move(callback)));
Java_DownloadCallbackProxy_allowDownload(
env, java_delegate_, static_cast<TabImpl*>(tab)->GetJavaTab(),
jstring_url, jstring_method, jstring_request_initator, callback_id);
}
void DownloadCallbackProxy::DownloadStarted(Download* download) {
DownloadImpl* download_impl = static_cast<DownloadImpl*>(download);
JNIEnv* env = AttachCurrentThread();
Java_DownloadCallbackProxy_createDownload(
env, java_delegate_, reinterpret_cast<jlong>(download_impl),
download_impl->GetNotificationId(), download_impl->IsTransient(),
url::GURLAndroid::FromNativeGURL(env, download_impl->GetSourceUrl()));
Java_DownloadCallbackProxy_downloadStarted(env, java_delegate_,
download_impl->java_download());
}
void DownloadCallbackProxy::DownloadProgressChanged(Download* download) {
DownloadImpl* download_impl = static_cast<DownloadImpl*>(download);
Java_DownloadCallbackProxy_downloadProgressChanged(
AttachCurrentThread(), java_delegate_, download_impl->java_download());
}
void DownloadCallbackProxy::DownloadCompleted(Download* download) {
DownloadImpl* download_impl = static_cast<DownloadImpl*>(download);
Java_DownloadCallbackProxy_downloadCompleted(
AttachCurrentThread(), java_delegate_, download_impl->java_download());
}
void DownloadCallbackProxy::DownloadFailed(Download* download) {
DownloadImpl* download_impl = static_cast<DownloadImpl*>(download);
Java_DownloadCallbackProxy_downloadFailed(
AttachCurrentThread(), java_delegate_, download_impl->java_download());
}
static jlong JNI_DownloadCallbackProxy_CreateDownloadCallbackProxy(
JNIEnv* env,
const base::android::JavaParamRef<jobject>& proxy,
jlong profile) {
return reinterpret_cast<jlong>(new DownloadCallbackProxy(
env, proxy, reinterpret_cast<ProfileImpl*>(profile)));
}
static void JNI_DownloadCallbackProxy_DeleteDownloadCallbackProxy(JNIEnv* env,
jlong proxy) {
delete reinterpret_cast<DownloadCallbackProxy*>(proxy);
}
static void JNI_DownloadCallbackProxy_AllowDownload(JNIEnv* env,
jlong callback_id,
jboolean allow) {
std::unique_ptr<AllowDownloadCallback> cb(
reinterpret_cast<AllowDownloadCallback*>(callback_id));
std::move(*cb).Run(allow);
}
} // namespace weblayer
| 1,941 |
5,169 |
<reponame>Gantios/Specs<filename>Specs/3/2/7/FFSafeKit/0.5.0/FFSafeKit.podspec.json
{
"name": "FFSafeKit",
"version": "0.5.0",
"summary": "Using NSArray, NSMutableArray, NSDictionary, NSMutableDictionary, NSMutableString safely.",
"description": "Now using NSArray, NSMutableArray, NSDictionary, NSMutableDictionary, NSMutableString as usual, and will never throw exception.",
"homepage": "https://github.com/JonyFang/FFSafeKit",
"license": {
"type": "MIT",
"file": "LICENSE"
},
"authors": {
"JonyFang": "<EMAIL>"
},
"social_media_url": "https://www.jonyfang.com",
"requires_arc": true,
"frameworks": "Foundation",
"platforms": {
"ios": "8.0"
},
"source_files": "FFSafeKit/**/*.{h,m}",
"public_header_files": "FFSafeKit/**/*.{h}",
"source": {
"git": "https://github.com/JonyFang/FFSafeKit.git",
"tag": "0.5.0"
}
}
| 364 |
5,169 |
<reponame>Ray0218/Specs<filename>Specs/MSTwitterSplashScreen/1.0.5/MSTwitterSplashScreen.podspec.json<gh_stars>1000+
{
"name": "MSTwitterSplashScreen",
"version": "1.0.5",
"summary": "Simple animation of splash screen like in Twitter App for iOS 7 & 8",
"homepage": "https://github.com/mateuszszklarek/MSTwitterSplashScreen.git",
"license": {
"type": "MIT",
"file": "LICENSE"
},
"authors": {
"<NAME>": "<EMAIL>"
},
"social_media_url": "https://twitter.com/szklarekmateusz",
"platforms": {
"ios": "7.0"
},
"source": {
"git": "https://github.com/mateuszszklarek/MSTwitterSplashScreen.git",
"tag": "v1.0.5"
},
"source_files": "MSTwitterSplashScreen",
"requires_arc": true
}
| 314 |
831 |
/*
* Copyright (C) 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.tools.idea.tests.gui.npw;
import static com.google.common.truth.Truth.assertThat;
import static com.intellij.openapi.util.text.StringUtil.getOccurrenceCount;
import static org.junit.Assert.assertEquals;
import com.android.tools.idea.tests.gui.framework.GuiTestRule;
import com.android.tools.idea.tests.gui.framework.RunIn;
import com.android.tools.idea.tests.gui.framework.TestGroup;
import com.android.tools.idea.tests.gui.framework.fixture.EditorFixture;
import com.android.tools.idea.tests.gui.framework.fixture.npw.ConfigureBasicActivityStepFixture;
import com.android.tools.idea.tests.gui.framework.fixture.npw.NewActivityWizardFixture;
import com.android.tools.idea.wizard.template.Language;
import com.intellij.ide.util.PropertiesComponent;
import com.intellij.testGuiFramework.framework.GuiTestRemoteRunner;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import org.fest.swing.timing.Wait;
import org.jetbrains.annotations.NotNull;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
@RunWith(GuiTestRemoteRunner.class)
public class CreateDefaultActivityTest {
private static final String PROVIDED_ACTIVITY = "app/src/main/java/google/simpleapplication/MyActivity.java";
private static final String PROVIDED_MANIFEST = "app/src/main/AndroidManifest.xml";
private static final String APP_BUILD_GRADLE = "app/build.gradle";
private static final String DEFAULT_ACTIVITY_NAME = "MainActivity";
private static final String DEFAULT_LAYOUT_NAME = "activity_main";
@Rule public final GuiTestRule guiTest = new GuiTestRule().withTimeout(10, TimeUnit.MINUTES);
private EditorFixture myEditor;
private NewActivityWizardFixture myDialog;
private ConfigureBasicActivityStepFixture<NewActivityWizardFixture> myConfigActivity;
@Before
public void setUp() throws IOException {
guiTest.importProjectAndWaitForProjectSyncToFinish("SimpleApplication", Wait.seconds(120));
guiTest.ideFrame().getProjectView().selectProjectPane();
myEditor = guiTest.ideFrame().getEditor();
myEditor.open(PROVIDED_ACTIVITY);
guiTest.ideFrame().getProjectView().assertFilesExist(
"settings.gradle",
"app",
PROVIDED_ACTIVITY,
PROVIDED_MANIFEST
);
invokeNewActivityMenu();
assertTextFieldValues(DEFAULT_ACTIVITY_NAME, DEFAULT_LAYOUT_NAME);
assertThat(getSavedKotlinSupport()).isFalse();
assertThat(getSavedRenderSourceLanguage()).isEqualTo(Language.Java);
}
/**
* Verifies that a new activity can be created through the Wizard
* <p>
* This is run to qualify releases. Please involve the test team in substantial changes.
* <p>
* TT ID: 9ab45c50-1eb0-44aa-95fb-17835baf2274
* <p>
* <pre>
* Test Steps:
* 1. Right click on the application module and select New > Activity > Basic Activity
* 2. Enter activity and package name. Click Finish
* Verify:
* Activity class and layout.xml files are created. The activity previews correctly in layout editor.
* </pre>
*/
@RunIn(TestGroup.SANITY_BAZEL)
@Test
public void createDefaultActivity() {
myDialog.clickFinishAndWaitForSyncToFinish();
guiTest.ideFrame().getProjectView().assertFilesExist(
"app/src/main/java/google/simpleapplication/MainActivity.java",
"app/src/main/res/layout/activity_main.xml"
);
String manifesText = guiTest.getProjectFileText(PROVIDED_MANIFEST);
assertEquals(1, getOccurrenceCount(manifesText, "android:name=\".MainActivity\""));
assertEquals(1, getOccurrenceCount(manifesText, "@string/title_activity_main"));
assertEquals(1, getOccurrenceCount(manifesText, "android.intent.category.LAUNCHER"));
String gradleText = guiTest.getProjectFileText(APP_BUILD_GRADLE);
assertEquals(1, getOccurrenceCount(gradleText, "com.android.support.constraint:constraint-layout"));
}
// Note: This should be called only when the last open file was a Java/Kotlin file
private void invokeNewActivityMenu() {
guiTest.ideFrame().invokeMenuPath("File", "New", "Activity", "Basic Activity");
myDialog = NewActivityWizardFixture.find(guiTest.ideFrame());
myConfigActivity = myDialog.getConfigureActivityStep();
}
private void assertTextFieldValues(@NotNull String activityName, @NotNull String layoutName) {
assertThat(myConfigActivity.getTextFieldValue(ConfigureBasicActivityStepFixture.ActivityTextField.NAME)).isEqualTo(activityName);
assertThat(myConfigActivity.getTextFieldValue(ConfigureBasicActivityStepFixture.ActivityTextField.LAYOUT)).isEqualTo(layoutName);
}
private static boolean getSavedKotlinSupport() {
return PropertiesComponent.getInstance().isTrueValue("SAVED_PROJECT_KOTLIN_SUPPORT");
}
@NotNull
private static Language getSavedRenderSourceLanguage() {
return Language.fromName(PropertiesComponent.getInstance().getValue("SAVED_RENDER_LANGUAGE"), Language.Java);
}
}
| 1,794 |
679 |
/**************************************************************
*
* 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 ov;
import javax.swing.JPanel;
import com.sun.star.accessibility.XAccessibleContext;
/** This is the base class for all object views that can be placed inside an
object view container.
<p>When provided with a new accessible object the container will call
the Create method to create a new instance when certain conditions are
met. It then calls SetObject to pass the object to the instance.
Finally it calls Update.</p>
<p>The SetObject and Update methods may be called for a new object
without calling Create first. In this way an existing instance is
recycled.</p>
*/
abstract public class ObjectView
extends JPanel
{
/** This factory method creates a new instance of the (derived) class
when the given accessible object supports all necessary features.
In the ususal case this will be the support of a specific
accessibility interface.
*/
static public ObjectView Create (
ObjectViewContainer aContainer,
XAccessibleContext xContext)
{
return null;
}
public ObjectView (ObjectViewContainer aContainer)
{
maContainer = aContainer;
mxContext = null;
}
/** Call this when you want the object to be destroyed. Release all
resources when called.
*/
public void Destroy ()
{
}
/** Tell the view to display information for a new accessible object.
@param xObject
The given object may be null. A typical behaviour in this case
would be to display a blank area. But is also possible to show
information about the last object.
*/
public void SetObject (XAccessibleContext xContext)
{
mxContext = xContext;
Update ();
}
/** This is a request of a repaint with the current state of the current
object. The current object may or may not be the same as the one
when Update() was called the last time.
*/
public void Update ()
{
}
/** Return a string that is used as a title of an enclosing frame.
*/
abstract public String GetTitle ();
/// Reference to the current object to display information about.
protected XAccessibleContext mxContext;
protected ObjectViewContainer maContainer;
}
| 957 |
3,934 |
# This sample tests various "literal math" binary and unary operations that
# are applied when all operands are literal types with the same associated
# class.
from typing import Literal
def func1(a: Literal[1, 2], b: Literal[0, 4], c: Literal[3, 4]):
c1 = a * b + c
reveal_type(c1, expected_text="Literal[3, 4, 7, 8, 11, 12]")
c2 = a // 0
reveal_type(c2, expected_text="int")
c3 = a % 0
reveal_type(c3, expected_text="int")
c4 = ((a * 1000) % 39) // c
reveal_type(c4, expected_text="Literal[8, 6, 3, 2]")
c5 = a + True
reveal_type(c5, expected_text="int")
c1 -= 5
reveal_type(c1, expected_text="Literal[-2, -1, 2, 3, 6, 7]")
c1 = -c1
reveal_type(c1, expected_text="Literal[2, 1, -2, -3, -6, -7]")
c1 = +c1
reveal_type(c1, expected_text="Literal[2, 1, -2, -3, -6, -7]")
c6 = 1
for _ in range(100):
c6 += a
reveal_type(c6, expected_text="int")
def func2(cond: bool):
c1 = "Hi " + ("Steve" if cond else "Amy")
reveal_type(c1, expected_text="Literal['Hi Steve', 'Hi Amy']")
def func3(cond: bool):
c1 = b"Hi " + (b"Steve" if cond else b"Amy")
reveal_type(c1, expected_text="Literal[b'Hi Steve', b'Hi Amy']")
def func4(a: Literal[True], b: Literal[False]):
c1 = a and b
reveal_type(c1, expected_text="Literal[False]")
c2 = a and a
reveal_type(c2, expected_text="Literal[True]")
c3 = a or b
reveal_type(c3, expected_text="Literal[True]")
c4 = not a
reveal_type(c4, expected_text="Literal[False]")
c5 = not b
reveal_type(c5, expected_text="Literal[True]")
c6 = not b and not a
reveal_type(c6, expected_text="Literal[False]")
c7 = not b or not a
reveal_type(c7, expected_text="Literal[True]")
c8 = b
reveal_type(c8, expected_text="Literal[False]")
while True:
c8 = not c8
reveal_type(c8, expected_text="bool")
mode = Literal[
"a",
"b",
"c",
"d",
"e",
"f",
"g",
"h",
"i",
"j",
"k",
"l",
"m",
"n",
"o",
"p",
"q",
"r",
"s",
"t",
"u",
"v",
"w",
"z",
"y",
"z",
]
def func5(
a: mode, b: mode, c: mode, d: mode, e: mode, f: mode, g: mode, h: mode, i: mode
):
# Make sure this degenerate case falls back to "str".
reveal_type(a + b + c + d + e + f + g + h + i, expected_text="str")
def func6(x: Literal[1, 3, 5, 7, 11, 13]):
y = x
y *= x
reveal_type(
y,
expected_text="Literal[1, 3, 5, 7, 11, 13, 9, 15, 21, 33, 39, 25, 35, 55, 65, 49, 77, 91, 121, 143, 169]",
)
y *= x
reveal_type(y, expected_text="int")
| 1,305 |
1,116 |
/*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2018 Pilz GmbH & Co. KG
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Pilz GmbH & Co. KG nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*********************************************************************/
#include "pilz_industrial_motion_planner/trajectory_blender_transition_window.h"
#include <algorithm>
#include <memory>
#include <math.h>
#include <tf2_eigen/tf2_eigen.h>
#include <moveit/planning_interface/planning_interface.h>
bool pilz_industrial_motion_planner::TrajectoryBlenderTransitionWindow::blend(
const planning_scene::PlanningSceneConstPtr& planning_scene,
const pilz_industrial_motion_planner::TrajectoryBlendRequest& req,
pilz_industrial_motion_planner::TrajectoryBlendResponse& res)
{
ROS_INFO("Start trajectory blending using transition window.");
double sampling_time = 0.;
if (!validateRequest(req, sampling_time, res.error_code))
{
ROS_ERROR("Trajectory blend request is not valid.");
return false;
}
// search for intersection points of the two trajectories with the blending
// sphere
// intersection points belongs to blend trajectory after blending
std::size_t first_intersection_index;
std::size_t second_intersection_index;
if (!searchIntersectionPoints(req, first_intersection_index, second_intersection_index))
{
ROS_ERROR("Blend radius to large.");
res.error_code.val = moveit_msgs::MoveItErrorCodes::INVALID_MOTION_PLAN;
return false;
}
// Select blending period and adjust the start and end point of the blend
// phase
std::size_t blend_align_index;
determineTrajectoryAlignment(req, first_intersection_index, second_intersection_index, blend_align_index);
// blend the trajectories in Cartesian space
pilz_industrial_motion_planner::CartesianTrajectory blend_trajectory_cartesian;
blendTrajectoryCartesian(req, first_intersection_index, second_intersection_index, blend_align_index, sampling_time,
blend_trajectory_cartesian);
// generate the blending trajectory in joint space
std::map<std::string, double> initial_joint_position, initial_joint_velocity;
for (const std::string& joint_name :
req.first_trajectory->getFirstWayPointPtr()->getJointModelGroup(req.group_name)->getActiveJointModelNames())
{
initial_joint_position[joint_name] =
req.first_trajectory->getWayPoint(first_intersection_index - 1).getVariablePosition(joint_name);
initial_joint_velocity[joint_name] =
req.first_trajectory->getWayPoint(first_intersection_index - 1).getVariableVelocity(joint_name);
}
trajectory_msgs::JointTrajectory blend_joint_trajectory;
moveit_msgs::MoveItErrorCodes error_code;
if (!generateJointTrajectory(planning_scene, limits_.getJointLimitContainer(), blend_trajectory_cartesian,
req.group_name, req.link_name, initial_joint_position, initial_joint_velocity,
blend_joint_trajectory, error_code, true))
{
// LCOV_EXCL_START
ROS_INFO("Failed to generate joint trajectory for blending trajectory.");
res.error_code.val = error_code.val;
return false;
// LCOV_EXCL_STOP
}
res.first_trajectory = std::make_shared<robot_trajectory::RobotTrajectory>(req.first_trajectory->getRobotModel(),
req.first_trajectory->getGroup());
res.blend_trajectory = std::make_shared<robot_trajectory::RobotTrajectory>(req.first_trajectory->getRobotModel(),
req.first_trajectory->getGroup());
res.second_trajectory = std::make_shared<robot_trajectory::RobotTrajectory>(req.first_trajectory->getRobotModel(),
req.first_trajectory->getGroup());
// set the three trajectories after blending in response
// erase the points [first_intersection_index, back()] from the first
// trajectory
for (size_t i = 0; i < first_intersection_index; ++i)
{
res.first_trajectory->insertWayPoint(i, req.first_trajectory->getWayPoint(i),
req.first_trajectory->getWayPointDurationFromPrevious(i));
}
// append the blend trajectory
res.blend_trajectory->setRobotTrajectoryMsg(req.first_trajectory->getFirstWayPoint(), blend_joint_trajectory);
// copy the points [second_intersection_index, len] from the second trajectory
for (size_t i = second_intersection_index + 1; i < req.second_trajectory->getWayPointCount(); ++i)
{
res.second_trajectory->insertWayPoint(i - (second_intersection_index + 1), req.second_trajectory->getWayPoint(i),
req.second_trajectory->getWayPointDurationFromPrevious(i));
}
// adjust the time from start
res.second_trajectory->setWayPointDurationFromPrevious(0, sampling_time);
res.error_code.val = moveit_msgs::MoveItErrorCodes::SUCCESS;
return true;
}
bool pilz_industrial_motion_planner::TrajectoryBlenderTransitionWindow::validateRequest(
const pilz_industrial_motion_planner::TrajectoryBlendRequest& req, double& sampling_time,
moveit_msgs::MoveItErrorCodes& error_code) const
{
ROS_DEBUG("Validate the trajectory blend request.");
// check planning group
if (!req.first_trajectory->getRobotModel()->hasJointModelGroup(req.group_name))
{
ROS_ERROR_STREAM("Unknown planning group: " << req.group_name);
error_code.val = moveit_msgs::MoveItErrorCodes::INVALID_GROUP_NAME;
return false;
}
// check link exists
if (!req.first_trajectory->getRobotModel()->hasLinkModel(req.link_name) &&
!req.first_trajectory->getLastWayPoint().hasAttachedBody(req.link_name))
{
ROS_ERROR_STREAM("Unknown link name: " << req.link_name);
error_code.val = moveit_msgs::MoveItErrorCodes::INVALID_LINK_NAME;
return false;
}
if (req.blend_radius <= 0)
{
ROS_ERROR("Blending radius must be positive");
error_code.val = moveit_msgs::MoveItErrorCodes::INVALID_MOTION_PLAN;
return false;
}
// end position of the first trajectory and start position of second
// trajectory must be the same
if (!pilz_industrial_motion_planner::isRobotStateEqual(
req.first_trajectory->getLastWayPoint(), req.second_trajectory->getFirstWayPoint(), req.group_name, EPSILON))
{
ROS_ERROR_STREAM("During blending the last point of the preceding and the first point of the succeding trajectory");
error_code.val = moveit_msgs::MoveItErrorCodes::INVALID_MOTION_PLAN;
return false;
}
// same uniform sampling time
if (!pilz_industrial_motion_planner::determineAndCheckSamplingTime(req.first_trajectory, req.second_trajectory,
EPSILON, sampling_time))
{
error_code.val = moveit_msgs::MoveItErrorCodes::INVALID_MOTION_PLAN;
return false;
}
// end position of the first trajectory and start position of second
// trajectory must have zero
// velocities/accelerations
if (!pilz_industrial_motion_planner::isRobotStateStationary(req.first_trajectory->getLastWayPoint(), req.group_name,
EPSILON) ||
!pilz_industrial_motion_planner::isRobotStateStationary(req.second_trajectory->getFirstWayPoint(), req.group_name,
EPSILON))
{
ROS_ERROR("Intersection point of the blending trajectories has non-zero "
"velocities/accelerations.");
error_code.val = moveit_msgs::MoveItErrorCodes::INVALID_MOTION_PLAN;
return false;
}
return true;
}
void pilz_industrial_motion_planner::TrajectoryBlenderTransitionWindow::blendTrajectoryCartesian(
const pilz_industrial_motion_planner::TrajectoryBlendRequest& req, const std::size_t first_interse_index,
const std::size_t second_interse_index, const std::size_t blend_align_index, double sampling_time,
pilz_industrial_motion_planner::CartesianTrajectory& trajectory) const
{
// other fields of the trajectory
trajectory.group_name = req.group_name;
trajectory.link_name = req.link_name;
// Pose on first trajectory
Eigen::Isometry3d blend_sample_pose1 =
req.first_trajectory->getWayPoint(first_interse_index).getFrameTransform(req.link_name);
// Pose on second trajectory
Eigen::Isometry3d blend_sample_pose2 =
req.second_trajectory->getWayPoint(second_interse_index).getFrameTransform(req.link_name);
// blend the trajectory
double blend_sample_num = second_interse_index + blend_align_index - first_interse_index + 1;
pilz_industrial_motion_planner::CartesianTrajectoryPoint waypoint;
blend_sample_pose2 = req.second_trajectory->getFirstWayPoint().getFrameTransform(req.link_name);
// Pose on blending trajectory
Eigen::Isometry3d blend_sample_pose;
for (std::size_t i = 0; i < blend_sample_num; ++i)
{
// if the first trajectory does not reach the last sample, update
if ((first_interse_index + i) < req.first_trajectory->getWayPointCount())
{
blend_sample_pose1 = req.first_trajectory->getWayPoint(first_interse_index + i).getFrameTransform(req.link_name);
}
// if after the alignment, the second trajectory starts, update
if ((first_interse_index + i) > blend_align_index)
{
blend_sample_pose2 = req.second_trajectory->getWayPoint(first_interse_index + i - blend_align_index)
.getFrameTransform(req.link_name);
}
double s = (i + 1) / blend_sample_num;
double alpha = 6 * std::pow(s, 5) - 15 * std::pow(s, 4) + 10 * std::pow(s, 3);
// blend the translation
blend_sample_pose.translation() = blend_sample_pose1.translation() +
alpha * (blend_sample_pose2.translation() - blend_sample_pose1.translation());
// blend the orientation
Eigen::Quaterniond start_quat(blend_sample_pose1.rotation());
Eigen::Quaterniond end_quat(blend_sample_pose2.rotation());
blend_sample_pose.linear() = start_quat.slerp(alpha, end_quat).toRotationMatrix();
// push to the trajectory
waypoint.pose = tf2::toMsg(blend_sample_pose);
waypoint.time_from_start = ros::Duration((i + 1.0) * sampling_time);
trajectory.points.push_back(waypoint);
}
}
bool pilz_industrial_motion_planner::TrajectoryBlenderTransitionWindow::searchIntersectionPoints(
const pilz_industrial_motion_planner::TrajectoryBlendRequest& req, std::size_t& first_interse_index,
std::size_t& second_interse_index) const
{
ROS_INFO("Search for start and end point of blending trajectory.");
// compute the position of the center of the blend sphere
// (last point of the first trajectory, first point of the second trajectory)
Eigen::Isometry3d circ_pose = req.first_trajectory->getLastWayPoint().getFrameTransform(req.link_name);
// Searh for intersection points according to distance
if (!linearSearchIntersectionPoint(req.link_name, circ_pose.translation(), req.blend_radius, req.first_trajectory,
true, first_interse_index))
{
ROS_ERROR_STREAM("Intersection point of first trajectory not found.");
return false;
}
ROS_INFO_STREAM("Intersection point of first trajectory found, index: " << first_interse_index);
if (!linearSearchIntersectionPoint(req.link_name, circ_pose.translation(), req.blend_radius, req.second_trajectory,
false, second_interse_index))
{
ROS_ERROR_STREAM("Intersection point of second trajectory not found.");
return false;
}
ROS_INFO_STREAM("Intersection point of second trajectory found, index: " << second_interse_index);
return true;
}
void pilz_industrial_motion_planner::TrajectoryBlenderTransitionWindow::determineTrajectoryAlignment(
const pilz_industrial_motion_planner::TrajectoryBlendRequest& req, std::size_t first_interse_index,
std::size_t second_interse_index, std::size_t& blend_align_index) const
{
size_t way_point_count_1 = req.first_trajectory->getWayPointCount() - first_interse_index;
size_t way_point_count_2 = second_interse_index + 1;
if (way_point_count_1 > way_point_count_2)
{
blend_align_index = req.first_trajectory->getWayPointCount() - second_interse_index - 1;
}
else
{
blend_align_index = first_interse_index;
}
}
| 5,136 |
1,511 |
<reponame>bingchunjin/1806_SDK
/*
* This is from the Android Project,
* Repository: https://android.googlesource.com/platform/system/core
* File: libsparse/sparse_format.h
* Commit: <PASSWORD>
* Copyright (C) 2010 The Android Open Source Project
*
* SPDX-License-Identifier: BSD-3-Clause
*/
#ifndef _LIBSPARSE_SPARSE_FORMAT_H_
#define _LIBSPARSE_SPARSE_FORMAT_H_
#include "sparse_defs.h"
typedef struct sparse_header {
__le32 magic; /* 0xed26ff3a */
__le16 major_version; /* (0x1) - reject images with higher major versions */
__le16 minor_version; /* (0x0) - allow images with higer minor versions */
__le16 file_hdr_sz; /* 28 bytes for first revision of the file format */
__le16 chunk_hdr_sz; /* 12 bytes for first revision of the file format */
__le32 blk_sz; /* block size in bytes, must be a multiple of 4 (4096) */
__le32 total_blks; /* total blocks in the non-sparse output image */
__le32 total_chunks; /* total chunks in the sparse input image */
__le32 image_checksum; /* CRC32 checksum of the original data, counting "don't care" */
/* as 0. Standard 802.3 polynomial, use a Public Domain */
/* table implementation */
} sparse_header_t;
#define SPARSE_HEADER_MAGIC 0xed26ff3a
#define CHUNK_TYPE_RAW 0xCAC1
#define CHUNK_TYPE_FILL 0xCAC2
#define CHUNK_TYPE_DONT_CARE 0xCAC3
#define CHUNK_TYPE_CRC32 0xCAC4
typedef struct chunk_header {
__le16 chunk_type; /* 0xCAC1 -> raw; 0xCAC2 -> fill; 0xCAC3 -> don't care */
__le16 reserved1;
__le32 chunk_sz; /* in blocks in output image */
__le32 total_sz; /* in bytes of chunk input file including chunk header and data */
} chunk_header_t;
/* Following a Raw or Fill or CRC32 chunk is data.
* For a Raw chunk, it's the data in chunk_sz * blk_sz.
* For a Fill chunk, it's 4 bytes of the fill data.
* For a CRC32 chunk, it's 4 bytes of CRC32
*/
#endif
| 719 |
3,358 |
<reponame>jiangjiali/QuantLib<filename>ql/models/marketmodels/callability/triggeredswapexercise.hpp<gh_stars>1000+
/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
Copyright (C) 2006 StatPro Italia srl
This file is part of QuantLib, a free-software/open-source library
for financial quantitative analysts and developers - http://quantlib.org/
QuantLib is free software: you can redistribute it and/or modify it
under the terms of the QuantLib license. You should have received a
copy of the license along with this program; if not, please email
<<EMAIL>>. The license is also available online at
<http://quantlib.org/license.shtml>.
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 license for more details.
*/
#ifndef quantlib_triggered_swap_exercise_hpp
#define quantlib_triggered_swap_exercise_hpp
#include <ql/models/marketmodels/callability/marketmodelparametricexercise.hpp>
#include <ql/models/marketmodels/evolutiondescription.hpp>
namespace QuantLib {
class TriggeredSwapExercise : public MarketModelParametricExercise {
public:
TriggeredSwapExercise(const std::vector<Time>& rateTimes,
const std::vector<Time>& exerciseTimes,
std::vector<Rate> strikes);
// NodeDataProvider interface
Size numberOfExercises() const override;
const EvolutionDescription& evolution() const override;
void nextStep(const CurveState&) override;
void reset() override;
std::valarray<bool> isExerciseTime() const override;
void values(const CurveState&, std::vector<Real>& results) const override;
// ParametricExercise interface
std::vector<Size> numberOfVariables() const override;
std::vector<Size> numberOfParameters() const override;
bool exercise(Size exerciseNumber,
const std::vector<Real>& parameters,
const std::vector<Real>& variables) const override;
void guess(Size exerciseNumber, std::vector<Real>& parameters) const override;
#if defined(QL_USE_STD_UNIQUE_PTR)
std::unique_ptr<MarketModelParametricExercise> clone() const override;
#else
std::auto_ptr<MarketModelParametricExercise> clone() const;
#endif
private:
std::vector<Time> rateTimes_, exerciseTimes_;
std::vector<Rate> strikes_;
Size currentStep_;
std::vector<Size> rateIndex_;
EvolutionDescription evolution_;
};
}
#endif
| 963 |
5,169 |
{
"name": "YGCVideoToolbox",
"version": "0.2.0",
"summary": "A collection of video edit tool",
"description": "A collection of video edit tool.make you slow motion, resize, crop, repeat video easily.",
"homepage": "https://github.com/zangqilong198812/YGCVideoToolbox",
"license": {
"type": "MIT",
"file": "LICENSE"
},
"authors": {
"zangqilong": "<EMAIL>"
},
"source": {
"git": "https://github.com/zangqilong198812/YGCVideoToolbox.git",
"tag": "0.2.0"
},
"platforms": {
"ios": "10.0"
},
"source_files": "YGCVideoToolbox/Classes/*.swift",
"frameworks": [
"AVFoundation",
"Photos"
],
"pod_target_xcconfig": {
"SWIFT_VERSION": "4.0"
},
"pushed_with_swift_version": "4.0"
}
| 320 |
1,455 |
/**
* Dedicated support package for Redis hashes. Provides mapping of objects to hashes/maps (and vice versa).
*/
@org.springframework.lang.NonNullApi
@org.springframework.lang.NonNullFields
package org.springframework.data.redis.hash;
| 68 |
3,702 |
<gh_stars>1000+
// Copyright (c) YugaByte, Inc.
package com.yugabyte.yw.commissioner;
@FunctionalInterface
public interface IUpgradeTaskWrapper {
void run();
}
| 58 |
778 |
// KRATOS ___| | | |
// \___ \ __| __| | | __| __| | | __| _` | |
// | | | | | ( | | | | ( | |
// _____/ \__|_| \__,_|\___|\__|\__,_|_| \__,_|_| MECHANICS
//
// License: BSD License
// license: structural_mechanics_application/license.txt
//
// Main authors: <NAME>
//
#if !defined(KRATOS_SMALL_DISPLACEMENT_SURFACE_LOAD_CONDITION_3D_H_INCLUDED )
#define KRATOS_SMALL_DISPLACEMENT_SURFACE_LOAD_CONDITION_3D_H_INCLUDED
// System includes
// External includes
// Project includes
#include "custom_conditions/surface_load_condition_3d.h"
namespace Kratos
{
///@name Kratos Globals
///@{
///@}
///@name Type Definitions
///@{
///@}
///@name Enum's
///@{
///@}
///@name Functions
///@{
///@}
///@name Kratos Classes
///@{
/**
* @class SmallDisplacementSurfaceLoadCondition3D
* @ingroup StructuralMechanicsApplication
* @brief This class is the responsible to add the contributions of the RHS and LHS of the surface loads of the structure
* @details It allows to consider different types of pressure and surface loads
* @author <NAME>
*/
class KRATOS_API(STRUCTURAL_MECHANICS_APPLICATION) SmallDisplacementSurfaceLoadCondition3D
: public SurfaceLoadCondition3D
{
public:
///@name Type Definitions
///@{
// Counted pointer of SmallDisplacementSurfaceLoadCondition3D
KRATOS_CLASS_INTRUSIVE_POINTER_DEFINITION( SmallDisplacementSurfaceLoadCondition3D );
///@}
///@name Life Cycle
///@{
// Constructor void
SmallDisplacementSurfaceLoadCondition3D();
// Constructor using an array of nodes
SmallDisplacementSurfaceLoadCondition3D(
IndexType NewId,
GeometryType::Pointer pGeometry
);
// Constructor using an array of nodes with properties
SmallDisplacementSurfaceLoadCondition3D(
IndexType NewId,
GeometryType::Pointer pGeometry,
PropertiesType::Pointer pProperties
);
// Destructor
~SmallDisplacementSurfaceLoadCondition3D() override;
///@}
///@name Operators
///@{
///@}
///@name Operations
///@{
/**
* @brief Creates a new condition pointer
* @param NewId the ID of the new condition
* @param ThisNodes the nodes of the new condition
* @param pProperties the properties assigned to the new condition
* @return a Pointer to the new condition
*/
Condition::Pointer Create(
IndexType NewId,
NodesArrayType const& ThisNodes,
PropertiesType::Pointer pProperties
) const override;
/**
* @brief Creates a new condition pointer
* @param NewId the ID of the new condition
* @param pGeom the geometry to be employed
* @param pProperties the properties assigned to the new condition
* @return a Pointer to the new condition
*/
Condition::Pointer Create(
IndexType NewId,
GeometryType::Pointer pGeom,
PropertiesType::Pointer pProperties
) const override;
/**
* @brief Creates a new condition pointer and clones the previous condition data
* @param NewId the ID of the new condition
* @param ThisNodes the nodes of the new condition
* @return a Pointer to the new condition
*/
Condition::Pointer Clone (
IndexType NewId,
NodesArrayType const& ThisNodes
) const override;
///@}
///@name Access
///@{
///@}
///@name Inquiry
///@{
///@}
///@name Input and output
///@{
/// Turn back information as a string.
std::string Info() const override
{
std::stringstream buffer;
buffer << "Small displacement surface load Condition #" << Id();
return buffer.str();
}
/// Print information about this object.
void PrintInfo(std::ostream& rOStream) const override
{
rOStream << "SmallDisplacementSurfaceLoadCondition3D #" << Id();
}
/// Print object's data.
void PrintData(std::ostream& rOStream) const override
{
pGetGeometry()->PrintData(rOStream);
}
///@}
///@name Friends
///@{
protected:
///@name Protected static Member Variables
///@{
///@}
///@name Protected member Variables
///@{
///@}
///@name Protected Operators
///@{
///@}
///@name Protected Operations
///@{
/**
* This functions calculates both the RHS and the LHS
* @param rLeftHandSideMatrix The local LHS contribution
* @param rRightHandSideVector The local RHS contribution
* @param rCurrentProcessInfo The current process info instance
* @param CalculateStiffnessMatrixFlag The flag to set if compute the LHS
* @param CalculateResidualVectorFlag The flag to set if compute the RHS
*/
void CalculateAll(
MatrixType& rLeftHandSideMatrix,
VectorType& rRightHandSideVector,
const ProcessInfo& rCurrentProcessInfo,
const bool CalculateStiffnessMatrixFlag,
const bool CalculateResidualVectorFlag
) override;
///@}
///@name Protected Access
///@{
///@}
///@name Protected Inquiry
///@{
///@}
///@name Protected LifeCycle
///@{
private:
///@name Private static Member Variables
///@{
///@}
///@name Private member Variables
///@{
///@}
///@name Private Operators
///@{
///@}
///@name Private Operations
///@{
///@}
///@name Private Access
///@{
///@}
///@name Private Inquiry
///@{
///@}
///@name Private LifeCycle
///@{
///@}
///@name Unaccessible methods
///@{
///@}
///@name Serialization
///@{
friend class Serializer;
void save( Serializer& rSerializer ) const override
{
KRATOS_SERIALIZE_SAVE_BASE_CLASS( rSerializer, SurfaceLoadCondition3D );
}
void load( Serializer& rSerializer ) override
{
KRATOS_SERIALIZE_LOAD_BASE_CLASS( rSerializer, SurfaceLoadCondition3D );
}
}; // class SmallDisplacementSurfaceLoadCondition3D.
///@name Type Definitions
///@{
///@}
///@name Input and output
///@{
} // namespace Kratos.
#endif // KRATOS_SMALL_DISPLACEMENT_SURFACE_LOAD_CONDITION_3D_H_INCLUDED defined
| 2,477 |
333 |
package com.alipay.api.response;
import com.alipay.api.internal.mapping.ApiField;
import com.alipay.api.AlipayResponse;
/**
* ALIPAY API: alipay.commerce.transport.veh.order.refund response.
*
* @author <NAME>
* @since 1.0, 2021-06-05 22:16:25
*/
public class AlipayCommerceTransportVehOrderRefundResponse extends AlipayResponse {
private static final long serialVersionUID = 2875625968292518153L;
/**
* 退款金额
*/
@ApiField("refund_amount")
private String refundAmount;
/**
* 分润金额
*/
@ApiField("refund_applets_service_amount")
private String refundAppletsServiceAmount;
/**
* 支付宝交易号
*/
@ApiField("trade_no")
private String tradeNo;
public void setRefundAmount(String refundAmount) {
this.refundAmount = refundAmount;
}
public String getRefundAmount( ) {
return this.refundAmount;
}
public void setRefundAppletsServiceAmount(String refundAppletsServiceAmount) {
this.refundAppletsServiceAmount = refundAppletsServiceAmount;
}
public String getRefundAppletsServiceAmount( ) {
return this.refundAppletsServiceAmount;
}
public void setTradeNo(String tradeNo) {
this.tradeNo = tradeNo;
}
public String getTradeNo( ) {
return this.tradeNo;
}
}
| 513 |
348 |
package com.netflix.raigad.defaultimpl;
import com.google.common.io.Files;
import com.netflix.raigad.configuration.FakeConfiguration;
import com.netflix.raigad.configuration.IConfiguration;
import org.junit.Before;
import org.junit.Test;
import java.io.File;
import java.io.IOException;
public class TestStandardTuner {
private IConfiguration config;
private StandardTuner tuner;
@Before
public void setup() {
config = new FakeConfiguration();
tuner = new StandardTuner(config);
}
@Test
public void dump() throws IOException {
String target = "/tmp/raigad_test.yaml";
Files.copy(new File("src/test/resources/elasticsearch.yml"), new File("/tmp/raigad_test.yaml"));
tuner.writeAllProperties(target, "your_host");
}
}
| 291 |
2,344 |
<reponame>atiasn/novel<gh_stars>1000+
#!/usr/bin/env python
"""
Created by howie.hu at 2018/10/17.
"""
import asyncio
import random
from ruia import Request
from owllook.config import CONFIG
async def get_proxy_ip(valid: int = 1) -> str:
# random_server = ['http://0.0.0.0:8662/']
proxy_server = CONFIG.REMOTE_SERVER.get('proxy_server')
# proxy_server = random_server[random.randint(0, 1)]
kwargs = {
'json': {
"act_id": 1704,
"version": "1.0",
"data": {
"valid": 1
}
}
}
res = await Request(url=proxy_server, method='POST', res_type='json', **kwargs).fetch()
proxy = ''
if res.status == 200:
proxy = res.html.get('info').get('proxy')
return proxy
if __name__ == '__main__':
print(asyncio.get_event_loop().run_until_complete(get_proxy_ip()))
| 402 |
2,724 |
<reponame>piejanssens/openui5<gh_stars>1000+
{
"sap.app": {
"id": "sap.ui.core.sample.ControllerExtension",
"applicationVersion": {
"version": "1.0.0"
}
},
"sap.ui5": {
"rootView": {
"viewName": "sap.ui.core.sample.ControllerExtension.Main",
"type": "XML",
"async": true,
"id": "main"
},
"dependencies": {
"libs": {
"sap.ui.fl": {}
}
},
"config": {
"sample": {
"files": [
"Main.view.xml",
"Main.controller.js",
"ReuseExtension.js",
"CustomerExtension.js",
"CustomerExtension.fragment.xml",
"OtherCustomerExtension.js",
"OtherCustomerExtension.fragment.xml",
"Component.js",
"manifest.json"
]
}
}
}
}
| 367 |
565 |
<reponame>emesz761/JniHelpers
/*
* Copyright (c) 2014 Spotify AB
*
* 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 "TestObject.h"
TestObject::TestObject() : JavaClass(),
string(), i(0), s(0), f(0.0f), d(0.0), z(false), b(0), c(0) {
}
TestObject::TestObject(JNIEnv *env) : JavaClass(env),
string(), i(0), s(0), f(0.0f), d(0.0), z(false), b(0), c(0) {
initialize(env);
// Set up field mappings for the instance. Normally this isn't necessary,
// since the global instance is typically used for merging into other objects.
// If you want to actually use the initialized instance in combination with
// setJavaObject(), you should call this though.
merge(this);
}
void TestObject::initialize(JNIEnv *env) {
setClass(env);
// Cache some jfieldIDs for quick lookup later. Note that this is necessary
// for the corresponding fields to be mapped in mapFields().
cacheField(env, "string", kTypeString);
cacheField(env, "i", kTypeInt);
cacheField(env, "s", kTypeShort);
cacheField(env, "f", kTypeFloat);
cacheField(env, "d", kTypeDouble);
cacheField(env, "z", kTypeBool);
cacheField(env, "b", kTypeByte);
cacheField(env, "c", kTypeChar);
// cacheField(env, "b", kTypeArray(kTypeByte));
// Cache default constructor
cacheConstructor(env);
// Cache methods for later. Currently these are unused, but would provide an
// easy mechanism for calling Java methods. Note that when calling cacheMethod,
// the last argument must always be NULL. See the documentation for
// JavaClassUtils::makeSignature for more details.
cacheMethod(env, "getString", kTypeString, NULL);
cacheMethod(env, "setString", kTypeVoid, kTypeString, NULL);
cacheMethod(env, "getI", kTypeInt, NULL);
cacheMethod(env, "setI", kTypeVoid, kTypeInt, NULL);
cacheMethod(env, "getS", kTypeShort, NULL);
cacheMethod(env, "setS", kTypeVoid, kTypeShort, NULL);
cacheMethod(env, "getF", kTypeFloat, NULL);
cacheMethod(env, "setF", kTypeVoid, kTypeFloat, NULL);
cacheMethod(env, "getD", kTypeDouble, NULL);
cacheMethod(env, "setD", kTypeVoid, kTypeDouble, NULL);
cacheMethod(env, "getZ", kTypeBool, NULL);
cacheMethod(env, "setZ", kTypeVoid, kTypeBool, NULL);
cacheMethod(env, "getB", kTypeByte, NULL);
cacheMethod(env, "setB", kTypeVoid, kTypeByte, NULL);
cacheMethod(env, "getC", kTypeChar, NULL);
cacheMethod(env, "setC", kTypeVoid, kTypeChar, NULL);
// TODO: Getters/setters for byte array
}
void TestObject::mapFields() {
mapField("i", kTypeInt, &i);
mapField("s", kTypeShort, &s);
mapField("f", kTypeFloat, &f);
mapField("d", kTypeDouble, &d);
mapField("string", kTypeString, &string);
mapField("z", kTypeBool, &z);
mapField("b", kTypeByte, &b);
mapField("c", kTypeChar, &c);
}
| 1,139 |
1,290 |
<filename>Z - Tool Box/LaZagne/Windows/lazagne/softwares/memory/libkeepass/common.py
# -*- coding: utf-8 -*-
import base64
import codecs
import io
import struct
from xml.etree import ElementTree
from .crypto import sha256
try:
file_types = (file, io.IOBase)
except NameError:
file_types = (io.IOBase,)
# file header
class HeaderDictionary(dict):
"""
A dictionary on steroids for comfortable header field storage and
manipulation.
Header fields must be defined in the `fields` property before filling the
dictionary with data. The `fields` property is a simple dictionary, where
keys are field names (string) and values are field ids (int)::
>>> h.fields['rounds'] = 4
Now you can set and get values using the field id or the field name
interchangeably::
>>> h[4] = 3000
>>> print h['rounds']
3000
>>> h['rounds'] = 6000
>>> print h[4]
6000
It is also possible to get and set data using the field name as an
attribute::
>>> h.rounds = 9000
>>> print h[4]
9000
>>> print h.rounds
9000
For some fields it is more comfortable to unpack their byte value into
a numeric or character value (eg. the transformation rounds). For those
fields add a format string to the `fmt` dictionary. Use the field id as
key::
>>> h.fmt[4] = '<q'
Continue setting the value as before if you have it as a number and if you
need it as a number, get it like before. Only when you have the packed value
use a different interface::
>>> h.b.rounds = '\x70\x17\x00\x00\x00\x00\x00\x00'
>>> print h.b.rounds
'\x70\x17\x00\x00\x00\x00\x00\x00'
>>> print h.rounds
6000
The `b` (binary?) attribute is a special way to set and get data in its
packed format, while the usual attribute or dictionary access allows
setting and getting a numeric value::
>>> h.rounds = 3000
>>> print h.b.rounds
'\xb8\x0b\x00\x00\x00\x00\x00\x00'
>>> print h.rounds
3000
"""
fields = {}
fmt = {}
def __init__(self, *args):
dict.__init__(self, *args)
def __getitem__(self, key):
if isinstance(key, int):
return dict.__getitem__(self, key)
else:
return dict.__getitem__(self, self.fields[key])
def __setitem__(self, key, val):
if isinstance(key, int):
dict.__setitem__(self, key, val)
else:
dict.__setitem__(self, self.fields[key], val)
def __getattr__(self, key):
class wrap(object):
def __init__(self, d):
object.__setattr__(self, 'd', d)
def __getitem__(self, key):
fmt = self.d.fmt.get(self.d.fields.get(key, key))
if fmt:
return struct.pack(fmt, self.d[key])
else:
return self.d[key]
__getattr__ = __getitem__
def __setitem__(self, key, val):
fmt = self.d.fmt.get(self.d.fields.get(key, key))
if fmt:
self.d[key] = struct.unpack(fmt, val)[0]
else:
self.d[key] = val
__setattr__ = __setitem__
if key == 'b':
return wrap(self)
try:
return self.__getitem__(key)
except KeyError:
raise AttributeError(key)
def __setattr__(self, key, val):
try:
return self.__setitem__(key, val)
except KeyError:
return dict.__setattr__(self, key, val)
# file baseclass
class KDBFile(object):
def __init__(self, stream=None, **credentials):
# list of hashed credentials (pre-transformation)
self.keys = []
self.add_credentials(**credentials)
# the buffer containing the decrypted/decompressed payload from a file
self.in_buffer = None
# the buffer filled with data for writing back to a file before
# encryption/compression
self.out_buffer = None
# position in the `in_buffer` where the payload begins
self.header_length = None
# decryption success flag, set this to true upon verification of the
# encryption masterkey. if this is True `in_buffer` must contain
# clear data.
self.opened = False
# the raw/basic file handle, expect it to be closed after __init__!
if stream is not None:
if not isinstance(stream, io.IOBase):
raise TypeError('Stream does not have the buffer interface.')
self.read_from(stream)
def read_from(self, stream):
if not (isinstance(stream, io.IOBase) or isinstance(stream, file_types)):
raise TypeError('Stream does not have the buffer interface.')
self._read_header(stream)
self._decrypt(stream)
def _read_header(self, stream):
raise NotImplementedError('The _read_header method was not '
'implemented propertly.')
def _decrypt(self, stream):
self._make_master_key()
# move read pointer beyond the file header
if self.header_length is None:
raise IOError('Header length unknown. Parse the header first!')
stream.seek(self.header_length)
def write_to(self, stream):
raise NotImplementedError('The write_to() method was not implemented.')
def add_credentials(self, **credentials):
if credentials.get('password'):
self.add_key_hash(sha256(credentials['password']))
if credentials.get('keyfile'):
self.add_key_hash(load_keyfile(credentials['keyfile']))
def clear_credentials(self):
"""Remove all previously set encryption key hashes."""
self.keys = []
def add_key_hash(self, key_hash):
"""
Add an encryption key hash, can be a hashed password or a hashed
keyfile. Two things are important: must be SHA256 hashes and sequence is
important: first password if any, second key file if any.
"""
if key_hash is not None:
self.keys.append(key_hash)
def _make_master_key(self):
if len(self.keys) == 0:
raise IndexError('No credentials found.')
def close(self):
if self.in_buffer:
self.in_buffer.close()
def read(self, n=-1):
"""
Read the decrypted and uncompressed data after the file header.
For example, in KDB4 this would be plain, utf-8 xml.
Note that this is the source data for the lxml.objectify element tree
at `self.obj_root`. Any changes made to the parsed element tree will
NOT be reflected in that data stream! Use `self.pretty_print` to get
XML output from the element tree.
"""
if self.in_buffer:
return self.in_buffer.read(n)
def seek(self, offset, whence=io.SEEK_SET):
if self.in_buffer:
return self.in_buffer.seek(offset, whence)
def tell(self):
if self.in_buffer:
return self.in_buffer.tell()
# loading keyfiles
def load_keyfile(filename):
try:
return load_xml_keyfile(filename)
except Exception:
pass
try:
return load_plain_keyfile(filename)
except Exception:
pass
def load_xml_keyfile(filename):
"""
// Sample XML file:
// <?xml version="1.0" encoding="utf-8"?>
// <KeyFile>
// <Meta>
// <Version>1.00</Version>
// </Meta>
// <Key>
// <Data>ySFoKuCcJblw8ie6RkMBdVCnAf4EedSch7ItujK6bmI=</Data>
// </Key>
// </KeyFile>
"""
with open(filename, 'r') as f:
# ignore meta, currently there is only version "1.00"
tree = ElementTree.parse(f).getroot()
# read text from key, data and convert from base64
return base64.b64decode(tree.find('Key/Data').text)
# raise IOError('Could not parse XML keyfile.')
def load_plain_keyfile(filename):
"""
A "plain" keyfile is a file containing only the key.
Any other file (JPEG, MP3, ...) can also be used as keyfile.
"""
with open(filename, 'rb') as f:
key = f.read()
# if the length is 32 bytes we assume it is the key
if len(key) == 32:
return key
# if the length is 64 bytes we assume the key is hex encoded
if len(key) == 64:
return codecs.decode(key, 'hex')
# anything else may be a file to hash for the key
return sha256(key)
# raise IOError('Could not read keyfile.')
def stream_unpack(stream, offset, length, typecode='I'):
if offset is not None:
stream.seek(offset)
data = stream.read(length)
return struct.unpack('<' + typecode, data)[0]
def read_signature(stream):
sig1 = stream_unpack(stream, 0, 4)
sig2 = stream_unpack(stream, None, 4)
# ver_minor = stream_unpack(stream, None, 2, 'h')
# ver_major = stream_unpack(stream, None, 2, 'h')
# return (sig1, sig2, ver_major, ver_minor)
return sig1, sig2
| 3,975 |
575 |
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CHROME_BROWSER_UI_ASH_CHROME_LAUNCHER_PREFS_H_
#define CHROME_BROWSER_UI_ASH_CHROME_LAUNCHER_PREFS_H_
#include <vector>
#include "ash/public/cpp/shelf_types.h"
#include "base/feature_list.h"
#include "base/metrics/field_trial_params.h"
class LauncherControllerHelper;
class PrefService;
class Profile;
namespace user_prefs {
class PrefRegistrySyncable;
} // namespace user_prefs
// Key for the dictionary entries in the prefs::kPinnedLauncherApps list
// specifying the extension ID of the app to be pinned by that entry.
extern const char kPinnedAppsPrefAppIDKey[];
extern const char kPinnedAppsPrefPinnedByPolicy[];
// Value used as a placeholder in the list of pinned applications.
// This is NOT a valid extension identifier so pre-M31 versions ignore it.
extern const char kPinnedAppsPlaceholder[];
void RegisterChromeLauncherUserPrefs(
user_prefs::PrefRegistrySyncable* registry);
// Init a local pref from a synced pref, if the local pref has no user setting.
// This is used to init shelf alignment and auto-hide on the first user sync.
// The goal is to apply the last elected shelf alignment and auto-hide values
// when a user signs in to a new device for the first time. Otherwise, shelf
// properties are persisted per-display/device. The local prefs are initialized
// with synced (or default) values when when syncing begins, to avoid syncing
// shelf prefs across devices after the very start of the user's first session.
void InitLocalPref(PrefService* prefs, const char* local, const char* synced);
// Gets the ordered list of pinned apps that exist on device from the app sync
// service.
std::vector<ash::ShelfID> GetPinnedAppsFromSync(
LauncherControllerHelper* helper);
// Gets the ordered list of apps that have been pinned by policy.
std::vector<std::string> GetAppsPinnedByPolicy(
LauncherControllerHelper* helper);
// Removes information about pin position from sync model for the app.
// Note, |shelf_id| with non-empty launch_id is not supported.
void RemovePinPosition(Profile* profile, const ash::ShelfID& shelf_id);
// Updates information about pin position in sync model for the app |shelf_id|.
// |shelf_id_before| optionally specifies an app that exists right before the
// target app. |shelf_ids_after| optionally specifies sorted by position apps
// that exist right after the target app.
// Note, |shelf_id| with non-empty launch_id is not supported.
void SetPinPosition(Profile* profile,
const ash::ShelfID& shelf_id,
const ash::ShelfID& shelf_id_before,
const std::vector<ash::ShelfID>& shelf_ids_after);
// Makes GetPinnedAppsFromSync() return an empty list. Avoids test failures with
// SplitSettingsSync due to an untitled Play Store icon in the shelf.
// https://crbug.com/1085597
void SkipPinnedAppsFromSyncForTest();
#endif // CHROME_BROWSER_UI_ASH_CHROME_LAUNCHER_PREFS_H_
| 935 |
1,473 |
<reponame>ljmf00/autopsy
/*
* Autopsy Forensic Browser
*
* Copyright 2014 Basis Technology Corp.
* Contact: carrier <at> sleuthkit <dot> org
*
* 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.sleuthkit.autopsy.modules.interestingitems;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.sleuthkit.autopsy.ingest.IngestModuleIngestJobSettings;
/**
* Ingest job settings for interesting files identifier ingest modules.
*/
final class FilesIdentifierIngestJobSettings implements IngestModuleIngestJobSettings {
private static final long serialVersionUID = 1L;
private Set<String> enabledFilesSetNames = new HashSet<>();
private Set<String> disabledFilesSetNames = new HashSet<>();
/**
* Construct the ingest job settings for an interesting files identifier
* ingest module.
*
* @param enabledFilesSetNames The names of the interesting files sets that
* are enabled for the ingest job.
*/
FilesIdentifierIngestJobSettings(List<String> enabledFilesSetNames) {
this(enabledFilesSetNames, new ArrayList<>());
}
/**
* Construct the ingest job settings for an interesting files identifier
* ingest module.
*
* @param enabledFilesSetNames The names of the interesting files sets that
* are enabled for the ingest job.
* @param disabledFilesSetNames The names of the interesting files sets that
* are disabled for the ingest job.
*/
FilesIdentifierIngestJobSettings(List<String> enabledFilesSetNames, List<String> disabledFilesSetNames) {
this.enabledFilesSetNames = new HashSet<>(enabledFilesSetNames);
this.disabledFilesSetNames = new HashSet<>(disabledFilesSetNames);
}
/**
* @inheritDoc
*/
@Override
public long getVersionNumber() {
return FilesIdentifierIngestJobSettings.serialVersionUID;
}
/**
* Determines whether or not an interesting files set definition is enabled
* for an ingest job. If there is no setting for the requested files set, it
* is deemed to be enabled.
*
* @param filesSetName The name of the files set definition to check.
*
* @return True if the file set is enabled, false otherwise.
*/
boolean interestingFilesSetIsEnabled(String filesSetName) {
return !(this.disabledFilesSetNames.contains(filesSetName));
}
/**
* Get the names of all explicitly enabled interesting files set
* definitions.
*
* @return The list of names.
*/
List<String> getNamesOfEnabledInterestingFilesSets() {
return new ArrayList<>(this.enabledFilesSetNames);
}
/**
* Get the names of all explicitly disabled interesting files set
* definitions.
*
* @return The list of names.
*/
List<String> getNamesOfDisabledInterestingFilesSets() {
return new ArrayList<>(disabledFilesSetNames);
}
}
| 1,190 |
615 |
<reponame>Lolik111/meta<gh_stars>100-1000
/**
* @file hash.h
* @author <NAME>
*
* All files in META are dual-licensed under the MIT and NCSA licenses. For more
* details, consult the file LICENSE.mit and LICENSE.ncsa in the root of the
* project.
*/
#ifndef META_HASHING_HASH_H_
#define META_HASHING_HASH_H_
#include <array>
#include <cassert>
#include <cstdint>
#include <random>
#include "hashes/farm_hash.h"
#include "hashes/metro_hash.h"
#include "hashes/murmur_hash.h"
#include "meta/config.h"
namespace meta
{
namespace hashing
{
template <std::size_t Size = sizeof(std::size_t)>
struct default_hasher;
template <>
struct default_hasher<4>
{
using type = murmur_hash<4>;
};
template <>
struct default_hasher<8>
{
using type = farm_hash_seeded;
};
namespace detail
{
template <bool...>
struct static_and;
template <bool B, bool... Bs>
struct static_and<B, Bs...>
{
const static constexpr bool value = B && static_and<Bs...>::value;
};
template <>
struct static_and<>
{
const static constexpr bool value = true;
};
template <std::size_t...>
struct static_add;
template <std::size_t Size, std::size_t... Sizes>
struct static_add<Size, Sizes...>
{
const static constexpr std::size_t value
= Size + static_add<Sizes...>::value;
};
template <>
struct static_add<>
{
const static constexpr std::size_t value = 0;
};
}
template <class T>
struct is_contiguously_hashable
{
const static constexpr bool value = std::is_integral<T>::value
|| std::is_enum<T>::value
|| std::is_pointer<T>::value;
};
template <class T>
struct is_contiguously_hashable<const T> : public is_contiguously_hashable<T>
{
};
template <class T>
struct is_contiguously_hashable<const volatile T>
: public is_contiguously_hashable<T>
{
};
template <class T, std::size_t N>
struct is_contiguously_hashable<T[N]> : public is_contiguously_hashable<T>
{
};
template <class T, class U>
struct is_contiguously_hashable<std::pair<T, U>>
{
const static constexpr bool value
= is_contiguously_hashable<T>::value
&& is_contiguously_hashable<U>::value
&& sizeof(T) + sizeof(U) == sizeof(std::pair<T, U>);
};
template <class... Ts>
struct is_contiguously_hashable<std::tuple<Ts...>>
{
const static constexpr bool value
= detail::static_and<is_contiguously_hashable<Ts>::value...>::value
&& detail::static_add<sizeof(Ts)...>::value
== sizeof(std::tuple<Ts...>);
};
template <class T, std::size_t N>
struct is_contiguously_hashable<std::array<T, N>>
{
const static constexpr bool value
= is_contiguously_hashable<T>::value
&& sizeof(T) * N == sizeof(std::array<T, N>);
};
template <class HashAlgorithm, class T>
inline typename std::enable_if<is_contiguously_hashable<T>::value>::type
hash_append(HashAlgorithm& h, const T& t)
{
h(std::addressof(t), sizeof(t));
}
template <class HashAlgorithm, class T>
inline typename std::enable_if<std::is_floating_point<T>::value>::type
hash_append(HashAlgorithm& h, T t)
{
// -0 and 0 are the same, but have different bit patterns, so normalize
// to positive zero before hashing
if (t == 0)
t = 0;
h(std::addressof(t), sizeof(t));
}
template <class HashAlgorithm>
inline void hash_append(HashAlgorithm& h, std::nullptr_t)
{
const void* p = nullptr;
h(std::addressof(p), sizeof(p));
}
// all of these hash_appends below need to be forward declared so they can
// find one another in their implementations
template <class HashAlgorithm, class T, std::size_t N>
typename std::enable_if<!is_contiguously_hashable<T>::value>::type
hash_append(HashAlgorithm& h, T (&a)[N]);
template <class HashAlgorithm, class T, class U>
typename std::enable_if<!is_contiguously_hashable<std::pair<T, U>>::value>::type
hash_append(HashAlgorithm& h, const std::pair<T, U>& p);
template <class HashAlgorithm, class... Ts>
typename std::enable_if<!is_contiguously_hashable<std::tuple<Ts...>>::value>::
type
hash_append(HashAlgorithm& h, const std::tuple<Ts...>& t);
template <class HashAlgorithm, class T, std::size_t N>
typename std::enable_if<!is_contiguously_hashable<std::array<T, N>>::value>::
type
hash_append(HashAlgorithm& h, const std::array<T, N>& a);
template <class HashAlgorithm, class Char, class Traits, class Alloc>
typename std::enable_if<is_contiguously_hashable<Char>::value>::type
hash_append(HashAlgorithm& h, const std::basic_string<Char, Traits, Alloc>& s);
template <class HashAlgorithm, class Char, class Traits, class Alloc>
typename std::enable_if<!is_contiguously_hashable<Char>::value>::type
hash_append(HashAlgorithm& h, const std::basic_string<Char, Traits, Alloc>& s);
template <class HashAlgorithm, class T1, class T2, class... Ts>
void hash_append(HashAlgorithm& h, const T1& first, const T2& second,
const Ts&... ts);
template <class HashAlgorithm, class T, class Alloc>
typename std::enable_if<is_contiguously_hashable<T>::value>::type
hash_append(HashAlgorithm& h, const std::vector<T, Alloc>& v);
template <class HashAlgorithm, class T, class Alloc>
typename std::enable_if<!is_contiguously_hashable<T>::value>::type
hash_append(HashAlgorithm& h, const std::vector<T, Alloc>& v);
// begin implementations for hash_append
template <class HashAlgorithm, class T, std::size_t N>
typename std::enable_if<!is_contiguously_hashable<T>::value>::type
hash_append(HashAlgorithm& h, T (&a)[N])
{
for (const auto& t : a)
hash_append(h, t);
}
template <class HashAlgorithm, class T, class U>
typename std::enable_if<!is_contiguously_hashable<std::pair<T, U>>::value>::type
hash_append(HashAlgorithm& h, const std::pair<T, U>& p)
{
hash_append(h, p.first, p.second);
}
namespace detail
{
// @see
// http://stackoverflow.com/questions/7858817/unpacking-a-tuple-to-call-a-matching-function-pointer
template <std::size_t...>
struct sequence;
template <std::size_t N, std::size_t... S>
struct generate : generate<N - 1, N - 1, S...>
{
// nothing
};
template <std::size_t... S>
struct generate<0, S...>
{
using type = sequence<S...>;
};
template <class HashAlgorithm, class... Ts, std::size_t... S>
void hash_tuple(HashAlgorithm& h, const std::tuple<Ts...>& t, sequence<S...>)
{
hash_append(h, std::get<S>(t)...);
}
}
template <class HashAlgorithm, class... Ts>
typename std::enable_if<!is_contiguously_hashable<std::tuple<Ts...>>::value>::
type
hash_append(HashAlgorithm& h, const std::tuple<Ts...>& t)
{
detail::hash_tuple(h, t, typename detail::generate<sizeof...(Ts)>::type{});
}
template <class HashAlgorithm, class T, std::size_t N>
typename std::enable_if<!is_contiguously_hashable<std::array<T, N>>::value>::
type
hash_append(HashAlgorithm& h, const std::array<T, N>& a)
{
for (const auto& t : a)
hash_append(h, a);
}
template <class HashAlgorithm, class Char, class Traits, class Alloc>
typename std::enable_if<is_contiguously_hashable<Char>::value>::type
hash_append(HashAlgorithm& h, const std::basic_string<Char, Traits, Alloc>& s)
{
h(s.data(), s.size() * sizeof(Char));
hash_append(h, s.size());
}
template <class HashAlgorithm, class Char, class Traits, class Alloc>
typename std::enable_if<!is_contiguously_hashable<Char>::value>::type
hash_append(HashAlgorithm& h, const std::basic_string<Char, Traits, Alloc>& s)
{
for (const auto& c : s)
hash_append(h, c);
hash_append(h, s.size());
}
template <class HashAlgorithm, class T, class Alloc>
typename std::enable_if<is_contiguously_hashable<T>::value>::type
hash_append(HashAlgorithm& h, const std::vector<T, Alloc>& v)
{
h(v.data(), v.size() * sizeof(T));
hash_append(h, v.size());
}
template <class HashAlgorithm, class T, class Alloc>
typename std::enable_if<!is_contiguously_hashable<T>::value>::type
hash_append(HashAlgorithm& h, const std::vector<T, Alloc>& v)
{
for (const auto& val : v)
hash_append(h, val);
hash_append(h, v.size());
}
template <class HashAlgorithm, class T1, class T2, class... Ts>
void hash_append(HashAlgorithm& h, const T1& first, const T2& second,
const Ts&... ts)
{
hash_append(h, first);
hash_append(h, second, ts...);
}
namespace detail
{
inline uint64_t get_process_seed()
{
static uint64_t seed = std::random_device{}();
return seed;
}
}
/**
* A generic, manually seeded hash function.
*/
template <class HashAlgorithm = typename default_hasher<>::type,
class SeedType = uint64_t>
class seeded_hash
{
public:
using result_type = typename HashAlgorithm::result_type;
seeded_hash(SeedType seed) : seed_{seed}
{
// nothing
}
template <class T>
result_type operator()(const T& t) const
{
HashAlgorithm h(seed_);
using hashing::hash_append;
hash_append(h, t);
return static_cast<result_type>(h);
}
SeedType seed() const
{
return seed_;
}
private:
SeedType seed_;
};
/**
* A generic, randomly seeded hash function.
* @see
* http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2014/n3980.html#seeding
*/
template <class HashAlgorithm = typename default_hasher<>::type>
struct hash
{
using result_type = typename HashAlgorithm::result_type;
template <class T>
result_type operator()(const T& t) const
{
auto seed = detail::get_process_seed();
HashAlgorithm h(seed);
using hashing::hash_append;
hash_append(h, t);
return static_cast<result_type>(h);
}
};
}
}
#endif
| 3,832 |
318 |
package xyz.msws.nope.checks.packet;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import javax.naming.OperationNotSupportedException;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.event.Listener;
import org.bukkit.scheduler.BukkitRunnable;
import com.comphenix.protocol.PacketType;
import com.comphenix.protocol.ProtocolLibrary;
import com.comphenix.protocol.ProtocolManager;
import com.comphenix.protocol.events.ListenerPriority;
import com.comphenix.protocol.events.PacketAdapter;
import com.comphenix.protocol.events.PacketContainer;
import com.comphenix.protocol.events.PacketEvent;
import xyz.msws.nope.NOPE;
import xyz.msws.nope.modules.checks.Check;
import xyz.msws.nope.modules.checks.CheckType;
import xyz.msws.nope.modules.checks.Global.Stat;
import xyz.msws.nope.modules.data.CPlayer;
import xyz.msws.nope.protocols.WrapperPlayClientSettings;
/**
* Listens for SETTINGS packets and checks if they're too often and the player
* is moving
*
* @author imodm
*
*/
public class SkinBlinker1 implements Check, Listener {
@Override
public CheckType getType() {
return CheckType.PACKET;
}
@SuppressWarnings("unused")
private NOPE plugin;
private Map<UUID, Integer> skinValue = new HashMap<>();
private Map<UUID, Long> skinPacket = new HashMap<>();
private Map<UUID, Integer> packetAmo = new HashMap<UUID, Integer>();
@Override
public void register(NOPE plugin) throws OperationNotSupportedException {
if (!Bukkit.getPluginManager().isPluginEnabled("ProtocolLib"))
throw new OperationNotSupportedException("ProtocolLib is not enabled");
this.plugin = plugin;
Bukkit.getPluginManager().registerEvents(this, plugin);
ProtocolManager manager = ProtocolLibrary.getProtocolManager();
PacketAdapter adapter = new PacketAdapter(plugin, ListenerPriority.NORMAL, PacketType.Play.Client.SETTINGS) {
@Override
public void onPacketReceiving(PacketEvent event) {
Player player = event.getPlayer();
PacketContainer packet = event.getPacket();
WrapperPlayClientSettings wrapped = new WrapperPlayClientSettings(packet);
int lastSkin = skinValue.getOrDefault(player.getUniqueId(), 0);
if (lastSkin == wrapped.getDisplayedSkinParts())
return;
skinValue.put(player.getUniqueId(), wrapped.getDisplayedSkinParts());
skinPacket.put(player.getUniqueId(), System.currentTimeMillis());
packetAmo.put(player.getUniqueId(), packetAmo.getOrDefault(player.getUniqueId(), 0) + 1);
}
@Override
public void onPacketSending(PacketEvent event) {
}
};
manager.addPacketListener(adapter);
new BukkitRunnable() {
@Override
public void run() {
for (Player player : Bukkit.getOnlinePlayers()) {
CPlayer cp = plugin.getCPlayer(player);
if (cp.timeSince(Stat.MOVE) > 500 || cp.timeSince(Stat.ON_GROUND) > 500
|| System.currentTimeMillis() - skinPacket.getOrDefault(player.getUniqueId(), 0L) > 200)
return;
int packets = packetAmo.getOrDefault(player.getUniqueId(), 0);
packetAmo.put(player.getUniqueId(), 0);
if (packets <= 20)
return;
cp.flagHack(SkinBlinker1.this, (packets - 8) * 10, "Packets: &e" + packets + ">&a20");
}
}
}.runTaskTimer(plugin, 0, 20);
}
@Override
public String getCategory() {
return "SkinBlinker";
}
@Override
public String getDebugName() {
return getCategory() + "#1";
}
@Override
public boolean lagBack() {
return false;
}
}
| 1,254 |
1,123 |
<reponame>AdmondGuo/kolo-lang<filename>external/mlsql-sql-profiler/src/main/java/tech/mlsql/tool/ZOrderingBytesUtil.java<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
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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 tech.mlsql.tool;
import sun.misc.Unsafe;
import java.nio.charset.Charset;
/**
* 所有列都表示为为8byte
* 我们限制z-ordering最大支持1024byte, 这意味着一个z-ordering 索引最多1024/8=128个字段。
*/
public class ZOrderingBytesUtil {
static final Unsafe theUnsafe;
public static final int SIZEOF_LONG = Long.SIZE / Byte.SIZE;
static {
theUnsafe = UnsafeAccess.theUnsafe;
// sanity check - this should never fail
if (theUnsafe.arrayIndexScale(byte[].class) != 1) {
throw new AssertionError();
}
}
public static byte[] toBytes(int val) {
byte[] b = new byte[4];
for (int i = 3; i > 0; i--) {
b[i] = (byte) val;
val >>>= 8;
}
b[0] = (byte) val;
return b;
}
public static byte[] toBytes(long val) {
long temp = val;
// 还原原码
// if(val <0){
// temp = (~(val -1))^(1L<<63);
// }
byte[] b = new byte[8];
for (int i = 7; i > 0; i--) {
b[i] = (byte) temp;
temp >>>= 8;
}
b[0] = (byte) temp;
return b;
}
//考虑负数,如果是负数,还原成原码表示,然后直接将第一位翻转,最后padding 成8字节
// 正数,第一位翻转,然后Padding成8字节
public static byte[] intTo8Byte(int a) {
int temp = a;
if (a < 0) {
temp = (~(a - 1))^ (1 << 31);
}
temp = temp ^ (1 << 31);
return paddingTo8Byte(toBytes(temp));
}
//考虑负数,如果是负数,还原成原码表示,然后直接将第一位翻转,最后padding 成8字节
// 正数,第一位翻转,然后Padding成8字节
public static byte[] longTo8Byte(long a) {
long temp = a;
if (a < 0) {
temp = (~(a - 1))^ (1L << 63);
}
temp = temp ^ (1L << 63);
return toBytes(temp);
}
public static byte[] toBytes(final double d) {
// Encode it as a long
return toBytes(Double.doubleToRawLongBits(d));
}
/**
* 1.先得到byte[]表示。
* 2.如果是正数,翻转第一个bit
* 3.如果是负数,翻转所有的bit
* 此时可以自然排序
*/
public static byte[] doubleTo8Byte(double a) {
byte[] temp = toBytes(a);
if (a > 0) {
temp[0] = (byte) (temp[0] ^ (1 << 7));
}
if (a < 0) {
for (int i = 0; i < temp.length; i++) {
temp[i] = (byte) ~temp[i];
}
}
return temp;
}
public static byte[] utf8To8Byte(String a) {
/**
* if is null, treat like empty string.
*/
if(a==null){
return paddingTo8Byte("".getBytes(Charset.forName("utf-8")));
}
return paddingTo8Byte(a.getBytes(Charset.forName("utf-8")));
}
/**
* buffer1,buffer2 必须是8字节,最后输出是16字节
* buffer2的值在奇数位
*/
public static byte[] interleave8Byte(byte[] buffer1, byte[] buffer2) {
byte[] result = new byte[16];
int j = 0;
for (int i = 0; i < 8; i++) {
byte[] temp = interleaveByte(buffer1[i], buffer2[i]);
result[j] = temp[0];
result[++j] = temp[1];
j++;
}
return result;
}
//用b 的bpos bit 位,设置a的 apos bit位
public static byte updatePos(byte a, int apos, byte b, int bpos) {
//将bpos以外的都设置为0
byte temp = (byte) (b & (1 << (7 - bpos)));
//把temp bpos位置的值移动到apos
//小于的话,左移
if (apos < bpos) {
temp = (byte) (temp << (bpos - apos));
}
//大于,右边移动
if (apos > bpos) {
temp = (byte) (temp >> (apos - bpos));
}
//把apos以外的都设置为0
byte atemp = (byte) (a & (1 << (7 - apos)));
if ((byte) (atemp ^ temp) == 0) {
return a;
}
return (byte) (a ^ (1 << (7 - apos)));
}
//每个属性用8byte表示。但是属性数目不确定。
public static byte[] interleaveMulti8Byte(byte[][] buffer) {
int attributesNum = buffer.length;
byte[] result = new byte[8 * attributesNum];
//结果的第几个byte的第几个位置
int resBitPos = 0;
//每个属性总的bit数
int totalBits = 64;
//第一层循环移动bit
for (int bitStep = 0; bitStep < totalBits; bitStep++) {
//首先获取当前属性在第几个byte(总共八个)
int tempBytePos = (int) Math.floor(bitStep / 8);
//获取bitStep在对应属性的byte位的第几个位置
int tempBitPos = bitStep % 8;
//获取每个属性的bitStep位置的值
for (int i = 0; i < attributesNum; i++) {
int tempResBytePos = (int) Math.floor(resBitPos / 8);
int tempResBitPos = resBitPos % 8;
result[tempResBytePos] = updatePos(result[tempResBytePos], tempResBitPos, buffer[i][tempBytePos], tempBitPos);
//结果bit要不断累加
resBitPos++;
}
}
return result;
}
/**
* x在奇数位,y在偶数位
*/
public static byte[] interleaveByte(byte x, byte y) {
long z = ((y * 0x0101010101010101L & 0x8040201008040201L) *
0x0102040810204081L >> 49) & 0x5555 |
((x * 0x0101010101010101L & 0x8040201008040201L) *
0x0102040810204081L >> 48) & 0xAAAA;
byte[] eightBytes = toBytes(z);
return new byte[]{eightBytes[6], eightBytes[7]};
}
public static String toString(final byte[] b) {
StringBuilder sb = new StringBuilder();
for (byte temp : b) {
sb.append(String.format("%8s", Integer.toBinaryString(temp & 0xFF)).replace(' ', '0') + " ");
}
return sb.toString();
}
//来自HBase的代码
public static int compareTo(byte[] buffer1, int offset1, int length1,
byte[] buffer2, int offset2, int length2) {
// Short circuit equal case
if (buffer1 == buffer2 &&
offset1 == offset2 &&
length1 == length2) {
return 0;
}
final int stride = 8;
final int minLength = Math.min(length1, length2);
int strideLimit = minLength & ~(stride - 1);
final long offset1Adj = offset1 + UnsafeAccess.BYTE_ARRAY_BASE_OFFSET;
final long offset2Adj = offset2 + UnsafeAccess.BYTE_ARRAY_BASE_OFFSET;
int i;
/*
* Compare 8 bytes at a time. Benchmarking on x86 shows a stride of 8 bytes is no slower
* than 4 bytes even on 32-bit. On the other hand, it is substantially faster on 64-bit.
*/
for (i = 0; i < strideLimit; i += stride) {
long lw = theUnsafe.getLong(buffer1, offset1Adj + i);
long rw = theUnsafe.getLong(buffer2, offset2Adj + i);
if (lw != rw) {
if (!UnsafeAccess.LITTLE_ENDIAN) {
return ((lw + Long.MIN_VALUE) < (rw + Long.MIN_VALUE)) ? -1 : 1;
}
/*
* We want to compare only the first index where left[index] != right[index]. This
* corresponds to the least significant nonzero byte in lw ^ rw, since lw and rw are
* little-endian. Long.numberOfTrailingZeros(diff) tells us the least significant
* nonzero bit, and zeroing out the first three bits of L.nTZ gives us the shift to get
* that least significant nonzero byte. This comparison logic is based on UnsignedBytes
* comparator from guava v21
*/
int n = Long.numberOfTrailingZeros(lw ^ rw) & ~0x7;
return ((int) ((lw >>> n) & 0xFF)) - ((int) ((rw >>> n) & 0xFF));
}
}
// The epilogue to cover the last (minLength % stride) elements.
for (; i < minLength; i++) {
int a = (buffer1[offset1 + i] & 0xFF);
int b = (buffer2[offset2 + i] & 0xFF);
if (a != b) {
return a - b;
}
}
return length1 - length2;
}
private static byte[] arrayConcat(byte[]... arrays) {
int length = 0;
for (byte[] array : arrays) {
length += array.length;
}
byte[] result = new byte[length];
int pos = 0;
for (byte[] array : arrays) {
System.arraycopy(array, 0, result, pos, array.length);
pos += array.length;
}
return result;
}
private static byte[] paddingTo8Byte(byte[] a) {
if (a.length == 8) return a;
if (a.length > 8) {
byte[] result = new byte[8];
System.arraycopy(a, 0, result, 0, 8);
return result;
}
int paddingSize = 8 - a.length;
byte[] result = new byte[paddingSize];
for (int i = 0; i < paddingSize; i++) {
result[i] = 0;
}
return arrayConcat(result, a);
}
}
| 5,274 |
9,680 |
<reponame>dutxubo/nni
from .base_mutator import BaseMutator
from .base_trainer import BaseTrainer
from .fixed import apply_fixed_architecture
from .mutables import Mutable, LayerChoice, InputChoice
from .mutator import Mutator
from .trainer import Trainer
| 77 |
4,002 |
<filename>src/main/java/me/zeroX150/cornos/etc/render/Notification.java
/*
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
# Project: Cornos
# File: Notification
# Created by constantin at 12:53, Apr 05 2021
PLEASE READ THE COPYRIGHT NOTICE IN THE PROJECT ROOT, IF EXISTENT
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
*/
package me.zeroX150.cornos.etc.render;
import me.zeroX150.cornos.Cornos;
public class Notification {
public final String title;
public final String[] description;
public final long creationTime;
public long duration;
public double animationProgress = 0;
public double animationProgress2 = 0;
public boolean isAnimationComplete = false;
public boolean markedForDeletion = false;
public Notification(String title, String[] description, long duration) {
this.title = title;
this.description = description;
this.creationTime = System.currentTimeMillis();
this.duration = duration;
}
public static Notification create(String t, String[] d, long d1) {
Notification r = new Notification(t, d, d1);
Cornos.notifMan.add(r);
return r;
}
}
| 376 |
339 |
<gh_stars>100-1000
{
"integrationFolder": "test/",
"testFiles": "**/**/*.spec.ts",
"screenshotOnRunFailure": false,
"video": false
}
| 56 |
3,269 |
// Time: O(n)
// Space: O(h)
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* lcaDeepestLeaves(TreeNode* root) {
return lcaDeepestLeavesHelper(root).second;
}
private:
pair<int, TreeNode*> lcaDeepestLeavesHelper(TreeNode *root) {
if (!root) {
return {0, nullptr};
}
const auto& [d1, lca1] = lcaDeepestLeavesHelper(root->left);
const auto& [d2, lca2] = lcaDeepestLeavesHelper(root->right);
if (d1 > d2) {
return {d1 + 1, lca1};
}
if (d1 < d2) {
return {d2 + 1, lca2};
}
return {d1 + 1, root};
}
};
| 407 |
1,350 |
<filename>sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/fluent/models/HubIpConfigurationPropertiesFormatInner.java<gh_stars>1000+
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.resourcemanager.network.fluent.models;
import com.azure.core.annotation.Fluent;
import com.azure.core.util.logging.ClientLogger;
import com.azure.resourcemanager.network.models.IpAllocationMethod;
import com.azure.resourcemanager.network.models.ProvisioningState;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
/** Properties of IP configuration. */
@Fluent
public final class HubIpConfigurationPropertiesFormatInner {
@JsonIgnore private final ClientLogger logger = new ClientLogger(HubIpConfigurationPropertiesFormatInner.class);
/*
* The private IP address of the IP configuration.
*/
@JsonProperty(value = "privateIPAddress")
private String privateIpAddress;
/*
* The private IP address allocation method.
*/
@JsonProperty(value = "privateIPAllocationMethod")
private IpAllocationMethod privateIpAllocationMethod;
/*
* The reference to the subnet resource.
*/
@JsonProperty(value = "subnet")
private SubnetInner subnet;
/*
* The reference to the public IP resource.
*/
@JsonProperty(value = "publicIPAddress")
private PublicIpAddressInner publicIpAddress;
/*
* The provisioning state of the IP configuration resource.
*/
@JsonProperty(value = "provisioningState", access = JsonProperty.Access.WRITE_ONLY)
private ProvisioningState provisioningState;
/**
* Get the privateIpAddress property: The private IP address of the IP configuration.
*
* @return the privateIpAddress value.
*/
public String privateIpAddress() {
return this.privateIpAddress;
}
/**
* Set the privateIpAddress property: The private IP address of the IP configuration.
*
* @param privateIpAddress the privateIpAddress value to set.
* @return the HubIpConfigurationPropertiesFormatInner object itself.
*/
public HubIpConfigurationPropertiesFormatInner withPrivateIpAddress(String privateIpAddress) {
this.privateIpAddress = privateIpAddress;
return this;
}
/**
* Get the privateIpAllocationMethod property: The private IP address allocation method.
*
* @return the privateIpAllocationMethod value.
*/
public IpAllocationMethod privateIpAllocationMethod() {
return this.privateIpAllocationMethod;
}
/**
* Set the privateIpAllocationMethod property: The private IP address allocation method.
*
* @param privateIpAllocationMethod the privateIpAllocationMethod value to set.
* @return the HubIpConfigurationPropertiesFormatInner object itself.
*/
public HubIpConfigurationPropertiesFormatInner withPrivateIpAllocationMethod(
IpAllocationMethod privateIpAllocationMethod) {
this.privateIpAllocationMethod = privateIpAllocationMethod;
return this;
}
/**
* Get the subnet property: The reference to the subnet resource.
*
* @return the subnet value.
*/
public SubnetInner subnet() {
return this.subnet;
}
/**
* Set the subnet property: The reference to the subnet resource.
*
* @param subnet the subnet value to set.
* @return the HubIpConfigurationPropertiesFormatInner object itself.
*/
public HubIpConfigurationPropertiesFormatInner withSubnet(SubnetInner subnet) {
this.subnet = subnet;
return this;
}
/**
* Get the publicIpAddress property: The reference to the public IP resource.
*
* @return the publicIpAddress value.
*/
public PublicIpAddressInner publicIpAddress() {
return this.publicIpAddress;
}
/**
* Set the publicIpAddress property: The reference to the public IP resource.
*
* @param publicIpAddress the publicIpAddress value to set.
* @return the HubIpConfigurationPropertiesFormatInner object itself.
*/
public HubIpConfigurationPropertiesFormatInner withPublicIpAddress(PublicIpAddressInner publicIpAddress) {
this.publicIpAddress = publicIpAddress;
return this;
}
/**
* Get the provisioningState property: The provisioning state of the IP configuration resource.
*
* @return the provisioningState value.
*/
public ProvisioningState provisioningState() {
return this.provisioningState;
}
/**
* Validates the instance.
*
* @throws IllegalArgumentException thrown if the instance is not valid.
*/
public void validate() {
if (subnet() != null) {
subnet().validate();
}
if (publicIpAddress() != null) {
publicIpAddress().validate();
}
}
}
| 1,772 |
679 |
<filename>main/editeng/inc/editeng/eerdll.hxx
/**************************************************************
*
* 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 _EERDLL_HXX
#define _EERDLL_HXX
class GlobalEditData;
#include <tools/resid.hxx>
#include <tools/shl.hxx>
#include <editeng/editengdllapi.h>
class EDITENG_DLLPUBLIC EditResId: public ResId
{
public:
EditResId( sal_uInt16 nId );
};
class EditDLL
{
ResMgr* pResMgr;
GlobalEditData* pGlobalData;
public:
EditDLL();
~EditDLL();
ResMgr* GetResMgr() const { return pResMgr; }
GlobalEditData* GetGlobalData() const { return pGlobalData; }
static EditDLL* Get();
};
#define EE_DLL() EditDLL::Get()
#define EE_RESSTR(x) String( EditResId(x) )
#endif //_EERDLL_HXX
| 503 |
2,151 |
<filename>net/third_party/quic/platform/api/quic_ip_address_family.h
// Copyright (c) 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef NET_THIRD_PARTY_QUIC_PLATFORM_API_QUIC_IP_ADDRESS_FAMILY_H_
#define NET_THIRD_PARTY_QUIC_PLATFORM_API_QUIC_IP_ADDRESS_FAMILY_H_
namespace net {
// IP address family type used in QUIC. This hides platform dependant IP address
// family types.
enum class IpAddressFamily {
IP_V4,
IP_V6,
IP_UNSPEC,
};
} // namespace net
#endif // NET_THIRD_PARTY_QUIC_PLATFORM_API_QUIC_IP_ADDRESS_FAMILY_H_
| 250 |
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.statistics;
import com.alibaba.polardbx.common.utils.logger.Logger;
import com.alibaba.polardbx.common.utils.logger.LoggerFactory;
import com.alibaba.polardbx.common.utils.thread.CpuStatHandler;
import com.alibaba.polardbx.common.utils.thread.RunnableWithStatHandler;
import com.alibaba.polardbx.common.utils.thread.ThreadCpuStatUtil;
import com.alibaba.polardbx.executor.cursor.AbstractCursor;
import com.alibaba.polardbx.executor.cursor.Cursor;
import com.alibaba.polardbx.executor.operator.Executor;
import com.alibaba.polardbx.executor.utils.ExecUtils;
import com.alibaba.polardbx.optimizer.context.ExecutionContext;
import com.alibaba.polardbx.optimizer.core.rel.LogicalView;
import com.alibaba.polardbx.optimizer.statis.OperatorStatistics;
import org.apache.calcite.rel.RelNode;
/**
* @author chenghui.lch
*/
public class RuntimeStatHelper {
private static final Logger logger = LoggerFactory.getLogger(RuntimeStatHelper.class);
public static RuntimeStatistics buildRuntimeStat(ExecutionContext executionContext) {
return new RuntimeStatistics(executionContext.getSchemaName(), executionContext);
}
public static void registerCursorStatForPlan(RelNode logicalPlan, ExecutionContext executionContext,
Cursor cursor) {
try {
boolean isApplySubQuery = executionContext.isApplyingSubquery();
boolean isInExplain = executionContext.getExplain() != null;
if (ExecUtils.isOperatorMetricEnabled(executionContext) && !isApplySubQuery && !isInExplain) {
// register the run time stat of cursor into logicalPlan
RuntimeStatistics runtimeStatistics = (RuntimeStatistics) executionContext.getRuntimeStatistics();
runtimeStatistics.register(logicalPlan, cursor);
}
} catch (Throwable e) {
logger.warn("do registerCursorStatForPlan failed", e);
}
}
public static void registerStatForExec(RelNode plan, Executor executor, ExecutionContext context) {
if (ExecUtils.isOperatorMetricEnabled(context)
&& context.getRuntimeStatistics() != null && !context.isApplyingSubquery()) {
RuntimeStatistics runtimeStatistics = (RuntimeStatistics) context.getRuntimeStatistics();
runtimeStatistics.register(plan, executor);
}
}
public static void registerCursorStatByParentCursor(ExecutionContext executionContext, Cursor parentCursor,
Cursor targetCursor) {
try {
RuntimeStatistics runtimeStatistics = (RuntimeStatistics) executionContext.getRuntimeStatistics();
RuntimeStatistics.OperatorStatisticsGroup operatorStatisticsGroup = ((AbstractCursor) parentCursor).getTargetPlanStatGroup();
if (operatorStatisticsGroup != null && operatorStatisticsGroup.targetRel != null) {
runtimeStatistics.register(operatorStatisticsGroup.targetRel, targetCursor);
}
} catch (Throwable e) {
logger.warn("do registerCursorStatByParentCursor failed", e);
}
}
public static void processResultSetStatForLv(RuntimeStatistics.OperatorStatisticsGroup lvStatGroup, Cursor inputCursor) {
if (lvStatGroup != null) {
RelNode targetRel = lvStatGroup.targetRel;
if (targetRel instanceof LogicalView) {
processPlanResultSetStat(lvStatGroup);
}
}
}
public static void processResultSetStatForLvInChunk(RuntimeStatistics.OperatorStatisticsGroup lvStatGroup, Cursor inputCursor) {
if (lvStatGroup != null) {
RelNode targetRel = lvStatGroup.targetRel;
if (targetRel instanceof LogicalView) {
if (!((LogicalView) targetRel).isMGetEnabled()) {
processPlanResultSetStat(lvStatGroup);
}
}
}
}
public static void statWaitLockTimecost(RuntimeStatistics.OperatorStatisticsGroup targetPlanStatGroup, long statWaitNano) {
try {
if (targetPlanStatGroup != null) {
RuntimeStatistics.registerWaitLockCpuTime(targetPlanStatGroup, System.nanoTime() - statWaitNano);
}
} catch (Throwable e) {
logger.warn("do statWaitLockTimecost failed", e);
}
}
public static RunnableWithStatHandler buildTaskWithCpuStat(final Runnable task, final Cursor targetCursor) {
RunnableWithStatHandler taskWithStat = new RunnableWithStatHandler(task, new CpuStatHandler() {
@Override
public long getStartTimeNano() {
return ThreadCpuStatUtil.getThreadCpuTimeNano();
}
@Override
public void handleCpuStat(long startTimeNano) {
RuntimeStatHelper.registerAsyncTaskCpuTimeForCursor(targetCursor,
ThreadCpuStatUtil.getThreadCpuTimeNano() - startTimeNano);
}
});
return taskWithStat;
}
public static RunnableWithStatHandler buildTaskWithCpuStat(final Runnable task, final Executor targetExec) {
RunnableWithStatHandler taskWithStat = new RunnableWithStatHandler(task, new CpuStatHandler() {
@Override
public long getStartTimeNano() {
return ThreadCpuStatUtil.getThreadCpuTimeNano();
}
@Override
public void handleCpuStat(long startTimeNano) {
RuntimeStatHelper.registerAsyncTaskCpuTimeForExec(targetExec, ThreadCpuStatUtil.getThreadCpuTimeNano()
- startTimeNano);
}
});
return taskWithStat;
}
public static void registerAsyncTaskCpuStatForCursor(Cursor targetCursor, long asyncTaskCpuTime,
long asyncTaskTimeCost) {
try {
RuntimeStatistics.registerAsyncTaskCpuTime(targetCursor, asyncTaskCpuTime);
RuntimeStatistics.registerAsyncTaskTimeCost(targetCursor, asyncTaskTimeCost);
} catch (Throwable e) {
logger.warn("do registerAsyncTaskCpuStatForCursor failed", e);
}
}
public static void addAsyncTaskCpuTimeToParent(RuntimeStatistics.OperatorStatisticsGroup targetPlanStatGroup) {
try {
RuntimeStatistics.addSelfAsyncTaskCpuTimeToParent(targetPlanStatGroup);
} catch (Throwable e) {
logger.warn("do addAsyncTaskCpuTimeToParent failed", e);
}
}
protected static void registerAsyncTaskCpuTimeForCursor(Cursor targetCursor, long asyncTaskCpuTime) {
try {
RuntimeStatistics.registerAsyncTaskCpuTime(targetCursor, asyncTaskCpuTime);
} catch (Throwable e) {
logger.warn("do registerAsyncTaskCpuTimeForCursor failed", e);
}
}
protected static void registerAsyncTaskCpuTimeForExec(Executor targetExec, long asyncTaskCpuTime) {
try {
RuntimeStatistics.registerAsyncTaskCpuTime(targetExec, asyncTaskCpuTime);
} catch (Throwable e) {
logger.warn("do registerAsyncTaskCpuTimeForExec failed", e);
}
}
protected static void processPlanResultSetStat(RuntimeStatistics.OperatorStatisticsGroup lvStatGroup) {
synchronized (lvStatGroup) {
lvStatGroup.finishCount.addAndGet(1);
if (lvStatGroup.totalCount.get() - lvStatGroup.finishCount.get() > 0) {
return;
}
}
long timeCostOfLvOperator = 0;
long rowCountOfLv = 0;
for (OperatorStatistics stat : lvStatGroup.statistics) {
rowCountOfLv += stat.getRowCount();
}
timeCostOfLvOperator = lvStatGroup.processLvTimeCost.get();
timeCostOfLvOperator += lvStatGroup.selfAsyncTaskTimeCost.get();
timeCostOfLvOperator -= lvStatGroup.waitLockDuration.get();
long fetchRsTimeCostOfInput = timeCostOfLvOperator - lvStatGroup.prepareStmtEnvDuration.get()
- lvStatGroup.execJdbcStmtDuration.get();
lvStatGroup.fetchJdbcResultSetDuration.addAndGet(fetchRsTimeCostOfInput);
lvStatGroup.phyResultSetRowCount.addAndGet(rowCountOfLv);
RuntimeStatHelper.addAsyncTaskCpuTimeToParent(lvStatGroup);
}
}
| 3,574 |
310 |
<reponame>dreeves/usesthis
{
"name": "<NAME>",
"description": "A CNC machine.",
"url": "https://carbide3d.com/shapeoko/"
}
| 55 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.