max_stars_count
int64 301
224k
| text
stringlengths 6
1.05M
| token_count
int64 3
727k
|
---|---|---|
2,132 | // Targeted by JavaCPP version 1.5.6: DO NOT EDIT THIS FILE
package org.bytedeco.hdf5;
import java.nio.*;
import org.bytedeco.javacpp.*;
import org.bytedeco.javacpp.annotation.*;
import static org.bytedeco.javacpp.presets.javacpp.*;
import static org.bytedeco.hdf5.global.hdf5.*;
/** <!-- [H5O_token_t_snip] -->
<p>
/**
* Allocation statistics info struct
*/
@Properties(inherit = org.bytedeco.hdf5.presets.hdf5.class)
public class H5_alloc_stats_t extends Pointer {
static { Loader.load(); }
/** Default native constructor. */
public H5_alloc_stats_t() { super((Pointer)null); allocate(); }
/** Native array allocator. Access with {@link Pointer#position(long)}. */
public H5_alloc_stats_t(long size) { super((Pointer)null); allocateArray(size); }
/** Pointer cast constructor. Invokes {@link Pointer#Pointer(Pointer)}. */
public H5_alloc_stats_t(Pointer p) { super(p); }
private native void allocate();
private native void allocateArray(long size);
@Override public H5_alloc_stats_t position(long position) {
return (H5_alloc_stats_t)super.position(position);
}
@Override public H5_alloc_stats_t getPointer(long i) {
return new H5_alloc_stats_t((Pointer)this).offsetAddress(i);
}
/** Running count of total # of bytes allocated */
public native @Cast("unsigned long long") long total_alloc_bytes(); public native H5_alloc_stats_t total_alloc_bytes(long setter);
/** Current # of bytes allocated */
public native @Cast("size_t") long curr_alloc_bytes(); public native H5_alloc_stats_t curr_alloc_bytes(long setter);
/** Peak # of bytes allocated */
public native @Cast("size_t") long peak_alloc_bytes(); public native H5_alloc_stats_t peak_alloc_bytes(long setter);
/** Largest block allocated */
public native @Cast("size_t") long max_block_size(); public native H5_alloc_stats_t max_block_size(long setter);
/** Running count of total # of blocks allocated */
public native @Cast("size_t") long total_alloc_blocks_count(); public native H5_alloc_stats_t total_alloc_blocks_count(long setter);
/** Current # of blocks allocated */
public native @Cast("size_t") long curr_alloc_blocks_count(); public native H5_alloc_stats_t curr_alloc_blocks_count(long setter);
/** Peak # of blocks allocated */
public native @Cast("size_t") long peak_alloc_blocks_count(); public native H5_alloc_stats_t peak_alloc_blocks_count(long setter);
}
| 856 |
3,288 | <reponame>AndroidKotlinID/objectbox-java<gh_stars>1000+
/*
* Copyright 2021 ObjectBox Ltd. 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 io.objectbox.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Marks a property as a companion to an @Id property. There can only be one companion property.
* <p>
* By defining an @Id companion property, the entity type uses a special ID encoding scheme involving this property
* in addition to the ID.
* <p>
* For Time Series IDs, a companion property of type Date or DateNano represents the exact timestamp.
*/
@Retention(RetentionPolicy.CLASS)
@Target(ElementType.FIELD)
public @interface IdCompanion {
}
| 360 |
388 | /* Copyright 2018 The TensorFlow 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.
==============================================================================*/
#include "tensorflow/compiler/tf2tensorrt/utils/trt_allocator.h"
#include "tensorflow/core/platform/logging.h"
#if GOOGLE_CUDA
#if GOOGLE_TENSORRT
#include "third_party/gpus/cuda/include/cuda_runtime_api.h"
#endif // GOOGLE_TENSORRT
#endif // GOOGLE_CUDA
namespace tensorflow {
namespace tensorrt {
// std::align is not supported, so this method mimic its behavior.
//
// NOTE(aaroey): according to the TensorRT API,
// nvinfer1::IGpuAllocator::allocate() uses uint64_t type for size and alignment
// parameters, so here we use the same type to make it compatible.
void* Align(uint64_t alignment, uint64_t size, void*& ptr, uint64_t& space) {
QCHECK_GT(alignment, 0ul) << "alignment must be greater than 0.";
QCHECK_EQ(0, alignment & (alignment - 1)) << "Alignment must be power of 2.";
QCHECK_GT(size, 0ul) << "size must be greater than 0.";
QCHECK(ptr) << "ptr must not be nullptr.";
QCHECK_GT(space, 0ul) << "space must be greater than 0.";
const uintptr_t ptr_val = reinterpret_cast<uintptr_t>(ptr);
QCHECK_GE(ptr_val + space, ptr_val) << "Provided space overflows.";
if (size > space) return nullptr;
const uintptr_t aligned_ptr_val = ((ptr_val + alignment - 1) & -alignment);
if (aligned_ptr_val > ptr_val + space - size) return nullptr;
ptr = reinterpret_cast<void*>(aligned_ptr_val);
const uintptr_t diff = aligned_ptr_val - ptr_val;
space -= diff;
return ptr;
}
} // namespace tensorrt
} // namespace tensorflow
#if GOOGLE_CUDA
#if GOOGLE_TENSORRT
namespace tensorflow {
namespace tensorrt {
void* TRTDeviceAllocator::allocate(uint64_t size, uint64_t alignment,
uint32_t flags) noexcept {
if (size == 0) return nullptr;
// WAR for allocator alignment requirement. Certain cuda API calls require GPU
// memory with alignment to cudaDeviceProp::textureAlignment.
// See issue #20856
alignment = 512;
assert((alignment & (alignment - 1)) == 0); // zero or a power of 2.
uint64_t total_size = size + alignment;
// TODO(aaroey): AllocateRaw takes size_t size as input, so it'll produce
// unexpected result when TRT tries to allocate more bytes than size_t can
// carry. Fix this.
void* mem = allocator_->AllocateRaw(alignment, total_size);
if (!mem) return nullptr;
void* alloc_mem = mem;
QCHECK(Align(alignment, size, mem, total_size));
if (mem != alloc_mem) {
QCHECK(mem_map_.insert({mem, alloc_mem}).second);
}
VLOG(2) << "Allocated " << total_size << " bytes memory @" << alloc_mem
<< "; aligned to " << size << " bytes @" << mem << " with alignment "
<< alignment;
return mem;
}
TRTDeviceAllocator::TRTDeviceAllocator(Allocator* allocator)
: allocator_(allocator) {
VLOG(1) << "Using " << allocator->Name() << " allocator from TensorFlow";
}
void TRTDeviceAllocator::free(void* memory) noexcept {
VLOG(2) << "Deallocating @ " << memory;
// allocated memory adjusted for alignment, restore the original pointer
if (memory) {
auto alloc_mem = mem_map_.find(memory);
if (alloc_mem != mem_map_.end()) {
memory = alloc_mem->second;
mem_map_.erase(alloc_mem->first);
}
allocator_->DeallocateRaw(memory);
}
}
} // namespace tensorrt
} // namespace tensorflow
#endif // GOOGLE_TENSORRT
#endif // GOOGLE_CUDA
| 1,372 |
1,062 | <reponame>icarazob/mr4c<filename>java/test/java/com/google/mr4c/keys/KeyspaceDimensionTest.java
/**
* Copyright 2014 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.
*/
package com.google.mr4c.keys;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.junit.*;
import static org.junit.Assert.*;
public class KeyspaceDimensionTest {
private DataKeyDimension m_dim1;
private DataKeyDimension m_dim2;
private DataKeyElement m_ele1;
private DataKeyElement m_ele2;
private DataKeyElement m_ele3;
private List<DataKeyElement> m_eles;
private KeyspaceDimension m_ksd1a;
private KeyspaceDimension m_ksd1b;
private KeyspaceDimension m_ksd2;
@Before public void setUp() {
m_dim1 = new DataKeyDimension("dim1");
m_dim2 = new DataKeyDimension("dim2");
m_ele1 = new DataKeyElement("ele1", m_dim1);
m_ele2 = new DataKeyElement("ele2", m_dim1);
m_ele3 = new DataKeyElement("ele3", m_dim1);
m_eles = Arrays.asList(m_ele1, m_ele2, m_ele3);
m_ksd1a = buildKeyspaceDimension1();
m_ksd1b = buildKeyspaceDimension1();
m_ksd2 = buildKeyspaceDimension2();
}
@Test
public void testElements() {
assertEquals(m_eles, m_ksd1a.getElements());
}
@Test
public void testEquals() {
assertEquals(m_ksd1a, m_ksd1b);
}
@Test
public void testNotEqual() {
assertFalse(m_ksd1a.equals(m_ksd2));
}
@Test(expected=IllegalArgumentException.class)
public void testAddElementFail() {
DataKeyElement element = new DataKeyElement("val", m_dim2);
m_ksd1a.addElement(element);
}
private KeyspaceDimension buildKeyspaceDimension1() {
KeyspaceDimension ksd = new KeyspaceDimension(m_dim1);
Collection<DataKeyElement> elements = Arrays.asList(m_ele1, m_ele2, m_ele3);
ksd.addElements(elements);
return ksd;
}
private KeyspaceDimension buildKeyspaceDimension2() {
KeyspaceDimension ksd = new KeyspaceDimension(m_dim1);
Collection<DataKeyElement> elements = Arrays.asList(m_ele1, m_ele2);
ksd.addElements(elements);
return ksd;
}
}
| 963 |
852 | <filename>Utilities/StaticAnalyzers/src/ConstCastChecker.h
//== ConstCastChecker.h - Checks for const_cast<> --------------*- C++ -*--==//
//
// by <NAME> [ <EMAIL> ]
//
//===----------------------------------------------------------------------===//
#ifndef Utilities_StaticAnalyzers_ConstCastChecker_h
#define Utilities_StaticAnalyzers_ConstCastChecker_h
#include <clang/StaticAnalyzer/Core/Checker.h>
#include <clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h>
#include <clang/StaticAnalyzer/Core/BugReporter/BugType.h>
#include "CmsException.h"
#include "FWCore/Utilities/interface/thread_safety_macros.h"
namespace clangcms {
class ConstCastChecker : public clang::ento::Checker<clang::ento::check::PreStmt<clang::CXXConstCastExpr> > {
public:
CMS_SA_ALLOW mutable std::unique_ptr<clang::ento::BugType> BT;
void checkPreStmt(const clang::CXXConstCastExpr *CE, clang::ento::CheckerContext &C) const;
private:
CmsException m_exception;
};
} // namespace clangcms
#endif
| 345 |
836 | // CoreBitcoin by <NAME> <<EMAIL>>, WTFPL.
#import <Foundation/Foundation.h>
#import "BTCUnitsAndLimits.h"
typedef NS_ENUM(NSInteger, BTCNumberFormatterUnit) {
BTCNumberFormatterUnitSatoshi = 0, // satoshis = 0.00000001 BTC
BTCNumberFormatterUnitBit = 2, // bits = 0.000001 BTC
BTCNumberFormatterUnitMilliBTC = 5, // mBTC = 0.001 BTC
BTCNumberFormatterUnitBTC = 8, // BTC = 100 million satoshis
};
typedef NS_ENUM(NSInteger, BTCNumberFormatterSymbolStyle) {
BTCNumberFormatterSymbolStyleNone = 0, // no suffix
BTCNumberFormatterSymbolStyleCode = 1, // suffix is BTC, mBTC, Bits or SAT
BTCNumberFormatterSymbolStyleLowercase = 2, // suffix is btc, mbtc, bits or sat
BTCNumberFormatterSymbolStyleSymbol = 3, // suffix is Ƀ, mɃ, ƀ or ṡ
};
extern NSString* const BTCNumberFormatterBitcoinCode; // XBT
extern NSString* const BTCNumberFormatterSymbolBTC; // Ƀ
extern NSString* const BTCNumberFormatterSymbolMilliBTC; // mɃ
extern NSString* const BTCNumberFormatterSymbolBit; // ƀ
extern NSString* const BTCNumberFormatterSymbolSatoshi; // ṡ
/*!
* Rounds the decimal number and returns its longLongValue.
* Do not use NSDecimalNumber.longLongValue as it will return 0 on iOS 8.0.2 if the number is not rounded first.
*/
BTCAmount BTCAmountFromDecimalNumber(NSNumber* num);
@interface BTCNumberFormatter : NSNumberFormatter
/*!
* Instantiates and configures number formatter with given unit and suffix style.
*/
- (id) initWithBitcoinUnit:(BTCNumberFormatterUnit)unit;
- (id) initWithBitcoinUnit:(BTCNumberFormatterUnit)unit symbolStyle:(BTCNumberFormatterSymbolStyle)symbolStyle;
/*!
* Unit size to be displayed (regardless of how it is presented)
*/
@property(nonatomic) BTCNumberFormatterUnit bitcoinUnit;
/*!
* Style of formatting the units regardless of the unit size.
*/
@property(nonatomic) BTCNumberFormatterSymbolStyle symbolStyle;
/*!
* Placeholder text for the input field.
* E.g. "0 000 000.00" for 'bits' and "0.00000000" for 'BTC'.
*/
@property(nonatomic, readonly) NSString* placeholderText;
/*!
* Returns a matching bitcoin symbol.
* If `symbolStyle` is BTCNumberFormatterSymbolStyleNone, returns the code (BTC, mBTC, Bits or SAT).
*/
@property(nonatomic, readonly) NSString* standaloneSymbol;
/*!
* Returns a matching bitcoin unit code (BTC, mBTC etc) regardless of the symbol style.
*/
@property(nonatomic, readonly) NSString* unitCode;
/*!
* Formats the amount according to units and current formatting style.
*/
- (NSString *) stringFromAmount:(BTCAmount)amount;
/*!
* Returns 0 in case of failure to parse the string.
* To handle that case, use `-[NSNumberFormatter numberFromString:]`, but keep in mind
* that NSNumber* will be in specified units, not in satoshis.
*/
- (BTCAmount) amountFromString:(NSString *)string;
@end
| 939 |
4,772 | <filename>jpa/deferred/src/main/java/example/repo/Customer696Repository.java<gh_stars>1000+
package example.repo;
import example.model.Customer696;
import java.util.List;
import org.springframework.data.repository.CrudRepository;
public interface Customer696Repository extends CrudRepository<Customer696, Long> {
List<Customer696> findByLastName(String lastName);
}
| 117 |
393 | package com.marverenic.music.data.store;
import com.marverenic.music.model.Song;
import rx.Observable;
public interface PlayCountStore {
Observable<Void> refresh();
void save();
int getPlayCount(Song song);
int getSkipCount(Song song);
long getPlayDate(Song song);
void incrementPlayCount(Song song);
void incrementSkipCount(Song song);
void setPlayDateToNow(Song song);
void setPlayCount(Song song, int count);
void setSkipCount(Song song, int count);
void setPlayDate(Song song, long timeInUnixSeconds);
}
| 194 |
4,816 | <reponame>mehrdad-shokri/retdec
/**
* @file include/retdec/unpacker/decompression/nrv/nrv2b_data.h
* @brief Declaration of class for NRV2B compressed data.
* @copyright (c) 2017 Avast Software, licensed under the MIT license
*/
#ifndef RETDEC_UNPACKER_DECOMPRESSION_NRV_NRV2B_DATA_H
#define RETDEC_UNPACKER_DECOMPRESSION_NRV_NRV2B_DATA_H
#include <cstdint>
#include <vector>
#include "retdec/unpacker/decompression/nrv/bit_parsers.h"
#include "retdec/unpacker/decompression/nrv/nrv_data.h"
namespace retdec {
namespace unpacker {
class Nrv2bData : public NrvData
{
public:
Nrv2bData() = delete;
Nrv2bData(const DynamicBuffer& buffer, BitParser* bitParser);
Nrv2bData(const Nrv2bData&) = delete;
virtual bool decompress(DynamicBuffer& outputBuffer) override;
private:
Nrv2bData& operator =(const Nrv2bData&);
};
} // namespace unpacker
} // namespace retdec
#endif
| 355 |
19,046 | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <folly/GroupVarint.h>
#include <folly/container/Array.h>
#if FOLLY_HAVE_GROUP_VARINT
namespace folly {
const uint32_t GroupVarint32::kMask[] = {
0xff,
0xffff,
0xffffff,
0xffffffff,
};
const uint64_t GroupVarint64::kMask[] = {
0xff,
0xffff,
0xffffff,
0xffffffff,
0xffffffffffULL,
0xffffffffffffULL,
0xffffffffffffffULL,
0xffffffffffffffffULL,
};
namespace detail {
struct group_varint_table_base_make_item {
constexpr std::size_t get_d(std::size_t index, std::size_t j) const {
return 1u + ((index >> (2 * j)) & 3u);
}
constexpr std::size_t get_offset(std::size_t index, std::size_t j) const {
// clang-format off
return
(j > 0 ? get_d(index, 0) : 0) +
(j > 1 ? get_d(index, 1) : 0) +
(j > 2 ? get_d(index, 2) : 0) +
(j > 3 ? get_d(index, 3) : 0) +
0;
// clang-format on
}
};
struct group_varint_table_length_make_item : group_varint_table_base_make_item {
constexpr std::uint8_t operator()(std::size_t index) const {
return 1u + get_offset(index, 4);
}
};
// Reference: http://www.stepanovpapers.com/CIKM_2011.pdf
//
// From 17 encoded bytes, we may use between 5 and 17 bytes to encode 4
// integers. The first byte is a key that indicates how many bytes each of
// the 4 integers takes:
//
// bit 0..1: length-1 of first integer
// bit 2..3: length-1 of second integer
// bit 4..5: length-1 of third integer
// bit 6..7: length-1 of fourth integer
//
// The value of the first byte is used as the index in a table which returns
// a mask value for the SSSE3 PSHUFB instruction, which takes an XMM register
// (16 bytes) and shuffles bytes from it into a destination XMM register
// (optionally setting some of them to 0)
//
// For example, if the key has value 4, that means that the first integer
// uses 1 byte, the second uses 2 bytes, the third and fourth use 1 byte each,
// so we set the mask value so that
//
// r[0] = a[0]
// r[1] = 0
// r[2] = 0
// r[3] = 0
//
// r[4] = a[1]
// r[5] = a[2]
// r[6] = 0
// r[7] = 0
//
// r[8] = a[3]
// r[9] = 0
// r[10] = 0
// r[11] = 0
//
// r[12] = a[4]
// r[13] = 0
// r[14] = 0
// r[15] = 0
struct group_varint_table_sse_mask_make_item
: group_varint_table_base_make_item {
constexpr auto partial_item(
std::size_t d, std::size_t offset, std::size_t k) const {
// if k < d, the j'th integer uses d bytes, consume them
// set remaining bytes in result to 0
// 0xff: set corresponding byte in result to 0
return std::uint32_t((k < d ? offset + k : std::size_t(0xff)) << (8 * k));
}
constexpr auto item_impl(std::size_t d, std::size_t offset) const {
// clang-format off
return
partial_item(d, offset, 0) |
partial_item(d, offset, 1) |
partial_item(d, offset, 2) |
partial_item(d, offset, 3) |
0;
// clang-format on
}
constexpr auto item(std::size_t index, std::size_t j) const {
return item_impl(get_d(index, j), get_offset(index, j));
}
constexpr auto operator()(std::size_t index) const {
return std::array<std::uint32_t, 4>{{
item(index, 0),
item(index, 1),
item(index, 2),
item(index, 3),
}};
}
};
#if FOLLY_SSE >= 3
alignas(16) FOLLY_STORAGE_CONSTEXPR
decltype(groupVarintSSEMasks) groupVarintSSEMasks =
make_array_with<256>(group_varint_table_sse_mask_make_item{});
#endif
FOLLY_STORAGE_CONSTEXPR decltype(groupVarintLengths) groupVarintLengths =
make_array_with<256>(group_varint_table_length_make_item{});
} // namespace detail
} // namespace folly
#endif
| 1,711 |
8,969 | // Copyright (c) 2020, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
// A slimmed down version of runtime/vm/unit_test.h that only runs C++
// non-DartVM unit tests.
#ifndef RUNTIME_VM_COMPILER_FFI_UNIT_TEST_H_
#define RUNTIME_VM_COMPILER_FFI_UNIT_TEST_H_
// Don't use the DartVM zone, so include this first.
#include "vm/compiler/ffi/unit_test_custom_zone.h"
#include "platform/globals.h"
// The UNIT_TEST_CASE macro is used for tests.
#define UNIT_TEST_CASE_WITH_EXPECTATION(name, expectation) \
void Dart_Test##name(); \
static const dart::compiler::ffi::RawTestCase kRegister##name( \
Dart_Test##name, #name, expectation); \
void Dart_Test##name()
#define UNIT_TEST_CASE(name) UNIT_TEST_CASE_WITH_EXPECTATION(name, "Pass")
// The UNIT_TEST_CASE_WITH_ZONE macro is used for tests that need a custom
// dart::Zone.
#define UNIT_TEST_CASE_WITH_ZONE_WITH_EXPECTATION(name, expectation) \
static void Dart_TestHelper##name(dart::Zone* Z); \
UNIT_TEST_CASE_WITH_EXPECTATION(name, expectation) { \
dart::Zone zone; \
Dart_TestHelper##name(&zone); \
} \
static void Dart_TestHelper##name(dart::Zone* Z)
#define UNIT_TEST_CASE_WITH_ZONE(name) \
UNIT_TEST_CASE_WITH_ZONE_WITH_EXPECTATION(name, "Pass")
namespace dart {
namespace compiler {
namespace ffi {
extern const char* kArch;
extern const char* kOs;
void WriteToFile(char* path, const char* contents);
void ReadFromFile(char* path, char** buffer_pointer);
class TestCaseBase {
public:
explicit TestCaseBase(const char* name, const char* expectation);
virtual ~TestCaseBase() {}
const char* name() const { return name_; }
const char* expectation() const { return expectation_; }
virtual void Run() = 0;
void RunTest();
static void RunAll();
static void RunAllRaw();
static bool update_expectations;
private:
static TestCaseBase* first_;
static TestCaseBase* tail_;
TestCaseBase* next_;
const char* name_;
const char* expectation_;
DISALLOW_COPY_AND_ASSIGN(TestCaseBase);
};
class RawTestCase : TestCaseBase {
public:
typedef void(RunEntry)();
RawTestCase(RunEntry* run, const char* name, const char* expectation)
: TestCaseBase(name, expectation), run_(run) {}
virtual void Run();
private:
RunEntry* const run_;
};
} // namespace ffi
} // namespace compiler
} // namespace dart
#endif // RUNTIME_VM_COMPILER_FFI_UNIT_TEST_H_
| 1,304 |
668 | /**
* 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.fineract.useradministration.service;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Collection;
import org.apache.fineract.infrastructure.core.domain.JdbcSupport;
import org.apache.fineract.infrastructure.core.service.RoutingDataSource;
import org.apache.fineract.useradministration.data.PasswordValidationPolicyData;
import org.apache.fineract.useradministration.exception.PasswordValidationPolicyNotFoundException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Service;
@Service
public class PasswordValidationPolicyReadPlatformServiceImpl implements PasswordValidationPolicyReadPlatformService {
private final JdbcTemplate jdbcTemplate;
private final PasswordValidationPolicyMapper passwordValidationPolicyMapper;
@Autowired
public PasswordValidationPolicyReadPlatformServiceImpl(final RoutingDataSource dataSource) {
this.jdbcTemplate = new JdbcTemplate(dataSource);
this.passwordValidationPolicyMapper = new PasswordValidationPolicyMapper();
}
@Override
public Collection<PasswordValidationPolicyData> retrieveAll() {
final String sql = "select " + this.passwordValidationPolicyMapper.schema() + " order by pvp.id";
return this.jdbcTemplate.query(sql, this.passwordValidationPolicyMapper);
}
@Override
public PasswordValidationPolicyData retrieveActiveValidationPolicy() {
try {
final String sql = "select " + this.passwordValidationPolicyMapper.schema() + " where pvp.active = true";
return this.jdbcTemplate.queryForObject(sql, this.passwordValidationPolicyMapper);
} catch (final EmptyResultDataAccessException e) {
throw new PasswordValidationPolicyNotFoundException(e);
}
}
protected static final class PasswordValidationPolicyMapper implements RowMapper<PasswordValidationPolicyData> {
@Override
public PasswordValidationPolicyData mapRow(final ResultSet rs, @SuppressWarnings("unused") final int rowNum) throws SQLException {
final Long id = JdbcSupport.getLong(rs, "id");
final Boolean active = rs.getBoolean("active");
final String description = rs.getString("description");
final String key = rs.getString("key");
return new PasswordValidationPolicyData(id, active, description, key);
}
public String schema() {
return " pvp.id as id, pvp.active as active, pvp.description as description, pvp.`key` as `key`"
+ " from m_password_validation_policy pvp";
}
}
}
| 1,140 |
603 | """
Copyright (c) 2018 <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.
"""
from myhdl import *
import math
import mmap
BURST_FIXED = 0b00
BURST_INCR = 0b01
BURST_WRAP = 0b10
BURST_SIZE_1 = 0b000
BURST_SIZE_2 = 0b001
BURST_SIZE_4 = 0b010
BURST_SIZE_8 = 0b011
BURST_SIZE_16 = 0b100
BURST_SIZE_32 = 0b101
BURST_SIZE_64 = 0b110
BURST_SIZE_128 = 0b111
LOCK_NORMAL = 0b0
LOCK_EXCLUSIVE = 0b1
CACHE_B = 0b0001
CACHE_M = 0b0010
CACHE_RA = 0b0100
CACHE_WA = 0b1000
ARCACHE_DEVICE_NON_BUFFERABLE = 0b0000
ARCACHE_DEVICE_BUFFERABLE = 0b0001
ARCACHE_NORMAL_NON_CACHEABLE_NON_BUFFERABLE = 0b0010
ARCACHE_NORMAL_NON_CACHEABLE_BUFFERABLE = 0b0011
ARCACHE_WRITE_THROUGH_NO_ALLOC = 0b1010
ARCACHE_WRITE_THROUGH_READ_ALLOC = 0b1110
ARCACHE_WRITE_THROUGH_WRITE_ALLOC = 0b1010
ARCACHE_WRITE_THROUGH_READ_AND_WRITE_ALLOC = 0b1110
ARCACHE_WRITE_BACK_NO_ALLOC = 0b1011
ARCACHE_WRITE_BACK_READ_ALLOC = 0b1111
ARCACHE_WRITE_BACK_WRITE_ALLOC = 0b1011
ARCACHE_WRITE_BACK_READ_AND_WRIE_ALLOC = 0b1111
AWCACHE_DEVICE_NON_BUFFERABLE = 0b0000
AWCACHE_DEVICE_BUFFERABLE = 0b0001
AWCACHE_NORMAL_NON_CACHEABLE_NON_BUFFERABLE = 0b0010
AWCACHE_NORMAL_NON_CACHEABLE_BUFFERABLE = 0b0011
AWCACHE_WRITE_THROUGH_NO_ALLOC = 0b0110
AWCACHE_WRITE_THROUGH_READ_ALLOC = 0b0110
AWCACHE_WRITE_THROUGH_WRITE_ALLOC = 0b1110
AWCACHE_WRITE_THROUGH_READ_AND_WRITE_ALLOC = 0b1110
AWCACHE_WRITE_BACK_NO_ALLOC = 0b0111
AWCACHE_WRITE_BACK_READ_ALLOC = 0b0111
AWCACHE_WRITE_BACK_WRITE_ALLOC = 0b1111
AWCACHE_WRITE_BACK_READ_AND_WRIE_ALLOC = 0b1111
PROT_PRIVILEGED = 0b001
PROT_NONSECURE = 0b010
PROT_INSTRUCTION = 0b100
RESP_OKAY = 0b00
RESP_EXOKAY = 0b01
RESP_SLVERR = 0b10
RESP_DECERR = 0b11
class AXIMaster(object):
def __init__(self):
self.write_command_queue = []
self.write_command_sync = Signal(False)
self.write_resp_queue = []
self.write_resp_sync = Signal(False)
self.read_command_queue = []
self.read_command_sync = Signal(False)
self.read_data_queue = []
self.read_data_sync = Signal(False)
self.cur_write_id = 0
self.cur_read_id = 0
self.int_write_addr_queue = []
self.int_write_addr_sync = Signal(False)
self.int_write_data_queue = []
self.int_write_data_sync = Signal(False)
self.int_write_resp_command_queue = []
self.int_write_resp_command_sync = Signal(False)
self.int_write_resp_queue = []
self.int_write_resp_sync = Signal(False)
self.int_read_addr_queue = []
self.int_read_addr_sync = Signal(False)
self.int_read_resp_command_queue = []
self.int_read_resp_command_sync = Signal(False)
self.int_read_resp_queue_list = {}
self.int_read_resp_sync = Signal(False)
self.in_flight_operations = 0
self.max_burst_len = 256
self.has_logic = False
self.clk = None
def init_read(self, address, length, burst=0b01, size=None, lock=0b0, cache=0b0011, prot=0b010, qos=0b0000, region=0b0000, user=None):
self.read_command_queue.append((address, length, burst, size, lock, cache, prot, qos, region, user))
self.read_command_sync.next = not self.read_command_sync
def init_write(self, address, data, burst=0b01, size=None, lock=0b0, cache=0b0011, prot=0b010, qos=0b0000, region=0b0000, user=None):
self.write_command_queue.append((address, data, burst, size, lock, cache, prot, qos, region, user))
self.write_command_sync.next = not self.write_command_sync
def idle(self):
return not self.write_command_queue and not self.read_command_queue and not self.in_flight_operations
def wait(self):
while not self.idle():
yield self.clk.posedge
def read_data_ready(self):
return bool(self.read_data_queue)
def get_read_data(self):
if self.read_data_queue:
return self.read_data_queue.pop(0)
return None
def create_logic(self,
clk,
rst,
m_axi_awid=None,
m_axi_awaddr=None,
m_axi_awlen=Signal(intbv(0)[8:]),
m_axi_awsize=Signal(intbv(0)[3:]),
m_axi_awburst=Signal(intbv(0)[2:]),
m_axi_awlock=Signal(intbv(0)[1:]),
m_axi_awcache=Signal(intbv(0)[4:]),
m_axi_awprot=Signal(intbv(0)[3:]),
m_axi_awqos=Signal(intbv(0)[4:]),
m_axi_awregion=Signal(intbv(0)[4:]),
m_axi_awuser=None,
m_axi_awvalid=Signal(bool(False)),
m_axi_awready=Signal(bool(True)),
m_axi_wdata=None,
m_axi_wstrb=Signal(intbv(1)[1:]),
m_axi_wlast=Signal(bool(True)),
m_axi_wuser=None,
m_axi_wvalid=Signal(bool(False)),
m_axi_wready=Signal(bool(True)),
m_axi_bid=None,
m_axi_bresp=Signal(intbv(0)[2:]),
m_axi_buser=None,
m_axi_bvalid=Signal(bool(False)),
m_axi_bready=Signal(bool(False)),
m_axi_arid=None,
m_axi_araddr=None,
m_axi_arlen=Signal(intbv(0)[8:]),
m_axi_arsize=Signal(intbv(0)[3:]),
m_axi_arburst=Signal(intbv(0)[2:]),
m_axi_arlock=Signal(intbv(0)[1:]),
m_axi_arcache=Signal(intbv(0)[4:]),
m_axi_arprot=Signal(intbv(0)[3:]),
m_axi_arqos=Signal(intbv(0)[4:]),
m_axi_arregion=Signal(intbv(0)[4:]),
m_axi_aruser=None,
m_axi_arvalid=Signal(bool(False)),
m_axi_arready=Signal(bool(True)),
m_axi_rid=None,
m_axi_rdata=None,
m_axi_rresp=Signal(intbv(0)[2:]),
m_axi_rlast=Signal(bool(True)),
m_axi_ruser=None,
m_axi_rvalid=Signal(bool(False)),
m_axi_rready=Signal(bool(False)),
pause=False,
awpause=False,
wpause=False,
bpause=False,
arpause=False,
rpause=False,
name=None
):
if self.has_logic:
raise Exception("Logic already instantiated!")
if m_axi_wdata is not None:
if m_axi_awid is not None:
assert m_axi_bid is not None
assert len(m_axi_awid) == len(m_axi_bid)
assert m_axi_awaddr is not None
assert len(m_axi_wdata) % 8 == 0
assert len(m_axi_wdata) / 8 == len(m_axi_wstrb)
w = len(m_axi_wdata)
if m_axi_rdata is not None:
if m_axi_arid is not None:
assert m_axi_rid is not None
assert len(m_axi_arid) == len(m_axi_rid)
assert m_axi_araddr is not None
assert len(m_axi_rdata) % 8 == 0
w = len(m_axi_rdata)
if m_axi_wdata is not None:
assert len(m_axi_awaddr) == len(m_axi_araddr)
assert len(m_axi_wdata) == len(m_axi_rdata)
bw = int(w/8)
assert bw in (1, 2, 4, 8, 16, 32, 64, 128)
self.has_logic = True
self.clk = clk
m_axi_bvalid_int = Signal(bool(False))
m_axi_bready_int = Signal(bool(False))
m_axi_rvalid_int = Signal(bool(False))
m_axi_rready_int = Signal(bool(False))
@always_comb
def pause_logic():
m_axi_bvalid_int.next = m_axi_bvalid and not (pause or bpause)
m_axi_bready.next = m_axi_bready_int and not (pause or bpause)
m_axi_rvalid_int.next = m_axi_rvalid and not (pause or rpause)
m_axi_rready.next = m_axi_rready_int and not (pause or rpause)
@instance
def write_logic():
while True:
if not self.write_command_queue:
yield self.write_command_sync
if m_axi_awaddr is None:
print("Error: attempted write on read-only interface")
raise StopSimulation
addr, data, burst, size, lock, cache, prot, qos, region, user = self.write_command_queue.pop(0)
self.in_flight_operations += 1
num_bytes = bw
if size is None:
size = int(math.log(bw, 2))
else:
num_bytes = 2**size
assert 0 < num_bytes <= bw
aligned_addr = int(addr/num_bytes)*num_bytes
word_addr = int(addr/bw)*bw
start_offset = addr % bw
end_offset = ((addr + len(data) - 1) % bw) + 1
cycles = int((len(data) + num_bytes-1 + (addr % num_bytes)) / num_bytes)
cur_addr = aligned_addr
offset = 0
cycle_offset = aligned_addr-word_addr
n = 0
transfer_count = 0
burst_length = 0
if name is not None:
print("[%s] Write data addr: 0x%08x prot: 0x%x data: %s" % (name, addr, prot, " ".join(("{:02x}".format(c) for c in bytearray(data)))))
for k in range(cycles):
start = cycle_offset
stop = cycle_offset+num_bytes
if k == 0:
start = start_offset
if k == cycles-1:
stop = end_offset
strb = ((2**bw-1) << start) & (2**bw-1) & (2**bw-1) >> (bw - stop)
val = 0
for j in range(start, stop):
val |= bytearray(data)[offset] << j*8
offset += 1
if n >= burst_length:
transfer_count += 1
n = 0
burst_length = min(cycles-k, min(max(self.max_burst_len, 1), 256)) # max len
burst_length = int((min(burst_length*num_bytes, 0x1000-(cur_addr&0xfff))+num_bytes-1)/num_bytes) # 4k align
awid = self.cur_write_id
if m_axi_awid is not None:
self.cur_write_id = (self.cur_write_id + 1) % 2**len(m_axi_awid)
else:
self.cur_write_id = 0
self.int_write_addr_queue.append((cur_addr, awid, burst_length-1, size, burst, lock, cache, prot, qos, region, user))
self.int_write_addr_sync.next = not self.int_write_addr_sync
if name is not None:
print("[%s] Write burst awid: 0x%x awaddr: 0x%08x awlen: %d awsize: %d" % (name, awid, cur_addr, burst_length-1, size))
n += 1
self.int_write_data_queue.append((val, strb, n >= burst_length))
self.int_write_data_sync.next = not self.int_write_data_sync
cur_addr += num_bytes
cycle_offset = (cycle_offset + num_bytes) % bw
self.int_write_resp_command_queue.append((addr, len(data), transfer_count, prot))
self.int_write_resp_command_sync.next = not self.int_write_resp_command_sync
@instance
def write_resp_logic():
while True:
if not self.int_write_resp_command_queue:
yield self.int_write_resp_command_sync
addr, length, transfer_count, prot = self.int_write_resp_command_queue.pop(0)
resp = 0
for k in range(transfer_count):
while not self.int_write_resp_queue:
yield clk.posedge
cycle_id, cycle_resp, cycle_user = self.int_write_resp_queue.pop(0)
if cycle_resp != 0:
resp = cycle_resp
self.write_resp_queue.append((addr, length, prot, resp))
self.write_resp_sync.next = not self.write_resp_sync
self.in_flight_operations -= 1
@instance
def write_addr_interface_logic():
while True:
while not self.int_write_addr_queue:
yield clk.posedge
addr, awid, length, size, burst, lock, cache, prot, qos, region, user = self.int_write_addr_queue.pop(0)
if m_axi_awaddr is not None:
m_axi_awaddr.next = addr
m_axi_awid.next = awid
m_axi_awlen.next = length
m_axi_awsize.next = size
m_axi_awburst.next = burst
m_axi_awlock.next = lock
m_axi_awcache.next = cache
m_axi_awprot.next = prot
m_axi_awqos.next = qos
m_axi_awregion.next = region
if m_axi_awuser is not None:
m_axi_awuser.next = user
m_axi_awvalid.next = not (pause or awpause)
yield clk.posedge
while not m_axi_awvalid or not m_axi_awready:
m_axi_awvalid.next = m_axi_awvalid or not (pause or awpause)
yield clk.posedge
m_axi_awvalid.next = False
@instance
def write_data_interface_logic():
while True:
while not self.int_write_data_queue:
yield clk.posedge
m_axi_wdata.next, m_axi_wstrb.next, m_axi_wlast.next = self.int_write_data_queue.pop(0)
m_axi_wvalid.next = not (pause or wpause)
yield clk.posedge
while not m_axi_wvalid or not m_axi_wready:
m_axi_wvalid.next = m_axi_wvalid or not (pause or wpause)
yield clk.posedge
m_axi_wvalid.next = False
@instance
def write_resp_interface_logic():
while True:
m_axi_bready_int.next = True
yield clk.posedge
if m_axi_bready and m_axi_bvalid_int:
if m_axi_bid is not None:
bid = int(m_axi_bid)
else:
bid = 0
bresp = int(m_axi_bresp)
if m_axi_buser is not None:
buser = int(m_axi_buser)
else:
buser = 0
self.int_write_resp_queue.append((bid, bresp, buser))
self.int_write_resp_sync.next = not self.int_write_resp_sync
@instance
def read_logic():
while True:
if not self.read_command_queue:
yield self.read_command_sync
if m_axi_araddr is None:
print("Error: attempted read on write-only interface")
raise StopSimulation
addr, length, burst, size, lock, cache, prot, qos, region, user = self.read_command_queue.pop(0)
self.in_flight_operations += 1
num_bytes = bw
if size is None:
size = int(math.log(bw, 2))
else:
num_bytes = 2**size
assert 0 < num_bytes <= bw
aligned_addr = int(addr/num_bytes)*num_bytes
word_addr = int(addr/bw)*bw
cycles = int((length + num_bytes-1 + (addr % num_bytes)) / num_bytes)
burst_list = []
self.int_read_resp_command_queue.append((addr, length, size, cycles, prot, burst_list))
self.int_read_resp_command_sync.next = not self.int_read_resp_command_sync
cur_addr = aligned_addr
n = 0
burst_length = 0
for k in range(cycles):
n += 1
if n >= burst_length:
n = 0
burst_length = min(cycles-k, min(max(self.max_burst_len, 1), 256)) # max len
burst_length = int((min(burst_length*num_bytes, 0x1000-(cur_addr&0xfff))+num_bytes-1)/num_bytes) # 4k align
arid = self.cur_read_id
if m_axi_arid is not None:
self.cur_read_id = (self.cur_read_id + 1) % 2**len(m_axi_arid)
else:
self.cur_read_id = 0
burst_list.append((arid, burst_length))
self.int_read_addr_queue.append((cur_addr, arid, burst_length-1, size, burst, lock, cache, prot, qos, region, user))
self.int_read_addr_sync.next = not self.int_read_addr_sync
if name is not None:
print("[%s] Read burst arid: 0x%x araddr: 0x%08x arlen: %d arsize: %d" % (name, arid, cur_addr, burst_length-1, size))
cur_addr += num_bytes
burst_list.append(None)
@instance
def read_resp_logic():
while True:
if not self.int_read_resp_command_queue:
yield self.int_read_resp_command_sync
addr, length, size, cycles, prot, burst_list = self.int_read_resp_command_queue.pop(0)
num_bytes = 2**size
assert 0 <= size <= int(math.log(bw, 2))
aligned_addr = int(addr/num_bytes)*num_bytes
word_addr = int(addr/bw)*bw
start_offset = addr % bw
end_offset = ((addr + length - 1) % bw) + 1
cycle_offset = aligned_addr-word_addr
data = b''
resp = 0
first = True
while True:
while not burst_list:
yield clk.posedge
cur_burst = burst_list.pop(0)
if cur_burst is None:
break
rid = cur_burst[0]
burst_length = cur_burst[1]
for k in range(burst_length):
self.int_read_resp_queue_list.setdefault(rid, [])
while not self.int_read_resp_queue_list[rid]:
yield self.int_read_resp_sync
cycle_id, cycle_data, cycle_resp, cycle_last, cycle_user = self.int_read_resp_queue_list[rid].pop(0)
if cycle_resp != 0:
resp = cycle_resp
start = cycle_offset
stop = cycle_offset+num_bytes
if first:
start = start_offset
assert cycle_last == (k == burst_length - 1)
for j in range(start, stop):
data += bytearray([(cycle_data >> j*8) & 0xff])
cycle_offset = (cycle_offset + num_bytes) % bw
first = False
data = data[:length]
if name is not None:
print("[%s] Read data addr: 0x%08x prot: 0x%x data: %s" % (name, addr, prot, " ".join(("{:02x}".format(c) for c in bytearray(data)))))
self.read_data_queue.append((addr, data, prot, resp))
self.read_data_sync.next = not self.read_data_sync
self.in_flight_operations -= 1
@instance
def read_addr_interface_logic():
while True:
while not self.int_read_addr_queue:
yield clk.posedge
addr, arid, length, size, burst, lock, cache, prot, qos, region, user = self.int_read_addr_queue.pop(0)
m_axi_araddr.next = addr
if m_axi_arid is not None:
m_axi_arid.next = arid
m_axi_arlen.next = length
m_axi_arsize.next = size
m_axi_arburst.next = burst
m_axi_arlock.next = lock
m_axi_arcache.next = cache
m_axi_arprot.next = prot
m_axi_arqos.next = qos
m_axi_arregion.next = region
if m_axi_aruser is not None:
m_axi_aruser.next = user
m_axi_arvalid.next = not (pause or arpause)
yield clk.posedge
while not m_axi_arvalid or not m_axi_arready:
m_axi_arvalid.next = m_axi_arvalid or not (pause or arpause)
yield clk.posedge
m_axi_arvalid.next = False
@instance
def read_resp_interface_logic():
while True:
m_axi_rready_int.next = True
yield clk.posedge
if m_axi_rready and m_axi_rvalid_int:
if m_axi_rid is not None:
rid = int(m_axi_rid)
else:
rid = 0
rdata = int(m_axi_rdata)
rresp = int(m_axi_rresp)
rlast = int(m_axi_rlast)
if m_axi_buser is not None:
ruser = int(m_axi_ruser)
else:
ruser = 0
self.int_read_resp_queue_list.setdefault(rid, [])
self.int_read_resp_queue_list[rid].append((rid, rdata, rresp, rlast, ruser))
self.int_read_resp_sync.next = not self.int_read_resp_sync
return instances()
class AXIRam(object):
def __init__(self, size = 1024):
self.size = size
self.mem = mmap.mmap(-1, size)
self.int_write_addr_queue = []
self.int_write_addr_sync = Signal(False)
self.int_write_data_queue = []
self.int_write_data_sync = Signal(False)
self.int_write_resp_queue = []
self.int_write_resp_sync = Signal(False)
self.int_read_addr_queue = []
self.int_read_addr_sync = Signal(False)
self.int_read_resp_queue = []
self.int_read_resp_sync = Signal(False)
def read_mem(self, address, length):
self.mem.seek(address % self.size)
return self.mem.read(length)
def write_mem(self, address, data):
self.mem.seek(address % self.size)
self.mem.write(bytes(data))
def create_port(self,
clk,
s_axi_awid=None,
s_axi_awaddr=None,
s_axi_awlen=Signal(intbv(0)[8:]),
s_axi_awsize=Signal(intbv(0)[3:]),
s_axi_awburst=Signal(intbv(0)[2:]),
s_axi_awlock=Signal(intbv(0)[1:]),
s_axi_awcache=Signal(intbv(0)[4:]),
s_axi_awprot=Signal(intbv(0)[3:]),
s_axi_awvalid=Signal(bool(False)),
s_axi_awready=Signal(bool(True)),
s_axi_wdata=None,
s_axi_wstrb=Signal(intbv(1)[1:]),
s_axi_wlast=Signal(bool(True)),
s_axi_wvalid=Signal(bool(False)),
s_axi_wready=Signal(bool(True)),
s_axi_bid=None,
s_axi_bresp=Signal(intbv(0)[2:]),
s_axi_bvalid=Signal(bool(False)),
s_axi_bready=Signal(bool(False)),
s_axi_arid=None,
s_axi_araddr=None,
s_axi_arlen=Signal(intbv(0)[8:]),
s_axi_arsize=Signal(intbv(0)[3:]),
s_axi_arburst=Signal(intbv(0)[2:]),
s_axi_arlock=Signal(intbv(0)[1:]),
s_axi_arcache=Signal(intbv(0)[4:]),
s_axi_arprot=Signal(intbv(0)[3:]),
s_axi_arvalid=Signal(bool(False)),
s_axi_arready=Signal(bool(True)),
s_axi_rid=None,
s_axi_rdata=None,
s_axi_rresp=Signal(intbv(0)[2:]),
s_axi_rlast=Signal(bool(True)),
s_axi_rvalid=Signal(bool(False)),
s_axi_rready=Signal(bool(False)),
pause=False,
awpause=False,
wpause=False,
bpause=False,
arpause=False,
rpause=False,
name=None
):
if s_axi_wdata is not None:
if s_axi_awid is not None:
assert s_axi_bid is not None
assert len(s_axi_awid) == len(s_axi_bid)
assert s_axi_awaddr is not None
assert len(s_axi_wdata) % 8 == 0
assert len(s_axi_wdata) / 8 == len(s_axi_wstrb)
w = len(s_axi_wdata)
if s_axi_rdata is not None:
if s_axi_arid is not None:
assert s_axi_rid is not None
assert len(s_axi_arid) == len(s_axi_rid)
assert s_axi_araddr is not None
assert len(s_axi_rdata) % 8 == 0
w = len(s_axi_rdata)
if s_axi_wdata is not None:
assert len(s_axi_awaddr) == len(s_axi_araddr)
assert len(s_axi_wdata) == len(s_axi_rdata)
bw = int(w/8)
assert bw in (1, 2, 4, 8, 16, 32, 64, 128)
s_axi_awvalid_int = Signal(bool(False))
s_axi_awready_int = Signal(bool(False))
s_axi_wvalid_int = Signal(bool(False))
s_axi_wready_int = Signal(bool(False))
s_axi_arvalid_int = Signal(bool(False))
s_axi_arready_int = Signal(bool(False))
@always_comb
def pause_logic():
s_axi_awvalid_int.next = s_axi_awvalid and not (pause or awpause)
s_axi_awready.next = s_axi_awready_int and not (pause or awpause)
s_axi_wvalid_int.next = s_axi_wvalid and not (pause or wpause)
s_axi_wready.next = s_axi_wready_int and not (pause or wpause)
s_axi_arvalid_int.next = s_axi_arvalid and not (pause or arpause)
s_axi_arready.next = s_axi_arready_int and not (pause or arpause)
@instance
def write_logic():
while True:
if not self.int_write_addr_queue:
yield self.int_write_addr_sync
addr, awid, length, size, burst, lock, cache, prot = self.int_write_addr_queue.pop(0)
if name is not None:
print("[%s] Write burst awid: 0x%x awaddr: 0x%08x awlen: %d awsize: %d" % (name, awid, addr, length, size))
num_bytes = 2**size
assert 0 < num_bytes <= bw
aligned_addr = int(addr/num_bytes)*num_bytes
length = length+1
transfer_size = num_bytes*length
if burst == BURST_WRAP:
lower_wrap_boundary = int(addr/transfer_size)*transfer_size
upper_wrap_boundary = lower_wrap_boundary+transfer_size
if burst == BURST_INCR:
# check for 4k boundary crossing
assert 0x1000-(aligned_addr&0xfff) >= transfer_size
cur_addr = aligned_addr
for n in range(length):
cur_word_addr = int(cur_addr/bw)*bw
if not self.int_write_data_queue:
yield self.int_write_data_sync
wdata, strb, last = self.int_write_data_queue.pop(0)
self.mem.seek(cur_word_addr % self.size)
data = bytearray()
for i in range(bw):
data.extend(bytearray([wdata & 0xff]))
wdata >>= 8
for i in range(bw):
if strb & (1 << i):
self.mem.write(bytes(data[i:i+1]))
else:
self.mem.seek(1, 1)
if n == length-1:
self.int_write_resp_queue.append((awid, 0b00))
self.int_write_resp_sync.next = not self.int_write_resp_sync
if last != (n == length-1):
print("Error: bad last assert")
raise StopSimulation
assert last == (n == length-1)
if name is not None:
print("[%s] Write word id: %d addr: 0x%08x prot: 0x%x wstrb: 0x%02x data: %s" % (name, awid, cur_addr, prot, s_axi_wstrb, " ".join(("{:02x}".format(c) for c in bytearray(data)))))
if burst != BURST_FIXED:
cur_addr += num_bytes
if burst == BURST_WRAP:
if cur_addr == upper_wrap_boundary:
cur_addr = lower_wrap_boundary
@instance
def write_addr_interface_logic():
while True:
s_axi_awready_int.next = True
yield clk.posedge
if s_axi_awready and s_axi_awvalid_int:
addr = int(s_axi_awaddr)
if s_axi_awid is not None:
awid = int(s_axi_awid)
else:
awid = 0
length = int(s_axi_awlen)
size = int(s_axi_awsize)
burst = int(s_axi_awburst)
lock = int(s_axi_awlock)
cache = int(s_axi_awcache)
prot = int(s_axi_awprot)
self.int_write_addr_queue.append((addr, awid, length, size, burst, lock, cache, prot))
self.int_write_addr_sync.next = not self.int_write_addr_sync
@instance
def write_data_interface_logic():
while True:
s_axi_wready_int.next = True
yield clk.posedge
if s_axi_wready and s_axi_wvalid_int:
data = int(s_axi_wdata)
strb = int(s_axi_wstrb)
last = bool(s_axi_wlast)
self.int_write_data_queue.append((data, strb, last))
self.int_write_data_sync.next = not self.int_write_data_sync
@instance
def write_resp_interface_logic():
while True:
while not self.int_write_resp_queue:
yield clk.posedge
bid, bresp = self.int_write_resp_queue.pop(0)
if s_axi_bid is not None:
s_axi_bid.next = bid
s_axi_bresp.next = bresp
s_axi_bvalid.next = not (pause or bpause)
yield clk.posedge
while not s_axi_bvalid or not s_axi_bready:
s_axi_bvalid.next = s_axi_bvalid or not (pause or bpause)
yield clk.posedge
s_axi_bvalid.next = False
@instance
def read_logic():
while True:
if not self.int_read_addr_queue:
yield self.int_read_addr_sync
addr, arid, length, size, burst, lock, cache, prot = self.int_read_addr_queue.pop(0)
if name is not None:
print("[%s] Read burst arid: 0x%x araddr: 0x%08x arlen: %d arsize: %d" % (name, arid, addr, length, size))
num_bytes = 2**size
assert 0 < num_bytes <= bw
aligned_addr = int(addr/num_bytes)*num_bytes
length = length+1
transfer_size = num_bytes*length
if burst == BURST_WRAP:
lower_wrap_boundary = int(addr/transfer_size)*transfer_size
upper_wrap_boundary = lower_wrap_boundary+transfer_size
if burst == BURST_INCR:
# check for 4k boundary crossing
assert 0x1000-(aligned_addr&0xfff) >= transfer_size
cur_addr = aligned_addr
for n in range(length):
cur_word_addr = int(cur_addr/bw)*bw
self.mem.seek(cur_word_addr % self.size)
data = bytearray(self.mem.read(bw))
val = 0
for i in range(bw-1,-1,-1):
val <<= 8
val += data[i]
self.int_read_resp_queue.append((arid, val, 0x00, n == length-1))
self.int_read_resp_sync.next = not self.int_read_resp_sync
if name is not None:
print("[%s] Read word id: %d addr: 0x%08x prot: 0x%x data: %s" % (name, arid, cur_addr, prot, " ".join(("{:02x}".format(c) for c in bytearray(data)))))
if burst != BURST_FIXED:
cur_addr += num_bytes
if burst == BURST_WRAP:
if cur_addr == upper_wrap_boundary:
cur_addr = lower_wrap_boundary
@instance
def read_addr_interface_logic():
while True:
s_axi_arready_int.next = True
yield clk.posedge
if s_axi_arready and s_axi_arvalid_int:
addr = int(s_axi_araddr)
if s_axi_arid is not None:
arid = int(s_axi_arid)
else:
arid = 0
length = int(s_axi_arlen)
size = int(s_axi_arsize)
burst = int(s_axi_arburst)
lock = int(s_axi_arlock)
cache = int(s_axi_arcache)
prot = int(s_axi_arprot)
self.int_read_addr_queue.append((addr, arid, length, size, burst, lock, cache, prot))
self.int_read_addr_sync.next = not self.int_read_addr_sync
@instance
def read_resp_interface_logic():
while True:
while not self.int_read_resp_queue:
yield clk.posedge
rid, rdata, rresp, rlast = self.int_read_resp_queue.pop(0)
if s_axi_rid is not None:
s_axi_rid.next = rid
s_axi_rdata.next = rdata
s_axi_rresp.next = rresp
s_axi_rlast.next = rlast
s_axi_rvalid.next = not (pause or rpause)
yield clk.posedge
while not s_axi_rvalid or not s_axi_rready:
s_axi_rvalid.next = s_axi_rvalid or not (pause or rpause)
yield clk.posedge
s_axi_rvalid.next = False
return instances()
| 20,463 |
1,363 | package com.github.liaochong.myexcel.core.templatehandler;
import com.github.liaochong.myexcel.core.parser.ParseConfig;
import com.github.liaochong.myexcel.core.parser.Table;
import java.util.List;
import java.util.Map;
/**
* @author liaochong
* @version 1.0
*/
public interface TemplateHandler {
/**
* 类路径模板
*
* @param path 类路径模板
* @return TemplateHandler
*/
TemplateHandler classpathTemplate(String path);
/**
* 文件路径模板
*
* @param dirPath 文件路径模板
* @param fileName 模板名称
* @return TemplateHandler
*/
TemplateHandler fileTemplate(String dirPath, String fileName);
/**
* 获取模板字符流
*
* @param renderData 被渲染的数据
* @param <E> 被渲染数据类型
* @return 模板字符流
*/
<E> String render(Map<String, E> renderData);
<F> List<Table> render(Map<String, F> renderData, ParseConfig parseConfig) throws Exception;
}
| 471 |
381 | # import the option --viewloops from the JIT
def pytest_addoption(parser):
from rpython.jit.conftest import pytest_addoption
pytest_addoption(parser)
| 55 |
709 | <gh_stars>100-1000
//-----------------------------------------------
//
// This file is part of the Siv3D Engine.
//
// Copyright (c) 2008-2021 <NAME>
// Copyright (c) 2016-2021 OpenSiv3D Project
//
// Licensed under the MIT License.
//
//-----------------------------------------------
# pragma once
# include <Siv3D/Common.hpp>
# include <Siv3D/String.hpp>
namespace s3d
{
namespace CacheDirectory
{
[[nodiscard]]
FilePath Engine();
[[nodiscard]]
FilePath Apps(StringView applicationName);
}
}
| 178 |
8,240 | from __future__ import absolute_import, print_function
from tweepy.streaming import StreamListener
from tweepy import OAuthHandler
from tweepy import Stream
import os
import json
import time
from flask import Flask, render_template, Response
from flask.ext.cors import CORS
app = Flask(__name__)
CORS(app)
@app.route("/api/bookmarks")
def bookmarks():
return Response(json.dumps(sorted(articles, key=lambda article: article["liked_on"], reverse=True)), mimetype='application/json')
@app.route("/")
def index():
return render_template("index.html", articles=sorted(articles, key=lambda article: article["liked_on"], reverse=True))
consumer_key=os.getenv("TWITTER_CONSUMER_KEY")
consumer_secret=os.getenv("TWITTER_CONSUMER_SECRET")
access_token=os.getenv("TWITTER_ACCESS_TOKEN")
access_token_secret=os.getenv("TWITTER_ACCESS_SECRET")
articles = []
class LikedTweetsListener(StreamListener):
def on_data(self, data):
tweet = json.loads(data)
if 'event' in tweet and tweet['event'] == "favorite":
liked_tweet = tweet["target_object"]
liked_tweet_text = liked_tweet["text"]
story_url = extract_url(liked_tweet)
if story_url:
article = extract_article(story_url)
if article:
article['story_url'] = story_url
article['liked_on'] = time.time()
articles.append(article)
return True
def on_error(self, status):
print("Error status received : {0}".format(status))
def extract_url(liked_tweet):
url_entities = liked_tweet["entities"]["urls"]
if url_entities and len(url_entities) > 0:
return url_entities[0]['expanded_url']
else:
return None
from newspaper import Article
def extract_article(story_url):
article = Article(story_url)
article.download()
article.parse()
title = article.title
img = article.top_image
publish_date = article.publish_date
text = article.text.split('\n\n')[0] if article.text else ""
return {
'title':title,
'img':img,
'text': text
}
if __name__ == '__main__':
l = LikedTweetsListener()
auth = OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
stream = Stream(auth, l)
stream.userstream(async=True)
app.run(debug=True)
| 971 |
32,544 | package com.baeldung.regexp.datepattern.gregorian;
import com.baeldung.regexp.datepattern.DateMatcher;
import java.util.regex.Pattern;
public class February29thMatcher implements DateMatcher {
private static final Pattern DATE_PATTERN = Pattern.compile(
"^((2000|2400|2800|(19|2[0-9](0[48]|[2468][048]|[13579][26])))-02-29)$");
@Override
public boolean matches(String date) {
return DATE_PATTERN.matcher(date).matches();
}
}
| 193 |
713 | package org.infinispan.persistence.jdbc.common.configuration;
import static org.infinispan.persistence.jdbc.common.configuration.AbstractUnmanagedConnectionFactoryConfiguration.CONNECTION_URL;
import static org.infinispan.persistence.jdbc.common.configuration.AbstractUnmanagedConnectionFactoryConfiguration.DRIVER_CLASS;
import static org.infinispan.persistence.jdbc.common.configuration.AbstractUnmanagedConnectionFactoryConfiguration.PASSWORD;
import static org.infinispan.persistence.jdbc.common.configuration.AbstractUnmanagedConnectionFactoryConfiguration.USERNAME;
import static org.infinispan.persistence.jdbc.common.configuration.PooledConnectionFactoryConfiguration.PROPERTY_FILE;
import java.sql.Driver;
import org.infinispan.commons.CacheConfigurationException;
import org.infinispan.commons.configuration.attributes.AttributeSet;
import org.infinispan.configuration.global.GlobalConfiguration;
/**
* PooledConnectionFactoryConfigurationBuilder.
*
* @author <NAME>
* @since 5.2
*/
public class PooledConnectionFactoryConfigurationBuilder<S extends AbstractJdbcStoreConfigurationBuilder<?, S>> extends AbstractJdbcStoreConfigurationChildBuilder<S>
implements ConnectionFactoryConfigurationBuilder<PooledConnectionFactoryConfiguration> {
private final AttributeSet attributes;
protected PooledConnectionFactoryConfigurationBuilder(AbstractJdbcStoreConfigurationBuilder<?, S> builder) {
super(builder);
attributes = PooledConnectionFactoryConfiguration.attributeSet();
}
public PooledConnectionFactoryConfigurationBuilder<S> propertyFile(String propertyFile) {
attributes.attribute(PROPERTY_FILE).set(propertyFile);
return this;
}
public PooledConnectionFactoryConfigurationBuilder<S> connectionUrl(String connectionUrl) {
attributes.attribute(CONNECTION_URL).set(connectionUrl);
return this;
}
public PooledConnectionFactoryConfigurationBuilder<S> driverClass(Class<? extends Driver> driverClass) {
attributes.attribute(DRIVER_CLASS).set(driverClass.getName());
return this;
}
public PooledConnectionFactoryConfigurationBuilder<S> driverClass(String driverClass) {
attributes.attribute(DRIVER_CLASS).set(driverClass);
return this;
}
public PooledConnectionFactoryConfigurationBuilder<S> username(String username) {
attributes.attribute(USERNAME).set(username);
return this;
}
public PooledConnectionFactoryConfigurationBuilder<S> password(String password) {
attributes.attribute(PASSWORD).set(password);
return this;
}
@Override
public void validate() {
// If a propertyFile is specified, then no exceptions are thrown for an incorrect config until the pool is created
String propertyFile = attributes.attribute(PROPERTY_FILE).get();
String connectionUrl = attributes.attribute(CONNECTION_URL).get();
if (propertyFile == null && connectionUrl == null) {
throw new CacheConfigurationException("Missing connectionUrl parameter");
}
}
@Override
public void validate(GlobalConfiguration globalConfig) {
}
@Override
public PooledConnectionFactoryConfiguration create() {
return new PooledConnectionFactoryConfiguration(attributes.protect());
}
@Override
public PooledConnectionFactoryConfigurationBuilder<S> read(PooledConnectionFactoryConfiguration template) {
attributes.read(template.attributes);
return this;
}
}
| 975 |
1,338 | /*
* ES1370 Haiku Driver for ES1370 audio
*
* Copyright 2002-2007, Haiku, Inc.
* Distributed under the terms of the MIT License.
*
* Authors:
* <NAME>, <EMAIL>
* <NAME>, <EMAIL>
*/
#include <KernelExport.h>
#include <OS.h>
#include "io.h"
#include "es1370reg.h"
#include "debug.h"
#include <PCI.h>
extern pci_module_info *pci;
uint8
es1370_reg_read_8(device_config *config, int regno)
{
ASSERT(regno >= 0);
return pci->read_io_8(config->base + regno);
}
uint16
es1370_reg_read_16(device_config *config, int regno)
{
ASSERT(regno >= 0);
return pci->read_io_16(config->base + regno);
}
uint32
es1370_reg_read_32(device_config *config, int regno)
{
ASSERT(regno >= 0);
return pci->read_io_32(config->base + regno);
}
void
es1370_reg_write_8(device_config *config, int regno, uint8 value)
{
ASSERT(regno >= 0);
pci->write_io_8(config->base + regno, value);
}
void
es1370_reg_write_16(device_config *config, int regno, uint16 value)
{
ASSERT(regno >= 0);
pci->write_io_16(config->base + regno, value);
}
void
es1370_reg_write_32(device_config *config, int regno, uint32 value)
{
ASSERT(regno >= 0);
pci->write_io_32(config->base + regno, value);
}
/* codec */
static int
es1370_codec_wait(device_config *config)
{
int i;
for (i = 0; i < 1100; i++) {
if ((es1370_reg_read_32(config, ES1370_REG_STATUS) & STAT_CWRIP) == 0)
return B_OK;
if (i > 100)
spin(1);
}
return B_TIMED_OUT;
}
uint16
es1370_codec_read(device_config *config, int regno)
{
ASSERT(regno >= 0);
if(es1370_codec_wait(config)!=B_OK) {
PRINT(("codec busy (2)\n"));
return -1;
}
return pci->read_io_32(config->base + ES1370_REG_CODEC);
}
void
es1370_codec_write(device_config *config, int regno, uint16 value)
{
ASSERT(regno >= 0);
if(es1370_codec_wait(config)!=B_OK) {
PRINT(("codec busy (4)\n"));
return;
}
pci->write_io_32(config->base + ES1370_REG_CODEC, (regno << 8) | value);
}
| 852 |
675 | <gh_stars>100-1000
/*
* Copyright 2012-2014 eBay Software Foundation and selendroid committers.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package io.selendroid.standalone.android;
import static io.selendroid.standalone.android.OS.platformExecutableSuffixExe;
import static org.openqa.selenium.Platform.MAC;
import io.selendroid.standalone.exceptions.ShellCommandException;
import io.selendroid.standalone.io.ShellCommand;
import java.io.File;
import org.apache.commons.exec.CommandLine;
import org.openqa.selenium.Platform;
public class JavaSdk {
public static String javaHome = null;
public static String javaHome() {
if (javaHome == null) {
// Sniff JAVA_HOME first
javaHome = System.getenv("JAVA_HOME");
// If that's not present, and we're on a Mac...
if (javaHome == null && Platform.getCurrent() == MAC) {
try {
javaHome = ShellCommand.exec(new CommandLine("/usr/libexec/java_home"));
if (javaHome != null) {
javaHome = javaHome.replaceAll("\\r|\\n", "");
}
} catch (ShellCommandException e) {}
}
// Finally, check java.home, though this may point to a JRE.
if (javaHome == null) {
javaHome = System.getProperty("java.home");
}
}
return javaHome;
}
public static File jarsigner() {
StringBuffer jarsigner = new StringBuffer();
jarsigner.append(javaHome());
jarsigner.append(File.separator);
jarsigner.append("bin");
jarsigner.append(File.separator);
return new File(jarsigner.toString(), "jarsigner" + platformExecutableSuffixExe());
}
public static File keytool() {
StringBuffer keytool = new StringBuffer();
keytool.append(javaHome());
keytool.append(File.separator);
keytool.append("bin");
keytool.append(File.separator);
return new File(keytool.toString(), "keytool" + platformExecutableSuffixExe());
}
}
| 832 |
622 |
public class Main {
public static void main(String[] args) {
Menu exactum = new Menu();
exactum.addMeal("Fish fingers with sour cream sauce");
exactum.addMeal("Vegetable casserole with salad cheese");
exactum.addMeal("Chicken and nacho salad");
exactum.printMeals();
exactum.clearMenu();
exactum.printMeals();
}
}
| 154 |
903 | /****************************************************************************
**
** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (<EMAIL>)
**
** This file is part of the QtGui module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** GNU Lesser General Public License Usage
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this
** file. Please review the following information to ensure the GNU Lesser
** General Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU General
** Public License version 3.0 as published by the Free Software Foundation
** and appearing in the file LICENSE.GPL included in the packaging of this
** file. Please review the following information to ensure the GNU General
** Public License version 3.0 requirements will be met:
** http://www.gnu.org/copyleft/gpl.html.
**
** Other Usage
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#ifndef QRAWFONT_H
#define QRAWFONT_H
#include <QtCore/qstring.h>
#include <QtCore/qiodevice.h>
#include <QtCore/qglobal.h>
#include <QtCore/qobject.h>
#include <QtCore/qpoint.h>
#include <QtGui/qfont.h>
#include <QtGui/qtransform.h>
#include <QtGui/qfontdatabase.h>
#if !defined(QT_NO_RAWFONT)
QT_BEGIN_HEADER
QT_BEGIN_NAMESPACE
QT_MODULE(Gui)
class QRawFontPrivate;
class Q_GUI_EXPORT QRawFont
{
public:
enum AntialiasingType {
PixelAntialiasing,
SubPixelAntialiasing
};
QRawFont();
QRawFont(const QString &fileName,
qreal pixelSize,
QFont::HintingPreference hintingPreference = QFont::PreferDefaultHinting);
QRawFont(const QByteArray &fontData,
qreal pixelSize,
QFont::HintingPreference hintingPreference = QFont::PreferDefaultHinting);
QRawFont(const QRawFont &other);
~QRawFont();
bool isValid() const;
QRawFont &operator=(const QRawFont &other);
bool operator==(const QRawFont &other) const;
inline bool operator!=(const QRawFont &other) const
{ return !operator==(other); }
QString familyName() const;
QString styleName() const;
QFont::Style style() const;
int weight() const;
QVector<quint32> glyphIndexesForString(const QString &text) const;
QVector<QPointF> advancesForGlyphIndexes(const QVector<quint32> &glyphIndexes) const;
bool glyphIndexesForChars(const QChar *chars, int numChars, quint32 *glyphIndexes, int *numGlyphs) const;
bool advancesForGlyphIndexes(const quint32 *glyphIndexes, QPointF *advances, int numGlyphs) const;
QImage alphaMapForGlyph(quint32 glyphIndex,
AntialiasingType antialiasingType = SubPixelAntialiasing,
const QTransform &transform = QTransform()) const;
QPainterPath pathForGlyph(quint32 glyphIndex) const;
void setPixelSize(qreal pixelSize);
qreal pixelSize() const;
QFont::HintingPreference hintingPreference() const;
qreal ascent() const;
qreal descent() const;
qreal leading() const;
qreal xHeight() const;
qreal averageCharWidth() const;
qreal maxCharWidth() const;
qreal unitsPerEm() const;
void loadFromFile(const QString &fileName,
qreal pixelSize,
QFont::HintingPreference hintingPreference);
void loadFromData(const QByteArray &fontData,
qreal pixelSize,
QFont::HintingPreference hintingPreference);
bool supportsCharacter(quint32 ucs4) const;
bool supportsCharacter(QChar character) const;
QList<QFontDatabase::WritingSystem> supportedWritingSystems() const;
QByteArray fontTable(const char *tagName) const;
static QRawFont fromFont(const QFont &font,
QFontDatabase::WritingSystem writingSystem = QFontDatabase::Any);
private:
friend class QRawFontPrivate;
QExplicitlySharedDataPointer<QRawFontPrivate> d;
};
QT_END_NAMESPACE
QT_END_HEADER
#endif // QT_NO_RAWFONT
#endif // QRAWFONT_H
| 1,709 |
2,151 | // Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chromeos/network/dhcp_pac_file_fetcher_factory_chromeos.h"
#include <memory>
#include "chromeos/network/dhcp_pac_file_fetcher_chromeos.h"
namespace chromeos {
DhcpPacFileFetcherFactoryChromeos::DhcpPacFileFetcherFactoryChromeos() =
default;
DhcpPacFileFetcherFactoryChromeos::~DhcpPacFileFetcherFactoryChromeos() =
default;
std::unique_ptr<net::DhcpPacFileFetcher>
DhcpPacFileFetcherFactoryChromeos::Create(
net::URLRequestContext* url_request_context) {
return std::make_unique<DhcpPacFileFetcherChromeos>(url_request_context);
}
} // namespace chromeos
| 268 |
1,840 | <filename>controller/src/main/java/io/pravega/controller/server/ControllerServiceMain.java<gh_stars>1000+
/**
* Copyright Pravega Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.pravega.controller.server;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
import com.google.common.util.concurrent.AbstractExecutionThreadService;
import com.google.common.util.concurrent.Monitor;
import io.pravega.common.LoggerHelpers;
import io.pravega.common.function.Callbacks;
import io.pravega.controller.metrics.ZookeeperMetrics;
import io.pravega.controller.store.client.StoreClient;
import io.pravega.controller.store.client.StoreClientFactory;
import io.pravega.controller.store.client.StoreType;
import java.util.concurrent.CompletableFuture;
import java.util.function.BiFunction;
import lombok.extern.slf4j.Slf4j;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.state.ConnectionState;
/**
* ControllerServiceMonitor, entry point into the controller service.
*/
@Slf4j
public class ControllerServiceMain extends AbstractExecutionThreadService implements AutoCloseable {
enum ServiceState {
NEW,
STARTING,
PAUSING,
}
private final String objectId;
private final ControllerServiceConfig serviceConfig;
private final BiFunction<ControllerServiceConfig, StoreClient, ControllerServiceStarter> starterFactory;
private ControllerServiceStarter starter;
private final CompletableFuture<Void> serviceStopFuture;
private StoreClient storeClient;
private ServiceState serviceState;
private final Monitor monitor = new Monitor();
private final Monitor.Guard hasReachedStarting = new HasReachedState(ServiceState.STARTING);
private final Monitor.Guard hasReachedPausing = new HasReachedState(ServiceState.PAUSING);
private final ZookeeperMetrics zookeeperMetrics;
final class HasReachedState extends Monitor.Guard {
private ServiceState desiredState;
HasReachedState(ServiceState desiredState) {
super(monitor);
this.desiredState = desiredState;
}
@Override
public boolean isSatisfied() {
return serviceState == desiredState;
}
}
public ControllerServiceMain(ControllerServiceConfig serviceConfig) {
this(serviceConfig, ControllerServiceStarter::new);
}
@VisibleForTesting
ControllerServiceMain(final ControllerServiceConfig serviceConfig,
final BiFunction<ControllerServiceConfig, StoreClient, ControllerServiceStarter> starterFactory) {
this.objectId = "ControllerServiceMain";
this.serviceConfig = serviceConfig;
this.starterFactory = starterFactory;
this.serviceStopFuture = new CompletableFuture<>();
this.serviceState = ServiceState.NEW;
this.zookeeperMetrics = new ZookeeperMetrics();
}
@Override
protected void triggerShutdown() {
log.info("Shutting down Controller Service.");
this.serviceStopFuture.complete(null);
}
@Override
protected void run() throws Exception {
long traceId = LoggerHelpers.traceEnter(log, this.objectId, "run");
try {
while (isRunning()) {
// Create store client.
log.debug("Creating store client");
storeClient = StoreClientFactory.createStoreClient(serviceConfig.getStoreClientConfig());
starter = starterFactory.apply(serviceConfig, storeClient);
boolean hasZkConnection = serviceConfig.getStoreClientConfig().getStoreType().equals(StoreType.Zookeeper) ||
serviceConfig.isControllerClusterListenerEnabled();
CompletableFuture<Void> sessionExpiryFuture = new CompletableFuture<>();
if (hasZkConnection) {
CuratorFramework client = (CuratorFramework) storeClient.getClient();
log.debug("Awaiting ZK client connection to ZK server");
client.blockUntilConnected();
// Await ZK session expiry.
log.debug("Awaiting ZK session expiry or termination trigger for ControllerServiceMain");
client.getConnectionStateListenable().addListener((client1, newState) -> {
if (newState.equals(ConnectionState.LOST)) {
sessionExpiryFuture.complete(null);
starter.notifySessionExpiration();
}
});
}
// Start controller services.
log.info("Starting Controller Services.");
notifyServiceStateChange(ServiceState.STARTING);
starter.startAsync();
starter.awaitRunning();
log.info("Controller Services started successfully.");
if (hasZkConnection) {
// At this point, wait until either of the two things happen
// 1. ZK session expires, i.e., sessionExpiryFuture completes, or
// 2. This ControllerServiceMain instance is stopped by invoking stopAsync() method,
// i.e., serviceStopFuture completes.
CompletableFuture.anyOf(sessionExpiryFuture, this.serviceStopFuture).join();
// Problem of curator automatically recreating ZK client on session expiry is mitigated by
// employing a custom ZookeeperFactory that always returns the same ZK client to curator
// Once ZK session expires or once ControllerServiceMain is externally stopped,
// stop ControllerServiceStarter.
if (sessionExpiryFuture.isDone()) {
zookeeperMetrics.reportZKSessionExpiration();
log.info("ZK session expired. Stopping Controller Services.");
}
} else {
this.serviceStopFuture.join();
log.info("Stopping Controller Services.");
}
notifyServiceStateChange(ServiceState.PAUSING);
starter.stopAsync();
log.debug("Awaiting termination of ControllerServices");
starter.awaitTerminated();
if (hasZkConnection) {
log.debug("Calling close on store client.");
storeClient.close();
}
log.info("Controller Services terminated successfully.");
}
} catch (Exception e) {
log.error("Controller Service Main thread exited exceptionally", e);
throw e;
} finally {
if (storeClient != null) {
storeClient.close();
}
LoggerHelpers.traceLeave(log, this.objectId, "run", traceId);
}
}
/**
* Changes internal state to the new value.
*
* @param newState new internal state.
*/
private void notifyServiceStateChange(ServiceState newState) {
monitor.enter();
try {
serviceState = newState;
} finally {
monitor.leave();
}
}
/**
* Awaits until the internal state changes to STARTING, and returns the reference
* of current ControllerServiceStarter.
*/
@VisibleForTesting
public ControllerServiceStarter awaitServiceStarting() {
monitor.enterWhenUninterruptibly(hasReachedStarting);
try {
if (serviceState != ServiceState.STARTING) {
throw new IllegalStateException("Expected state=" + ServiceState.STARTING +
", but actual state=" + serviceState);
} else {
return this.starter;
}
} finally {
monitor.leave();
}
}
/**
* Awaits until the internal state changes to PAUSING, and returns the reference
* of current ControllerServiceStarter.
*/
@VisibleForTesting
public ControllerServiceStarter awaitServicePausing() {
monitor.enterWhenUninterruptibly(hasReachedPausing);
try {
if (serviceState != ServiceState.PAUSING) {
throw new IllegalStateException("Expected state=" + ServiceState.PAUSING +
", but actual state=" + serviceState);
} else {
return this.starter;
}
} finally {
monitor.leave();
}
}
@VisibleForTesting
public void forceClientSessionExpiry() throws Exception {
Preconditions.checkState(serviceConfig.isControllerClusterListenerEnabled(),
"Controller Cluster not enabled");
awaitServiceStarting();
((CuratorFramework) this.storeClient.getClient()).getZookeeperClient().getZooKeeper()
.getTestable().injectSessionExpiration();
}
@Override
protected void shutDown() throws Exception {
if (starter != null) {
if (starter.isRunning()) {
triggerShutdown();
starter.awaitTerminated();
}
}
if (storeClient != null) {
storeClient.close();
}
}
@Override
public void close() {
if (starter != null) {
triggerShutdown();
Callbacks.invokeSafely(starter::close, ex -> log.debug("Error closing starter. " + ex.getMessage()));
}
if (storeClient != null) {
Callbacks.invokeSafely(storeClient::close, ex -> log.debug("Error closing storeClient. " + ex.getMessage()));
}
}
} | 4,217 |
1,056 | <gh_stars>1000+
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*
* MetalScrollPaneBorder.java
*
* Created on March 14, 2004, 4:33 AM
*/
package org.netbeans.swing.plaf.nimbus;
import java.awt.Color;
import java.awt.Component;
import java.awt.Graphics;
import java.awt.Insets;
import javax.swing.UIManager;
import javax.swing.border.AbstractBorder;
/** Scroll pane border for Metal look and feel
*
* @author <NAME>
*/
class NimbusScrollPaneBorder extends AbstractBorder {
private static final Insets insets = new Insets(1, 1, 2, 2);
@Override
public void paintBorder(Component c, Graphics g, int x, int y,
int w, int h) {
g.translate(x, y);
Color color = UIManager.getColor("controlShadow");
g.setColor(color == null ? Color.darkGray : color);
g.drawRect(0, 0, w-2, h-2);
color = UIManager.getColor("controlHighlight");
g.setColor(color == null ? Color.white : color);
g.drawLine(w-1, 1, w-1, h-1);
g.drawLine(1, h-1, w-1, h-1);
g.translate(-x, -y);
}
@Override
public Insets getBorderInsets(Component c) {
return insets;
}
}
| 661 |
407 | {
"name": "table-radium-table",
"version": "1.0.0",
"private": true,
"scripts": {
"start": "devServer --package radium",
"build": "devBuild --package radium"
},
"license": "MIT",
"dependencies": {
"benchmarks-utils": "1.0.0",
"radium": "0.18.2"
},
"devDependencies": {
"dev-tasks": "1.0.0"
},
"benchmarks": {
"name": "radium",
"useInlineStyles": true,
"link": "https://github.com/FormidableLabs/radium"
}
}
| 210 |
415 | # Copyright 2021 Amazon.com, Inc. or its affiliates. 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. A copy of the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "LICENSE.txt" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
# OR CONDITIONS OF ANY KIND, express or implied. See the License for the specific language governing permissions and
# limitations under the License.
from pcluster.aws.common import AWSExceptionHandler, Boto3Resource
class DynamoResource(Boto3Resource):
"""S3 Boto3 resource."""
def __init__(self):
super().__init__("dynamodb")
@AWSExceptionHandler.handle_client_exception
def get_item(self, table_name, key):
"""Get item from a DynamoDB table."""
return self._resource.Table(table_name).get_item(ConsistentRead=True, Key=key)
@AWSExceptionHandler.handle_client_exception
def put_item(self, table_name, item, condition_expression=None):
"""Put item into a DynamoDB table."""
optional_args = {}
if condition_expression:
optional_args["ConditionExpression"] = condition_expression
self._resource.Table(table_name).put_item(Item=item, **optional_args)
| 438 |
421 | <gh_stars>100-1000
// <Snippet1>
using namespace System;
void main()
{
// Creates and initializes two new Array instances.
Array^ mySourceArray = Array::CreateInstance(String::typeid, 6);
mySourceArray->SetValue("three", 0);
mySourceArray->SetValue("napping", 1);
mySourceArray->SetValue("cats", 2);
mySourceArray->SetValue("in", 3);
mySourceArray->SetValue("the", 4);
mySourceArray->SetValue("barn", 5);
Array^ myTargetArray = Array::CreateInstance(String::typeid, 15);
myTargetArray->SetValue("The", 0);
myTargetArray->SetValue("quick", 1);
myTargetArray->SetValue("brown", 2);
myTargetArray->SetValue("fox", 3);
myTargetArray->SetValue("jumps", 4);
myTargetArray->SetValue("over", 5);
myTargetArray->SetValue("the", 6);
myTargetArray->SetValue("lazy", 7);
myTargetArray->SetValue("dog", 8);
// Displays the values of the Array.
Console::WriteLine( "The target Array instance contains the following (before and after copying):");
PrintValues(myTargetArray);
// Copies the source Array to the target Array, starting at index 6.
mySourceArray->CopyTo(myTargetArray, 6);
// Displays the values of the Array.
PrintValues(myTargetArray);
}
void PrintValues(Array^ myArr)
{
System::Collections::IEnumerator^ myEnumerator = myArr->GetEnumerator();
int i = 0;
int cols = myArr->GetLength(myArr->Rank - 1);
while (myEnumerator->MoveNext())
{
if (i < cols)
{
i++;
}
else
{
Console::WriteLine();
i = 1;
}
Console::Write( " {0}", myEnumerator->Current);
}
Console::WriteLine();
}
/*
This code produces the following output.
The target Array instance contains the following (before and after copying):
The quick brown fox jumps over the lazy dog
The quick brown fox jumps over three napping cats in the barn
*/
// </Snippet1>
| 756 |
5,766 | <gh_stars>1000+
//
// HTTPNTLMCredentials.cpp
//
// Library: Net
// Package: HTTP
// Module: HTTPNTLMCredentials
//
// Copyright (c) 2019, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#include "Poco/Net/HTTPNTLMCredentials.h"
#include "Poco/Net/NTLMCredentials.h"
#include "Poco/Net/HTTPAuthenticationParams.h"
#include "Poco/Net/HTTPRequest.h"
#include "Poco/Net/HTTPResponse.h"
#include "Poco/Net/NetException.h"
#include "Poco/DateTime.h"
#include "Poco/NumberFormatter.h"
#include "Poco/Exception.h"
namespace Poco {
namespace Net {
const std::string HTTPNTLMCredentials::SCHEME = "NTLM";
HTTPNTLMCredentials::HTTPNTLMCredentials()
{
}
HTTPNTLMCredentials::HTTPNTLMCredentials(const std::string& username, const std::string& password):
_username(username),
_password(password)
{
}
HTTPNTLMCredentials::~HTTPNTLMCredentials()
{
}
void HTTPNTLMCredentials::reset()
{
}
void HTTPNTLMCredentials::clear()
{
_username.clear();
_password.clear();
_host.clear();
}
void HTTPNTLMCredentials::setUsername(const std::string& username)
{
_username = username;
}
void HTTPNTLMCredentials::setPassword(const std::string& password)
{
_password = password;
}
void HTTPNTLMCredentials::setHost(const std::string& host)
{
_host = host;
}
void HTTPNTLMCredentials::authenticate(HTTPRequest& request, const HTTPResponse& response)
{
HTTPAuthenticationParams params(response);
authenticate(request, params.get(HTTPAuthenticationParams::NTLM, ""));
}
void HTTPNTLMCredentials::authenticate(HTTPRequest& request, const std::string& ntlmChallengeBase64)
{
std::string ntlmMessage = createNTLMMessage(ntlmChallengeBase64);
request.setCredentials(SCHEME, ntlmMessage);
}
void HTTPNTLMCredentials::updateAuthInfo(HTTPRequest& request)
{
request.removeCredentials();
}
void HTTPNTLMCredentials::proxyAuthenticate(HTTPRequest& request, const HTTPResponse& response)
{
HTTPAuthenticationParams params(response, HTTPAuthenticationParams::PROXY_AUTHENTICATE);
proxyAuthenticate(request, params.get(HTTPAuthenticationParams::NTLM, ""));
}
void HTTPNTLMCredentials::proxyAuthenticate(HTTPRequest& request, const std::string& ntlmChallengeBase64)
{
std::string ntlmMessage = createNTLMMessage(ntlmChallengeBase64);
request.setProxyCredentials(SCHEME, ntlmMessage);
}
void HTTPNTLMCredentials::updateProxyAuthInfo(HTTPRequest& request)
{
request.removeProxyCredentials();
}
std::string HTTPNTLMCredentials::createNTLMMessage(const std::string& responseAuthParams)
{
if (responseAuthParams.empty())
{
std::vector<unsigned char> negotiateBuf;
if (useSSPINTLM())
{
_pNTLMContext = SSPINTLMCredentials::createNTLMContext(_host, SSPINTLMCredentials::SERVICE_HTTP);
negotiateBuf = SSPINTLMCredentials::negotiate(*_pNTLMContext);
}
else
{
NTLMCredentials::NegotiateMessage negotiateMsg;
std::string username;
NTLMCredentials::splitUsername(_username, username, negotiateMsg.domain);
negotiateBuf = NTLMCredentials::formatNegotiateMessage(negotiateMsg);
}
return NTLMCredentials::toBase64(negotiateBuf);
}
else
{
std::vector<unsigned char> buffer = NTLMCredentials::fromBase64(responseAuthParams);
if (buffer.empty()) throw HTTPException("Invalid NTLM challenge");
std::vector<unsigned char> authenticateBuf;
if (useSSPINTLM() && _pNTLMContext)
{
authenticateBuf = SSPINTLMCredentials::authenticate(*_pNTLMContext, buffer);
}
else
{
NTLMCredentials::ChallengeMessage challengeMsg;
if (NTLMCredentials::parseChallengeMessage(&buffer[0], buffer.size(), challengeMsg))
{
if ((challengeMsg.flags & NTLMCredentials::NTLM_FLAG_NEGOTIATE_NTLM2_KEY) == 0)
{
throw HTTPException("Proxy does not support NTLMv2 authentication");
}
std::string username;
std::string domain;
NTLMCredentials::splitUsername(_username, username, domain);
NTLMCredentials::AuthenticateMessage authenticateMsg;
authenticateMsg.flags = challengeMsg.flags;
authenticateMsg.target = challengeMsg.target;
authenticateMsg.username = username;
std::vector<unsigned char> lmNonce = NTLMCredentials::createNonce();
std::vector<unsigned char> ntlmNonce = NTLMCredentials::createNonce();
Poco::UInt64 timestamp = NTLMCredentials::createTimestamp();
std::vector<unsigned char> ntlm2Hash = NTLMCredentials::createNTLMv2Hash(username, challengeMsg.target, _password);
authenticateMsg.lmResponse = NTLMCredentials::createLMv2Response(ntlm2Hash, challengeMsg.challenge, lmNonce);
authenticateMsg.ntlmResponse = NTLMCredentials::createNTLMv2Response(ntlm2Hash, challengeMsg.challenge, ntlmNonce, challengeMsg.targetInfo, timestamp);
authenticateBuf = NTLMCredentials::formatAuthenticateMessage(authenticateMsg);
}
else throw HTTPException("Invalid NTLM challenge");
}
return NTLMCredentials::toBase64(authenticateBuf);
}
}
} } // namespace Poco::Net
| 1,788 |
521 | import io
from mock import MagicMock
from tests.helper.voctomix_test import VoctomixTest
from gi.repository import Gst
from lib.sources import TCPAVSource
from lib.config import Config
# noinspection PyUnusedLocal
class AudiomixMultipleSources(VoctomixTest):
def setUp(self):
super().setUp()
Config.given("mix", "videocaps", "video/x-raw")
self.source = TCPAVSource('cam1', 42, ['test_mixer', 'test_preview'], has_audio=True, has_video=True)
self.mock_fp = MagicMock(spec=io.IOBase)
def test_unconfigured_does_not_add_a_deinterlacer(self):
pipeline = self.simulate_connection_and_aquire_pipeline_description()
self.assertContainsIgnoringWhitespace(pipeline, "demux. ! video/x-raw ! queue ! tee name=vtee")
def test_no_does_not_add_a_deinterlacer(self):
Config.given("source.cam1", "deinterlace", "no")
pipeline = self.simulate_connection_and_aquire_pipeline_description()
self.assertContainsIgnoringWhitespace(pipeline, "demux. ! video/x-raw ! queue ! tee name=vtee")
def test_yes_does_add_yadif(self):
Config.given("source.cam1", "deinterlace", "yes")
pipeline = self.simulate_connection_and_aquire_pipeline_description()
self.assertContainsIgnoringWhitespace(
pipeline,
"demux. ! video/x-raw ! videoconvert ! yadif mode=interlaced name=deinter")
def test_assume_progressive_does_add_capssetter(self):
Config.given("source.cam1", "deinterlace", "assume-progressive")
pipeline = self.simulate_connection_and_aquire_pipeline_description()
self.assertContainsIgnoringWhitespace(
pipeline,
"demux. ! video/x-raw ! capssetter caps=video/x-raw,interlace-mode=progressive name=deinter"
)
def simulate_connection_and_aquire_pipeline_description(self):
Gst.parse_launch.reset_mock()
self.source.on_accepted(self.mock_fp, '127.0.0.42')
Gst.parse_launch.assert_called()
args, kwargs = Gst.parse_launch.call_args_list[0]
pipeline = args[0]
return pipeline
| 884 |
2,436 | package com.ss.android.ugc.bytex.example.closeable;
import android.os.Build;
import android.text.TextUtils;
import android.util.Log;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.EOFException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.RandomAccessFile;
import java.io.Reader;
import java.io.StringWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.util.zip.GZIPInputStream;
import static java.nio.charset.StandardCharsets.UTF_8;
public class CloseableCheckTest implements Closeable {
public String getString(int index) throws IOException {
InputStream in =new FileInputStream(""+index);
return in != null ? inputStreamToString(in) : null;
}
private static String inputStreamToString(InputStream in) throws IOException {
return readFully(new InputStreamReader(in, UTF_8));
}
public static String readFully(Reader reader) throws IOException {
try {
StringWriter writer = new StringWriter();
char[] buffer = new char[1024];
int count;
while ((count = reader.read(buffer)) != -1) {
writer.write(buffer, 0, count);
}
return writer.toString();
} finally {
reader.close();
}
}
static String[] mVersion;
public static String[] getVersion() {
if (mVersion == null) {
String[] version = new String[]{"null", "null", "null", "null"};
String str1 = "/proc/version";
try {
FileReader localFileReader = new FileReader(str1);
BufferedReader localBufferedReader = new BufferedReader(localFileReader, 8192);
String str2 = localBufferedReader.readLine();
String[] arrayOfString = str2.split("\\s+");
version[0] = arrayOfString[2];
localBufferedReader.close();
} catch (IOException var6) {
;
}
version[1] = Build.VERSION.RELEASE;
version[2] = Build.MODEL;
version[3] = Build.DISPLAY;
mVersion = version;
}
return mVersion;
}
private static void closeQuietly(Closeable c) {
if (c != null) {
try {
c.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private static final String TAG = "CloseableCheckTest";
private static String readTextFile(List<String> filePaths) {
if (filePaths == null || filePaths.isEmpty()) {
return null;
}
Log.v(TAG, "all file path : " + filePaths.toString());
StringBuilder content = new StringBuilder(); //文件内容字符串
for (String filePath : filePaths) {
if (!TextUtils.isEmpty(filePath)) {
content = new StringBuilder();
File file = new File(filePath);
if (file.isFile()) {
Log.v(TAG, "available filePath: " + filePath);
if (file.isFile()) {
InputStream inputStream = null;
InputStreamReader streamReader = null;
BufferedReader buffreader = null;
try {
inputStream = new FileInputStream(file);
streamReader = new InputStreamReader(inputStream);
buffreader = new BufferedReader(streamReader);
String line;
while ((line = buffreader.readLine()) != null) {
content.append(line);
content.append("\n");
}
if (!TextUtils.isEmpty(content)) {
break;
}
} catch (java.io.FileNotFoundException e) {
Log.d(TAG, "The File doesn't not exist.");
} catch (IOException e) {
Log.d(TAG, e.getMessage());
} finally {
try {
if (inputStream != null) {
inputStream.close();
}
if (streamReader != null) {
streamReader.close();
}
if (buffreader != null) {
buffreader.close();
}
} catch (IOException ignore) {
}
}
}
}
}
}
return content.toString();
}
public void test() throws IOException {
String urlStr = "https://www.baidu.com/";
URL url = new URL(urlStr);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.connect();
if (urlConnection.getResponseCode() == 200) {
InputStream inputStream = urlConnection.getInputStream();
byte[] temp = new byte[1024];
int length;
while ((length = inputStream.read(temp)) != -1) {
System.out.println(length);
}
if (inputStream != null) {
inputStream.close();
}
}
}
BufferedReader mInputStream;
InputStream mRe;
public InputStream test2() throws IOException {
String urlStr = "https://www.baidu.com/";
URL url = new URL(urlStr);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.connect();
if (urlConnection.getResponseCode() == 200) {
BufferedReader inputStream = new BufferedReader(new InputStreamReader(new BufferedInputStream(urlConnection.getInputStream())));
mInputStream = new BufferedReader(new InputStreamReader(new BufferedInputStream(urlConnection.getInputStream())));
BufferedInputStream re = new BufferedInputStream(urlConnection.getInputStream());
inputStream.close();
mInputStream.close();
return re;
}
return mRe;
}
public InputStream test3() {
try {
String urlStr = "https://www.baidu.com/";
URL url = new URL(urlStr);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.connect();
if (urlConnection.getResponseCode() == 200) {
BufferedReader inputStream = new BufferedReader(new InputStreamReader(new BufferedInputStream(urlConnection.getInputStream())));
mInputStream = new BufferedReader(new InputStreamReader(new BufferedInputStream(urlConnection.getInputStream())));
BufferedInputStream re = new BufferedInputStream(urlConnection.getInputStream());
inputStream.close();
re.close();
mInputStream.close();
return re;
}
return mRe;
} catch (IOException e) {
e.printStackTrace();
} finally {
System.out.println();
}
return null;
}
public static String inputStream2String(InputStream inputStream, String encoding) {
InputStreamReader reader = null;
StringWriter writer = new StringWriter();
try {
if (encoding == null || "".equals(encoding.trim())) {
reader = new InputStreamReader(inputStream);
} else {
reader = new InputStreamReader(inputStream, encoding);
}
//将输入流写入输出流
char[] buffer = new char[8192];
int n = 0;
while (-1 != (n = reader.read(buffer))) {
writer.write(buffer, 0, n);
}
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
if (reader != null)
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
//返回转换结果
if (writer != null)
return writer.toString();
else return null;
}
public static boolean writeFile(InputStream is, String path,
boolean recreate) {
boolean res = false;
File f = new File(path);
FileOutputStream fos = null;
try {
if (recreate && f.exists()) {
f.delete();
}
if (!f.exists() && null != is) {
File parentFile = new File(f.getParent());
parentFile.mkdirs();
int count = -1;
byte[] buffer = new byte[1024];
fos = new FileOutputStream(f);
while ((count = is.read(buffer)) != -1) {
fos.write(buffer, 0, count);
}
res = true;
}
} catch (Exception e) {
} finally {
close(fos);
close(is);
}
return res;
}
public static boolean close(Closeable io) {
if (io != null) {
try {
io.close();
} catch (IOException e) {
}
}
return true;
}
public static boolean writeFile(byte[] content, String path, boolean append) {
boolean res = false;
File f = new File(path);
RandomAccessFile raf = null;
try {
if (f.exists()) {
if (!append) {
f.delete();
f.createNewFile();
}
} else {
f.createNewFile();
}
if (f.canWrite()) {
raf = new RandomAccessFile(f, "rw");
raf.seek(raf.length());
raf.write(content);
res = true;
}
} catch (Exception e) {
} finally {
close(raf);
}
return res;
}
@Override
public void close() throws IOException {
}
public static byte[] readResponse(boolean use_gzip, int maxLength, InputStream in, int[] out_off) throws IOException {
if (maxLength <= 0)
maxLength = 100;
if (maxLength < 1024 * 1024)
maxLength = 1024 * 1024;
if (in == null) {
return null;
}
try {
if (use_gzip) {
in = new GZIPInputStream(in);
}
byte[] buf = new byte[8 * 1024];
int n = 0;
int off = 0;
int count = 4 * 1024;
while (true) {
// some gateway pack wrong 'chunked' data, without crc32 and isize
try {
if (off + count > buf.length) {
byte[] newbuf = new byte[buf.length * 2];
System.arraycopy(buf, 0, newbuf, 0, off);
buf = newbuf;
}
n = in.read(buf, off, count);
if (n > 0) {
off += n;
} else {
break;
}
if (maxLength > 0 && off > maxLength) {
return null;
}
} catch (EOFException e) {
if (use_gzip && off > 0) {
break;
} else {
throw e;
}
} catch (IOException e) {
String msg = e.getMessage();
if (use_gzip && off > 0 && ("CRC mismatch".equals(msg) || "Size mismatch".equals(msg))) {
break;
} else {
throw e;
}
}
}
if (off > 0) {
out_off[0] = off;
return buf;
} else {
return null;
}
} finally {
safeClose(in);
}
}
public static void safeClose(Closeable c) {
safeClose(c, null);
}
private static void safeClose(Closeable c, String msg) {
try {
if (c != null) {
c.close();
}
if (c != null) {
c.close();
}else{
System.out.println(msg);
}
} catch (Exception e) {
}
}
public byte[] bytes() {
final ByteArrayOutputStream output = byteStream();
return output.toByteArray();
}
protected ByteArrayOutputStream byteStream() {
final int size = hashCode();
if (size > 0)
return new ByteArrayOutputStream(size);
else
return new ByteArrayOutputStream();
}
}
| 7,177 |
332 | <filename>spring-xd-integration-test/src/test/java/org/springframework/xd/integration/test/IntegrationTestConfig.java
/*
* Copyright 2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.springframework.xd.integration.test;
import java.io.IOException;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.xd.integration.fixtures.Jobs;
import org.springframework.xd.integration.fixtures.Processors;
import org.springframework.xd.integration.fixtures.Sinks;
import org.springframework.xd.integration.fixtures.Sources;
import org.springframework.xd.integration.util.ConfigUtil;
import org.springframework.xd.integration.util.HadoopUtils;
import org.springframework.xd.integration.util.XdEc2Validation;
import org.springframework.xd.integration.util.XdEnvironment;
/**
* Provides the container configuration when running integration tests. Declares {@link XdEnvironment},
* {@link XdEc2Validation}, {@link Sinks}, {@link Sources} and {@link ConfigUtil} in the application context.
*
* @author <NAME>
*/
@Configuration
@EnableAutoConfiguration
public class IntegrationTestConfig {
@Bean
public XdEnvironment xdEnvironment() {
return new XdEnvironment();
}
@Bean
public XdEc2Validation validation() throws IOException {
return new XdEc2Validation(hadoopUtil(), xdEnvironment());
}
@Bean
public Sinks sinks() {
return new Sinks(xdEnvironment());
}
@Bean
public Sources sources() {
// The Environment Assumes that the RabbitMQ broker is running on the same host as the admin server.
return new Sources(xdEnvironment());
}
@Bean
public Jobs jobs() {
return new Jobs(xdEnvironment());
}
@Bean
public Processors processors() {
return new Processors();
}
@Bean
public ConfigUtil configUtil() throws IOException {
return new ConfigUtil();
}
@Bean
HadoopUtils hadoopUtil() throws IOException {
return new HadoopUtils(xdEnvironment());
}
}
| 763 |
9,734 | <gh_stars>1000+
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.arrow.c;
import static org.apache.arrow.c.NativeUtil.NULL;
import static org.apache.arrow.util.Preconditions.checkNotNull;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import org.apache.arrow.c.jni.JniWrapper;
import org.apache.arrow.memory.ArrowBuf;
import org.apache.arrow.memory.BufferAllocator;
import org.apache.arrow.memory.ReferenceManager;
import org.apache.arrow.memory.util.MemoryUtil;
/**
* C Data Interface ArrowArray.
* <p>
* Represents a wrapper for the following C structure:
*
* <pre>
* struct ArrowArray {
* // Array data description
* int64_t length;
* int64_t null_count;
* int64_t offset;
* int64_t n_buffers;
* int64_t n_children;
* const void** buffers;
* struct ArrowArray** children;
* struct ArrowArray* dictionary;
*
* // Release callback
* void (*release)(struct ArrowArray*);
* // Opaque producer-specific data
* void* private_data;
* };
* </pre>
*/
public class ArrowArray implements BaseStruct {
private static final int SIZE_OF = 80;
private static final int INDEX_RELEASE_CALLBACK = 64;
private ArrowBuf data;
/**
* Snapshot of the ArrowArray raw data.
*/
public static class Snapshot {
public long length;
public long null_count;
public long offset;
public long n_buffers;
public long n_children;
public long buffers;
public long children;
public long dictionary;
public long release;
public long private_data;
/**
* Initialize empty ArrowArray snapshot.
*/
public Snapshot() {
length = NULL;
null_count = NULL;
offset = NULL;
n_buffers = NULL;
n_children = NULL;
buffers = NULL;
children = NULL;
dictionary = NULL;
release = NULL;
private_data = NULL;
}
}
/**
* Create ArrowArray from an existing memory address.
* <p>
* The resulting ArrowArray does not own the memory.
*
* @param memoryAddress Memory address to wrap
* @return A new ArrowArray instance
*/
public static ArrowArray wrap(long memoryAddress) {
return new ArrowArray(new ArrowBuf(ReferenceManager.NO_OP, null, ArrowArray.SIZE_OF, memoryAddress));
}
/**
* Create ArrowArray by allocating memory.
* <p>
* The resulting ArrowArray owns the memory.
*
* @param allocator Allocator for memory allocations
* @return A new ArrowArray instance
*/
public static ArrowArray allocateNew(BufferAllocator allocator) {
ArrowArray array = new ArrowArray(allocator.buffer(ArrowArray.SIZE_OF));
array.markReleased();
return array;
}
ArrowArray(ArrowBuf data) {
checkNotNull(data, "ArrowArray initialized with a null buffer");
this.data = data;
}
/**
* Mark the array as released.
*/
public void markReleased() {
directBuffer().putLong(INDEX_RELEASE_CALLBACK, NULL);
}
@Override
public long memoryAddress() {
checkNotNull(data, "ArrowArray is already closed");
return data.memoryAddress();
}
@Override
public void release() {
long address = memoryAddress();
JniWrapper.get().releaseArray(address);
}
@Override
public void close() {
if (data != null) {
data.close();
data = null;
}
}
private ByteBuffer directBuffer() {
return MemoryUtil.directBuffer(memoryAddress(), ArrowArray.SIZE_OF).order(ByteOrder.nativeOrder());
}
/**
* Take a snapshot of the ArrowArray raw values.
*
* @return snapshot
*/
public Snapshot snapshot() {
ByteBuffer data = directBuffer();
Snapshot snapshot = new Snapshot();
snapshot.length = data.getLong();
snapshot.null_count = data.getLong();
snapshot.offset = data.getLong();
snapshot.n_buffers = data.getLong();
snapshot.n_children = data.getLong();
snapshot.buffers = data.getLong();
snapshot.children = data.getLong();
snapshot.dictionary = data.getLong();
snapshot.release = data.getLong();
snapshot.private_data = data.getLong();
return snapshot;
}
/**
* Write values from Snapshot to the underlying ArrowArray memory buffer.
*/
public void save(Snapshot snapshot) {
directBuffer().putLong(snapshot.length).putLong(snapshot.null_count).putLong(snapshot.offset)
.putLong(snapshot.n_buffers).putLong(snapshot.n_children).putLong(snapshot.buffers).putLong(snapshot.children)
.putLong(snapshot.dictionary).putLong(snapshot.release).putLong(snapshot.private_data);
}
}
| 1,765 |
376 | #include <Nazara/Math/Algorithm.hpp>
#include <Nazara/Math/Angle.hpp>
#include <catch2/catch.hpp>
#include <limits>
TEST_CASE("Approach", "[MATH][ALGORITHM]")
{
SECTION("Approach 8 with 5 by 2")
{
REQUIRE(Nz::Approach(5, 8, 2) == 7);
}
SECTION("Approach 5 with 8 by 2")
{
REQUIRE(Nz::Approach(8, 5, 2) == 6);
}
SECTION("Approach 8 with 8 by 2")
{
REQUIRE(Nz::Approach(8, 8, 2) == 8);
}
}
TEST_CASE("Clamp", "[MATH][ALGORITHM]")
{
SECTION("Clamp 8 between 5 and 10")
{
REQUIRE(Nz::Clamp(8, 5, 10) == 8);
}
SECTION("Clamp 4 between 5 and 10")
{
REQUIRE(Nz::Clamp(4, 5, 10) == 5);
}
SECTION("Clamp 12 between 5 and 10")
{
REQUIRE(Nz::Clamp(12, 5, 10) == 10);
}
}
TEST_CASE("CountBits", "[MATH][ALGORITHM]")
{
SECTION("Number 10 has 2 bits set to 1")
{
REQUIRE(Nz::CountBits(10) == 2);
}
SECTION("Number 0 has 0 bit set to 1")
{
REQUIRE(Nz::CountBits(0) == 0);
}
SECTION("Number 0xFFFFFFFF has 32 bit set to 1")
{
REQUIRE(Nz::CountBits(0xFFFFFFFF) == 32);
}
}
TEST_CASE("DegreeToRadian", "[MATH][ALGORITHM]")
{
SECTION("Convert 45.f degree to radian")
{
REQUIRE(Nz::DegreeToRadian(45.f) == Approx(Nz::Pi<float> / 4.f));
}
}
TEST_CASE("GetNearestPowerOfTwo", "[MATH][ALGORITHM]")
{
SECTION("Nearest power of two of 0 = 1")
{
REQUIRE(Nz::GetNearestPowerOfTwo(0) == 1);
}
SECTION("Nearest power of two of 16 = 16")
{
REQUIRE(Nz::GetNearestPowerOfTwo(16) == 16);
}
SECTION("Nearest power of two of 17 = 32")
{
REQUIRE(Nz::GetNearestPowerOfTwo(17) == 32);
}
}
TEST_CASE("GetNumberLength", "[MATH][ALGORITHM]")
{
SECTION("GetNumberLength of -127 signed char")
{
signed char minus127 = -127;
REQUIRE(Nz::GetNumberLength(minus127) == 4);
}
SECTION("GetNumberLength of 255 unsigned char")
{
unsigned char plus255 = 255;
REQUIRE(Nz::GetNumberLength(plus255) == 3);
}
SECTION("GetNumberLength of -1270 signed int")
{
signed int minus1270 = -1270;
REQUIRE(Nz::GetNumberLength(minus1270) == 5);
}
SECTION("GetNumberLength of 2550 unsigned int")
{
unsigned int plus2550 = 2550;
REQUIRE(Nz::GetNumberLength(plus2550) == 4);
}
SECTION("GetNumberLength of -1270 signed long long")
{
signed long long minus12700 = -12700;
REQUIRE(Nz::GetNumberLength(minus12700) == 6);
}
SECTION("GetNumberLength of 2550 unsigned long long")
{
unsigned long long plus25500 = 25500;
REQUIRE(Nz::GetNumberLength(plus25500) == 5);
}
SECTION("GetNumberLength of -2.456f float")
{
float minus2P456 = -2.456f;
REQUIRE(Nz::GetNumberLength(minus2P456, 3) == 6);
}
SECTION("GetNumberLength of -2.456 double")
{
double minus2P456 = -2.456;
REQUIRE(Nz::GetNumberLength(minus2P456, 3) == 6);
}
SECTION("GetNumberLength of -2.456 long double")
{
long double minus2P456 = -2.456L;
REQUIRE(Nz::GetNumberLength(minus2P456, 3) == 6);
}
}
TEST_CASE("IntegralLog2", "[MATH][ALGORITHM]")
{
SECTION("According to implementation, log in base 2 of 0 = 0")
{
REQUIRE(Nz::IntegralLog2(0) == 0);
}
SECTION("Log in base 2 of 1 = 0")
{
REQUIRE(Nz::IntegralLog2(1) == 0);
}
SECTION("Log in base 2 of 4 = 2")
{
REQUIRE(Nz::IntegralLog2(4) == 2);
}
SECTION("Log in base 2 of 5 = 2")
{
REQUIRE(Nz::IntegralLog2(5) == 2);
}
}
TEST_CASE("IntegralLog2Pot", "[MATH][ALGORITHM]")
{
SECTION("According to implementation, log in base 2 of 0 = 0")
{
REQUIRE(Nz::IntegralLog2Pot(0) == 0);
}
SECTION("Log in base 2 of 1 = 0")
{
REQUIRE(Nz::IntegralLog2Pot(1) == 0);
}
SECTION("Log in base 2 of 4 = 2")
{
REQUIRE(Nz::IntegralLog2Pot(4) == 2);
}
}
TEST_CASE("IntegralPow", "[MATH][ALGORITHM]")
{
SECTION("2 to power 4")
{
REQUIRE(Nz::IntegralPow(2, 4) == 16);
}
}
TEST_CASE("Lerp", "[MATH][ALGORITHM]")
{
SECTION("Lerp 2 to 6 with 0.5")
{
REQUIRE(Nz::Lerp(2, 6, 0.5) == 4);
}
}
TEST_CASE("MultiplyAdd", "[MATH][ALGORITHM]")
{
SECTION("2 * 3 + 1")
{
REQUIRE(Nz::MultiplyAdd(2, 3, 1) == 7);
}
}
TEST_CASE("NormalizeAngle", "[MATH][ALGORITHM]")
{
SECTION("-90 should be normalized to +270")
{
REQUIRE(Nz::DegreeAnglef(-90.f).Normalize() == Nz::DegreeAnglef(270.f));
}
SECTION("-540 should be normalized to +180")
{
REQUIRE(Nz::DegreeAnglef(-540.f).Normalize() == Nz::DegreeAnglef(180.f));
}
SECTION("0 should remain 0")
{
REQUIRE(Nz::DegreeAnglef(0.f).Normalize() == Nz::DegreeAnglef(0.f));
}
SECTION("90 should remain 90")
{
REQUIRE(Nz::DegreeAnglef(90.f).Normalize() == Nz::DegreeAnglef(90.f));
}
SECTION("360 should be normalized to 0")
{
REQUIRE(Nz::DegreeAnglef(360.f).Normalize() == Nz::DegreeAnglef(0.f));
}
SECTION("450 should be normalized to 90")
{
REQUIRE(Nz::DegreeAnglef(450.f).Normalize() == Nz::DegreeAnglef(90.f));
}
SECTION("-90 should be normalized to +270")
{
REQUIRE(Nz::DegreeAnglef(-90).Normalize() == Nz::DegreeAnglef(270));
}
SECTION("-540 should be normalized to +180")
{
REQUIRE(Nz::DegreeAnglef(-540).Normalize() == Nz::DegreeAnglef(180));
}
SECTION("0 should remain 0")
{
REQUIRE(Nz::DegreeAnglef(0).Normalize() == Nz::DegreeAnglef(0));
}
SECTION("90 should remain 90")
{
REQUIRE(Nz::DegreeAnglef(90).Normalize() == Nz::DegreeAnglef(90));
}
SECTION("360 should be normalized to 0")
{
REQUIRE(Nz::DegreeAnglef(360).Normalize() == Nz::DegreeAnglef(0));
}
SECTION("450 should be normalized to 90")
{
REQUIRE(Nz::DegreeAnglef(450).Normalize() == Nz::DegreeAnglef(90));
}
}
TEST_CASE("NumberEquals", "[MATH][ALGORITHM]")
{
SECTION("2.35 and 2.351 should be the same at 0.01")
{
CHECK(Nz::NumberEquals(2.35, 2.35, 0.01));
}
SECTION("0 and 4 unsigned should be the same at 4")
{
CHECK(Nz::NumberEquals(0U, 4U, 4U));
}
SECTION("1 and -1 signed should be the same at 2")
{
CHECK(Nz::NumberEquals(1, -1, 2));
}
SECTION("Maximum integer and -1 should not be equal")
{
CHECK_FALSE(Nz::NumberEquals(std::numeric_limits<int>::max(), -1));
}
SECTION("Maximum integer and minimum integer should not be equal")
{
CHECK_FALSE(Nz::NumberEquals(std::numeric_limits<int>::max(), std::numeric_limits<int>::min()));
}
}
TEST_CASE("NumberToString", "[MATH][ALGORITHM]")
{
SECTION("0 to string")
{
REQUIRE(Nz::NumberToString(0) == "0");
}
SECTION("235 to string")
{
REQUIRE(Nz::NumberToString(235) == "235");
}
SECTION("-235 to string")
{
REQUIRE(Nz::NumberToString(-235) == "-235");
}
SECTION("16 in base 16 to string")
{
REQUIRE(Nz::NumberToString(16, 16) == "10");
}
}
TEST_CASE("RadianToDegree", "[MATH][ALGORITHM]")
{
SECTION("PI / 4 to degree")
{
REQUIRE(Nz::RadianToDegree(Nz::Pi<float> / 4.f) == Approx(45.f));
}
}
TEST_CASE("StringToNumber", "[MATH][ALGORITHM]")
{
SECTION("235 in string")
{
REQUIRE(Nz::StringToNumber("235") == 235);
}
SECTION("-235 in string")
{
REQUIRE(Nz::StringToNumber("-235") == -235);
}
SECTION("235 157 in string")
{
REQUIRE(Nz::StringToNumber("235 157") == 235157);
}
SECTION("16 in base 16 in string")
{
REQUIRE(Nz::StringToNumber("10", 16) == 16);
}
SECTION("8 in base 4 in string should not be valid")
{
bool ok = true;
REQUIRE(Nz::StringToNumber("8", 4, &ok) == 0);
REQUIRE(!ok);
}
}
| 3,232 |
348 | {"nom":"Laurière","circ":"3ème circonscription","dpt":"Haute-Vienne","inscrits":436,"abs":194,"votants":242,"blancs":20,"nuls":17,"exp":205,"res":[{"nuance":"REM","nom":"<NAME>","voix":113},{"nuance":"LR","nom":"<NAME>","voix":92}]} | 91 |
13,648 | <gh_stars>1000+
/*
* This file is part of the MicroPython project, http://micropython.org/
*
* The MIT License (MIT)
*
* Copyright (c) 2018-2019 <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.
*/
#include <stdio.h>
#include "py/mperrno.h"
#include "py/mphal.h"
#include "dma.h"
#include "pin.h"
#include "pin_static_af.h"
#include "pendsv.h"
#include "sdio.h"
#if MICROPY_PY_NETWORK_CYW43
#define DEFAULT_MASK (0)
enum {
SDMMC_IRQ_STATE_DONE,
SDMMC_IRQ_STATE_CMD_DONE,
SDMMC_IRQ_STATE_CMD_DATA_PENDING,
};
static volatile int sdmmc_irq_state;
static volatile uint32_t sdmmc_block_size_log2;
static volatile bool sdmmc_write;
static volatile bool sdmmc_dma;
static volatile uint32_t sdmmc_error;
static volatile uint8_t *sdmmc_buf_cur;
static volatile uint8_t *sdmmc_buf_top;
// The H7/F7/L4 have 2 SDMMC peripherals, but at the moment this driver only supports
// using one of them in a given build, selected by MICROPY_HW_SDIO_SDMMC.
#if MICROPY_HW_SDIO_SDMMC == 1
#define SDMMC SDMMC1
#define SDMMC_IRQn SDMMC1_IRQn
#define SDMMC_IRQHandler SDMMC1_IRQHandler
#define SDMMC_CLK_ENABLE() __HAL_RCC_SDMMC1_CLK_ENABLE()
#define SDMMC_CLK_DISABLE() __HAL_RCC_SDMMC1_CLK_DISABLE()
#define SDMMC_IS_CLK_DISABLED() __HAL_RCC_SDMMC1_IS_CLK_DISABLED()
#define STATIC_AF_SDMMC_CK STATIC_AF_SDMMC1_CK
#define STATIC_AF_SDMMC_CMD STATIC_AF_SDMMC1_CMD
#define STATIC_AF_SDMMC_D0 STATIC_AF_SDMMC1_D0
#define STATIC_AF_SDMMC_D1 STATIC_AF_SDMMC1_D1
#define STATIC_AF_SDMMC_D2 STATIC_AF_SDMMC1_D2
#define STATIC_AF_SDMMC_D3 STATIC_AF_SDMMC1_D3
#else
#if defined(STM32F7)
#error Due to DMA configuration, only SDMMC1 is currently supported on F7
#endif
#define SDMMC SDMMC2
#define SDMMC_IRQn SDMMC2_IRQn
#define SDMMC_IRQHandler SDMMC2_IRQHandler
#define SDMMC_CLK_ENABLE() __HAL_RCC_SDMMC2_CLK_ENABLE()
#define SDMMC_CLK_DISABLE() __HAL_RCC_SDMMC2_CLK_DISABLE()
#define SDMMC_IS_CLK_DISABLED() __HAL_RCC_SDMMC2_IS_CLK_DISABLED()
#define STATIC_AF_SDMMC_CK STATIC_AF_SDMMC2_CK
#define STATIC_AF_SDMMC_CMD STATIC_AF_SDMMC2_CMD
#define STATIC_AF_SDMMC_D0 STATIC_AF_SDMMC2_D0
#define STATIC_AF_SDMMC_D1 STATIC_AF_SDMMC2_D1
#define STATIC_AF_SDMMC_D2 STATIC_AF_SDMMC2_D2
#define STATIC_AF_SDMMC_D3 STATIC_AF_SDMMC2_D3
#endif
// If no custom SDIO pins defined, use the default ones
#ifndef MICROPY_HW_SDIO_CK
#define MICROPY_HW_SDIO_D0 (pin_C8)
#define MICROPY_HW_SDIO_D1 (pin_C9)
#define MICROPY_HW_SDIO_D2 (pin_C10)
#define MICROPY_HW_SDIO_D3 (pin_C11)
#define MICROPY_HW_SDIO_CK (pin_C12)
#define MICROPY_HW_SDIO_CMD (pin_D2)
#endif
void sdio_init(uint32_t irq_pri) {
// configure IO pins
mp_hal_pin_config_alt_static(MICROPY_HW_SDIO_D0, MP_HAL_PIN_MODE_ALT, MP_HAL_PIN_PULL_UP, STATIC_AF_SDMMC_D0);
mp_hal_pin_config_alt_static(MICROPY_HW_SDIO_D1, MP_HAL_PIN_MODE_ALT, MP_HAL_PIN_PULL_UP, STATIC_AF_SDMMC_D1);
mp_hal_pin_config_alt_static(MICROPY_HW_SDIO_D2, MP_HAL_PIN_MODE_ALT, MP_HAL_PIN_PULL_UP, STATIC_AF_SDMMC_D2);
mp_hal_pin_config_alt_static(MICROPY_HW_SDIO_D3, MP_HAL_PIN_MODE_ALT, MP_HAL_PIN_PULL_UP, STATIC_AF_SDMMC_D3);
mp_hal_pin_config_alt_static(MICROPY_HW_SDIO_CK, MP_HAL_PIN_MODE_ALT, MP_HAL_PIN_PULL_NONE, STATIC_AF_SDMMC_CK);
mp_hal_pin_config_alt_static(MICROPY_HW_SDIO_CMD, MP_HAL_PIN_MODE_ALT, MP_HAL_PIN_PULL_UP, STATIC_AF_SDMMC_CMD);
SDMMC_CLK_ENABLE(); // enable SDIO peripheral
SDMMC_TypeDef *SDIO = SDMMC;
#if defined(STM32F7)
SDIO->CLKCR = SDMMC_CLKCR_HWFC_EN | SDMMC_CLKCR_PWRSAV | (120 - 2); // 1-bit, 400kHz
#else
SDIO->CLKCR = SDMMC_CLKCR_HWFC_EN | SDMMC_CLKCR_PWRSAV | (120 / 2); // 1-bit, 400kHz
#endif
mp_hal_delay_us(10);
SDIO->POWER = 3; // the card is clocked
mp_hal_delay_us(10);
SDIO->DCTRL = SDMMC_DCTRL_RWMOD; // RWMOD is SDIO_CK
#if defined(STM32F7)
SDIO->CLKCR |= SDMMC_CLKCR_CLKEN;
#endif
mp_hal_delay_us(10);
#if defined(STM32F7)
__HAL_RCC_DMA2_CLK_ENABLE(); // enable DMA2 peripheral
#endif
NVIC_SetPriority(SDMMC_IRQn, irq_pri);
SDIO->MASK = 0;
HAL_NVIC_EnableIRQ(SDMMC_IRQn);
}
void sdio_deinit(void) {
SDMMC_CLK_DISABLE();
#if defined(STM32F7)
__HAL_RCC_DMA2_CLK_DISABLE();
#endif
}
void sdio_reenable(void) {
if (SDMMC_IS_CLK_DISABLED()) {
SDMMC_CLK_ENABLE(); // enable SDIO peripheral
sdio_enable_high_speed_4bit();
}
}
void sdio_enable_irq(bool enable) {
if (enable) {
SDMMC->MASK |= SDMMC_MASK_SDIOITIE;
} else {
SDMMC->MASK &= ~SDMMC_MASK_SDIOITIE;
}
}
void sdio_enable_high_speed_4bit(void) {
SDMMC_TypeDef *SDIO = SDMMC;
SDIO->POWER = 0; // power off
mp_hal_delay_us(10);
#if defined(STM32F7)
SDIO->CLKCR = SDMMC_CLKCR_HWFC_EN | SDMMC_CLKCR_WIDBUS_0 | SDMMC_CLKCR_BYPASS /*| SDMMC_CLKCR_PWRSAV*/; // 4-bit, 48MHz
#else
SDIO->CLKCR = SDMMC_CLKCR_HWFC_EN | SDMMC_CLKCR_WIDBUS_0; // 4-bit, 48MHz
#endif
mp_hal_delay_us(10);
SDIO->POWER = 3; // the card is clocked
mp_hal_delay_us(10);
SDIO->DCTRL = SDMMC_DCTRL_SDIOEN | SDMMC_DCTRL_RWMOD; // SDIOEN, RWMOD is SDIO_CK
#if defined(STM32F7)
SDIO->CLKCR |= SDMMC_CLKCR_CLKEN;
#endif
SDIO->MASK = DEFAULT_MASK;
mp_hal_delay_us(10);
}
void SDMMC_IRQHandler(void) {
if (SDMMC->STA & SDMMC_STA_CMDREND) {
SDMMC->ICR = SDMMC_ICR_CMDRENDC;
uint32_t r1 = SDMMC->RESP1;
if (SDMMC->RESPCMD == 53 && r1 & 0x800) {
printf("bad RESP1: %lu %lx\n", SDMMC->RESPCMD, r1);
sdmmc_error = 0xffffffff;
SDMMC->MASK &= SDMMC_MASK_SDIOITIE;
sdmmc_irq_state = SDMMC_IRQ_STATE_DONE;
return;
}
#if defined(STM32H7)
if (!sdmmc_dma) {
while (sdmmc_buf_cur < sdmmc_buf_top && (SDMMC->STA & SDMMC_STA_DPSMACT) && !(SDMMC->STA & SDMMC_STA_RXFIFOE)) {
*(uint32_t *)sdmmc_buf_cur = SDMMC->FIFO;
sdmmc_buf_cur += 4;
}
}
#endif
if (sdmmc_buf_cur >= sdmmc_buf_top) {
// data transfer finished, so we are done
SDMMC->MASK &= SDMMC_MASK_SDIOITIE;
sdmmc_irq_state = SDMMC_IRQ_STATE_DONE;
return;
}
if (sdmmc_write) {
SDMMC->DCTRL =
SDMMC_DCTRL_SDIOEN
| SDMMC_DCTRL_RWMOD
| sdmmc_block_size_log2 << SDMMC_DCTRL_DBLOCKSIZE_Pos
#if defined(STM32F7)
| (sdmmc_dma << SDMMC_DCTRL_DMAEN_Pos)
#endif
| (!sdmmc_write) << SDMMC_DCTRL_DTDIR_Pos
| SDMMC_DCTRL_DTEN
;
if (!sdmmc_dma) {
SDMMC->MASK |= SDMMC_MASK_TXFIFOHEIE;
}
}
sdmmc_irq_state = SDMMC_IRQ_STATE_CMD_DONE;
} else if (SDMMC->STA & SDMMC_STA_DATAEND) {
// data transfer complete
// note: it's possible to get DATAEND before CMDREND
SDMMC->ICR = SDMMC_ICR_DATAENDC;
#if defined(STM32F7)
// check if there is some remaining data in RXFIFO
if (!sdmmc_dma) {
while (SDMMC->STA & SDMMC_STA_RXDAVL) {
*(uint32_t *)sdmmc_buf_cur = SDMMC->FIFO;
sdmmc_buf_cur += 4;
}
}
#endif
if (sdmmc_irq_state == SDMMC_IRQ_STATE_CMD_DONE) {
// command and data finished, so we are done
SDMMC->MASK &= SDMMC_MASK_SDIOITIE;
sdmmc_irq_state = SDMMC_IRQ_STATE_DONE;
}
} else if (SDMMC->STA & SDMMC_STA_TXFIFOHE) {
if (!sdmmc_dma && sdmmc_write) {
// write up to 8 words to fifo
for (size_t i = 8; i && sdmmc_buf_cur < sdmmc_buf_top; --i) {
SDMMC->FIFO = *(uint32_t *)sdmmc_buf_cur;
sdmmc_buf_cur += 4;
}
if (sdmmc_buf_cur >= sdmmc_buf_top) {
// finished, disable IRQ
SDMMC->MASK &= ~SDMMC_MASK_TXFIFOHEIE;
}
}
} else if (SDMMC->STA & SDMMC_STA_RXFIFOHF) {
if (!sdmmc_dma && !sdmmc_write) {
// read up to 8 words from fifo
for (size_t i = 8; i && sdmmc_buf_cur < sdmmc_buf_top; --i) {
*(uint32_t *)sdmmc_buf_cur = SDMMC->FIFO;
sdmmc_buf_cur += 4;
}
}
} else if (SDMMC->STA & SDMMC_STA_SDIOIT) {
SDMMC->MASK &= ~SDMMC_MASK_SDIOITIE;
SDMMC->ICR = SDMMC_ICR_SDIOITC;
#if MICROPY_PY_NETWORK_CYW43
extern void (*cyw43_poll)(void);
if (cyw43_poll) {
pendsv_schedule_dispatch(PENDSV_DISPATCH_CYW43, cyw43_poll);
}
#endif
} else if (SDMMC->STA & 0x3f) {
// an error
sdmmc_error = SDMMC->STA;
SDMMC->ICR = SDMMC_STATIC_FLAGS;
SDMMC->MASK &= SDMMC_MASK_SDIOITIE;
sdmmc_irq_state = SDMMC_IRQ_STATE_DONE;
}
}
int sdio_transfer(uint32_t cmd, uint32_t arg, uint32_t *resp) {
#if defined(STM32F7)
// Wait for any outstanding TX to complete
while (SDMMC->STA & SDMMC_STA_TXACT) {
}
#endif
#if defined(STM32F7)
DMA2_Stream3->CR = 0; // ensure DMA is reset
#endif
SDMMC->ICR = SDMMC_STATIC_FLAGS; // clear interrupts
SDMMC->ARG = arg;
SDMMC->CMD = cmd | SDMMC_CMD_WAITRESP_0 | SDMMC_CMD_CPSMEN;
sdmmc_irq_state = SDMMC_IRQ_STATE_CMD_DATA_PENDING;
sdmmc_error = 0;
sdmmc_buf_cur = NULL;
sdmmc_buf_top = NULL;
SDMMC->MASK = (SDMMC->MASK & SDMMC_MASK_SDIOITIE) | SDMMC_MASK_CMDRENDIE | 0x3f;
uint32_t start = mp_hal_ticks_ms();
for (;;) {
__WFI();
if (sdmmc_irq_state == SDMMC_IRQ_STATE_DONE) {
break;
}
if (mp_hal_ticks_ms() - start > 1000) {
SDMMC->MASK = DEFAULT_MASK;
printf("sdio_transfer timeout STA=0x%08x\n", (uint)SDMMC->STA);
return -MP_ETIMEDOUT;
}
}
SDMMC->MASK &= SDMMC_MASK_SDIOITIE;
if (sdmmc_error == SDMMC_STA_CCRCFAIL && cmd == 5) {
// Errata: CMD CRC error is incorrectly generated for CMD 5
return 0;
} else if (sdmmc_error) {
return -(0x1000000 | sdmmc_error);
}
uint32_t rcmd = SDMMC->RESPCMD;
if (rcmd != cmd) {
printf("sdio_transfer: cmd=%lu rcmd=%lu\n", cmd, rcmd);
return -MP_EIO;
}
if (resp != NULL) {
*resp = SDMMC->RESP1;
}
return 0;
}
int sdio_transfer_cmd53(bool write, uint32_t block_size, uint32_t arg, size_t len, uint8_t *buf) {
#if defined(STM32F7)
// Wait for any outstanding TX to complete
while (SDMMC->STA & SDMMC_STA_TXACT) {
}
#endif
// for SDIO_BYTE_MODE the SDIO chuck of data must be a single block of the length of buf
int block_size_log2 = 0;
if (block_size == 4) {
block_size_log2 = 2;
} else if (block_size == 8) {
block_size_log2 = 3;
} else if (block_size == 16) {
block_size_log2 = 4;
} else if (block_size == 32) {
block_size_log2 = 5;
} else if (block_size == 64) {
block_size_log2 = 6;
} else if (block_size == 128) {
block_size_log2 = 7;
} else if (block_size == 256) {
block_size_log2 = 8;
} else {
printf("sdio_transfer_cmd53: invalid block_size %lu", block_size);
return -MP_EINVAL;
}
bool dma = (len > 16);
SDMMC->ICR = SDMMC_STATIC_FLAGS; // clear interrupts
SDMMC->MASK &= SDMMC_MASK_SDIOITIE;
SDMMC->DTIMER = 0x2000000; // about 700ms running at 48MHz
SDMMC->DLEN = (len + block_size - 1) & ~(block_size - 1);
#if defined(STM32F7)
DMA2_Stream3->CR = 0;
#endif
if (dma) {
// prepare DMA so it's ready when the DPSM starts its transfer
#if defined(STM32F7)
// enable DMA2 peripheral in case it was turned off by someone else
RCC->AHB1ENR |= RCC_AHB1ENR_DMA2EN;
#endif
if (write) {
// make sure cache is flushed to RAM so the DMA can read the correct data
MP_HAL_CLEAN_DCACHE(buf, len);
} else {
// make sure cache is flushed and invalidated so when DMA updates the RAM
// from reading the peripheral the CPU then reads the new data
MP_HAL_CLEANINVALIDATE_DCACHE(buf, len);
}
#if defined(STM32F7)
if ((uint32_t)buf & 3) {
printf("sdio_transfer_cmd53: buf=%p is not aligned for DMA\n", buf);
return -MP_EINVAL;
}
uint32_t dma_config =
2 << DMA_SxCR_MSIZE_Pos // MSIZE word
| 2 << DMA_SxCR_PSIZE_Pos // PSIZE word
| write << DMA_SxCR_DIR_Pos // DIR mem-to-periph
| 1 << DMA_SxCR_PFCTRL_Pos // PFCTRL periph is flow controller
;
uint32_t dma_src = (uint32_t)buf;
uint32_t dma_dest = (uint32_t)&SDMMC->FIFO;
uint32_t dma_len = ((len + block_size - 1) & ~(block_size - 1)) / 4;
dma_nohal_init(&dma_SDIO_0, dma_config);
dma_nohal_start(&dma_SDIO_0, dma_src, dma_dest, dma_len);
#else
SDMMC->IDMABASE0 = (uint32_t)buf;
SDMMC->IDMACTRL = SDMMC_IDMA_IDMAEN;
#endif
} else {
#if defined(STM32H7)
SDMMC->IDMACTRL = 0;
#endif
}
// for reading, need to initialise the DPSM before starting the CPSM
// so that the DPSM is ready to receive when the device sends data
// (and in case we get a long-running unrelated IRQ here on the host just
// after writing to CMD to initiate the command)
if (!write) {
SDMMC->DCTRL =
SDMMC_DCTRL_SDIOEN
| SDMMC_DCTRL_RWMOD
| block_size_log2 << SDMMC_DCTRL_DBLOCKSIZE_Pos
#if defined(STM32F7)
| (dma << SDMMC_DCTRL_DMAEN_Pos)
#endif
| (!write) << SDMMC_DCTRL_DTDIR_Pos
| SDMMC_DCTRL_DTEN
;
}
SDMMC->ARG = arg;
SDMMC->CMD = 53 | SDMMC_CMD_WAITRESP_0 | SDMMC_CMD_CPSMEN;
sdmmc_irq_state = SDMMC_IRQ_STATE_CMD_DATA_PENDING;
sdmmc_block_size_log2 = block_size_log2;
sdmmc_write = write;
sdmmc_dma = dma;
sdmmc_error = 0;
sdmmc_buf_cur = (uint8_t *)buf;
sdmmc_buf_top = (uint8_t *)buf + len;
SDMMC->MASK = (SDMMC->MASK & SDMMC_MASK_SDIOITIE) | SDMMC_MASK_CMDRENDIE | SDMMC_MASK_DATAENDIE | SDMMC_MASK_RXFIFOHFIE | 0x3f;
// wait to complete transfer
uint32_t start = mp_hal_ticks_ms();
for (;;) {
__WFI();
if (sdmmc_irq_state == SDMMC_IRQ_STATE_DONE) {
break;
}
if (mp_hal_ticks_ms() - start > 200) {
SDMMC->MASK &= SDMMC_MASK_SDIOITIE;
#if defined(STM32F7)
printf("sdio_transfer_cmd53: timeout wr=%d len=%u dma=%u buf_idx=%u STA=%08x SDMMC=%08x:%08x DMA=%08x:%08x:%08x RCC=%08x\n", write, (uint)len, (uint)dma, sdmmc_buf_cur - buf, (uint)SDMMC->STA, (uint)SDMMC->DCOUNT, (uint)SDMMC->FIFOCNT, (uint)DMA2->LISR, (uint)DMA2->HISR, (uint)DMA2_Stream3->NDTR, (uint)RCC->AHB1ENR);
#else
printf("sdio_transfer_cmd53: timeout wr=%d len=%u dma=%u buf_idx=%u STA=%08x SDMMC=%08x:%08x IDMA=%08x\n", write, (uint)len, (uint)dma, sdmmc_buf_cur - buf, (uint)SDMMC->STA, (uint)SDMMC->DCOUNT, (uint)SDMMC->DCTRL, (uint)SDMMC->IDMACTRL);
#endif
#if defined(STM32F7)
if (sdmmc_dma) {
dma_nohal_deinit(&dma_SDIO_0);
}
#endif
return -MP_ETIMEDOUT;
}
}
SDMMC->MASK &= SDMMC_MASK_SDIOITIE;
if (sdmmc_error) {
#if defined(STM32F7)
printf("sdio_transfer_cmd53: error=%08lx wr=%d len=%u dma=%u buf_idx=%u STA=%08x SDMMC=%08x:%08x DMA=%08x:%08x:%08x RCC=%08x\n", sdmmc_error, write, (uint)len, (uint)dma, sdmmc_buf_cur - buf, (uint)SDMMC->STA, (uint)SDMMC->DCOUNT, (uint)SDMMC->FIFOCNT, (uint)DMA2->LISR, (uint)DMA2->HISR, (uint)DMA2_Stream3->NDTR, (uint)RCC->AHB1ENR);
#else
printf("sdio_transfer_cmd53: error=%08lx wr=%d len=%u dma=%u buf_idx=%u STA=%08x SDMMC=%08x:%08x IDMA=%08x\n", sdmmc_error, write, (uint)len, (uint)dma, sdmmc_buf_cur - buf, (uint)SDMMC->STA, (uint)SDMMC->DCOUNT, (uint)SDMMC->DCTRL, (uint)SDMMC->IDMACTRL);
#endif
#if defined(STM32F7)
if (sdmmc_dma) {
dma_nohal_deinit(&dma_SDIO_0);
}
#endif
return -(0x1000000 | sdmmc_error);
}
if (!sdmmc_dma) {
if (sdmmc_buf_cur != sdmmc_buf_top) {
printf("sdio_transfer_cmd53: didn't transfer correct length: cur=%p top=%p\n", sdmmc_buf_cur, sdmmc_buf_top);
return -MP_EIO;
}
} else {
#if defined(STM32F7)
dma_nohal_deinit(&dma_SDIO_0);
#endif
}
return 0;
}
#endif
| 9,610 |
32,544 | <filename>spring-boot-modules/spring-boot/src/test/java/com/baeldung/boot/DemoApplicationIntegrationTest.java<gh_stars>1000+
package com.baeldung.boot;
import com.baeldung.demo.DemoApplication;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = DemoApplication.class, webEnvironment = WebEnvironment.RANDOM_PORT)
public class DemoApplicationIntegrationTest {
@Test
public void contextLoads() {
}
}
| 225 |
649 | {
"title": "Output validation of credit account",
"name": "Output validation of credit account",
"result": "PENDING",
"steps": "1",
"successful": "0",
"failures": "0",
"skipped": "0",
"ignored": "0",
"pending": "1",
"duration": "13",
"timestamp": "2013-08-03T18:25:37.216+10:00",
"user-story": {
"qualifiedStoryClassName": "robas",
"storyName": "Robas",
"path": "stories/browsing_listings/browsing_by_category/robas.story"
},
"issues": [],
"tags": [
{
"name": "Browsing listings",
"type": "capability"
},
{
"name": "Browsing by category",
"type": "feature"
},
{
"name": "Robas",
"type": "story"
}
],
"test-steps": [
{
"description": "Given a credit account associated with an RBA BSB\nCheck that it is a valid open a/c\nIf not valid replace a/c with 002814091\nand report only on final validation report\nand do not reject payment\n\nV2)",
"duration": 0,
"startTime": 1375518337225,
"screenshots": [],
"result": "PENDING",
"children": []
}
]
} | 472 |
438 | <reponame>Pocoyo-dev/Discord-Bot<filename>src/languages/en-upside/plugins/set-plugin.json
{
"DESCRIPTION": "ɟɟo puɐ uo suᴉƃnld ǝlƃƃo┴",
"USAGE": "set-plugin <uoᴉʇdo>",
"ADDED": "˙suᴉƃnld s,plᴉnפ oʇ {{PLUGINS}} pǝpp∀",
"REMOVED": "˙suᴉƃnld s,plᴉnפ oʇ {{PLUGINS}} pǝʌoɯǝɹ",
"INVALID": "uᴉƃnld pǝʇɹoddns ɐ ʇoN"
}
| 221 |
2,059 | #include <stdlib.h>
#include <math.h>
#include "fab/tree/node/node.h"
#include "fab/tree/math/math_g.h"
void fill_results(Node* n, float value)
{
n->results.f = value;
n->results.i = (Interval) { .lower=value, .upper=value};
// Fill the region cache
for (int q = 0; q < MIN_VOLUME; ++q)
n->results.r[q] = value;
}
void fill_results_g(Node* n, float value)
{
for (int q=0; q < MIN_VOLUME/4; ++q)
{
((derivative*)(n->results.r))[q].v = value;
((derivative*)(n->results.r))[q].dx = 0;
((derivative*)(n->results.r))[q].dy = 0;
((derivative*)(n->results.r))[q].dz = 0;
}
}
| 314 |
2,504 | /////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Tencent is pleased to support the open source community by making behaviac available.
//
// Copyright (C) 2015-2017 THL A29 Limited, a Tencent company. All rights reserved.
//
// Licensed under the BSD 3-Clause License (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at http://opensource.org/licenses/BSD-3-Clause
//
// 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 _BEHAVIAC_COMMON_PARSESTRING_H_
#define _BEHAVIAC_COMMON_PARSESTRING_H_
#include "behaviac/common/base.h"
#include "behaviac/common/container/string.h"
#include "behaviac/common/container/vector.h"
#include "behaviac/common/container/list.h"
#include "behaviac/common/container/map.h"
#include "behaviac/common/container/set.h"
#include "behaviac/common/meta/meta.h"
namespace behaviac {
template<typename T>
bool EnumValueFromString(const char* valueStr, T& v);
namespace StringUtils {
template<typename T>
bool ParseString(const char* str, T& val);
template<typename T>
inline bool FromString_Struct(const char* str, T& val);
namespace internal {
template<typename T, bool bAgent>
struct FromStringSelector {
static bool ParseString(const char* str, T& val) {
BEHAVIAC_UNUSED_VAR(str);
BEHAVIAC_UNUSED_VAR(val);
return false;
}
};
template<typename T>
struct FromStringSelector<T, true> {
static bool ParseString(const char* str, T& val) {
BEHAVIAC_UNUSED_VAR(str);
BEHAVIAC_ASSERT(string_nicmp(str, "null", 4) == 0);
val = 0;
return true;
}
};
template<typename T>
inline bool ParseString(const char* str, T& val) {
bool result = FromStringSelector<T, behaviac::Meta::IsRefType<T>::Result>::ParseString(str, val);
return result;
}
inline bool ParseString(const char* str, bool& val) {
if ((str[0] == '0' || str[0] == '1') && str[1] == '\0') {
val = *str == '1';
return true;
} else {
if (string_nicmp(str, "true", 4) == 0) {
val = true;
return true;
} else if (string_nicmp(str, "false", 5) == 0) {
val = false;
return true;
}
}
return false;
}
inline bool ParseString(const char* str, char& val) {
return sscanf(str, "%c", &val) == 1;
}
inline bool ParseString(const char* str, signed char& val) {
int i;
if (sscanf(str, "%i", &i) == 1) {
BEHAVIAC_ASSERT(i >= -128 && i <= 127);
val = (char)i;
return true;
}
return false;
}
inline bool ParseString(const char* str, unsigned char& val) {
unsigned int u;
if (sscanf(str, "%u", &u) == 1) {
BEHAVIAC_ASSERT(u <= 255);
val = (unsigned char)u;
return true;
}
return false;
}
inline bool ParseString(const char* str, signed short& val) {
int i;
if (sscanf(str, "%i", &i) == 1) {
BEHAVIAC_ASSERT(i >= -32768 && i <= 32767);
val = (short)i;
return true;
}
return false;
}
inline bool ParseString(const char* str, unsigned short& val) {
unsigned int u;
if (sscanf(str, "%u", &u) == 1) {
BEHAVIAC_ASSERT(u <= 65535);
val = (unsigned short)u;
return true;
}
return false;
}
inline bool ParseString(const char* str, signed int& val) {
return sscanf(str, "%i", &val) == 1;
}
inline bool ParseString(const char* str, unsigned int& val) {
return sscanf(str, "%u", &val) == 1;
}
inline bool ParseString(const char* str, signed long& val) {
return sscanf(str, "%li", &val) == 1;
}
inline bool ParseString(const char* str, unsigned long& val) {
return sscanf(str, "%lu", &val) == 1;
}
#if !BEHAVIAC_CCDEFINE_64BITS
inline bool ParseString(const char* str, int64_t& val) {
return sscanf(str, "%lli", &val) == 1;
}
inline bool ParseString(const char* str, uint64_t& val) {
return sscanf(str, "%llu", &val) == 1;
}
#else
inline bool ParseString(const char* str, long long& val) {
return sscanf(str, "%lli", &val) == 1;
}
inline bool ParseString(const char* str, unsigned long long& val) {
return sscanf(str, "%llu", &val) == 1;
}
#endif
inline bool ParseString(const char* str, float& val) {
return sscanf(str, "%f", &val) == 1;
}
inline bool ParseString(const char* str, double& val) {
return sscanf(str, "%lg", &val) == 1;
}
inline bool ParseString(const char* str, void*& val) {
return sscanf(str, "%p", &val) == 1;
}
inline bool ParseString(const char* str, behaviac::string& val) {
if (str) {
if (str[0] == '"') {
//strip the start/end ""
int length = (int)strlen(str) - 2;
val.resize(length);
char* destP = (char*)val.data();
const char* p = str + 1;
const char* endP = p + length;
while (p != endP) {
*destP++ = *p++;
}
return true;
} else if (str[0] == '\0') {
val = "";
return true;
} else {
val = str;
return true;
}
} else {
val = "";
return true;
}
}
inline bool ParseString(const char* str, behaviac::wstring& val) {
if (str) {
if (str[0] == '"') {
//strip the start/end ""
behaviac::string valT = str + 1;
int length = (int)valT.size();
valT[length - 1] = '\0';
behaviac::StringUtils::Char2Wide(val, valT);
return true;
}
val = behaviac::StringUtils::Char2Wide(str);
return true;
} else {
val = L"";
}
return false;
}
//inline bool ParseString(const char* str, const char*& val)
//{
// val = str;
// return true;
//}
template <typename T> void ContainerReserve(behaviac::vector<T>& container, uint32_t size) {
container.reserve(size);
}
template <typename T> void ContainerReserve(behaviac::list<T>& container, uint32_t size) {}
template <typename T> void ContainerReserve(behaviac::set<T>& container, uint32_t size) {}
template <typename T> void ContainerInsert(behaviac::vector<T>& container, T item) {
container.push_back(item);
}
template <typename T> void ContainerInsert(behaviac::list<T>& container, T item) {
container.push_back(item);
}
template <typename T> void ContainerInsert(behaviac::set<T>& container, T item) {
container.insert(item);
}
template <typename T, typename ContentType> bool ContainerFromStringPrimtive(const char* str, T& contVal, const ContentType&) {
contVal.clear();
const char* pos = str;
uint32_t count = 0;
if (sscanf(pos, "%u:", &count) == 1) {
if (count > 0) {
ContainerReserve(contVal, count);
pos = strchr(pos, ':');
} else {
return true;
}
} else {
BEHAVIAC_LOGWARNING("Fail read container count from behaviac::string");
return false;
}
do {
ContentType itemVal;
//this only works for primitive type, if the element type is a struct, it can't work
behaviac::string itemTemp;
const char* posNext = strchr(pos + 1, '|');
if (posNext) {
//*(char*)posNext = '\0';
size_t len = posNext - (pos + 1);
itemTemp.resize(len);
char* data = (char*)itemTemp.data();
for (size_t i = 0; i < len; ++i) {
data[i] = pos[i + 1];
}
} else {
itemTemp = pos + 1;
}
if (behaviac::StringUtils::ParseString(itemTemp.c_str(), itemVal)) {
ContainerInsert(contVal, itemVal);
if (pos[1] == '{') {
//struct array
pos = SkipPairedBrackets(pos + 1);
}
const char* posNext1 = strchr(pos + 1, '|');
pos = posNext1;
} else {
BEHAVIAC_LOGWARNING("Fail read container from behaviac::string at position %u", static_cast<unsigned int>(pos - str));
return false;
}
} while (pos && *(pos + 1));
return true;
}
template <typename T, typename ContentType> bool ContainerFromStringStruct(const char* str, T& contVal, const ContentType&) {
contVal.clear();
const char* pos = str;
uint32_t count = 0;
if (sscanf(pos, "%u:", &count) == 1) {
if (count > 0) {
ContainerReserve(contVal, count);
pos = strchr(pos, ':');
} else {
return true;
}
} else {
BEHAVIAC_LOGWARNING("Fail read container count from behaviac::string");
return false;
}
do {
ContentType itemVal;
if (behaviac::StringUtils::ParseString(pos + 1, itemVal)) {
ContainerInsert(contVal, itemVal);
if (pos[1] == '{') {
//struct array
pos = SkipPairedBrackets(pos + 1);
}
const char* posNext = strchr(pos + 1, '|');
pos = posNext;
} else {
BEHAVIAC_LOGWARNING("Fail read container from behaviac::string at position %u", static_cast<unsigned int>(pos - str));
return false;
}
} while (pos && *(pos + 1));
return true;
}
template<typename ContentType, bool bHasFromString>
struct ContainerFromStringSelector {
template<typename T>
static bool ParseString(const char* str, T& val, const ContentType& element) {
return ContainerFromStringPrimtive(str, val, element);
}
};
template<typename ContentType>
struct ContainerFromStringSelector < ContentType, true > {
template<typename T>
static bool ParseString(const char* str, T& val, const ContentType& element) {
return ContainerFromStringStruct(str, val, element);
}
};
template <typename T> bool ParseString(const char* str, behaviac::vector<T>& contVal) {
return ContainerFromStringSelector<T, behaviac::Meta::HasFromString<T>::Result>::ParseString(str, contVal, T());
}
template <typename T> bool ParseString(const char* str, behaviac::list<T>& contVal) {
return ContainerFromStringSelector<T, behaviac::Meta::HasFromString<T>::Result>::ParseString(str, contVal, T());
}
template <typename T> bool ParseString(const char* str, behaviac::set<T>& contVal) {
return ContainerFromStringSelector<T, behaviac::Meta::HasFromString<T>::Result>::ParseString(str, contVal, T());
}
}//namespace internal
namespace Detail {
////////////////////////////////////////////////////////////////////////
template<typename T, bool bIsEnum>
struct FromStringEnumHanler {
static bool ParseString(const char* valueStr, T& v) {
if (internal::ParseString(valueStr, v)) {
return true;
}
return false;
}
};
template<typename T>
struct FromStringEnumHanler<T, true> {
static bool ParseString(const char* valueStr, T& v) {
return behaviac::EnumValueFromString(valueStr, v);
}
};
template<typename T, bool bHasFromString>
struct FromStringStructHanler {
static bool ParseString(const char* str, T& val) {
return FromStringEnumHanler<T, behaviac::Meta::IsEnum<T>::Result>::ParseString(str, val);
}
};
template<typename T>
struct FromStringStructHanler<T, true> {
static bool ParseString(const char* str, T& val) {
return behaviac::StringUtils::FromString_Struct(str, val);
}
};
}//namespace Detail
template<typename T>
inline bool ParseString(const char* str, T& val) {
return Detail::FromStringStructHanler<T, behaviac::Meta::HasFromString<T>::Result>::ParseString(str, val);
}
}
}
#endif // #ifndef _BEHAVIAC_COMMON_PARSESTRING_H_
| 8,594 |
734 | package com.cheikh.lazywaimai.ui.activity;
import android.content.Intent;
import com.cheikh.lazywaimai.R;
import com.cheikh.lazywaimai.base.BaseActivity;
import com.cheikh.lazywaimai.base.BaseController;
import com.cheikh.lazywaimai.context.AppContext;
import com.cheikh.lazywaimai.controller.UserController;
import com.cheikh.lazywaimai.ui.Display;
import com.cheikh.lazywaimai.util.ContentView;
/**
* author: cheikh.wang on 17/1/5
* email: <EMAIL>
*/
@ContentView(R.layout.activity_user_profile)
public class UserProfileActivity extends BaseActivity<UserController.UserUiCallbacks>
implements UserController.UserUi {
@Override
protected BaseController getController() {
return AppContext.getContext().getMainController().getUserController();
}
@Override
protected void handleIntent(Intent intent, Display display) {
if (!display.hasMainFragment()) {
display.showUserProfileFragment();
}
}
}
| 349 |
679 | <reponame>Grosskopf/openoffice<filename>main/ucb/source/ucp/odma/odma_contentprops.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 ODMA_CONTENTPROPS_HXX
#define ODMA_CONTENTPROPS_HXX
#include "rtl/ref.hxx"
#include "salhelper/simplereferenceobject.hxx"
#include <rtl/ustring.hxx>
#include <com/sun/star/util/DateTime.hpp>
#include <functional>
namespace odma
{
class ContentProperties : public salhelper::SimpleReferenceObject
{
public:
com::sun::star::util::DateTime m_aDateCreated; // when was the document created
com::sun::star::util::DateTime m_aDateModified; // when was the document last modified
::rtl::OUString m_sTitle; // Title
::rtl::OUString m_sContentType; // ContentType
::rtl::OString m_sDocumentId; // the document id given from the DMS
::rtl::OUString m_sDocumentName;// document name
::rtl::OUString m_sFileURL; // the temporary file location
::rtl::OUString m_sAuthor; // the Author of the document
::rtl::OUString m_sSubject; // the subject of the document
::rtl::OUString m_sKeywords; // the keywords of the document
::rtl::OUString m_sSavedAsName; // the name which was used to save it
sal_Bool m_bIsDocument; // IsDocument
sal_Bool m_bIsFolder; // IsFolder
sal_Bool m_bIsOpen; // is true when OpenDoc was called
sal_Bool m_bIsReadOnly; // true when the document is read-only
// @@@ Add other properties supported by your content.
ContentProperties()
:m_bIsDocument( sal_True )
,m_bIsFolder( sal_False )
,m_bIsOpen( sal_False )
,m_bIsReadOnly( sal_False )
{}
inline ::rtl::OUString getTitle() const { return m_sTitle; }
inline ::rtl::OUString getSavedAsName() const { return m_sSavedAsName; }
};
typedef ::std::binary_function< ::rtl::Reference<ContentProperties>, ::rtl::OUString,bool> TContentPropertiesFunctorBase;
/// binary_function Functor object for class ContentProperties return type is bool
class ContentPropertiesMemberFunctor : public TContentPropertiesFunctorBase
{
::std::const_mem_fun_t< ::rtl::OUString,ContentProperties> m_aFunction;
public:
ContentPropertiesMemberFunctor(const ::std::const_mem_fun_t< ::rtl::OUString,ContentProperties>& _rFunc)
: m_aFunction(_rFunc){}
inline bool operator()(const ::rtl::Reference<ContentProperties>& lhs,const ::rtl::OUString& rhs) const
{
return !!(m_aFunction(lhs.get()) == rhs);
}
};
}
#endif // ODMA_CONTENTPROPS_HXX
| 1,173 |
496 | /*
* Copyright (C) 2018 <NAME>
*
* Author: <NAME> <<EMAIL>>
*/
/*
* Caution!
* This file generated by the script "utils/lexbor/tag_ns/tags.py"!
* Do not change this file!
*/
#ifndef LXB_TAG_RES_H
#define LXB_TAG_RES_H
#endif /* LXB_TAG_RES_H */
#ifdef LXB_TAG_CONST_VERSION
#ifndef LXB_TAG_CONST_VERSION_A161EC911182C3254E7A972D5C51DF86
#error Mismatched tags version! See "lexbor/tag/const.h".
#endif /* LXB_TAG_CONST_VERSION_A161EC911182C3254E7A972D5C51DF86 */
#else
#error You need to include "lexbor/tag/const.h".
#endif /* LXB_TAG_CONST_VERSION */
static const lxb_tag_data_t lxb_tag_res_data_default[LXB_TAG__LAST_ENTRY] =
{
{{.u.short_str = "#undef", .length = 6, .next = NULL}, LXB_TAG__UNDEF, 1, true},
{{.u.short_str = "#end-of-file", .length = 12, .next = NULL}, LXB_TAG__END_OF_FILE, 1, true},
{{.u.short_str = "#text", .length = 5, .next = NULL}, LXB_TAG__TEXT, 1, true},
{{.u.short_str = "#document", .length = 9, .next = NULL}, LXB_TAG__DOCUMENT, 1, true},
{{.u.short_str = "!--", .length = 3, .next = NULL}, LXB_TAG__EM_COMMENT, 1, true},
{{.u.short_str = "!doctype", .length = 8, .next = NULL}, LXB_TAG__EM_DOCTYPE, 1, true},
{{.u.short_str = "a", .length = 1, .next = NULL}, LXB_TAG_A, 1, true},
{{.u.short_str = "abbr", .length = 4, .next = NULL}, LXB_TAG_ABBR, 1, true},
{{.u.short_str = "acronym", .length = 7, .next = NULL}, LXB_TAG_ACRONYM, 1, true},
{{.u.short_str = "address", .length = 7, .next = NULL}, LXB_TAG_ADDRESS, 1, true},
{{.u.short_str = "altglyph", .length = 8, .next = NULL}, LXB_TAG_ALTGLYPH, 1, true},
{{.u.short_str = "altglyphdef", .length = 11, .next = NULL}, LXB_TAG_ALTGLYPHDEF, 1, true},
{{.u.short_str = "altglyphitem", .length = 12, .next = NULL}, LXB_TAG_ALTGLYPHITEM, 1, true},
{{.u.short_str = "animatecolor", .length = 12, .next = NULL}, LXB_TAG_ANIMATECOLOR, 1, true},
{{.u.short_str = "animatemotion", .length = 13, .next = NULL}, LXB_TAG_ANIMATEMOTION, 1, true},
{{.u.short_str = "animatetransform", .length = 16, .next = NULL}, LXB_TAG_ANIMATETRANSFORM, 1, true},
{{.u.short_str = "annotation-xml", .length = 14, .next = NULL}, LXB_TAG_ANNOTATION_XML, 1, true},
{{.u.short_str = "applet", .length = 6, .next = NULL}, LXB_TAG_APPLET, 1, true},
{{.u.short_str = "area", .length = 4, .next = NULL}, LXB_TAG_AREA, 1, true},
{{.u.short_str = "article", .length = 7, .next = NULL}, LXB_TAG_ARTICLE, 1, true},
{{.u.short_str = "aside", .length = 5, .next = NULL}, LXB_TAG_ASIDE, 1, true},
{{.u.short_str = "audio", .length = 5, .next = NULL}, LXB_TAG_AUDIO, 1, true},
{{.u.short_str = "b", .length = 1, .next = NULL}, LXB_TAG_B, 1, true},
{{.u.short_str = "base", .length = 4, .next = NULL}, LXB_TAG_BASE, 1, true},
{{.u.short_str = "basefont", .length = 8, .next = NULL}, LXB_TAG_BASEFONT, 1, true},
{{.u.short_str = "bdi", .length = 3, .next = NULL}, LXB_TAG_BDI, 1, true},
{{.u.short_str = "bdo", .length = 3, .next = NULL}, LXB_TAG_BDO, 1, true},
{{.u.short_str = "bgsound", .length = 7, .next = NULL}, LXB_TAG_BGSOUND, 1, true},
{{.u.short_str = "big", .length = 3, .next = NULL}, LXB_TAG_BIG, 1, true},
{{.u.short_str = "blink", .length = 5, .next = NULL}, LXB_TAG_BLINK, 1, true},
{{.u.short_str = "blockquote", .length = 10, .next = NULL}, LXB_TAG_BLOCKQUOTE, 1, true},
{{.u.short_str = "body", .length = 4, .next = NULL}, LXB_TAG_BODY, 1, true},
{{.u.short_str = "br", .length = 2, .next = NULL}, LXB_TAG_BR, 1, true},
{{.u.short_str = "button", .length = 6, .next = NULL}, LXB_TAG_BUTTON, 1, true},
{{.u.short_str = "canvas", .length = 6, .next = NULL}, LXB_TAG_CANVAS, 1, true},
{{.u.short_str = "caption", .length = 7, .next = NULL}, LXB_TAG_CAPTION, 1, true},
{{.u.short_str = "center", .length = 6, .next = NULL}, LXB_TAG_CENTER, 1, true},
{{.u.short_str = "cite", .length = 4, .next = NULL}, LXB_TAG_CITE, 1, true},
{{.u.short_str = "clippath", .length = 8, .next = NULL}, LXB_TAG_CLIPPATH, 1, true},
{{.u.short_str = "code", .length = 4, .next = NULL}, LXB_TAG_CODE, 1, true},
{{.u.short_str = "col", .length = 3, .next = NULL}, LXB_TAG_COL, 1, true},
{{.u.short_str = "colgroup", .length = 8, .next = NULL}, LXB_TAG_COLGROUP, 1, true},
{{.u.short_str = "data", .length = 4, .next = NULL}, LXB_TAG_DATA, 1, true},
{{.u.short_str = "datalist", .length = 8, .next = NULL}, LXB_TAG_DATALIST, 1, true},
{{.u.short_str = "dd", .length = 2, .next = NULL}, LXB_TAG_DD, 1, true},
{{.u.short_str = "del", .length = 3, .next = NULL}, LXB_TAG_DEL, 1, true},
{{.u.short_str = "desc", .length = 4, .next = NULL}, LXB_TAG_DESC, 1, true},
{{.u.short_str = "details", .length = 7, .next = NULL}, LXB_TAG_DETAILS, 1, true},
{{.u.short_str = "dfn", .length = 3, .next = NULL}, LXB_TAG_DFN, 1, true},
{{.u.short_str = "dialog", .length = 6, .next = NULL}, LXB_TAG_DIALOG, 1, true},
{{.u.short_str = "dir", .length = 3, .next = NULL}, LXB_TAG_DIR, 1, true},
{{.u.short_str = "div", .length = 3, .next = NULL}, LXB_TAG_DIV, 1, true},
{{.u.short_str = "dl", .length = 2, .next = NULL}, LXB_TAG_DL, 1, true},
{{.u.short_str = "dt", .length = 2, .next = NULL}, LXB_TAG_DT, 1, true},
{{.u.short_str = "em", .length = 2, .next = NULL}, LXB_TAG_EM, 1, true},
{{.u.short_str = "embed", .length = 5, .next = NULL}, LXB_TAG_EMBED, 1, true},
{{.u.short_str = "feblend", .length = 7, .next = NULL}, LXB_TAG_FEBLEND, 1, true},
{{.u.short_str = "fecolormatrix", .length = 13, .next = NULL}, LXB_TAG_FECOLORMATRIX, 1, true},
{{.u.long_str = (lxb_char_t *) "fecomponenttransfer", .length = 19, .next = NULL}, LXB_TAG_FECOMPONENTTRANSFER, 1, true},
{{.u.short_str = "fecomposite", .length = 11, .next = NULL}, LXB_TAG_FECOMPOSITE, 1, true},
{{.u.short_str = "feconvolvematrix", .length = 16, .next = NULL}, LXB_TAG_FECONVOLVEMATRIX, 1, true},
{{.u.long_str = (lxb_char_t *) "fediffuselighting", .length = 17, .next = NULL}, LXB_TAG_FEDIFFUSELIGHTING, 1, true},
{{.u.long_str = (lxb_char_t *) "fedisplacementmap", .length = 17, .next = NULL}, LXB_TAG_FEDISPLACEMENTMAP, 1, true},
{{.u.short_str = "fedistantlight", .length = 14, .next = NULL}, LXB_TAG_FEDISTANTLIGHT, 1, true},
{{.u.short_str = "fedropshadow", .length = 12, .next = NULL}, LXB_TAG_FEDROPSHADOW, 1, true},
{{.u.short_str = "feflood", .length = 7, .next = NULL}, LXB_TAG_FEFLOOD, 1, true},
{{.u.short_str = "fefunca", .length = 7, .next = NULL}, LXB_TAG_FEFUNCA, 1, true},
{{.u.short_str = "fefuncb", .length = 7, .next = NULL}, LXB_TAG_FEFUNCB, 1, true},
{{.u.short_str = "fefuncg", .length = 7, .next = NULL}, LXB_TAG_FEFUNCG, 1, true},
{{.u.short_str = "fefuncr", .length = 7, .next = NULL}, LXB_TAG_FEFUNCR, 1, true},
{{.u.short_str = "fegaussianblur", .length = 14, .next = NULL}, LXB_TAG_FEGAUSSIANBLUR, 1, true},
{{.u.short_str = "feimage", .length = 7, .next = NULL}, LXB_TAG_FEIMAGE, 1, true},
{{.u.short_str = "femerge", .length = 7, .next = NULL}, LXB_TAG_FEMERGE, 1, true},
{{.u.short_str = "femergenode", .length = 11, .next = NULL}, LXB_TAG_FEMERGENODE, 1, true},
{{.u.short_str = "femorphology", .length = 12, .next = NULL}, LXB_TAG_FEMORPHOLOGY, 1, true},
{{.u.short_str = "feoffset", .length = 8, .next = NULL}, LXB_TAG_FEOFFSET, 1, true},
{{.u.short_str = "fepointlight", .length = 12, .next = NULL}, LXB_TAG_FEPOINTLIGHT, 1, true},
{{.u.long_str = (lxb_char_t *) "fespecularlighting", .length = 18, .next = NULL}, LXB_TAG_FESPECULARLIGHTING, 1, true},
{{.u.short_str = "fespotlight", .length = 11, .next = NULL}, LXB_TAG_FESPOTLIGHT, 1, true},
{{.u.short_str = "fetile", .length = 6, .next = NULL}, LXB_TAG_FETILE, 1, true},
{{.u.short_str = "feturbulence", .length = 12, .next = NULL}, LXB_TAG_FETURBULENCE, 1, true},
{{.u.short_str = "fieldset", .length = 8, .next = NULL}, LXB_TAG_FIELDSET, 1, true},
{{.u.short_str = "figcaption", .length = 10, .next = NULL}, LXB_TAG_FIGCAPTION, 1, true},
{{.u.short_str = "figure", .length = 6, .next = NULL}, LXB_TAG_FIGURE, 1, true},
{{.u.short_str = "font", .length = 4, .next = NULL}, LXB_TAG_FONT, 1, true},
{{.u.short_str = "footer", .length = 6, .next = NULL}, LXB_TAG_FOOTER, 1, true},
{{.u.short_str = "foreignobject", .length = 13, .next = NULL}, LXB_TAG_FOREIGNOBJECT, 1, true},
{{.u.short_str = "form", .length = 4, .next = NULL}, LXB_TAG_FORM, 1, true},
{{.u.short_str = "frame", .length = 5, .next = NULL}, LXB_TAG_FRAME, 1, true},
{{.u.short_str = "frameset", .length = 8, .next = NULL}, LXB_TAG_FRAMESET, 1, true},
{{.u.short_str = "glyphref", .length = 8, .next = NULL}, LXB_TAG_GLYPHREF, 1, true},
{{.u.short_str = "h1", .length = 2, .next = NULL}, LXB_TAG_H1, 1, true},
{{.u.short_str = "h2", .length = 2, .next = NULL}, LXB_TAG_H2, 1, true},
{{.u.short_str = "h3", .length = 2, .next = NULL}, LXB_TAG_H3, 1, true},
{{.u.short_str = "h4", .length = 2, .next = NULL}, LXB_TAG_H4, 1, true},
{{.u.short_str = "h5", .length = 2, .next = NULL}, LXB_TAG_H5, 1, true},
{{.u.short_str = "h6", .length = 2, .next = NULL}, LXB_TAG_H6, 1, true},
{{.u.short_str = "head", .length = 4, .next = NULL}, LXB_TAG_HEAD, 1, true},
{{.u.short_str = "header", .length = 6, .next = NULL}, LXB_TAG_HEADER, 1, true},
{{.u.short_str = "hgroup", .length = 6, .next = NULL}, LXB_TAG_HGROUP, 1, true},
{{.u.short_str = "hr", .length = 2, .next = NULL}, LXB_TAG_HR, 1, true},
{{.u.short_str = "html", .length = 4, .next = NULL}, LXB_TAG_HTML, 1, true},
{{.u.short_str = "i", .length = 1, .next = NULL}, LXB_TAG_I, 1, true},
{{.u.short_str = "iframe", .length = 6, .next = NULL}, LXB_TAG_IFRAME, 1, true},
{{.u.short_str = "image", .length = 5, .next = NULL}, LXB_TAG_IMAGE, 1, true},
{{.u.short_str = "img", .length = 3, .next = NULL}, LXB_TAG_IMG, 1, true},
{{.u.short_str = "input", .length = 5, .next = NULL}, LXB_TAG_INPUT, 1, true},
{{.u.short_str = "ins", .length = 3, .next = NULL}, LXB_TAG_INS, 1, true},
{{.u.short_str = "isindex", .length = 7, .next = NULL}, LXB_TAG_ISINDEX, 1, true},
{{.u.short_str = "kbd", .length = 3, .next = NULL}, LXB_TAG_KBD, 1, true},
{{.u.short_str = "keygen", .length = 6, .next = NULL}, LXB_TAG_KEYGEN, 1, true},
{{.u.short_str = "label", .length = 5, .next = NULL}, LXB_TAG_LABEL, 1, true},
{{.u.short_str = "legend", .length = 6, .next = NULL}, LXB_TAG_LEGEND, 1, true},
{{.u.short_str = "li", .length = 2, .next = NULL}, LXB_TAG_LI, 1, true},
{{.u.short_str = "lineargradient", .length = 14, .next = NULL}, LXB_TAG_LINEARGRADIENT, 1, true},
{{.u.short_str = "link", .length = 4, .next = NULL}, LXB_TAG_LINK, 1, true},
{{.u.short_str = "listing", .length = 7, .next = NULL}, LXB_TAG_LISTING, 1, true},
{{.u.short_str = "main", .length = 4, .next = NULL}, LXB_TAG_MAIN, 1, true},
{{.u.short_str = "malignmark", .length = 10, .next = NULL}, LXB_TAG_MALIGNMARK, 1, true},
{{.u.short_str = "map", .length = 3, .next = NULL}, LXB_TAG_MAP, 1, true},
{{.u.short_str = "mark", .length = 4, .next = NULL}, LXB_TAG_MARK, 1, true},
{{.u.short_str = "marquee", .length = 7, .next = NULL}, LXB_TAG_MARQUEE, 1, true},
{{.u.short_str = "math", .length = 4, .next = NULL}, LXB_TAG_MATH, 1, true},
{{.u.short_str = "menu", .length = 4, .next = NULL}, LXB_TAG_MENU, 1, true},
{{.u.short_str = "meta", .length = 4, .next = NULL}, LXB_TAG_META, 1, true},
{{.u.short_str = "meter", .length = 5, .next = NULL}, LXB_TAG_METER, 1, true},
{{.u.short_str = "mfenced", .length = 7, .next = NULL}, LXB_TAG_MFENCED, 1, true},
{{.u.short_str = "mglyph", .length = 6, .next = NULL}, LXB_TAG_MGLYPH, 1, true},
{{.u.short_str = "mi", .length = 2, .next = NULL}, LXB_TAG_MI, 1, true},
{{.u.short_str = "mn", .length = 2, .next = NULL}, LXB_TAG_MN, 1, true},
{{.u.short_str = "mo", .length = 2, .next = NULL}, LXB_TAG_MO, 1, true},
{{.u.short_str = "ms", .length = 2, .next = NULL}, LXB_TAG_MS, 1, true},
{{.u.short_str = "mtext", .length = 5, .next = NULL}, LXB_TAG_MTEXT, 1, true},
{{.u.short_str = "multicol", .length = 8, .next = NULL}, LXB_TAG_MULTICOL, 1, true},
{{.u.short_str = "nav", .length = 3, .next = NULL}, LXB_TAG_NAV, 1, true},
{{.u.short_str = "nextid", .length = 6, .next = NULL}, LXB_TAG_NEXTID, 1, true},
{{.u.short_str = "nobr", .length = 4, .next = NULL}, LXB_TAG_NOBR, 1, true},
{{.u.short_str = "noembed", .length = 7, .next = NULL}, LXB_TAG_NOEMBED, 1, true},
{{.u.short_str = "noframes", .length = 8, .next = NULL}, LXB_TAG_NOFRAMES, 1, true},
{{.u.short_str = "noscript", .length = 8, .next = NULL}, LXB_TAG_NOSCRIPT, 1, true},
{{.u.short_str = "object", .length = 6, .next = NULL}, LXB_TAG_OBJECT, 1, true},
{{.u.short_str = "ol", .length = 2, .next = NULL}, LXB_TAG_OL, 1, true},
{{.u.short_str = "optgroup", .length = 8, .next = NULL}, LXB_TAG_OPTGROUP, 1, true},
{{.u.short_str = "option", .length = 6, .next = NULL}, LXB_TAG_OPTION, 1, true},
{{.u.short_str = "output", .length = 6, .next = NULL}, LXB_TAG_OUTPUT, 1, true},
{{.u.short_str = "p", .length = 1, .next = NULL}, LXB_TAG_P, 1, true},
{{.u.short_str = "param", .length = 5, .next = NULL}, LXB_TAG_PARAM, 1, true},
{{.u.short_str = "path", .length = 4, .next = NULL}, LXB_TAG_PATH, 1, true},
{{.u.short_str = "picture", .length = 7, .next = NULL}, LXB_TAG_PICTURE, 1, true},
{{.u.short_str = "plaintext", .length = 9, .next = NULL}, LXB_TAG_PLAINTEXT, 1, true},
{{.u.short_str = "pre", .length = 3, .next = NULL}, LXB_TAG_PRE, 1, true},
{{.u.short_str = "progress", .length = 8, .next = NULL}, LXB_TAG_PROGRESS, 1, true},
{{.u.short_str = "q", .length = 1, .next = NULL}, LXB_TAG_Q, 1, true},
{{.u.short_str = "radialgradient", .length = 14, .next = NULL}, LXB_TAG_RADIALGRADIENT, 1, true},
{{.u.short_str = "rb", .length = 2, .next = NULL}, LXB_TAG_RB, 1, true},
{{.u.short_str = "rp", .length = 2, .next = NULL}, LXB_TAG_RP, 1, true},
{{.u.short_str = "rt", .length = 2, .next = NULL}, LXB_TAG_RT, 1, true},
{{.u.short_str = "rtc", .length = 3, .next = NULL}, LXB_TAG_RTC, 1, true},
{{.u.short_str = "ruby", .length = 4, .next = NULL}, LXB_TAG_RUBY, 1, true},
{{.u.short_str = "s", .length = 1, .next = NULL}, LXB_TAG_S, 1, true},
{{.u.short_str = "samp", .length = 4, .next = NULL}, LXB_TAG_SAMP, 1, true},
{{.u.short_str = "script", .length = 6, .next = NULL}, LXB_TAG_SCRIPT, 1, true},
{{.u.short_str = "section", .length = 7, .next = NULL}, LXB_TAG_SECTION, 1, true},
{{.u.short_str = "select", .length = 6, .next = NULL}, LXB_TAG_SELECT, 1, true},
{{.u.short_str = "slot", .length = 4, .next = NULL}, LXB_TAG_SLOT, 1, true},
{{.u.short_str = "small", .length = 5, .next = NULL}, LXB_TAG_SMALL, 1, true},
{{.u.short_str = "source", .length = 6, .next = NULL}, LXB_TAG_SOURCE, 1, true},
{{.u.short_str = "spacer", .length = 6, .next = NULL}, LXB_TAG_SPACER, 1, true},
{{.u.short_str = "span", .length = 4, .next = NULL}, LXB_TAG_SPAN, 1, true},
{{.u.short_str = "strike", .length = 6, .next = NULL}, LXB_TAG_STRIKE, 1, true},
{{.u.short_str = "strong", .length = 6, .next = NULL}, LXB_TAG_STRONG, 1, true},
{{.u.short_str = "style", .length = 5, .next = NULL}, LXB_TAG_STYLE, 1, true},
{{.u.short_str = "sub", .length = 3, .next = NULL}, LXB_TAG_SUB, 1, true},
{{.u.short_str = "summary", .length = 7, .next = NULL}, LXB_TAG_SUMMARY, 1, true},
{{.u.short_str = "sup", .length = 3, .next = NULL}, LXB_TAG_SUP, 1, true},
{{.u.short_str = "svg", .length = 3, .next = NULL}, LXB_TAG_SVG, 1, true},
{{.u.short_str = "table", .length = 5, .next = NULL}, LXB_TAG_TABLE, 1, true},
{{.u.short_str = "tbody", .length = 5, .next = NULL}, LXB_TAG_TBODY, 1, true},
{{.u.short_str = "td", .length = 2, .next = NULL}, LXB_TAG_TD, 1, true},
{{.u.short_str = "template", .length = 8, .next = NULL}, LXB_TAG_TEMPLATE, 1, true},
{{.u.short_str = "textarea", .length = 8, .next = NULL}, LXB_TAG_TEXTAREA, 1, true},
{{.u.short_str = "textpath", .length = 8, .next = NULL}, LXB_TAG_TEXTPATH, 1, true},
{{.u.short_str = "tfoot", .length = 5, .next = NULL}, LXB_TAG_TFOOT, 1, true},
{{.u.short_str = "th", .length = 2, .next = NULL}, LXB_TAG_TH, 1, true},
{{.u.short_str = "thead", .length = 5, .next = NULL}, LXB_TAG_THEAD, 1, true},
{{.u.short_str = "time", .length = 4, .next = NULL}, LXB_TAG_TIME, 1, true},
{{.u.short_str = "title", .length = 5, .next = NULL}, LXB_TAG_TITLE, 1, true},
{{.u.short_str = "tr", .length = 2, .next = NULL}, LXB_TAG_TR, 1, true},
{{.u.short_str = "track", .length = 5, .next = NULL}, LXB_TAG_TRACK, 1, true},
{{.u.short_str = "tt", .length = 2, .next = NULL}, LXB_TAG_TT, 1, true},
{{.u.short_str = "u", .length = 1, .next = NULL}, LXB_TAG_U, 1, true},
{{.u.short_str = "ul", .length = 2, .next = NULL}, LXB_TAG_UL, 1, true},
{{.u.short_str = "var", .length = 3, .next = NULL}, LXB_TAG_VAR, 1, true},
{{.u.short_str = "video", .length = 5, .next = NULL}, LXB_TAG_VIDEO, 1, true},
{{.u.short_str = "wbr", .length = 3, .next = NULL}, LXB_TAG_WBR, 1, true},
{{.u.short_str = "xmp", .length = 3, .next = NULL}, LXB_TAG_XMP, 1, true}
};
static const lxb_tag_data_t lxb_tag_res_data_upper_default[LXB_TAG__LAST_ENTRY] =
{
{{.u.short_str = "#UNDEF", .length = 6, .next = NULL}, LXB_TAG__UNDEF, 1, true},
{{.u.short_str = "#END-OF-FILE", .length = 12, .next = NULL}, LXB_TAG__END_OF_FILE, 1, true},
{{.u.short_str = "#TEXT", .length = 5, .next = NULL}, LXB_TAG__TEXT, 1, true},
{{.u.short_str = "#DOCUMENT", .length = 9, .next = NULL}, LXB_TAG__DOCUMENT, 1, true},
{{.u.short_str = "!--", .length = 3, .next = NULL}, LXB_TAG__EM_COMMENT, 1, true},
{{.u.short_str = "!DOCTYPE", .length = 8, .next = NULL}, LXB_TAG__EM_DOCTYPE, 1, true},
{{.u.short_str = "A", .length = 1, .next = NULL}, LXB_TAG_A, 1, true},
{{.u.short_str = "ABBR", .length = 4, .next = NULL}, LXB_TAG_ABBR, 1, true},
{{.u.short_str = "ACRONYM", .length = 7, .next = NULL}, LXB_TAG_ACRONYM, 1, true},
{{.u.short_str = "ADDRESS", .length = 7, .next = NULL}, LXB_TAG_ADDRESS, 1, true},
{{.u.short_str = "ALTGLYPH", .length = 8, .next = NULL}, LXB_TAG_ALTGLYPH, 1, true},
{{.u.short_str = "ALTGLYPHDEF", .length = 11, .next = NULL}, LXB_TAG_ALTGLYPHDEF, 1, true},
{{.u.short_str = "ALTGLYPHITEM", .length = 12, .next = NULL}, LXB_TAG_ALTGLYPHITEM, 1, true},
{{.u.short_str = "ANIMATECOLOR", .length = 12, .next = NULL}, LXB_TAG_ANIMATECOLOR, 1, true},
{{.u.short_str = "ANIMATEMOTION", .length = 13, .next = NULL}, LXB_TAG_ANIMATEMOTION, 1, true},
{{.u.short_str = "ANIMATETRANSFORM", .length = 16, .next = NULL}, LXB_TAG_ANIMATETRANSFORM, 1, true},
{{.u.short_str = "ANNOTATION-XML", .length = 14, .next = NULL}, LXB_TAG_ANNOTATION_XML, 1, true},
{{.u.short_str = "APPLET", .length = 6, .next = NULL}, LXB_TAG_APPLET, 1, true},
{{.u.short_str = "AREA", .length = 4, .next = NULL}, LXB_TAG_AREA, 1, true},
{{.u.short_str = "ARTICLE", .length = 7, .next = NULL}, LXB_TAG_ARTICLE, 1, true},
{{.u.short_str = "ASIDE", .length = 5, .next = NULL}, LXB_TAG_ASIDE, 1, true},
{{.u.short_str = "AUDIO", .length = 5, .next = NULL}, LXB_TAG_AUDIO, 1, true},
{{.u.short_str = "B", .length = 1, .next = NULL}, LXB_TAG_B, 1, true},
{{.u.short_str = "BASE", .length = 4, .next = NULL}, LXB_TAG_BASE, 1, true},
{{.u.short_str = "BASEFONT", .length = 8, .next = NULL}, LXB_TAG_BASEFONT, 1, true},
{{.u.short_str = "BDI", .length = 3, .next = NULL}, LXB_TAG_BDI, 1, true},
{{.u.short_str = "BDO", .length = 3, .next = NULL}, LXB_TAG_BDO, 1, true},
{{.u.short_str = "BGSOUND", .length = 7, .next = NULL}, LXB_TAG_BGSOUND, 1, true},
{{.u.short_str = "BIG", .length = 3, .next = NULL}, LXB_TAG_BIG, 1, true},
{{.u.short_str = "BLINK", .length = 5, .next = NULL}, LXB_TAG_BLINK, 1, true},
{{.u.short_str = "BLOCKQUOTE", .length = 10, .next = NULL}, LXB_TAG_BLOCKQUOTE, 1, true},
{{.u.short_str = "BODY", .length = 4, .next = NULL}, LXB_TAG_BODY, 1, true},
{{.u.short_str = "BR", .length = 2, .next = NULL}, LXB_TAG_BR, 1, true},
{{.u.short_str = "BUTTON", .length = 6, .next = NULL}, LXB_TAG_BUTTON, 1, true},
{{.u.short_str = "CANVAS", .length = 6, .next = NULL}, LXB_TAG_CANVAS, 1, true},
{{.u.short_str = "CAPTION", .length = 7, .next = NULL}, LXB_TAG_CAPTION, 1, true},
{{.u.short_str = "CENTER", .length = 6, .next = NULL}, LXB_TAG_CENTER, 1, true},
{{.u.short_str = "CITE", .length = 4, .next = NULL}, LXB_TAG_CITE, 1, true},
{{.u.short_str = "CLIPPATH", .length = 8, .next = NULL}, LXB_TAG_CLIPPATH, 1, true},
{{.u.short_str = "CODE", .length = 4, .next = NULL}, LXB_TAG_CODE, 1, true},
{{.u.short_str = "COL", .length = 3, .next = NULL}, LXB_TAG_COL, 1, true},
{{.u.short_str = "COLGROUP", .length = 8, .next = NULL}, LXB_TAG_COLGROUP, 1, true},
{{.u.short_str = "DATA", .length = 4, .next = NULL}, LXB_TAG_DATA, 1, true},
{{.u.short_str = "DATALIST", .length = 8, .next = NULL}, LXB_TAG_DATALIST, 1, true},
{{.u.short_str = "DD", .length = 2, .next = NULL}, LXB_TAG_DD, 1, true},
{{.u.short_str = "DEL", .length = 3, .next = NULL}, LXB_TAG_DEL, 1, true},
{{.u.short_str = "DESC", .length = 4, .next = NULL}, LXB_TAG_DESC, 1, true},
{{.u.short_str = "DETAILS", .length = 7, .next = NULL}, LXB_TAG_DETAILS, 1, true},
{{.u.short_str = "DFN", .length = 3, .next = NULL}, LXB_TAG_DFN, 1, true},
{{.u.short_str = "DIALOG", .length = 6, .next = NULL}, LXB_TAG_DIALOG, 1, true},
{{.u.short_str = "DIR", .length = 3, .next = NULL}, LXB_TAG_DIR, 1, true},
{{.u.short_str = "DIV", .length = 3, .next = NULL}, LXB_TAG_DIV, 1, true},
{{.u.short_str = "DL", .length = 2, .next = NULL}, LXB_TAG_DL, 1, true},
{{.u.short_str = "DT", .length = 2, .next = NULL}, LXB_TAG_DT, 1, true},
{{.u.short_str = "EM", .length = 2, .next = NULL}, LXB_TAG_EM, 1, true},
{{.u.short_str = "EMBED", .length = 5, .next = NULL}, LXB_TAG_EMBED, 1, true},
{{.u.short_str = "FEBLEND", .length = 7, .next = NULL}, LXB_TAG_FEBLEND, 1, true},
{{.u.short_str = "FECOLORMATRIX", .length = 13, .next = NULL}, LXB_TAG_FECOLORMATRIX, 1, true},
{{.u.long_str = (lxb_char_t *) "FECOMPONENTTRANSFER", .length = 19, .next = NULL}, LXB_TAG_FECOMPONENTTRANSFER, 1, true},
{{.u.short_str = "FECOMPOSITE", .length = 11, .next = NULL}, LXB_TAG_FECOMPOSITE, 1, true},
{{.u.short_str = "FECONVOLVEMATRIX", .length = 16, .next = NULL}, LXB_TAG_FECONVOLVEMATRIX, 1, true},
{{.u.long_str = (lxb_char_t *) "FEDIFFUSELIGHTING", .length = 17, .next = NULL}, LXB_TAG_FEDIFFUSELIGHTING, 1, true},
{{.u.long_str = (lxb_char_t *) "FEDISPLACEMENTMAP", .length = 17, .next = NULL}, LXB_TAG_FEDISPLACEMENTMAP, 1, true},
{{.u.short_str = "FEDISTANTLIGHT", .length = 14, .next = NULL}, LXB_TAG_FEDISTANTLIGHT, 1, true},
{{.u.short_str = "FEDROPSHADOW", .length = 12, .next = NULL}, LXB_TAG_FEDROPSHADOW, 1, true},
{{.u.short_str = "FEFLOOD", .length = 7, .next = NULL}, LXB_TAG_FEFLOOD, 1, true},
{{.u.short_str = "FEFUNCA", .length = 7, .next = NULL}, LXB_TAG_FEFUNCA, 1, true},
{{.u.short_str = "FEFUNCB", .length = 7, .next = NULL}, LXB_TAG_FEFUNCB, 1, true},
{{.u.short_str = "FEFUNCG", .length = 7, .next = NULL}, LXB_TAG_FEFUNCG, 1, true},
{{.u.short_str = "FEFUNCR", .length = 7, .next = NULL}, LXB_TAG_FEFUNCR, 1, true},
{{.u.short_str = "FEGAUSSIANBLUR", .length = 14, .next = NULL}, LXB_TAG_FEGAUSSIANBLUR, 1, true},
{{.u.short_str = "FEIMAGE", .length = 7, .next = NULL}, LXB_TAG_FEIMAGE, 1, true},
{{.u.short_str = "FEMERGE", .length = 7, .next = NULL}, LXB_TAG_FEMERGE, 1, true},
{{.u.short_str = "FEMERGENODE", .length = 11, .next = NULL}, LXB_TAG_FEMERGENODE, 1, true},
{{.u.short_str = "FEMORPHOLOGY", .length = 12, .next = NULL}, LXB_TAG_FEMORPHOLOGY, 1, true},
{{.u.short_str = "FEOFFSET", .length = 8, .next = NULL}, LXB_TAG_FEOFFSET, 1, true},
{{.u.short_str = "FEPOINTLIGHT", .length = 12, .next = NULL}, LXB_TAG_FEPOINTLIGHT, 1, true},
{{.u.long_str = (lxb_char_t *) "FESPECULARLIGHTING", .length = 18, .next = NULL}, LXB_TAG_FESPECULARLIGHTING, 1, true},
{{.u.short_str = "FESPOTLIGHT", .length = 11, .next = NULL}, LXB_TAG_FESPOTLIGHT, 1, true},
{{.u.short_str = "FETILE", .length = 6, .next = NULL}, LXB_TAG_FETILE, 1, true},
{{.u.short_str = "FETURBULENCE", .length = 12, .next = NULL}, LXB_TAG_FETURBULENCE, 1, true},
{{.u.short_str = "FIELDSET", .length = 8, .next = NULL}, LXB_TAG_FIELDSET, 1, true},
{{.u.short_str = "FIGCAPTION", .length = 10, .next = NULL}, LXB_TAG_FIGCAPTION, 1, true},
{{.u.short_str = "FIGURE", .length = 6, .next = NULL}, LXB_TAG_FIGURE, 1, true},
{{.u.short_str = "FONT", .length = 4, .next = NULL}, LXB_TAG_FONT, 1, true},
{{.u.short_str = "FOOTER", .length = 6, .next = NULL}, LXB_TAG_FOOTER, 1, true},
{{.u.short_str = "FOREIGNOBJECT", .length = 13, .next = NULL}, LXB_TAG_FOREIGNOBJECT, 1, true},
{{.u.short_str = "FORM", .length = 4, .next = NULL}, LXB_TAG_FORM, 1, true},
{{.u.short_str = "FRAME", .length = 5, .next = NULL}, LXB_TAG_FRAME, 1, true},
{{.u.short_str = "FRAMESET", .length = 8, .next = NULL}, LXB_TAG_FRAMESET, 1, true},
{{.u.short_str = "GLYPHREF", .length = 8, .next = NULL}, LXB_TAG_GLYPHREF, 1, true},
{{.u.short_str = "H1", .length = 2, .next = NULL}, LXB_TAG_H1, 1, true},
{{.u.short_str = "H2", .length = 2, .next = NULL}, LXB_TAG_H2, 1, true},
{{.u.short_str = "H3", .length = 2, .next = NULL}, LXB_TAG_H3, 1, true},
{{.u.short_str = "H4", .length = 2, .next = NULL}, LXB_TAG_H4, 1, true},
{{.u.short_str = "H5", .length = 2, .next = NULL}, LXB_TAG_H5, 1, true},
{{.u.short_str = "H6", .length = 2, .next = NULL}, LXB_TAG_H6, 1, true},
{{.u.short_str = "HEAD", .length = 4, .next = NULL}, LXB_TAG_HEAD, 1, true},
{{.u.short_str = "HEADER", .length = 6, .next = NULL}, LXB_TAG_HEADER, 1, true},
{{.u.short_str = "HGROUP", .length = 6, .next = NULL}, LXB_TAG_HGROUP, 1, true},
{{.u.short_str = "HR", .length = 2, .next = NULL}, LXB_TAG_HR, 1, true},
{{.u.short_str = "HTML", .length = 4, .next = NULL}, LXB_TAG_HTML, 1, true},
{{.u.short_str = "I", .length = 1, .next = NULL}, LXB_TAG_I, 1, true},
{{.u.short_str = "IFRAME", .length = 6, .next = NULL}, LXB_TAG_IFRAME, 1, true},
{{.u.short_str = "IMAGE", .length = 5, .next = NULL}, LXB_TAG_IMAGE, 1, true},
{{.u.short_str = "IMG", .length = 3, .next = NULL}, LXB_TAG_IMG, 1, true},
{{.u.short_str = "INPUT", .length = 5, .next = NULL}, LXB_TAG_INPUT, 1, true},
{{.u.short_str = "INS", .length = 3, .next = NULL}, LXB_TAG_INS, 1, true},
{{.u.short_str = "ISINDEX", .length = 7, .next = NULL}, LXB_TAG_ISINDEX, 1, true},
{{.u.short_str = "KBD", .length = 3, .next = NULL}, LXB_TAG_KBD, 1, true},
{{.u.short_str = "KEYGEN", .length = 6, .next = NULL}, LXB_TAG_KEYGEN, 1, true},
{{.u.short_str = "LABEL", .length = 5, .next = NULL}, LXB_TAG_LABEL, 1, true},
{{.u.short_str = "LEGEND", .length = 6, .next = NULL}, LXB_TAG_LEGEND, 1, true},
{{.u.short_str = "LI", .length = 2, .next = NULL}, LXB_TAG_LI, 1, true},
{{.u.short_str = "LINEARGRADIENT", .length = 14, .next = NULL}, LXB_TAG_LINEARGRADIENT, 1, true},
{{.u.short_str = "LINK", .length = 4, .next = NULL}, LXB_TAG_LINK, 1, true},
{{.u.short_str = "LISTING", .length = 7, .next = NULL}, LXB_TAG_LISTING, 1, true},
{{.u.short_str = "MAIN", .length = 4, .next = NULL}, LXB_TAG_MAIN, 1, true},
{{.u.short_str = "MALIGNMARK", .length = 10, .next = NULL}, LXB_TAG_MALIGNMARK, 1, true},
{{.u.short_str = "MAP", .length = 3, .next = NULL}, LXB_TAG_MAP, 1, true},
{{.u.short_str = "MARK", .length = 4, .next = NULL}, LXB_TAG_MARK, 1, true},
{{.u.short_str = "MARQUEE", .length = 7, .next = NULL}, LXB_TAG_MARQUEE, 1, true},
{{.u.short_str = "MATH", .length = 4, .next = NULL}, LXB_TAG_MATH, 1, true},
{{.u.short_str = "MENU", .length = 4, .next = NULL}, LXB_TAG_MENU, 1, true},
{{.u.short_str = "META", .length = 4, .next = NULL}, LXB_TAG_META, 1, true},
{{.u.short_str = "METER", .length = 5, .next = NULL}, LXB_TAG_METER, 1, true},
{{.u.short_str = "MFENCED", .length = 7, .next = NULL}, LXB_TAG_MFENCED, 1, true},
{{.u.short_str = "MGLYPH", .length = 6, .next = NULL}, LXB_TAG_MGLYPH, 1, true},
{{.u.short_str = "MI", .length = 2, .next = NULL}, LXB_TAG_MI, 1, true},
{{.u.short_str = "MN", .length = 2, .next = NULL}, LXB_TAG_MN, 1, true},
{{.u.short_str = "MO", .length = 2, .next = NULL}, LXB_TAG_MO, 1, true},
{{.u.short_str = "MS", .length = 2, .next = NULL}, LXB_TAG_MS, 1, true},
{{.u.short_str = "MTEXT", .length = 5, .next = NULL}, LXB_TAG_MTEXT, 1, true},
{{.u.short_str = "MULTICOL", .length = 8, .next = NULL}, LXB_TAG_MULTICOL, 1, true},
{{.u.short_str = "NAV", .length = 3, .next = NULL}, LXB_TAG_NAV, 1, true},
{{.u.short_str = "NEXTID", .length = 6, .next = NULL}, LXB_TAG_NEXTID, 1, true},
{{.u.short_str = "NOBR", .length = 4, .next = NULL}, LXB_TAG_NOBR, 1, true},
{{.u.short_str = "NOEMBED", .length = 7, .next = NULL}, LXB_TAG_NOEMBED, 1, true},
{{.u.short_str = "NOFRAMES", .length = 8, .next = NULL}, LXB_TAG_NOFRAMES, 1, true},
{{.u.short_str = "NOSCRIPT", .length = 8, .next = NULL}, LXB_TAG_NOSCRIPT, 1, true},
{{.u.short_str = "OBJECT", .length = 6, .next = NULL}, LXB_TAG_OBJECT, 1, true},
{{.u.short_str = "OL", .length = 2, .next = NULL}, LXB_TAG_OL, 1, true},
{{.u.short_str = "OPTGROUP", .length = 8, .next = NULL}, LXB_TAG_OPTGROUP, 1, true},
{{.u.short_str = "OPTION", .length = 6, .next = NULL}, LXB_TAG_OPTION, 1, true},
{{.u.short_str = "OUTPUT", .length = 6, .next = NULL}, LXB_TAG_OUTPUT, 1, true},
{{.u.short_str = "P", .length = 1, .next = NULL}, LXB_TAG_P, 1, true},
{{.u.short_str = "PARAM", .length = 5, .next = NULL}, LXB_TAG_PARAM, 1, true},
{{.u.short_str = "PATH", .length = 4, .next = NULL}, LXB_TAG_PATH, 1, true},
{{.u.short_str = "PICTURE", .length = 7, .next = NULL}, LXB_TAG_PICTURE, 1, true},
{{.u.short_str = "PLAINTEXT", .length = 9, .next = NULL}, LXB_TAG_PLAINTEXT, 1, true},
{{.u.short_str = "PRE", .length = 3, .next = NULL}, LXB_TAG_PRE, 1, true},
{{.u.short_str = "PROGRESS", .length = 8, .next = NULL}, LXB_TAG_PROGRESS, 1, true},
{{.u.short_str = "Q", .length = 1, .next = NULL}, LXB_TAG_Q, 1, true},
{{.u.short_str = "RADIALGRADIENT", .length = 14, .next = NULL}, LXB_TAG_RADIALGRADIENT, 1, true},
{{.u.short_str = "RB", .length = 2, .next = NULL}, LXB_TAG_RB, 1, true},
{{.u.short_str = "RP", .length = 2, .next = NULL}, LXB_TAG_RP, 1, true},
{{.u.short_str = "RT", .length = 2, .next = NULL}, LXB_TAG_RT, 1, true},
{{.u.short_str = "RTC", .length = 3, .next = NULL}, LXB_TAG_RTC, 1, true},
{{.u.short_str = "RUBY", .length = 4, .next = NULL}, LXB_TAG_RUBY, 1, true},
{{.u.short_str = "S", .length = 1, .next = NULL}, LXB_TAG_S, 1, true},
{{.u.short_str = "SAMP", .length = 4, .next = NULL}, LXB_TAG_SAMP, 1, true},
{{.u.short_str = "SCRIPT", .length = 6, .next = NULL}, LXB_TAG_SCRIPT, 1, true},
{{.u.short_str = "SECTION", .length = 7, .next = NULL}, LXB_TAG_SECTION, 1, true},
{{.u.short_str = "SELECT", .length = 6, .next = NULL}, LXB_TAG_SELECT, 1, true},
{{.u.short_str = "SLOT", .length = 4, .next = NULL}, LXB_TAG_SLOT, 1, true},
{{.u.short_str = "SMALL", .length = 5, .next = NULL}, LXB_TAG_SMALL, 1, true},
{{.u.short_str = "SOURCE", .length = 6, .next = NULL}, LXB_TAG_SOURCE, 1, true},
{{.u.short_str = "SPACER", .length = 6, .next = NULL}, LXB_TAG_SPACER, 1, true},
{{.u.short_str = "SPAN", .length = 4, .next = NULL}, LXB_TAG_SPAN, 1, true},
{{.u.short_str = "STRIKE", .length = 6, .next = NULL}, LXB_TAG_STRIKE, 1, true},
{{.u.short_str = "STRONG", .length = 6, .next = NULL}, LXB_TAG_STRONG, 1, true},
{{.u.short_str = "STYLE", .length = 5, .next = NULL}, LXB_TAG_STYLE, 1, true},
{{.u.short_str = "SUB", .length = 3, .next = NULL}, LXB_TAG_SUB, 1, true},
{{.u.short_str = "SUMMARY", .length = 7, .next = NULL}, LXB_TAG_SUMMARY, 1, true},
{{.u.short_str = "SUP", .length = 3, .next = NULL}, LXB_TAG_SUP, 1, true},
{{.u.short_str = "SVG", .length = 3, .next = NULL}, LXB_TAG_SVG, 1, true},
{{.u.short_str = "TABLE", .length = 5, .next = NULL}, LXB_TAG_TABLE, 1, true},
{{.u.short_str = "TBODY", .length = 5, .next = NULL}, LXB_TAG_TBODY, 1, true},
{{.u.short_str = "TD", .length = 2, .next = NULL}, LXB_TAG_TD, 1, true},
{{.u.short_str = "TEMPLATE", .length = 8, .next = NULL}, LXB_TAG_TEMPLATE, 1, true},
{{.u.short_str = "TEXTAREA", .length = 8, .next = NULL}, LXB_TAG_TEXTAREA, 1, true},
{{.u.short_str = "TEXTPATH", .length = 8, .next = NULL}, LXB_TAG_TEXTPATH, 1, true},
{{.u.short_str = "TFOOT", .length = 5, .next = NULL}, LXB_TAG_TFOOT, 1, true},
{{.u.short_str = "TH", .length = 2, .next = NULL}, LXB_TAG_TH, 1, true},
{{.u.short_str = "THEAD", .length = 5, .next = NULL}, LXB_TAG_THEAD, 1, true},
{{.u.short_str = "TIME", .length = 4, .next = NULL}, LXB_TAG_TIME, 1, true},
{{.u.short_str = "TITLE", .length = 5, .next = NULL}, LXB_TAG_TITLE, 1, true},
{{.u.short_str = "TR", .length = 2, .next = NULL}, LXB_TAG_TR, 1, true},
{{.u.short_str = "TRACK", .length = 5, .next = NULL}, LXB_TAG_TRACK, 1, true},
{{.u.short_str = "TT", .length = 2, .next = NULL}, LXB_TAG_TT, 1, true},
{{.u.short_str = "U", .length = 1, .next = NULL}, LXB_TAG_U, 1, true},
{{.u.short_str = "UL", .length = 2, .next = NULL}, LXB_TAG_UL, 1, true},
{{.u.short_str = "VAR", .length = 3, .next = NULL}, LXB_TAG_VAR, 1, true},
{{.u.short_str = "VIDEO", .length = 5, .next = NULL}, LXB_TAG_VIDEO, 1, true},
{{.u.short_str = "WBR", .length = 3, .next = NULL}, LXB_TAG_WBR, 1, true},
{{.u.short_str = "XMP", .length = 3, .next = NULL}, LXB_TAG_XMP, 1, true}
};
static const lexbor_shs_entry_t lxb_tag_res_shs_data_default[] =
{
{NULL, NULL, 262, 0}, {"radialgradient", (void *) &lxb_tag_res_data_default[153], 14, 0},
{"fecomponenttransfer", (void *) &lxb_tag_res_data_default[58], 19, 0}, {"abbr", (void *) &lxb_tag_res_data_default[7], 4, 1},
{"feflood", (void *) &lxb_tag_res_data_default[65], 7, 0}, {"marquee", (void *) &lxb_tag_res_data_default[121], 7, 0},
{"feblend", (void *) &lxb_tag_res_data_default[56], 7, 4}, {"optgroup", (void *) &lxb_tag_res_data_default[142], 8, 0},
{"video", (void *) &lxb_tag_res_data_default[193], 5, 10}, {"u", (void *) &lxb_tag_res_data_default[190], 1, 0},
{"iframe", (void *) &lxb_tag_res_data_default[103], 6, 0}, {"animatecolor", (void *) &lxb_tag_res_data_default[13], 12, 0},
{"output", (void *) &lxb_tag_res_data_default[144], 6, 0}, {"figcaption", (void *) &lxb_tag_res_data_default[82], 10, 0},
{"mglyph", (void *) &lxb_tag_res_data_default[127], 6, 0}, {"!--", (void *) &lxb_tag_res_data_default[4], 3, 0},
{"fefuncg", (void *) &lxb_tag_res_data_default[68], 7, 0}, {"aside", (void *) &lxb_tag_res_data_default[20], 5, 0},
{"style", (void *) &lxb_tag_res_data_default[171], 5, 0}, {"strike", (void *) &lxb_tag_res_data_default[169], 6, 0},
{"header", (void *) &lxb_tag_res_data_default[98], 6, 0}, {"glyphref", (void *) &lxb_tag_res_data_default[90], 8, 23},
{"label", (void *) &lxb_tag_res_data_default[111], 5, 0}, {"feconvolvematrix", (void *) &lxb_tag_res_data_default[60], 16, 0},
{"altglyphdef", (void *) &lxb_tag_res_data_default[11], 11, 0}, {"title", (void *) &lxb_tag_res_data_default[186], 5, 0},
{"head", (void *) &lxb_tag_res_data_default[97], 4, 0}, {"noframes", (void *) &lxb_tag_res_data_default[138], 8, 0},
{"code", (void *) &lxb_tag_res_data_default[39], 4, 30}, {"rb", (void *) &lxb_tag_res_data_default[154], 2, 5},
{"blink", (void *) &lxb_tag_res_data_default[29], 5, 0}, {"image", (void *) &lxb_tag_res_data_default[104], 5, 0},
{"col", (void *) &lxb_tag_res_data_default[40], 3, 8}, {"object", (void *) &lxb_tag_res_data_default[140], 6, 12},
{"template", (void *) &lxb_tag_res_data_default[179], 8, 36}, {"h2", (void *) &lxb_tag_res_data_default[92], 2, 13},
{"lineargradient", (void *) &lxb_tag_res_data_default[114], 14, 0}, {"math", (void *) &lxb_tag_res_data_default[122], 4, 0},
{"base", (void *) &lxb_tag_res_data_default[23], 4, 45}, {"dl", (void *) &lxb_tag_res_data_default[52], 2, 14},
{"del", (void *) &lxb_tag_res_data_default[45], 3, 16}, {"svg", (void *) &lxb_tag_res_data_default[175], 3, 17},
{"dir", (void *) &lxb_tag_res_data_default[50], 3, 0}, {"article", (void *) &lxb_tag_res_data_default[19], 7, 0},
{"strong", (void *) &lxb_tag_res_data_default[170], 6, 0}, {"dialog", (void *) &lxb_tag_res_data_default[49], 6, 0},
{"details", (void *) &lxb_tag_res_data_default[47], 7, 0}, {"textpath", (void *) &lxb_tag_res_data_default[181], 8, 52},
{"mark", (void *) &lxb_tag_res_data_default[120], 4, 0}, {"basefont", (void *) &lxb_tag_res_data_default[24], 8, 0},
{"fediffuselighting", (void *) &lxb_tag_res_data_default[61], 17, 0}, {"fespecularlighting", (void *) &lxb_tag_res_data_default[77], 18, 0},
{"blockquote", (void *) &lxb_tag_res_data_default[30], 10, 0}, {"script", (void *) &lxb_tag_res_data_default[161], 6, 58},
{"malignmark", (void *) &lxb_tag_res_data_default[118], 10, 0}, {"hr", (void *) &lxb_tag_res_data_default[100], 2, 18},
{"source", (void *) &lxb_tag_res_data_default[166], 6, 19}, {"mn", (void *) &lxb_tag_res_data_default[129], 2, 0},
{"select", (void *) &lxb_tag_res_data_default[163], 6, 0}, {"main", (void *) &lxb_tag_res_data_default[117], 4, 20},
{"fieldset", (void *) &lxb_tag_res_data_default[81], 8, 62}, {"ins", (void *) &lxb_tag_res_data_default[107], 3, 0},
{"frameset", (void *) &lxb_tag_res_data_default[89], 8, 0}, {"button", (void *) &lxb_tag_res_data_default[33], 6, 0},
{"fecolormatrix", (void *) &lxb_tag_res_data_default[57], 13, 0}, {"q", (void *) &lxb_tag_res_data_default[152], 1, 0},
{"animatemotion", (void *) &lxb_tag_res_data_default[14], 13, 0}, {"time", (void *) &lxb_tag_res_data_default[185], 4, 21},
{"table", (void *) &lxb_tag_res_data_default[176], 5, 25}, {"h6", (void *) &lxb_tag_res_data_default[96], 2, 26},
{"cite", (void *) &lxb_tag_res_data_default[37], 4, 28}, {"img", (void *) &lxb_tag_res_data_default[105], 3, 34},
{"fepointlight", (void *) &lxb_tag_res_data_default[76], 12, 0}, {"audio", (void *) &lxb_tag_res_data_default[21], 5, 0},
{"#end-of-file", (void *) &lxb_tag_res_data_default[1], 12, 0}, {"noscript", (void *) &lxb_tag_res_data_default[139], 8, 0},
{"foreignobject", (void *) &lxb_tag_res_data_default[86], 13, 0}, {"spacer", (void *) &lxb_tag_res_data_default[167], 6, 0},
{"samp", (void *) &lxb_tag_res_data_default[160], 4, 0}, {"altglyphitem", (void *) &lxb_tag_res_data_default[12], 12, 0},
{"dt", (void *) &lxb_tag_res_data_default[53], 2, 0}, {"data", (void *) &lxb_tag_res_data_default[42], 4, 0},
{"mtext", (void *) &lxb_tag_res_data_default[132], 5, 0}, {"path", (void *) &lxb_tag_res_data_default[147], 4, 0},
{"input", (void *) &lxb_tag_res_data_default[106], 5, 0}, {"th", (void *) &lxb_tag_res_data_default[183], 2, 38},
{"p", (void *) &lxb_tag_res_data_default[145], 1, 0}, {"animatetransform", (void *) &lxb_tag_res_data_default[15], 16, 0},
{"datalist", (void *) &lxb_tag_res_data_default[43], 8, 0}, {"small", (void *) &lxb_tag_res_data_default[165], 5, 0},
{"b", (void *) &lxb_tag_res_data_default[22], 1, 46}, {"nextid", (void *) &lxb_tag_res_data_default[135], 6, 47},
{"noembed", (void *) &lxb_tag_res_data_default[137], 7, 0}, {"nav", (void *) &lxb_tag_res_data_default[134], 3, 0},
{"bgsound", (void *) &lxb_tag_res_data_default[27], 7, 0}, {"slot", (void *) &lxb_tag_res_data_default[164], 4, 0},
{"param", (void *) &lxb_tag_res_data_default[146], 5, 0}, {"font", (void *) &lxb_tag_res_data_default[84], 4, 53},
{"figure", (void *) &lxb_tag_res_data_default[83], 6, 0}, {"femerge", (void *) &lxb_tag_res_data_default[72], 7, 0},
{"femergenode", (void *) &lxb_tag_res_data_default[73], 11, 0}, {"feoffset", (void *) &lxb_tag_res_data_default[75], 8, 60},
{"#text", (void *) &lxb_tag_res_data_default[2], 5, 0}, {"ul", (void *) &lxb_tag_res_data_default[191], 2, 0},
{"fespotlight", (void *) &lxb_tag_res_data_default[78], 11, 66}, {"form", (void *) &lxb_tag_res_data_default[87], 4, 72},
{"#document", (void *) &lxb_tag_res_data_default[3], 9, 76}, {"fedistantlight", (void *) &lxb_tag_res_data_default[63], 14, 0},
{"track", (void *) &lxb_tag_res_data_default[188], 5, 0}, {"h3", (void *) &lxb_tag_res_data_default[93], 2, 77},
{"h1", (void *) &lxb_tag_res_data_default[91], 2, 0}, {"i", (void *) &lxb_tag_res_data_default[102], 1, 0},
{"altglyph", (void *) &lxb_tag_res_data_default[10], 8, 0}, {"legend", (void *) &lxb_tag_res_data_default[112], 6, 115},
{"tbody", (void *) &lxb_tag_res_data_default[177], 5, 0}, {"address", (void *) &lxb_tag_res_data_default[9], 7, 0},
{"caption", (void *) &lxb_tag_res_data_default[35], 7, 0}, {"option", (void *) &lxb_tag_res_data_default[143], 6, 0},
{"sup", (void *) &lxb_tag_res_data_default[174], 3, 0}, {"body", (void *) &lxb_tag_res_data_default[31], 4, 78},
{"progress", (void *) &lxb_tag_res_data_default[151], 8, 122}, {"acronym", (void *) &lxb_tag_res_data_default[8], 7, 0},
{"fegaussianblur", (void *) &lxb_tag_res_data_default[70], 14, 0}, {NULL, NULL, 0, 0},
{NULL, NULL, 0, 0}, {NULL, NULL, 0, 0},
{"mi", (void *) &lxb_tag_res_data_default[128], 2, 79}, {NULL, NULL, 0, 0},
{"dfn", (void *) &lxb_tag_res_data_default[48], 3, 0}, {"a", (void *) &lxb_tag_res_data_default[6], 1, 80},
{"listing", (void *) &lxb_tag_res_data_default[116], 7, 87}, {"span", (void *) &lxb_tag_res_data_default[168], 4, 0},
{"area", (void *) &lxb_tag_res_data_default[18], 4, 0}, {"clippath", (void *) &lxb_tag_res_data_default[38], 8, 0},
{"section", (void *) &lxb_tag_res_data_default[162], 7, 0}, {"li", (void *) &lxb_tag_res_data_default[113], 2, 88},
{NULL, NULL, 0, 0}, {"html", (void *) &lxb_tag_res_data_default[101], 4, 0},
{NULL, NULL, 0, 0}, {"fedropshadow", (void *) &lxb_tag_res_data_default[64], 12, 0},
{"embed", (void *) &lxb_tag_res_data_default[55], 5, 0}, {NULL, NULL, 0, 0},
{NULL, NULL, 0, 0}, {"multicol", (void *) &lxb_tag_res_data_default[133], 8, 0},
{"var", (void *) &lxb_tag_res_data_default[192], 3, 89}, {"rp", (void *) &lxb_tag_res_data_default[155], 2, 0},
{NULL, NULL, 0, 0}, {"link", (void *) &lxb_tag_res_data_default[115], 4, 0},
{"mo", (void *) &lxb_tag_res_data_default[130], 2, 0}, {NULL, NULL, 0, 0},
{NULL, NULL, 0, 0}, {"annotation-xml", (void *) &lxb_tag_res_data_default[16], 14, 0},
{"fedisplacementmap", (void *) &lxb_tag_res_data_default[62], 17, 0}, {"center", (void *) &lxb_tag_res_data_default[36], 6, 0},
{NULL, NULL, 0, 0}, {NULL, NULL, 0, 0},
{NULL, NULL, 0, 0}, {NULL, NULL, 0, 0},
{"fefuncb", (void *) &lxb_tag_res_data_default[67], 7, 0}, {NULL, NULL, 0, 0},
{NULL, NULL, 0, 0}, {NULL, NULL, 0, 0},
{"meter", (void *) &lxb_tag_res_data_default[125], 5, 0}, {NULL, NULL, 0, 0},
{NULL, NULL, 0, 0}, {"tt", (void *) &lxb_tag_res_data_default[189], 2, 0},
{"big", (void *) &lxb_tag_res_data_default[28], 3, 93}, {NULL, NULL, 0, 0},
{"tfoot", (void *) &lxb_tag_res_data_default[182], 5, 0}, {"desc", (void *) &lxb_tag_res_data_default[46], 4, 0},
{"isindex", (void *) &lxb_tag_res_data_default[108], 7, 0}, {NULL, NULL, 0, 0},
{"menu", (void *) &lxb_tag_res_data_default[123], 4, 0}, {"hgroup", (void *) &lxb_tag_res_data_default[99], 6, 0},
{NULL, NULL, 0, 0}, {NULL, NULL, 0, 0},
{"wbr", (void *) &lxb_tag_res_data_default[194], 3, 0}, {NULL, NULL, 0, 0},
{"pre", (void *) &lxb_tag_res_data_default[150], 3, 94}, {NULL, NULL, 0, 0},
{NULL, NULL, 0, 0}, {NULL, NULL, 0, 0},
{"picture", (void *) &lxb_tag_res_data_default[148], 7, 0}, {"h4", (void *) &lxb_tag_res_data_default[94], 2, 0},
{NULL, NULL, 0, 0}, {NULL, NULL, 0, 0},
{"meta", (void *) &lxb_tag_res_data_default[124], 4, 96}, {NULL, NULL, 0, 0},
{"rtc", (void *) &lxb_tag_res_data_default[157], 3, 0}, {NULL, NULL, 0, 0},
{"frame", (void *) &lxb_tag_res_data_default[88], 5, 0}, {"fetile", (void *) &lxb_tag_res_data_default[79], 6, 98},
{"feimage", (void *) &lxb_tag_res_data_default[71], 7, 99}, {NULL, NULL, 0, 0},
{"xmp", (void *) &lxb_tag_res_data_default[195], 3, 0}, {NULL, NULL, 0, 0},
{"fecomposite", (void *) &lxb_tag_res_data_default[59], 11, 100}, {"feturbulence", (void *) &lxb_tag_res_data_default[80], 12, 0},
{NULL, NULL, 0, 0}, {"summary", (void *) &lxb_tag_res_data_default[173], 7, 0},
{"mfenced", (void *) &lxb_tag_res_data_default[126], 7, 0}, {NULL, NULL, 0, 0},
{"sub", (void *) &lxb_tag_res_data_default[172], 3, 0}, {"colgroup", (void *) &lxb_tag_res_data_default[41], 8, 0},
{NULL, NULL, 0, 0}, {NULL, NULL, 0, 0},
{NULL, NULL, 0, 0}, {NULL, NULL, 0, 0},
{NULL, NULL, 0, 0}, {NULL, NULL, 0, 0},
{NULL, NULL, 0, 0}, {"dd", (void *) &lxb_tag_res_data_default[44], 2, 103},
{NULL, NULL, 0, 0}, {NULL, NULL, 0, 0},
{NULL, NULL, 0, 0}, {NULL, NULL, 0, 0},
{NULL, NULL, 0, 0}, {NULL, NULL, 0, 0},
{"div", (void *) &lxb_tag_res_data_default[51], 3, 0}, {"textarea", (void *) &lxb_tag_res_data_default[180], 8, 0},
{"!doctype", (void *) &lxb_tag_res_data_default[5], 8, 0}, {"applet", (void *) &lxb_tag_res_data_default[17], 6, 0},
{NULL, NULL, 0, 0}, {"br", (void *) &lxb_tag_res_data_default[32], 2, 110},
{NULL, NULL, 0, 0}, {"keygen", (void *) &lxb_tag_res_data_default[110], 6, 0},
{"kbd", (void *) &lxb_tag_res_data_default[109], 3, 0}, {NULL, NULL, 0, 0},
{"plaintext", (void *) &lxb_tag_res_data_default[149], 9, 0}, {"s", (void *) &lxb_tag_res_data_default[159], 1, 0},
{NULL, NULL, 0, 0}, {NULL, NULL, 0, 0},
{"bdo", (void *) &lxb_tag_res_data_default[26], 3, 0}, {"td", (void *) &lxb_tag_res_data_default[178], 2, 0},
{"fefunca", (void *) &lxb_tag_res_data_default[66], 7, 0}, {"ol", (void *) &lxb_tag_res_data_default[141], 2, 0},
{"thead", (void *) &lxb_tag_res_data_default[184], 5, 0}, {"nobr", (void *) &lxb_tag_res_data_default[136], 4, 112},
{NULL, NULL, 0, 0}, {"tr", (void *) &lxb_tag_res_data_default[187], 2, 0},
{"map", (void *) &lxb_tag_res_data_default[119], 3, 0}, {NULL, NULL, 0, 0},
{NULL, NULL, 0, 0}, {NULL, NULL, 0, 0},
{NULL, NULL, 0, 0}, {"#undef", (void *) &lxb_tag_res_data_default[0], 6, 113},
{"em", (void *) &lxb_tag_res_data_default[54], 2, 0}, {NULL, NULL, 0, 0},
{"bdi", (void *) &lxb_tag_res_data_default[25], 3, 0}, {"femorphology", (void *) &lxb_tag_res_data_default[74], 12, 0},
{"ms", (void *) &lxb_tag_res_data_default[131], 2, 116}, {"footer", (void *) &lxb_tag_res_data_default[85], 6, 0},
{"fefuncr", (void *) &lxb_tag_res_data_default[69], 7, 0}, {"rt", (void *) &lxb_tag_res_data_default[156], 2, 117},
{NULL, NULL, 0, 0}, {NULL, NULL, 0, 0},
{NULL, NULL, 0, 0}, {"h5", (void *) &lxb_tag_res_data_default[95], 2, 0},
{NULL, NULL, 0, 0}, {"ruby", (void *) &lxb_tag_res_data_default[158], 4, 120},
{"canvas", (void *) &lxb_tag_res_data_default[34], 6, 0}, {NULL, NULL, 0, 0},
{NULL, NULL, 0, 0}
};
| 21,869 |
341 | package travel2.init;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
import travel2.entity.TravelInfo;
import travel2.service.Travel2Service;
import java.util.Date;
/**
* @author fdse
*/
@Component
public class InitData implements CommandLineRunner {
@Autowired
Travel2Service service;
String zhiDa = "ZhiDa";
String shanghai = "shanghai";
String nanjing = "nanjing";
String beijing = "beijing";
@Override
public void run(String... args)throws Exception{
TravelInfo info = new TravelInfo();
info.setTripId("Z1234");
info.setTrainTypeId(zhiDa);
info.setRouteId("0b23bd3e-876a-4af3-b920-c50a90c90b04");
info.setStartingStationId(shanghai);
info.setStationsId(nanjing);
info.setTerminalStationId(beijing);
info.setStartingTime(new Date("Mon May 04 09:51:52 GMT+0800 2013")); //NOSONAR
info.setEndTime(new Date("Mon May 04 15:51:52 GMT+0800 2013")); //NOSONAR
service.create(info,null);
info.setTripId("Z1235");
info.setTrainTypeId(zhiDa);
info.setRouteId("9fc9c261-3263-4bfa-82f8-bb44e06b2f52");
info.setStartingStationId(shanghai);
info.setStationsId(nanjing);
info.setTerminalStationId(beijing);
info.setStartingTime(new Date("Mon May 04 11:31:52 GMT+0800 2013")); //NOSONAR
info.setEndTime(new Date("Mon May 04 17:51:52 GMT+0800 2013")); //NOSONAR
service.create(info,null);
info.setTripId("Z1236");
info.setTrainTypeId(zhiDa);
info.setRouteId("d693a2c5-ef87-4a3c-bef8-600b43f62c68");
info.setStartingStationId(shanghai);
info.setStationsId(nanjing);
info.setTerminalStationId(beijing);
info.setStartingTime(new Date("Mon May 04 7:05:52 GMT+0800 2013")); //NOSONAR
info.setEndTime(new Date("Mon May 04 12:51:52 GMT+0800 2013")); //NOSONAR
service.create(info,null);
info.setTripId("T1235");
info.setTrainTypeId("TeKuai");
info.setRouteId("20eb7122-3a11-423f-b10a-be0dc5bce7db");
info.setStartingStationId(shanghai);
info.setStationsId(nanjing);
info.setTerminalStationId(beijing);
info.setStartingTime(new Date("Mon May 04 08:31:52 GMT+0800 2013")); //NOSONAR
info.setEndTime(new Date("Mon May 04 17:21:52 GMT+0800 2013")); //NOSONAR
service.create(info,null);
info.setTripId("K1345");
info.setTrainTypeId("KuaiSu");
info.setRouteId("1367db1f-461e-4ab7-87ad-2bcc05fd9cb7");
info.setStartingStationId(shanghai);
info.setStationsId(nanjing);
info.setTerminalStationId(beijing);
info.setStartingTime(new Date("Mon May 04 07:51:52 GMT+0800 2013")); //NOSONAR
info.setEndTime(new Date("Mon May 04 19:59:52 GMT+0800 2013")); //NOSONAR
service.create(info,null);
}
}
| 1,341 |
1,657 | <gh_stars>1000+
from autoPyTorch.pipeline.base.pipeline_node import PipelineNode
from autoPyTorch.utils.config.config_option import ConfigOption
import json, os, csv, traceback
class GetAdditionalTrajectories(PipelineNode):
def fit(self, pipeline_config, trajectories, optimize_metrics, instance):
for additional_trajectory_path in pipeline_config["additional_trajectories"]:
# open trajectory description file
with open(additional_trajectory_path, "r") as f:
trajectories_description = json.load(f)
config_name = trajectories_description["name"]
file_format = trajectories_description["format"]
assert file_format in trajectory_loaders.keys(), "Unsupported file type %s" % file_format
assert not any(config_name in t.keys() for t in trajectories.values()), "Invalid additional trajectory name %s" % config_name
if instance not in trajectories_description["instances"]:
continue
columns_description = trajectories_description["columns"]
# process all trajectories for current instance
for path in trajectories_description["instances"][instance]:
path = os.path.join(os.path.dirname(additional_trajectory_path), path)
try:
trajectory_loaders[file_format](path, config_name, columns_description, trajectories)
except FileNotFoundError as e:
print("Trajectory could not be loaded: %s. Skipping." % e)
traceback.print_exc()
return {"trajectories": trajectories,
"optimize_metrics": optimize_metrics}
def get_pipeline_config_options(self):
options = [
ConfigOption("additional_trajectories", default=list(), type="directory", list=True)
]
return options
def csv_trajectory_loader(path, config_name, columns_description, trajectories):
with open(path, "r", newline="") as f:
reader = csv.reader(f, delimiter=",")
next(reader)
# parse the csv
times_finished = list()
performances = dict()
losses = dict()
for row in reader:
for i, col in enumerate(row):
if i == columns_description["time_column"]:
times_finished.append(max(0, float(col)))
if str(i) in columns_description["metric_columns"].keys():
log_name = columns_description["metric_columns"][str(i)]["name"]
transform = columns_description["metric_columns"][str(i)]["transform"] \
if "transform" in columns_description["metric_columns"][str(i)] else "x"
loss_transform = columns_description["metric_columns"][str(i)]["loss_transform"] \
if "loss_transform" in columns_description["metric_columns"][str(i)] else "x"
if log_name not in performances:
performances[log_name] = list()
losses[log_name] = list()
performances[log_name].append(eval_expr(transform.replace("x", col)))
losses[log_name].append(eval_expr(loss_transform.replace("x", col)))
# add data to the other trajectories
for log_name in performances.keys():
if log_name not in trajectories:
trajectories[log_name] = dict()
if config_name not in trajectories[log_name]:
trajectories[log_name][config_name] = list()
trajectories[log_name][config_name].append({
"times_finished": sorted(times_finished),
"values": list(zip(*sorted(zip(times_finished, performances[log_name]))))[1],
"losses": list(zip(*sorted(zip(times_finished, losses[log_name]))))[1]
})
trajectory_loaders = {"csv": csv_trajectory_loader}
import ast
import operator as op
# supported operators
operators = {ast.Add: op.add, ast.Sub: op.sub, ast.Mult: op.mul,
ast.Div: op.truediv, ast.Pow: op.pow, ast.BitXor: op.xor,
ast.USub: op.neg}
def eval_expr(expr):
return eval_(ast.parse(expr, mode='eval').body)
def eval_(node):
if isinstance(node, ast.Num): # <number>
return node.n
elif isinstance(node, ast.BinOp): # <left> <operator> <right>
return operators[type(node.op)](eval_(node.left), eval_(node.right))
elif isinstance(node, ast.UnaryOp): # <operator> <operand> e.g., -1
return operators[type(node.op)](eval_(node.operand))
else:
raise TypeError(node)
| 2,173 |
3,386 | <reponame>pjvm742/sc-im
/* dumb ui */
#include <unistd.h>
#include <termios.h>
#include <stdio.h>
#include <string.h>
#include "main.h"
#include "conf.h"
#include "input.h"
#include "tui.h"
#include "range.h"
#include "sc.h"
#include "cmds.h"
#include "cmds_visual.h"
#include "conf.h"
#include "version.h"
#include "file.h"
#include "format.h"
#include "utils/string.h"
#define NB_ENABLE 0
#define NB_DISABLE 1
void ui_start_screen() {
printf("started screen\n");
}
void ui_stop_screen() {
printf("stopped screen\n");
}
void nonblock(int state) {
struct termios ttystate;
tcgetattr(STDIN_FILENO, &ttystate);
if (state==NB_ENABLE) {
ttystate.c_lflag &= ~ICANON;
ttystate.c_cc[VMIN] = 1;
} else if (state==NB_DISABLE) {
ttystate.c_lflag |= ICANON;
}
tcsetattr(STDIN_FILENO, TCSANOW, &ttystate);
return;
}
int kbhit() {
struct timeval tv;
fd_set fds;
tv.tv_sec = 0;
tv.tv_usec = 0;
FD_ZERO(&fds);
FD_SET(STDIN_FILENO, &fds); //STDIN_FILENO is 0
select(STDIN_FILENO+1, &fds, NULL, NULL, &tv);
return FD_ISSET(STDIN_FILENO, &fds);
}
/* this function asks user for input from stdin.
* should be non blocking and should
* return -1 when no key was press
* return 0 when key was press.
* it receives * wint_t as a parameter.
* when a valid key is press, its value its then updated in that wint_t variable.
*/
int ui_getch(wint_t * wd) {
char c;
int i=0;
nonblock(NB_ENABLE);
while (!i) {
usleep(1);
i=kbhit();
if (i!=0) {
c = fgetc(stdin);
//printf("\n you hit %c. \n",c);
nonblock(NB_DISABLE);
*wd = (wint_t) c;
return 0;
}
}
return -1;
}
/* this function asks user for input from stdin.
* should be blocking and should
* return -1 when ESC was pressed
* return 0 otherwise.
* it receives * wint_t as a parameter.
* when a valid key is press, its value its then updated in that wint_t variable.
*/
int ui_getch_b(wint_t * wd) {
printf("calling uigetch_b\n");
char c;
int i=0;
nonblock(NB_DISABLE);
while (!i) {
usleep(1);
i=kbhit();
if (i!=0) {
c = fgetc(stdin);
if (c == 27) {
nonblock(NB_ENABLE);
return -1;
}
printf("you hit %d %c\n", c, c);
*wd = (wint_t) c;
nonblock(NB_ENABLE);
return 0;
}
}
nonblock(NB_ENABLE);
return -1;
}
// sc_msg - used for sc_info, sc_error and sc_debug macros
void ui_sc_msg(char * s, int type, ...) {
char t[BUFFERSIZE];
va_list args;
va_start(args, type);
vsprintf (t, s, args);
printf("%s\n", t);
va_end(args);
return;
}
// Welcome screen
void ui_do_welcome() {
printf("welcome screen\n");
return;
}
// function that refreshes grid of screen
// if header flag is set, the first column of screen gets refreshed
void ui_update(int header) {
printf("update\n");
printf("value of current cell: %d %d %f\n", currow, curcol, lookat(currow, curcol)->v);
return;
}
// Enable cursor and echo depending on the current mode
void ui_handle_cursor() {
}
// Print multiplier and pending operator on the status bar
void ui_print_mult_pend() {
return;
}
void ui_show_header() {
return;
}
void ui_clr_header(int i) {
return;
}
void ui_print_mode() {
return;
}
// Draw cell content detail in header
void ui_show_celldetails() {
return;
}
// error routine for yacc (gram.y)
void yyerror(char * err) {
printf("%s: %.*s<=%s\n", err, linelim, line, line + linelim);
return;
}
int ui_get_formated_value(struct ent ** p, int col, char * value) {
return -1;
}
void ui_show_text(char * val) {
printf("%s", val);
return;
}
void winchg() {
return;
}
#ifdef XLUA
/* function to print errors of lua scripts */
void ui_bail(lua_State *L, char * msg) {
return;
}
#endif
/* function to read text from stdin */
char * ui_query(char * initial_msg) {
return NULL;
}
void ui_start_colors() {
return;
}
| 1,900 |
393 | <gh_stars>100-1000
/*******************************************************************************
* Copyright 2011 <NAME>
* <p>
* 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
* <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 pl.otros.logview.api.store;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import pl.otros.logview.api.model.LogData;
import pl.otros.logview.api.model.LogDataBuilder;
import pl.otros.logview.api.model.LogDataStore;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertTrue;
public abstract class LogDataStoreTestBase {
protected LogDataStore logDataStore;
public abstract LogDataStore getLogDataStore() throws Exception;
@BeforeMethod
public void prepare() throws Exception {
logDataStore = getLogDataStore();
}
@Test
public void testGetCount() {
// given
// when
for (int i = 0; i < 100; i++) {
logDataStore.add(new LogDataBuilder().withId(i).withDate(new Date(i)).build());
}
// then
assertEquals(100, logDataStore.getCount());
}
@Test
public void testGetCountWithLimit() {
// given
// when
logDataStore.setLimit(20);
for (int i = 0; i < 100; i++) {
logDataStore.add(new LogDataBuilder().withId(i).withDate(new Date(i)).build());
}
// then
assertEquals(20, logDataStore.getCount());
}
@Test
public void testGetCountEmpty() {
// given
// when
// then
assertEquals(0, logDataStore.getCount());
}
@Test
public void testRemove() {
// given
for (int i = 0; i < 100; i++) {
logDataStore.add(new LogDataBuilder().withId(i).withDate(new Date(i)).build());
}
// when
logDataStore.remove(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 20, 21, 22, 23);
assertEquals(10, logDataStore.getLogData(0).getId());
assertEquals(24, logDataStore.getLogData(10).getId());
assertEquals(86, logDataStore.getCount());
}
@Test
public void testGetLogDataInt() {
// given
for (int i = 0; i < 10; i++) {
logDataStore.add(new LogDataBuilder().withId(i).withDate(new Date(i)).build());
}
// when
// then
assertEquals(1, logDataStore.getLogData(1).getId());
}
@Test
public void testGetLogData() {
// given
for (int i = 0; i < 10; i++) {
logDataStore.add(new LogDataBuilder().withId(i).withDate(new Date(i)).build());
}
// when
LogData[] logData = logDataStore.getLogData();
// then
assertEquals(10, logData.length);
for (int i = 0; i < 10; i++) {
assertEquals(i, logData[i].getId());
}
}
@Test
public void testClear() {
// given
for (int i = 0; i < 100; i++) {
logDataStore.add(new LogDataBuilder().withId(i).withDate(new Date(i)).build());
}
// when
logDataStore.clear();
// then
assertEquals(0, logDataStore.getCount());
assertEquals(0, logDataStore.getAllNotes().size());
}
@Test
public void testIterator() {
// given
LogData ld1 = new LogDataBuilder().withId(1).withDate(new Date(1)).build();
LogData ld2 = new LogDataBuilder().withId(2).withDate(new Date(2)).build();
LogData ld3 = new LogDataBuilder().withId(3).withDate(new Date(3)).build();
LogData ld4 = new LogDataBuilder().withId(4).withDate(new Date(4)).build();
LogData[] lds = {ld1, ld2, ld3, ld4};
logDataStore.add(lds);
HashMap<Integer, LogData> logDataList = new HashMap<>();
for (LogData logData : lds) {
logDataList.put(logData.getId(), logData);
}
// when
Iterator<LogData> iterator = logDataStore.iterator();
while (iterator.hasNext()) {
LogData next = iterator.next();
logDataList.remove(next.getId());
}
// then
assertEquals(0, logDataList.size());
}
@Test
public void testGetLogDataIdInRow() {
// given
for (int i = 0; i < 10; i++) {
logDataStore.add(new LogDataBuilder().withId(i).withDate(new Date(i)).build());
}
// when
// then
for (int i = 0; i < 10; i++) {
assertEquals(i, logDataStore.getLogDataIdInRow(i).intValue());
}
}
@Test
public void testAddInDateOrder() {
LogData ld1 = new LogDataBuilder().withId(1).withDate(new Date(1)).build();
LogData ld2 = new LogDataBuilder().withId(2).withDate(new Date(2)).build();
LogData ld3 = new LogDataBuilder().withId(3).withDate(new Date(3)).build();
LogData ld4 = new LogDataBuilder().withId(4).withDate(new Date(4)).build();
LogData ld5 = new LogDataBuilder().withId(5).withDate(new Date(5)).build();
LogData ld6 = new LogDataBuilder().withId(6).withDate(new Date(6)).build();
LogData ld7 = new LogDataBuilder().withId(7).withDate(new Date(7)).build();
LogData ld8 = new LogDataBuilder().withId(8).withDate(new Date(8)).build();
LogData ld9 = new LogDataBuilder().withId(9).withDate(new Date(9)).build();
logDataStore.add(ld4, ld5, ld3);
logDataStore.add(ld2, ld1);
logDataStore.add(ld7, ld8);
logDataStore.add(ld6);
logDataStore.add(ld9);
assertEquals(ld1.getId(), logDataStore.getLogData(0).getId());
assertEquals(ld2.getId(), logDataStore.getLogData(1).getId());
assertEquals(ld3.getId(), logDataStore.getLogData(2).getId());
assertEquals(ld4.getId(), logDataStore.getLogData(3).getId());
assertEquals(ld5.getId(), logDataStore.getLogData(4).getId());
assertEquals(ld6.getId(), logDataStore.getLogData(5).getId());
assertEquals(ld7.getId(), logDataStore.getLogData(6).getId());
assertEquals(ld8.getId(), logDataStore.getLogData(7).getId());
assertEquals(ld9.getId(), logDataStore.getLogData(8).getId());
}
@Test
public void testAddInDateOrderWithTheSameDate() {
LogData ld1 = new LogDataBuilder().withId(1).withDate(new Date(1)).withMessage("m1").build();
LogData ld2 = new LogDataBuilder().withId(2).withDate(new Date(2)).withMessage("m2").build();
LogData ld3 = new LogDataBuilder().withId(3).withDate(new Date(3)).withMessage("m3").build();
LogData ld4 = new LogDataBuilder().withId(4).withDate(new Date(4)).withMessage("m4").build();
LogData ld5 = new LogDataBuilder().withId(5).withDate(new Date(4)).withMessage("m5").build();
LogData ld6 = new LogDataBuilder().withId(6).withDate(new Date(4)).withMessage("m6").build();
LogData ld7 = new LogDataBuilder().withId(7).withDate(new Date(4)).withMessage("m7").build();
LogData ld8 = new LogDataBuilder().withId(8).withDate(new Date(4)).withMessage("m8").build();
LogData ld9 = new LogDataBuilder().withId(9).withDate(new Date(9)).withMessage("m9").build();
logDataStore.add(ld3);
logDataStore.add(ld2, ld1);
logDataStore.add(ld7, ld8, ld6, ld5, ld4);
logDataStore.add(ld9);
assertEquals("m1", logDataStore.getLogData(0).getMessage());
assertEquals("m2", logDataStore.getLogData(1).getMessage());
assertEquals("m3", logDataStore.getLogData(2).getMessage());
assertEquals("m4", logDataStore.getLogData(3).getMessage());
assertEquals("m5", logDataStore.getLogData(4).getMessage());
assertEquals("m6", logDataStore.getLogData(5).getMessage());
assertEquals("m7", logDataStore.getLogData(6).getMessage());
assertEquals("m8", logDataStore.getLogData(7).getMessage());
assertEquals("m9", logDataStore.getLogData(8).getMessage());
}
@Test
public void testAddInDateOrderTheSameDate() {
LogData ld1 = new LogDataBuilder().withId(1).withDate(new Date(1)).build();
LogData ld2 = new LogDataBuilder().withId(2).withDate(new Date(2)).build();
LogData ld3 = new LogDataBuilder().withId(3).withDate(new Date(3)).build();
LogData ld4 = new LogDataBuilder().withId(4).withDate(new Date(4)).build();
LogData ld5 = new LogDataBuilder().withId(5).withDate(new Date(7)).build();
LogData ld6 = new LogDataBuilder().withId(6).withDate(new Date(7)).build();
LogData ld7 = new LogDataBuilder().withId(7).withDate(new Date(7)).build();
LogData ld8 = new LogDataBuilder().withId(8).withDate(new Date(8)).build();
LogData ld9 = new LogDataBuilder().withId(9).withDate(new Date(9)).build();
logDataStore.add(ld4, ld5, ld3);
logDataStore.add(ld2, ld1);
logDataStore.add(ld7, ld8);
logDataStore.add(ld6);
logDataStore.add(ld9);
long lastTime = 0;
for (LogData ld : logDataStore) {
assertTrue(ld.getDate().getTime() >= lastTime);
lastTime = ld.getDate().getTime();
}
}
@Test
public void testAddWithIDGeneration() {
for (int i = 0; i < 10; i++) {
logDataStore.add(new LogDataBuilder().withId(0).withDate(new Date(i)).build());
}
long lastTime = 0;
int lastId = -1;
for (LogData ld : logDataStore) {
assertTrue(ld.getDate().getTime() >= lastTime);
assertEquals(ld.getId(), lastId + 1);
lastTime = ld.getDate().getTime();
lastId = ld.getId();
}
}
}
| 3,633 |
4,050 | package azkaban.execapp.event;
import azkaban.execapp.FlowRunner;
import azkaban.executor.ExecutableFlow;
import azkaban.executor.ExecutableNode;
import azkaban.executor.Status;
import org.junit.Assert;
public class FlowWatcherTestUtil {
public static void assertPipelineLevel1(final FlowRunner runner1,
final FlowRunner runner2) throws Exception {
run(runner1, runner2);
final ExecutableFlow first = runner1.getExecutableFlow();
final ExecutableFlow second = runner2.getExecutableFlow();
for (final ExecutableNode node : second.getExecutableNodes()) {
Assert.assertEquals(Status.SUCCEEDED, node.getStatus());
// check it's start time is after the first's children.
final ExecutableNode watchedNode = first.getExecutableNode(node.getId());
if (watchedNode == null) {
continue;
}
Assert.assertEquals(Status.SUCCEEDED, watchedNode.getStatus());
System.out.println("Node " + node.getId() + " start: "
+ node.getStartTime() + " dependent on " + watchedNode.getId() + " "
+ watchedNode.getEndTime() + " diff: "
+ (node.getStartTime() - watchedNode.getEndTime()));
Assert.assertTrue(node.getStartTime() >= watchedNode.getEndTime());
long minParentDiff = 0;
if (node.getInNodes().size() > 0) {
minParentDiff = Long.MAX_VALUE;
for (final String dependency : node.getInNodes()) {
final ExecutableNode parent = second.getExecutableNode(dependency);
final long diff = node.getStartTime() - parent.getEndTime();
minParentDiff = Math.min(minParentDiff, diff);
}
}
final long diff = node.getStartTime() - watchedNode.getEndTime();
Assert.assertTrue(minParentDiff < 500 || diff < 500);
}
}
public static void assertPipelineLevel2(final FlowRunner runner1, final FlowRunner runner2,
final boolean job4Skipped) throws Exception {
run(runner1, runner2);
assertPipelineLevel2(runner1.getExecutableFlow(), runner2.getExecutableFlow(), job4Skipped);
}
public static void assertPipelineLevel2(final ExecutableFlow first,
final ExecutableFlow second, final boolean job4Skipped) {
for (final ExecutableNode node : second.getExecutableNodes()) {
Assert.assertEquals(Status.SUCCEEDED, node.getStatus());
// check it's start time is after the first's children.
final ExecutableNode watchedNode = first.getExecutableNode(node.getId());
if (watchedNode == null) {
continue;
}
Assert.assertEquals(watchedNode.getStatus(),
job4Skipped && watchedNode.getId().equals("job4") ? Status.READY : Status.SUCCEEDED);
long minDiff = Long.MAX_VALUE;
for (final String watchedChild : watchedNode.getOutNodes()) {
final ExecutableNode child = first.getExecutableNode(watchedChild);
if (child == null) {
continue;
}
Assert.assertEquals(child.getStatus(),
job4Skipped && child.getId().equals("job4") ? Status.READY : Status.SUCCEEDED);
final long diff = node.getStartTime() - child.getEndTime();
minDiff = Math.min(minDiff, diff);
Assert.assertTrue(
"Node " + node.getId() + " start: " + node.getStartTime() + " dependent on "
+ watchedChild + " " + child.getEndTime() + " diff: " + diff,
node.getStartTime() >= child.getEndTime());
}
long minParentDiff = Long.MAX_VALUE;
for (final String dependency : node.getInNodes()) {
final ExecutableNode parent = second.getExecutableNode(dependency);
final long diff = node.getStartTime() - parent.getEndTime();
minParentDiff = Math.min(minParentDiff, diff);
}
Assert.assertTrue("minPipelineTimeDiff:" + minDiff
+ " minDependencyTimeDiff:" + minParentDiff,
minParentDiff < 5000 || minDiff < 5000);
}
}
private static void run(final FlowRunner runner1, final FlowRunner runner2)
throws InterruptedException {
final Thread runner1Thread = new Thread(runner1);
final Thread runner2Thread = new Thread(runner2);
runner1Thread.start();
runner2Thread.start();
runner2Thread.join();
}
}
| 1,589 |
308 | try:
from pylons.templating import render_mako # noqa
# Pylons > 0.9.7
legacy_pylons = False
except ImportError:
# Pylons <= 0.9.7
legacy_pylons = True
| 79 |
3,934 | <reponame>Jasha10/pyright
# This sample tests that a class that derives from Any can be used
# to satisfy a TypeVar.
from typing import Any, TypeVar
T = TypeVar("T")
def foo(self, obj: T, foo: Any) -> T:
# NotImplemented is an instance of a class that derives from Any.
return NotImplemented
| 100 |
2,151 | <reponame>zipated/src
// Copyright 2014 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.
// This file has been auto-generated from the Jinja2 template
// third_party/blink/renderer/bindings/templates/dictionary_v8.h.tmpl
// by the script code_generator_v8.py.
// DO NOT MODIFY!
// clang-format off
#ifndef V8TestPermissiveDictionary_h
#define V8TestPermissiveDictionary_h
#include "third_party/blink/renderer/bindings/core/v8/native_value_traits.h"
#include "third_party/blink/renderer/bindings/core/v8/to_v8_for_core.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_binding_for_core.h"
#include "third_party/blink/renderer/bindings/tests/idls/core/test_permissive_dictionary.h"
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/platform/heap/handle.h"
namespace blink {
class ExceptionState;
class V8TestPermissiveDictionary {
public:
CORE_EXPORT static void ToImpl(v8::Isolate*, v8::Local<v8::Value>, TestPermissiveDictionary&, ExceptionState&);
};
CORE_EXPORT bool toV8TestPermissiveDictionary(const TestPermissiveDictionary&, v8::Local<v8::Object> dictionary, v8::Local<v8::Object> creationContext, v8::Isolate*);
template <class CallbackInfo>
inline void V8SetReturnValue(const CallbackInfo& callbackInfo, TestPermissiveDictionary& impl) {
V8SetReturnValue(callbackInfo, ToV8(impl, callbackInfo.Holder(), callbackInfo.GetIsolate()));
}
template <class CallbackInfo>
inline void V8SetReturnValue(const CallbackInfo& callbackInfo, TestPermissiveDictionary& impl, v8::Local<v8::Object> creationContext) {
V8SetReturnValue(callbackInfo, ToV8(impl, creationContext, callbackInfo.GetIsolate()));
}
template <>
struct NativeValueTraits<TestPermissiveDictionary> : public NativeValueTraitsBase<TestPermissiveDictionary> {
CORE_EXPORT static TestPermissiveDictionary NativeValue(v8::Isolate*, v8::Local<v8::Value>, ExceptionState&);
};
template <>
struct V8TypeOf<TestPermissiveDictionary> {
typedef V8TestPermissiveDictionary Type;
};
} // namespace blink
#endif // V8TestPermissiveDictionary_h
| 726 |
679 | <reponame>Grosskopf/openoffice
/**************************************************************
*
* 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 _UNOCONTROLS_MULTIPLEXER_HXX
#define _UNOCONTROLS_MULTIPLEXER_HXX
//____________________________________________________________________________________________________________
// includes of other projects
//____________________________________________________________________________________________________________
#include <com/sun/star/awt/XKeyListener.hpp>
#include <com/sun/star/awt/XPaintListener.hpp>
#include <com/sun/star/awt/KeyEvent.hpp>
#include <com/sun/star/awt/KeyModifier.hpp>
#include <com/sun/star/awt/XMouseMotionListener.hpp>
#include <com/sun/star/awt/FocusEvent.hpp>
#include <com/sun/star/awt/XWindowListener.hpp>
#include <com/sun/star/awt/XActivateListener.hpp>
#include <com/sun/star/awt/MouseEvent.hpp>
#include <com/sun/star/awt/XTopWindowListener.hpp>
#include <com/sun/star/awt/PaintEvent.hpp>
#include <com/sun/star/awt/InputEvent.hpp>
#include <com/sun/star/awt/KeyGroup.hpp>
#include <com/sun/star/awt/Key.hpp>
#include <com/sun/star/awt/WindowEvent.hpp>
#include <com/sun/star/awt/XMouseListener.hpp>
#include <com/sun/star/awt/KeyFunction.hpp>
#include <com/sun/star/awt/FocusChangeReason.hpp>
#include <com/sun/star/awt/MouseButton.hpp>
#include <com/sun/star/awt/XFocusListener.hpp>
#include <com/sun/star/awt/XTopWindow.hpp>
#include <com/sun/star/awt/XWindow.hpp>
#include <com/sun/star/awt/PosSize.hpp>
#include <cppuhelper/weak.hxx>
#include <cppuhelper/interfacecontainer.hxx>
//____________________________________________________________________________________________________________
// includes of my own project
//____________________________________________________________________________________________________________
//____________________________________________________________________________________________________________
// "namespaces"
//____________________________________________________________________________________________________________
namespace unocontrols{
#define UNO3_OWEAKOBJECT ::cppu::OWeakObject
#define UNO3_XWINDOW ::com::sun::star::awt::XWindow
#define UNO3_REFERENCE ::com::sun::star::uno::Reference
#define UNO3_WEAKREFERENCE ::com::sun::star::uno::WeakReference
#define UNO3_MUTEX ::osl::Mutex
#define UNO3_XWINDOWLISTENER ::com::sun::star::awt::XWindowListener
#define UNO3_XKEYLISTENER ::com::sun::star::awt::XKeyListener
#define UNO3_XMOUSELISTENER ::com::sun::star::awt::XMouseListener
#define UNO3_XMOUSEMOTIONLISTENER ::com::sun::star::awt::XMouseMotionListener
#define UNO3_XPAINTLISTENER ::com::sun::star::awt::XPaintListener
#define UNO3_XTOPWINDOWLISTENER ::com::sun::star::awt::XTopWindowListener
#define UNO3_XFOCUSLISTENER ::com::sun::star::awt::XFocusListener
#define UNO3_ANY ::com::sun::star::uno::Any
#define UNO3_TYPE ::com::sun::star::uno::Type
#define UNO3_RUNTIMEEXCEPTION ::com::sun::star::uno::RuntimeException
#define UNO3_XINTERFACE ::com::sun::star::uno::XInterface
#define UNO3_EVENTOBJECT ::com::sun::star::lang::EventObject
#define UNO3_FOCUSEVENT ::com::sun::star::awt::FocusEvent
#define UNO3_WINDOWEVENT ::com::sun::star::awt::WindowEvent
#define UNO3_KEYEVENT ::com::sun::star::awt::KeyEvent
#define UNO3_MOUSEEVENT ::com::sun::star::awt::MouseEvent
#define UNO3_PAINTEVENT ::com::sun::star::awt::PaintEvent
#define UNO3_OMULTITYPEINTERFACECONTAINERHELPER ::cppu::OMultiTypeInterfaceContainerHelper
//____________________________________________________________________________________________________________
// class
//____________________________________________________________________________________________________________
class OMRCListenerMultiplexerHelper : public UNO3_XFOCUSLISTENER
, public UNO3_XWINDOWLISTENER
, public UNO3_XKEYLISTENER
, public UNO3_XMOUSELISTENER
, public UNO3_XMOUSEMOTIONLISTENER
, public UNO3_XPAINTLISTENER
, public UNO3_XTOPWINDOWLISTENER
, public UNO3_OWEAKOBJECT
{
//____________________________________________________________________________________________________________
// public methods
//____________________________________________________________________________________________________________
public:
//________________________________________________________________________________________________________
// construct/destruct
//________________________________________________________________________________________________________
/**_______________________________________________________________________________________________________
@short constructor
@descr Create a Multiplexer of XWindowEvents.
@seealso -
@param rControl The control. All listeners think that this is the original broadcaster.
@param rPeer The peer from which the original events are dispatched. Null is allowed.
@return -
@onerror -
*/
OMRCListenerMultiplexerHelper( const UNO3_REFERENCE< UNO3_XWINDOW >& xControl ,
const UNO3_REFERENCE< UNO3_XWINDOW >& xPeer );
/**_______________________________________________________________________________________________________
@short copy-constructor
@descr
@seealso -
@param rCopyInstance C++-Reference to instance to make copy from.
@return -
@onerror -
*/
OMRCListenerMultiplexerHelper( const OMRCListenerMultiplexerHelper& aCopyInstance );
/**_______________________________________________________________________________________________________
@short destructor
@descr -
@seealso -
@param -
@return -
@onerror -
*/
~OMRCListenerMultiplexerHelper();
//________________________________________________________________________________________________________
// XInterface
//________________________________________________________________________________________________________
/**_______________________________________________________________________________________________________
@short give answer, if interface is supported
@descr The interfaces are searched by type.
@seealso XInterface
@param "rType" is the type of searched interface.
@return Any information about found interface
@onerror A RuntimeException is thrown.
*/
virtual UNO3_ANY SAL_CALL queryInterface( const UNO3_TYPE& aType ) throw( UNO3_RUNTIMEEXCEPTION );
/**_______________________________________________________________________________________________________
@short increment refcount
@descr -
@seealso XInterface
@seealso release()
@param -
@return -
@onerror A RuntimeException is thrown.
*/
virtual void SAL_CALL acquire() throw();
/**_______________________________________________________________________________________________________
@short decrement refcount
@descr -
@seealso XInterface
@seealso acquire()
@param -
@return -
@onerror A RuntimeException is thrown.
*/
virtual void SAL_CALL release() throw();
//________________________________________________________________________________________________________
// operator
//________________________________________________________________________________________________________
/**_______________________________________________________________________________________________________
@short -
@descr -
@seealso -
@param -
@return -
@onerror -
*/
operator UNO3_REFERENCE< UNO3_XINTERFACE >() const;
/**_______________________________________________________________________________________________________
@short -
@descr -
@seealso -
@param -
@return -
@onerror -
*/
OMRCListenerMultiplexerHelper& operator= ( const OMRCListenerMultiplexerHelper& aCopyInstance );
//________________________________________________________________________________________________________
// container methods
//________________________________________________________________________________________________________
/**_______________________________________________________________________________________________________
@short Remove all listeners from the previous set peer and add the needed listeners to rPeer.
@descr -
@seealso -
@param rPeer The peer from which the original events are dispatched. Null is allowed.
@return -
@onerror -
*/
void setPeer( const UNO3_REFERENCE< UNO3_XWINDOW >& xPeer );
/**_______________________________________________________________________________________________________
@short Remove all listeners and send a disposing message.
@descr -
@seealso -
@param -
@return -
@onerror -
*/
void disposeAndClear();
/**_______________________________________________________________________________________________________
@short Add the specified listener to the source.
@descr -
@seealso -
@param -
@return -
@onerror -
*/
void advise( const UNO3_TYPE& aType ,
const UNO3_REFERENCE< UNO3_XINTERFACE >& xListener );
/**_______________________________________________________________________________________________________
@short Remove the specified listener from the source.
@descr -
@seealso -
@param -
@return -
@onerror -
*/
void unadvise( const UNO3_TYPE& aType ,
const UNO3_REFERENCE< UNO3_XINTERFACE >& xListener );
//________________________________________________________________________________________________________
// XEventListener
//________________________________________________________________________________________________________
/**_______________________________________________________________________________________________________
@short -
@descr -
@seealso -
@seealso -
@param -
@return -
@onerror -
*/
virtual void SAL_CALL disposing(const UNO3_EVENTOBJECT& aSource) throw( UNO3_RUNTIMEEXCEPTION ) ;
//________________________________________________________________________________________________________
// XFocusListener
//________________________________________________________________________________________________________
/**_______________________________________________________________________________________________________
@short -
@descr -
@seealso -
@seealso -
@param -
@return -
@onerror -
*/
virtual void SAL_CALL focusGained(const UNO3_FOCUSEVENT& aEvent ) throw( UNO3_RUNTIMEEXCEPTION ) ;
/**_______________________________________________________________________________________________________
@short -
@descr -
@seealso -
@seealso -
@param -
@return -
@onerror -
*/
virtual void SAL_CALL focusLost(const UNO3_FOCUSEVENT& aEvent ) throw( UNO3_RUNTIMEEXCEPTION ) ;
//________________________________________________________________________________________________________
// XWindowListener
//________________________________________________________________________________________________________
/**_______________________________________________________________________________________________________
@short -
@descr -
@seealso -
@seealso -
@param -
@return -
@onerror -
*/
virtual void SAL_CALL windowResized(const UNO3_WINDOWEVENT& aEvent ) throw( UNO3_RUNTIMEEXCEPTION ) ;
/**_______________________________________________________________________________________________________
@short -
@descr -
@seealso -
@seealso -
@param -
@return -
@onerror -
*/
virtual void SAL_CALL windowMoved(const UNO3_WINDOWEVENT& aEvent ) throw( UNO3_RUNTIMEEXCEPTION ) ;
/**_______________________________________________________________________________________________________
@short -
@descr -
@seealso -
@seealso -
@param -
@return -
@onerror -
*/
virtual void SAL_CALL windowShown(const UNO3_EVENTOBJECT& aEvent ) throw( UNO3_RUNTIMEEXCEPTION ) ;
/**_______________________________________________________________________________________________________
@short -
@descr -
@seealso -
@seealso -
@param -
@return -
@onerror -
*/
virtual void SAL_CALL windowHidden(const UNO3_EVENTOBJECT& aEvent ) throw( UNO3_RUNTIMEEXCEPTION ) ;
//________________________________________________________________________________________________________
// XKeyListener
//________________________________________________________________________________________________________
/**_______________________________________________________________________________________________________
@short -
@descr -
@seealso -
@seealso -
@param -
@return -
@onerror -
*/
virtual void SAL_CALL keyPressed( const UNO3_KEYEVENT& aEvent ) throw( UNO3_RUNTIMEEXCEPTION ) ;
/**_______________________________________________________________________________________________________
@short -
@descr -
@seealso -
@seealso -
@param -
@return -
@onerror -
*/
virtual void SAL_CALL keyReleased( const UNO3_KEYEVENT& aEvent ) throw( UNO3_RUNTIMEEXCEPTION ) ;
//________________________________________________________________________________________________________
// XMouseListener
//________________________________________________________________________________________________________
/**_______________________________________________________________________________________________________
@short -
@descr -
@seealso -
@seealso -
@param -
@return -
@onerror -
*/
virtual void SAL_CALL mousePressed(const UNO3_MOUSEEVENT& aEvent ) throw( UNO3_RUNTIMEEXCEPTION ) ;
/**_______________________________________________________________________________________________________
@short -
@descr -
@seealso -
@seealso -
@param -
@return -
@onerror -
*/
virtual void SAL_CALL mouseReleased(const UNO3_MOUSEEVENT& aEvent ) throw( UNO3_RUNTIMEEXCEPTION ) ;
/**_______________________________________________________________________________________________________
@short -
@descr -
@seealso -
@seealso -
@param -
@return -
@onerror -
*/
virtual void SAL_CALL mouseEntered(const UNO3_MOUSEEVENT& aEvent ) throw( UNO3_RUNTIMEEXCEPTION ) ;
/**_______________________________________________________________________________________________________
@short -
@descr -
@seealso -
@seealso -
@param -
@return -
@onerror -
*/
virtual void SAL_CALL mouseExited(const UNO3_MOUSEEVENT& aEvent ) throw( UNO3_RUNTIMEEXCEPTION ) ;
//________________________________________________________________________________________________________
// XMouseMotionListener
//________________________________________________________________________________________________________
/**_______________________________________________________________________________________________________
@short -
@descr -
@seealso -
@seealso -
@param -
@return -
@onerror -
*/
virtual void SAL_CALL mouseDragged(const UNO3_MOUSEEVENT& aEvent ) throw( UNO3_RUNTIMEEXCEPTION ) ;
/**_______________________________________________________________________________________________________
@short -
@descr -
@seealso -
@seealso -
@param -
@return -
@onerror -
*/
virtual void SAL_CALL mouseMoved(const UNO3_MOUSEEVENT& aEvent ) throw( UNO3_RUNTIMEEXCEPTION ) ;
//________________________________________________________________________________________________________
// XPaintListener
//________________________________________________________________________________________________________
/**_______________________________________________________________________________________________________
@short -
@descr -
@seealso -
@seealso -
@param -
@return -
@onerror -
*/
virtual void SAL_CALL windowPaint(const UNO3_PAINTEVENT& aEvent ) throw( UNO3_RUNTIMEEXCEPTION ) ;
//________________________________________________________________________________________________________
// XTopWindowListener
//________________________________________________________________________________________________________
/**_______________________________________________________________________________________________________
@short -
@descr -
@seealso -
@seealso -
@param -
@return -
@onerror -
*/
virtual void SAL_CALL windowOpened( const UNO3_EVENTOBJECT& aEvent ) throw( UNO3_RUNTIMEEXCEPTION ) ;
/**_______________________________________________________________________________________________________
@short -
@descr -
@seealso -
@seealso -
@param -
@return -
@onerror -
*/
virtual void SAL_CALL windowClosing( const UNO3_EVENTOBJECT& aEvent ) throw( UNO3_RUNTIMEEXCEPTION ) ;
/**_______________________________________________________________________________________________________
@short -
@descr -
@seealso -
@seealso -
@param -
@return -
@onerror -
*/
virtual void SAL_CALL windowClosed( const UNO3_EVENTOBJECT& aEvent ) throw( UNO3_RUNTIMEEXCEPTION ) ;
/**_______________________________________________________________________________________________________
@short -
@descr -
@seealso -
@seealso -
@param -
@return -
@onerror -
*/
virtual void SAL_CALL windowMinimized( const UNO3_EVENTOBJECT& aEvent ) throw( UNO3_RUNTIMEEXCEPTION ) ;
/**_______________________________________________________________________________________________________
@short -
@descr -
@seealso -
@seealso -
@param -
@return -
@onerror -
*/
virtual void SAL_CALL windowNormalized( const UNO3_EVENTOBJECT& aEvent ) throw( UNO3_RUNTIMEEXCEPTION ) ;
/**_______________________________________________________________________________________________________
@short -
@descr -
@seealso -
@seealso -
@param -
@return -
@onerror -
*/
virtual void SAL_CALL windowActivated( const UNO3_EVENTOBJECT& aEvent ) throw( UNO3_RUNTIMEEXCEPTION ) ;
/**_______________________________________________________________________________________________________
@short -
@descr -
@seealso -
@seealso -
@param -
@return -
@onerror -
*/
virtual void SAL_CALL windowDeactivated( const UNO3_EVENTOBJECT& aEvent ) throw( UNO3_RUNTIMEEXCEPTION ) ;
//____________________________________________________________________________________________________________
// protected methods
//____________________________________________________________________________________________________________
protected:
/**_______________________________________________________________________________________________________
@short Remove the listener from the peer.
@descr -
@seealso -
@param xPeer The peer from which the listener is removed.
@param rType The listener type, which specify the type of the listener.
@return -
@onerror -
*/
void impl_adviseToPeer( const UNO3_REFERENCE< UNO3_XWINDOW >& xPeer ,
const UNO3_TYPE& aType );
/**_______________________________________________________________________________________________________
@short Add the listener to the peer.
@descr -
@seealso -
@param xPeer The peer to which the listener is added.
@param rType The listener type, which specify the type of the listener.
@return -
@onerror -
*/
void impl_unadviseFromPeer( const UNO3_REFERENCE< UNO3_XWINDOW >& xPeer ,
const UNO3_TYPE& aType );
//____________________________________________________________________________________________________________
// private variables
//____________________________________________________________________________________________________________
private:
UNO3_MUTEX m_aMutex ;
UNO3_REFERENCE< UNO3_XWINDOW > m_xPeer ; /// The source of the events. Normally this is the peer object.
UNO3_WEAKREFERENCE< UNO3_XWINDOW > m_xControl ;
UNO3_OMULTITYPEINTERFACECONTAINERHELPER m_aListenerHolder ;
}; // class OMRCListenerMultiplexerHelper
} // namespace unocontrols
#endif // ifndef _UNOCONTROLS_MULTIPLEXER_HXX
| 6,353 |
575 |
/*****************************************************************************
*作者:evilbinary on 2017-09-17 13:52:31.
*邮箱:<EMAIL>
******************************************************************************/
#include "c.h"
// //long a64l(const char* )
// long c_a64l (const char* arg0){
// return a64l(arg0);
// }
//void abort(void )
void c_abort (){
abort();
}
//int abs(int )
int c_abs (int arg0){
return abs(arg0);
}
//int atexit()
int c_atexit (void (*arg0)(void) ){
return atexit(arg0);
}
//double atof(const char* )
double c_atof (const char* arg0){
return atof(arg0);
}
//int atoi(const char* )
int c_atoi (const char* arg0){
return atoi(arg0);
}
//long atol(const char* )
long c_atol (const char* arg0){
return atol(arg0);
}
//void* bsearch(const void* ,const void* ,size_t ,size_t )
void* c_bsearch (const void* arg0,const void* arg1,size_t arg2,size_t arg3,int (*arg4)(const void *, const void *)){
return bsearch(arg0,arg1,arg2,arg3,arg4);
}
//void* calloc(size_t ,size_t )
void* c_calloc (size_t arg0,size_t arg1){
return calloc(arg0,arg1);
}
//div_t div(int ,int )
div_t c_div (int arg0,int arg1){
return div(arg0,arg1);
}
// //double drand48(void )
// double c_drand48 (){
// return drand48();
// }
//char* ecvt(double ,int , int* , int* )
char* c_ecvt (double arg0,int arg1, int* arg2, int* arg3){
return ecvt(arg0,arg1,arg2,arg3);
}
// //double erand48(unsigned )
// double c_erand48 (unsigned short int arg0[3] ){
// return erand48(arg0);
// }
//void exit(int )
void c_exit (int arg0){
exit(arg0);
}
//char* fcvt(double ,int , int* , int* )
char* c_fcvt (double arg0,int arg1, int* arg2, int* arg3){
return fcvt(arg0,arg1,arg2,arg3);
}
//void free( void* )
void c_free ( void* arg0){
free(arg0);
}
//char* gcvt(double ,int , char* )
char* c_gcvt (double arg0,int arg1, char* arg2){
return gcvt(arg0,arg1,arg2);
}
//char* getenv(const char* )
char* c_getenv (const char* arg0){
return getenv(arg0);
}
// //int getsubopt(char ,char ,char )
// int c_getsubopt (char** arg0,char *const * arg1,char** arg2){
// return getsubopt(arg0,arg1,arg2);
// }
// //int grantpt(int )
// int c_grantpt (int arg0){
// return grantpt(arg0);
// }
// //char* initstate(unsigned int , char* ,size_t )
// char* c_initstate (unsigned int arg0, char* arg1,size_t arg2){
// return initstate(arg0,arg1,arg2);
// }
// //char* l64a(long )
// char* c_l64a (long arg0){
// return l64a(arg0);
// }
//long labs(long int )
long c_labs (long int arg0){
return labs(arg0);
}
// //void lcong48(unsigned )
// void c_lcong(unsigned short int arg0[7]){
// lcong(arg0);
// }
//ldiv_t ldiv(long int ,long int )
ldiv_t c_ldiv (long int arg0,long int arg1){
return ldiv(arg0,arg1);
}
// //long lrand(void )
// long c_lrand (){
// return lrand();
// }
//void* malloc(size_t )
void* c_malloc (size_t arg0){
return malloc(arg0);
}
//int mblen(const char* ,size_t )
int c_mblen (const char* arg0,size_t arg1){
return mblen(arg0,arg1);
}
//size_t mbstowcs( wchar_t* ,const char* ,size_t )
size_t c_mbstowcs ( wchar_t* arg0,const char* arg1,size_t arg2){
return mbstowcs(arg0,arg1,arg2);
}
//int mbtowc( wchar_t* ,const char* ,size_t )
int c_mbtowc ( wchar_t* arg0,const char* arg1,size_t arg2){
return mbtowc(arg0,arg1,arg2);
}
//char* mktemp( char* )
char* c_mktemp ( char* arg0){
return mktemp(arg0);
}
//int mkstemp( char* )
int c_mkstemp ( char* arg0){
return mkstemp(arg0);
}
// //long mrand48(void )
// long int c_nrand48(unsigned short int arg0[3]){
// return mrand48(arg0);
// }
//char* ptsname(int )
// char* c_ptsname (int arg0){
// return ptsname(arg0);
// }
//int putenv( char* )
int c_putenv ( char* arg0){
return putenv(arg0);
}
//void qsort( void* ,size_t ,size_t )
void c_qsort ( void* arg0,size_t arg1,size_t arg2,int (*arg3)(const void *, const void *) ){
qsort(arg0,arg1,arg2,arg3);
}
//int rand(void )
int c_rand (){
return rand();
}
// //int rand_r( unsigned int* )
// int c_rand_r ( unsigned int* arg0){
// return rand_r(arg0);
// }
// //long random(void )
// long c_random (){
// return random();
// }
//void* realloc( void* ,size_t )
void* c_realloc ( void* arg0,size_t arg1){
return realloc(arg0,arg1);
}
//char* realpath(const char* , char* )
// char* c_realpath (const char* arg0, char* arg1){
// return realpath(arg0,arg1);
// }
// //unsigned short int seed(unsigned )
// unsigned short int c_seed (unsigned short int arg0[3] ){
// return seed(arg0);
// }
// //void setkey(const char* )
// void c_setkey (const char* arg0){
// setkey(arg0);
// }
// //char* setstate(const char* )
// char* c_setstate (const char* arg0){
// return setstate(arg0);
// }
//void srand(unsigned int )
void c_srand (unsigned int arg0){
srand(arg0);
}
// //void srand48(long int )
// void c_srand (long int arg0){
// srand(arg0);
// }
//void srandom(unsigned )
// void c_srandom (unsigned arg0){
// srandom(arg0);
// }
//double strtod(const char* ,char )
double c_strtod (const char* arg0,char** arg1){
return strtod(arg0,arg1);
}
//long strtol(const char* ,char ,int )
long int c_strtol (const char* arg0,char** arg1,int arg2){
return strtol(arg0,arg1,arg2);
}
//unsigned strtoul(const char* ,char ,int )
unsigned long int c_strtoul (const char* arg0,char** arg1,int arg2){
return strtoul(arg0,arg1,arg2);
}
//int system(const char* )
int c_system (const char* arg0){
return system(arg0);
}
// //int unlockpt(int )
// int c_unlockpt (int arg0){
// return unlockpt(arg0);
// }
//size_t wcstombs( char* ,const wchar_t* ,size_t )
size_t c_wcstombs ( char* arg0,const wchar_t* arg1,size_t arg2){
return wcstombs(arg0,arg1,arg2);
}
//int wctomb( char* ,wchar_t )
int c_wctomb ( char* arg0,wchar_t arg1){
return wctomb(arg0,arg1);
}
//double acos(double )
double c_acos (double arg0){
return acos(arg0);
}
//double asin(double )
double c_asin (double arg0){
return asin(arg0);
}
//double atan(double )
double c_atan (double arg0){
return atan(arg0);
}
//double atan2(double ,double )
double c_atan2 (double arg0,double arg1){
return atan2(arg0,arg1);
}
//double ceil(double )
double c_ceil (double arg0){
return ceil(arg0);
}
//double cos(double )
double c_cos (double arg0){
return cos(arg0);
}
//double cosh(double )
double c_cosh (double arg0){
return cosh(arg0);
}
//double exp(double )
double c_exp (double arg0){
return exp(arg0);
}
//double fabs(double )
double c_fabs (double arg0){
return fabs(arg0);
}
//double floor(double )
double c_floor (double arg0){
return floor(arg0);
}
//double fmod(double ,double )
double c_fmod (double arg0,double arg1){
return fmod(arg0,arg1);
}
//double frexp(double , int* )
double c_frexp (double arg0, int* arg1){
return frexp(arg0,arg1);
}
//double ldexp(double ,int )
double c_ldexp (double arg0,int arg1){
return ldexp(arg0,arg1);
}
//double log(double )
double c_log (double arg0){
return log(arg0);
}
//double log10(double )
double c_log10 (double arg0){
return log10(arg0);
}
//double modf(double , double* )
double c_modf (double arg0, double* arg1){
return modf(arg0,arg1);
}
//double pow(double ,double )
double c_pow (double arg0,double arg1){
return pow(arg0,arg1);
}
//double sin(double )
double c_sin (double arg0){
return sin(arg0);
}
//double sinh(double )
double c_sinh (double arg0){
return sinh(arg0);
}
//double sqrt(double )
double c_sqrt (double arg0){
return sqrt(arg0);
}
//double tan(double )
double c_tan (double arg0){
return tan(arg0);
}
//double tanh(double )
double c_tanh (double arg0){
return tanh(arg0);
}
//double erf(double )
double c_erf (double arg0){
return erf(arg0);
}
//double erfc(double )
double c_erfc (double arg0){
return erfc(arg0);
}
// //double gamma(double )
// double c_gamma (double arg0){
// return gamma(arg0);
// }
//double hypot(double ,double )
double c_hypot (double arg0,double arg1){
return hypot(arg0,arg1);
}
//double j0(double )
double c_j0 (double arg0){
return j0(arg0);
}
//double j1(double )
double c_j1 (double arg0){
return j1(arg0);
}
//double jn(int ,double )
double c_jn (int arg0,double arg1){
return jn(arg0,arg1);
}
//double lgamma(double )
double c_lgamma (double arg0){
return lgamma(arg0);
}
//double y0(double )
double c_y0 (double arg0){
return y0(arg0);
}
//double y1(double )
double c_y1 (double arg0){
return y1(arg0);
}
//double yn(int ,double )
double c_yn (int arg0,double arg1){
return yn(arg0,arg1);
}
//int isnan(double )
int c_isnan (double arg0){
return isnan(arg0);
}
//double acosh(double )
double c_acosh (double arg0){
return acosh(arg0);
}
//double asinh(double )
double c_asinh (double arg0){
return asinh(arg0);
}
//double atanh(double )
double c_atanh (double arg0){
return atanh(arg0);
}
//double cbrt(double )
double c_cbrt (double arg0){
return cbrt(arg0);
}
//double expm1(double )
double c_expm1 (double arg0){
return expm1(arg0);
}
//int ilogb(double )
int c_ilogb (double arg0){
return ilogb(arg0);
}
//double log1p(double )
double c_log1p (double arg0){
return log1p(arg0);
}
//double logb(double )
double c_logb (double arg0){
return logb(arg0);
}
//double nextafter(double ,double )
double c_nextafter (double arg0,double arg1){
return nextafter(arg0,arg1);
}
//double remainder(double ,double )
double c_remainder (double arg0,double arg1){
return remainder(arg0,arg1);
}
//double rint(double )
double c_rint (double arg0){
return rint(arg0);
}
// //double scalb(double ,double )
// double c_scalb (double arg0,double arg1){
// return scalb(arg0,arg1);
// }
//void clearerr( FILE* )
void c_clearerr ( FILE* arg0){
clearerr(arg0);
}
// //char* ctermid( char* )
// char* c_ctermid ( char* arg0){
// return ctermid(arg0);
// }
// //char* cuserid( char* )
// char* c_cuserid ( char* arg0){
// return cuserid(arg0);
// }
//int fclose( FILE* )
int c_fclose ( FILE* arg0){
return fclose(arg0);
}
//FILE* fdopen(int ,const char* )
FILE* c_fdopen (int arg0,const char* arg1){
return fdopen(arg0,arg1);
}
//int feof( FILE* )
int c_feof ( FILE* arg0){
return feof(arg0);
}
//int ferror( FILE* )
int c_ferror ( FILE* arg0){
return ferror(arg0);
}
//int fflush( FILE* )
int c_fflush ( FILE* arg0){
return fflush(arg0);
}
//int fgetc( FILE* )
int c_fgetc ( FILE* arg0){
return fgetc(arg0);
}
//int fgetpos( FILE* , fpos_t* )
int c_fgetpos ( FILE* arg0, fpos_t* arg1){
return fgetpos(arg0,arg1);
}
//char* fgets( char* ,int , FILE* )
char* c_fgets ( char* arg0,int arg1, FILE* arg2){
return fgets(arg0,arg1,arg2);
}
//int fileno( FILE* )
int c_fileno ( FILE* arg0){
return fileno(arg0);
}
// //void flockfile( FILE* )
// void c_flockfile ( FILE* arg0){
// flockfile(arg0);
// }
//FILE* fopen(const char* ,const char* )
FILE* c_fopen (const char* arg0,const char* arg1){
return fopen(arg0,arg1);
}
//int fprintf( FILE* ,const char* )
int c_fprintf ( FILE* arg0,const char* arg1,...){
int nret = 0;
va_list args;
va_start(args, arg1);
nret = fprintf(arg0,arg1, args);
va_end(args);
return nret;
}
//int fputc(int , FILE* )
int c_fputc (int arg0, FILE* arg1){
return fputc(arg0,arg1);
}
//int fputs(const char* , FILE* )
int c_fputs (const char* arg0, FILE* arg1){
return fputs(arg0,arg1);
}
//size_t fread( void* ,size_t ,size_t , FILE* )
size_t c_fread (char* arg0,size_t arg1,size_t arg2, FILE* arg3){
return fread(arg0,arg1,arg2,arg3);
}
//FILE* freopen(const char* ,const char* , FILE* )
FILE* c_freopen (const char* arg0,const char* arg1, FILE* arg2){
return freopen(arg0,arg1,arg2);
}
//int fscanf( FILE* ,const char* )
int c_fscanf ( FILE* arg0,const char* arg1,...){
int nret=0;
va_list args;
va_start(args,arg1);
nret=fscanf(arg0,arg1,args);
va_end(args);
return nret;
}
//int fseek( FILE* ,long int ,int )
int c_fseek ( FILE* arg0,long int arg1,int arg2){
return fseek(arg0,arg1,arg2);
}
//int fseeko( FILE* ,off_t ,int )
int c_fseeko ( FILE* arg0,off_t arg1,int arg2){
return fseeko(arg0,arg1,arg2);
}
//int fsetpos( FILE* ,const fpos_t* )
int c_fsetpos ( FILE* arg0,const fpos_t* arg1){
return fsetpos(arg0,arg1);
}
//long ftell( FILE* )
long c_ftell ( FILE* arg0){
return ftell(arg0);
}
//off_t ftello( FILE* )
off_t c_ftello ( FILE* arg0){
return ftello(arg0);
}
// //int ftrylockfile( FILE* )
// int c_ftrylockfile ( FILE* arg0){
// return ftrylockfile(arg0);
// }
// //void funlockfile( FILE* )
// void c_funlockfile ( FILE* arg0){
// funlockfile(arg0);
// }
//size_t fwrite(const void* ,size_t ,size_t , FILE* )
size_t c_fwrite (const void* arg0,size_t arg1,size_t arg2, FILE* arg3){
return fwrite(arg0,arg1,arg2,arg3);
}
//int getc( FILE* )
int c_getc ( FILE* arg0){
return getc(arg0);
}
//int getchar(void )
int c_getchar (){
return getchar();
}
// //int getunlocked( FILE* )
// int c_getunlocked ( FILE* arg0){
// return getunlocked(arg0);
// }
// //int getchar_unlocked(void )
// int c_getchar_unlocked (){
// return getchar_unlocked();
// }
//int getopt(int ,const char* )
int c_getopt(int arg0, char ** arg1,const char* arg2){
return getopt(arg0,arg1,arg2);
}
//char* gets( char* )
char* c_gets ( char* arg0){
return gets(arg0);
}
//int getw( FILE* )
int c_getw ( FILE* arg0){
return getw(arg0);
}
//int pclose( FILE* )
int c_pclose ( FILE* arg0){
return pclose(arg0);
}
//void perror(const char* )
void c_perror (const char* arg0){
perror(arg0);
}
//FILE* popen(const char* ,const char* )
FILE* c_popen (const char* arg0,const char* arg1){
return popen(arg0,arg1);
}
//int printf(const char* )
int c_printf (const char* arg0,...){
int nret=0;
va_list args;
va_start(args,arg0);
nret=printf(arg0,args);
va_end(args);
return nret;
}
//int putc(int , FILE* )
int c_putc (int arg0, FILE* arg1){
return putc(arg0,arg1);
}
//int putchar(int )
int c_putchar (int arg0){
return putchar(arg0);
}
// //int putunlocked(int , FILE* )
// int c_putunlocked (int arg0, FILE* arg1){
// return putunlocked(arg0,arg1);
// }
// //int putchar_unlocked(int )
// int c_putchar_unlocked (int arg0){
// return putchar_unlocked(arg0);
// }
//int puts(const char* )
int c_puts (const char* arg0){
return puts(arg0);
}
//int putw(int , FILE* )
int c_putw (int arg0, FILE* arg1){
return putw(arg0,arg1);
}
//int remove(const char* )
int c_remove (const char* arg0){
return remove(arg0);
}
//int rename(const char* ,const char* )
int c_rename (const char* arg0,const char* arg1){
return rename(arg0,arg1);
}
//void rewind( FILE* )
void c_rewind ( FILE* arg0){
rewind(arg0);
}
//int scanf(const char* )
int c_scanf (const char* arg0,...){
int nret=0;
va_list args;
va_start(args,arg0);
nret=scanf(arg0,args);
va_end(args);
}
//void setbuf( FILE* , char* )
void c_setbuf ( FILE* arg0, char* arg1){
setbuf(arg0,arg1);
}
//int setvbuf( FILE* , char* ,int ,size_t )
int c_setvbuf ( FILE* arg0, char* arg1,int arg2,size_t arg3){
return setvbuf(arg0,arg1,arg2,arg3);
}
//int snprintf( char* ,size_t ,const char* )
int c_snprintf ( char* arg0,size_t arg1,const char* arg2,...){
int nret;
va_list args;
va_start(args, arg0);
nret = snprintf(arg0,arg1,args);
va_end(args);
return nret;
}
//int sprintf( char* ,const char* )
int c_sprintf ( char* arg0,const char* arg1,...){
int nret;
va_list args;
va_start(args, arg1);
nret = sprintf(arg0,arg1,args);
va_end(args);
return nret;
}
//int sscanf(const char* ,const char* )
int c_sscanf (const char* arg0,const char* arg1,...){
int nret;
va_list args;
va_start(args, arg0);
nret = sscanf(arg0,arg1,args);
va_end(args);
return nret;
}
//char* tempnam(const char* ,const char* )
char* c_tempnam (const char* arg0,const char* arg1){
return tempnam(arg0,arg1);
}
//FILE* tmpfile(void )
FILE* c_tmpfile (){
return tmpfile();
}
//char* tmpnam( char* )
char* c_tmpnam ( char* arg0){
return tmpnam(arg0);
}
//int ungetc(int , FILE* )
int c_ungetc (int arg0, FILE* arg1){
return ungetc(arg0,arg1);
}
//int vfprintf( FILE* ,const char* ,va_list )
int c_vfprintf ( FILE* arg0,const char* arg1,va_list arg2){
return vfprintf(arg0,arg1,arg2);
}
//int vprintf(const char* ,va_list )
int c_vprintf (const char* arg0,va_list arg1){
return vprintf(arg0,arg1);
}
//int vsnprintf( char* ,size_t ,const char* ,va_list )
int c_vsnprintf ( char* arg0,size_t arg1,const char* arg2,va_list arg3){
return vsnprintf(arg0,arg1,arg2,arg3);
}
//int vsprintf( char* ,const char* ,va_list )
int c_vsprintf ( char* arg0,const char* arg1,va_list arg2){
return vsprintf(arg0,arg1,arg2);
}
//void* memccpy( void* ,const void* ,int ,size_t )
void* c_memccpy ( void* arg0,const void* arg1,int arg2,size_t arg3){
return memccpy(arg0,arg1,arg2,arg3);
}
//void* memchr(const void* ,int ,size_t )
void* c_memchr (const void* arg0,int arg1,size_t arg2){
return memchr(arg0,arg1,arg2);
}
//int memcmp(const void* ,const void* ,size_t )
int c_memcmp (const void* arg0,const void* arg1,size_t arg2){
return memcmp(arg0,arg1,arg2);
}
//void* memcpy( void* ,const void* ,size_t )
void* c_memcpy ( void* arg0,const void* arg1,size_t arg2){
return memcpy(arg0,arg1,arg2);
}
//void* memmove( void* ,const void* ,size_t )
void* c_memmove ( void* arg0,const void* arg1,size_t arg2){
return memmove(arg0,arg1,arg2);
}
//void* memset( void* ,int ,size_t )
void* c_memset ( void* arg0,int arg1,size_t arg2){
return memset(arg0,arg1,arg2);
}
//char* strcat( char* ,const char* )
char* c_strcat ( char* arg0,const char* arg1){
return strcat(arg0,arg1);
}
//char* strchr(const char* ,int )
char* c_strchr (const char* arg0,int arg1){
return strchr(arg0,arg1);
}
//int strcmp(const char* ,const char* )
int c_strcmp (const char* arg0,const char* arg1){
return strcmp(arg0,arg1);
}
//int strcoll(const char* ,const char* )
int c_strcoll (const char* arg0,const char* arg1){
return strcoll(arg0,arg1);
}
//char* strcpy( char* ,const char* )
char* c_strcpy ( char* arg0,const char* arg1){
return strcpy(arg0,arg1);
}
//size_t strcspn(const char* ,const char* )
size_t c_strcspn (const char* arg0,const char* arg1){
return strcspn(arg0,arg1);
}
//char* strdup(const char* )
char* c_strdup (const char* arg0){
return strdup(arg0);
}
//char* strerror(int )
char* c_strerror (int arg0){
return strerror(arg0);
}
//size_t strlen(const char* )
size_t c_strlen (const char* arg0){
return strlen(arg0);
}
//char* strncat( char* ,const char* ,size_t )
char* c_strncat ( char* arg0,const char* arg1,size_t arg2){
return strncat(arg0,arg1,arg2);
}
//int strncmp(const char* ,const char* ,size_t )
int c_strncmp (const char* arg0,const char* arg1,size_t arg2){
return strncmp(arg0,arg1,arg2);
}
//char* strncpy( char* ,const char* ,size_t )
char* c_strncpy ( char* arg0,const char* arg1,size_t arg2){
return strncpy(arg0,arg1,arg2);
}
//char* strpbrk(const char* ,const char* )
char* c_strpbrk (const char* arg0,const char* arg1){
return strpbrk(arg0,arg1);
}
//char* strrchr(const char* ,int )
char* c_strrchr (const char* arg0,int arg1){
return strrchr(arg0,arg1);
}
//size_t strspn(const char* ,const char* )
size_t c_strspn (const char* arg0,const char* arg1){
return strspn(arg0,arg1);
}
//char* strstr(const char* ,const char* )
char* c_strstr (const char* arg0,const char* arg1){
return strstr(arg0,arg1);
}
//char* strtok( char* ,const char* )
char* c_strtok ( char* arg0,const char* arg1){
return strtok(arg0,arg1);
}
//char* strtok_r( char* ,const char* ,char )
char* c_strtok_r ( char* arg0,const char* arg1,char** arg2){
return strtok_r(arg0,arg1,arg2);
}
//size_t strxfrm( char* ,const char* ,size_t )
size_t c_strxfrm ( char* arg0,const char* arg1,size_t arg2){
return strxfrm(arg0,arg1,arg2);
}
// //char* strndup(const char* s ,size_t n)
// char* c_strndup (const char* arg0,size_t arg1){
// return strndup(arg0,arg1);
// }
// //int bcmp(const void* ,const void* ,size_t )
// int c_bcmp (const void* arg0,const void* arg1,size_t arg2){
// return bcmp(arg0,arg1,arg2);
// }
// //void bcopy(const void* , void* ,size_t )
// void c_bcopy (const void* arg0, void* arg1,size_t arg2){
// bcopy(arg0,arg1,arg2);
// }
// //void bzero( void* ,size_t )
// void c_bzero ( void* arg0,size_t arg1){
// bzero(arg0,arg1);
// }
//int ffs(int )
// int c_ffs (int arg0){
// return ffs(arg0);
// }
//char* index(const char* ,int )
// char* c_index (const char* arg0,int arg1){
// return index(arg0,arg1);
// }
//char* rindex(const char* ,int )
// char* c_rindex (const char* arg0,int arg1){
// return rindex(arg0,arg1);
// }
//int strcasecmp(const char* ,const char* )
int c_strcasecmp (const char* arg0,const char* arg1){
return strcasecmp(arg0,arg1);
}
//int strncasecmp(const char* ,const char* ,size_t )
int c_strncasecmp (const char* arg0,const char* arg1,size_t arg2){
return strncasecmp(arg0,arg1,arg2);
}
| 9,076 |
2,860 | """RoboMaker component for creating a simulation application."""
# 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 logging
from typing import Dict
from create_simulation_app.src.robomaker_create_simulation_app_spec import (
RoboMakerCreateSimulationAppSpec,
RoboMakerCreateSimulationAppInputs,
RoboMakerCreateSimulationAppOutputs,
)
from common.sagemaker_component import (
SageMakerComponent,
ComponentMetadata,
SageMakerJobStatus,
)
from common.boto3_manager import Boto3Manager
from common.common_inputs import SageMakerComponentCommonInputs
@ComponentMetadata(
name="RoboMaker - Create Simulation Application",
description="Creates a simulation application.",
spec=RoboMakerCreateSimulationAppSpec,
)
class RoboMakerCreateSimulationAppComponent(SageMakerComponent):
"""RoboMaker component for creating a simulation application."""
def Do(self, spec: RoboMakerCreateSimulationAppSpec):
self._app_name = (
spec.inputs.app_name
if spec.inputs.app_name
else RoboMakerCreateSimulationAppComponent._generate_unique_timestamped_id(
prefix="SimulationApplication"
)
)
super().Do(spec.inputs, spec.outputs, spec.output_paths)
def _get_job_status(self) -> SageMakerJobStatus:
try:
response = self._rm_client.describe_simulation_application(
application=self._arn
)
status = response["arn"]
if status is not None:
return SageMakerJobStatus(is_completed=True, raw_status=status)
else:
return SageMakerJobStatus(
is_completed=True,
has_error=True,
error_message="No ARN present",
raw_status=status,
)
except Exception as ex:
return SageMakerJobStatus(
is_completed=True,
has_error=True,
error_message=str(ex),
raw_status=str(ex),
)
def _configure_aws_clients(self, inputs: SageMakerComponentCommonInputs):
"""Configures the internal AWS clients for the component.
Args:
inputs: A populated list of user inputs.
"""
self._rm_client = Boto3Manager.get_robomaker_client(
self._get_component_version(),
inputs.region,
endpoint_url=inputs.endpoint_url,
assume_role_arn=inputs.assume_role,
)
self._cw_client = Boto3Manager.get_cloudwatch_client(
inputs.region, assume_role_arn=inputs.assume_role
)
def _after_job_complete(
self,
job: Dict,
request: Dict,
inputs: RoboMakerCreateSimulationAppInputs,
outputs: RoboMakerCreateSimulationAppOutputs,
):
outputs.app_name = self._app_name
outputs.arn = job["arn"]
outputs.version = job["version"]
outputs.revision_id = job["revisionId"]
logging.info(
"Simulation Application in RoboMaker: https://{}.console.aws.amazon.com/robomaker/home?region={}#/simulationApplications/{}".format(
inputs.region, inputs.region, str(outputs.arn).split("/", 1)[1]
)
)
def _on_job_terminated(self):
self._rm_client.delete_simulation_application(application=self._arn)
def _create_job_request(
self,
inputs: RoboMakerCreateSimulationAppInputs,
outputs: RoboMakerCreateSimulationAppOutputs,
) -> Dict:
"""
Documentation: https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/robomaker.html#RoboMaker.Client.create_simulation_application
"""
request = self._get_request_template("robomaker.create.simulation.app")
request["name"] = self._app_name
request["sources"] = inputs.sources
request["simulationSoftwareSuite"]["name"] = inputs.simulation_software_name
request["simulationSoftwareSuite"][
"version"
] = inputs.simulation_software_version
request["robotSoftwareSuite"]["name"] = inputs.robot_software_name
request["robotSoftwareSuite"]["version"] = inputs.robot_software_version
if inputs.rendering_engine_name:
request["renderingEngine"]["name"] = inputs.rendering_engine_name
request["renderingEngine"]["version"] = inputs.rendering_engine_version
else:
request.pop("renderingEngine")
return request
def _submit_job_request(self, request: Dict) -> Dict:
return self._rm_client.create_simulation_application(**request)
def _after_submit_job_request(
self,
job: Dict,
request: Dict,
inputs: RoboMakerCreateSimulationAppInputs,
outputs: RoboMakerCreateSimulationAppOutputs,
):
outputs.arn = self._arn = job["arn"]
logging.info(
f"Created Robomaker Simulation Application with name: {self._app_name}"
)
def _print_logs_for_job(self):
pass
if __name__ == "__main__":
import sys
spec = RoboMakerCreateSimulationAppSpec(sys.argv[1:])
component = RoboMakerCreateSimulationAppComponent()
component.Do(spec)
| 2,379 |
308 | #include <mav_planning_common/utils.h>
#include <mav_trajectory_generation/timing.h>
#include "voxblox_skeleton_planner/skeleton_graph_planner.h"
namespace mav_planning {
SkeletonGraphPlanner::SkeletonGraphPlanner(const ros::NodeHandle& nh,
const ros::NodeHandle& nh_private)
: nh_(nh),
nh_private_(nh_private),
robot_radius_(1.0),
verbose_(true),
shorten_path_(true) {
nh_private_.param("robot_radius", robot_radius_, robot_radius_);
nh_private_.param("verbose", verbose_, verbose_);
nh_private_.param("shorten_path", shorten_path_, shorten_path_);
setRobotRadius(robot_radius_);
skeleton_planner_.setMaxIterations(10000);
}
void SkeletonGraphPlanner::setRobotRadius(double robot_radius) {
robot_radius_ = robot_radius;
skeleton_planner_.setMinEsdfDistance(robot_radius);
mav_planning::PhysicalConstraints constraints;
constraints.robot_radius = robot_radius_;
path_shortener_.setConstraints(constraints);
}
void SkeletonGraphPlanner::setEsdfLayer(
voxblox::Layer<voxblox::EsdfVoxel>* esdf_layer) {
// Set up the A* planners.
skeleton_planner_.setEsdfLayer(esdf_layer);
// Set up shortener.
path_shortener_.setEsdfLayer(esdf_layer);
}
void SkeletonGraphPlanner::setSkeletonLayer(
voxblox::Layer<voxblox::SkeletonVoxel>* skeleton_layer) {
skeleton_planner_.setSkeletonLayer(skeleton_layer);
}
void SkeletonGraphPlanner::setSparseGraph(
voxblox::SparseSkeletonGraph* sparse_graph) {
sparse_graph_planner_.setGraph(sparse_graph);
mav_trajectory_generation::timing::Timer kd_tree_init("skeleton_plan/setup");
sparse_graph_planner_.setup();
kd_tree_init.Stop();
}
// Fixed start and end locations, returns list of waypoints between.
bool SkeletonGraphPlanner::getPathBetweenWaypoints(
const mav_msgs::EigenTrajectoryPoint& start,
const mav_msgs::EigenTrajectoryPoint& goal,
mav_msgs::EigenTrajectoryPoint::Vector* solution) {
voxblox::Point start_point = start.position_W.cast<voxblox::FloatingPoint>();
voxblox::Point goal_point = goal.position_W.cast<voxblox::FloatingPoint>();
mav_trajectory_generation::timing::Timer graph_timer("skeleton_plan");
voxblox::AlignedVector<voxblox::Point> graph_coordinate_path;
bool success = sparse_graph_planner_.getPath(start_point, goal_point,
&graph_coordinate_path);
mav_msgs::EigenTrajectoryPointVector graph_path;
convertCoordinatePathToPath(graph_coordinate_path, &graph_path);
ROS_INFO("Got sparse graph path.");
if (!success) {
return false;
}
voxblox::AlignedVector<voxblox::Point> exact_start_path, exact_goal_path;
success &= skeleton_planner_.getPathInEsdf(
start_point, graph_coordinate_path.front(), &exact_start_path);
success &= skeleton_planner_.getPathInEsdf(graph_coordinate_path.back(),
goal_point, &exact_goal_path);
graph_coordinate_path.insert(graph_coordinate_path.begin(),
exact_start_path.begin(),
exact_start_path.end());
graph_coordinate_path.insert(graph_coordinate_path.end(),
exact_goal_path.begin(), exact_goal_path.end());
convertCoordinatePathToPath(graph_coordinate_path, &graph_path);
ROS_INFO("Got ESDF path.");
if (shorten_path_) {
shortenPath(graph_path, solution);
} else {
*solution = graph_path;
}
return success;
}
void SkeletonGraphPlanner::convertCoordinatePathToPath(
const voxblox::AlignedVector<voxblox::Point>& coordinate_path,
mav_msgs::EigenTrajectoryPointVector* path) const {
CHECK_NOTNULL(path);
path->clear();
path->reserve(coordinate_path.size());
for (const voxblox::Point& voxblox_point : coordinate_path) {
mav_msgs::EigenTrajectoryPoint point;
point.position_W = voxblox_point.cast<double>();
path->push_back(point);
}
}
void SkeletonGraphPlanner::shortenPath(
const mav_msgs::EigenTrajectoryPoint::Vector& path_in,
mav_msgs::EigenTrajectoryPoint::Vector* path_out) const {
path_shortener_.shortenPath(path_in, path_out);
}
} // namespace mav_planning
| 1,692 |
310 | <filename>deslib/des/des_mi.py
# coding=utf-8
# Author: <NAME> <<EMAIL>>
#
# License: BSD 3 clause
import numpy as np
from sklearn.preprocessing import normalize
from deslib.base import BaseDS
from deslib.util.aggregation import sum_votes_per_class
class DESMI(BaseDS):
"""Dynamic ensemble Selection for multi-class imbalanced datasets (DES-MI).
Parameters
----------
pool_classifiers : list of classifiers (Default = None)
The generated_pool of classifiers trained for the corresponding
classification problem. Each base classifiers should support the method
"predict". If None, then the pool of classifiers is a bagging
classifier.
k : int (Default = 7)
Number of neighbors used to estimate the competence of the base
classifiers.
DFP : Boolean (Default = False)
Determines if the dynamic frienemy pruning is applied.
with_IH : Boolean (Default = False)
Whether the hardness level of the region of competence is used to
decide between using the DS algorithm or the KNN for classification of
a given query sample.
safe_k : int (default = None)
The size of the indecision region.
IH_rate : float (default = 0.3)
Hardness threshold. If the hardness level of the competence region is
lower than the IH_rate the KNN classifier is used. Otherwise, the DS
algorithm is used for classification.
alpha : float (Default = 0.9)
Scaling coefficient to regulate the weight value
random_state : int, RandomState instance or None, optional (default=None)
If int, random_state is the seed used by the random number generator;
If RandomState instance, random_state is the random number generator;
If None, the random number generator is the RandomState instance used
by `np.random`.
knn_classifier : {'knn', 'faiss', None} (Default = 'knn')
The algorithm used to estimate the region of competence:
- 'knn' will use :class:`KNeighborsClassifier` from sklearn
:class:`KNNE` available on `deslib.utils.knne`
- 'faiss' will use Facebook's Faiss similarity search through the
class :class:`FaissKNNClassifier`
- None, will use sklearn :class:`KNeighborsClassifier`.
knne : bool (Default=False)
Whether to use K-Nearest Neighbor Equality (KNNE) for the region
of competence estimation.
DSEL_perc : float (Default = 0.5)
Percentage of the input data used to fit DSEL.
Note: This parameter is only used if the pool of classifier is None or
unfitted.
voting : {'hard', 'soft'}, default='hard'
If 'hard', uses predicted class labels for majority rule voting.
Else if 'soft', predicts the class label based on the argmax of
the sums of the predicted probabilities, which is recommended for
an ensemble of well-calibrated classifiers.
n_jobs : int, default=-1
The number of parallel jobs to run. None means 1 unless in
a joblib.parallel_backend context. -1 means using all processors.
Doesn’t affect fit method.
References
----------
<NAME>.; <NAME>.; <NAME>.; <NAME>. & <NAME>.
"Dynamic ensemble selection for multi-class
imbalanced datasets." Information Sciences, 2018, 445-446, 22 - 37
<NAME>., <NAME>, and <NAME>. "Dynamic selection
of classifiers—a comprehensive review."
Pattern Recognition 47.11 (2014): 3665-3680
<NAME>, <NAME>, and <NAME>, “Dynamic classifier
selection: Recent advances and perspectives,”
Information Fusion, vol. 41, pp. 195 – 216, 2018.
"""
def __init__(self, pool_classifiers=None, k=7, pct_accuracy=0.4, alpha=0.9,
DFP=False, with_IH=False, safe_k=None,
IH_rate=0.30, random_state=None, knn_classifier='knn',
knne=False, DSEL_perc=0.5, n_jobs=-1, voting='hard'):
super(DESMI, self).__init__(pool_classifiers=pool_classifiers,
k=k,
DFP=DFP,
with_IH=with_IH,
safe_k=safe_k,
IH_rate=IH_rate,
random_state=random_state,
knn_classifier=knn_classifier,
knne=knne,
DSEL_perc=DSEL_perc,
n_jobs=n_jobs)
self.alpha = alpha
self.pct_accuracy = pct_accuracy
self.voting = voting
def estimate_competence(self, competence_region, distances=None,
predictions=None):
"""estimate the competence level of each base classifier :math:`c_{i}`
for the classification of the query sample. Returns a ndarray
containing the competence level of each base classifier.
The competence is estimated using the accuracy criteria.
The accuracy is estimated by the weighted results of classifiers who
correctly classify the members in the competence region. The weight
of member :math:`x_i` is related to the number of samples of the same
class of :math:`x_i` in the training dataset.
For detail, please see the first reference, Algorithm 2.
Parameters
----------
competence_region : array of shape (n_samples, n_neighbors)
Indices of the k nearest neighbors according for each test sample.
distances : array of shape (n_samples, n_neighbors)
Distances from the k nearest neighbors to the query.
predictions : array of shape (n_samples, n_classifiers)
Predictions of the base classifiers for all test examples.
Returns
-------
accuracy : array of shape = [n_samples, n_classifiers}
Local Accuracy estimates (competences) of the base classifiers
for all query samples.
"""
# calculate the weight
class_frequency = np.bincount(self.DSEL_target_)
targets = self.DSEL_target_[competence_region]
num = class_frequency[targets]
weight = 1. / (1 + np.exp(self.alpha * num))
weight = normalize(weight, norm='l1')
correct_num = self.DSEL_processed_[competence_region, :]
correct = np.zeros((competence_region.shape[0], self.k_,
self.n_classifiers_))
for i in range(self.n_classifiers_):
correct[:, :, i] = correct_num[:, :, i] * weight
# Apply the weights to each sample for each base classifier
competence = correct_num * weight[:, :, np.newaxis]
# calculate the classifiers mean competence for all
# samples/base classifier
competence = np.sum(competence, axis=1)
return competence
def select(self, competences):
"""Select an ensemble containing the N most accurate classifiers for
the classification of the query sample.
Parameters
----------
competences : array of shape (n_samples, n_classifiers)
Competence estimates of each base classifiers for all query
samples.
Returns
-------
selected_classifiers : array of shape = [n_samples, self.N]
Matrix containing the indices of the N selected base classifier
for each test example.
"""
# Check if the accuracy and diversity arrays have
# the correct dimensionality.
if competences.ndim < 2:
competences = competences.reshape(1, -1)
# sort the array to remove the most accurate classifiers
selected_classifiers = np.argsort(competences, axis=1)
selected_classifiers = selected_classifiers[:, ::-1][:, 0:self.N_]
return selected_classifiers
def classify_with_ds(self, predictions, probabilities=None,
neighbors=None, distances=None, DFP_mask=None):
"""Predicts the label of the corresponding query sample.
Parameters
----------
predictions : array of shape (n_samples, n_classifiers)
Predictions of the base classifiers for all test examples.
probabilities : array of shape (n_samples, n_classifiers, n_classes)
Probabilities estimates of each base classifier for all test
examples.
neighbors : array of shape (n_samples, n_neighbors)
Indices of the k nearest neighbors according for each test sample.
distances : array of shape (n_samples, n_neighbors)
Distances from the k nearest neighbors to the query
DFP_mask : array of shape (n_samples, n_classifiers)
Mask containing 1 for the selected base classifier and 0 otherwise.
Notes
------
Different than other DES techniques, this method only select N
candidates from the pool of classifiers.
Returns
-------
predicted_label : array of shape (n_samples)
Predicted class label for each test example.
"""
proba = self.predict_proba_with_ds(predictions, probabilities,
neighbors, distances, DFP_mask)
predicted_label = proba.argmax(axis=1)
return predicted_label
def predict_proba_with_ds(self, predictions, probabilities,
competence_region=None, distances=None,
DFP_mask=None):
"""Predicts the posterior probabilities of the corresponding
query sample.
Parameters
----------
predictions : array of shape (n_samples, n_classifiers)
Predictions of the base classifiers for all test examples.
probabilities : array of shape (n_samples, n_classifiers, n_classes)
Probabilities estimates of each base classifier for all test
examples.
competence_region : array of shape (n_samples, n_neighbors)
Indices of the k nearest neighbors according for each test sample.
distances : array of shape (n_samples, n_neighbors)
Distances from the k nearest neighbors to each test
sample.
DFP_mask : array of shape (n_samples, n_classifiers)
Mask containing 1 for the selected base classifier and 0 otherwise.
Returns
-------
predicted_proba : array = [n_samples, n_classes]
Probability estimates for all test examples.
"""
accuracy = self.estimate_competence(
competence_region=competence_region,
distances=distances)
if self.DFP:
accuracy = accuracy * DFP_mask
selected_classifiers = self.select(accuracy)
if self.voting == 'hard':
votes = predictions[np.arange(predictions.shape[0])[:, None],
selected_classifiers]
votes = sum_votes_per_class(votes, self.n_classes_)
predicted_proba = votes / votes.sum(axis=1)[:, None]
else:
ensemble_proba = probabilities[
np.arange(probabilities.shape[0])[:, None],
selected_classifiers, :]
predicted_proba = np.mean(ensemble_proba, axis=1)
return predicted_proba
def _validate_parameters(self):
"""Check if the parameters passed as argument are correct.
Raises
------
ValueError
If the hyper-parameters are incorrect.
"""
super(DESMI, self)._validate_parameters()
self.N_ = int(self.n_classifiers_ * self.pct_accuracy)
if self.N_ <= 0:
raise ValueError("The value of N_ should be higher than 0"
"N_ = {}".format(self.N_))
# The value of Scaling coefficient (alpha) should be positive
# to add more weight to the minority class
if self.alpha <= 0:
raise ValueError("The value of alpha should be higher than 0"
"alpha = {}".format(self.alpha))
if not isinstance(self.alpha, np.float):
raise TypeError("parameter alpha should be a float!")
if self.pct_accuracy <= 0. or self.pct_accuracy > 1:
raise ValueError(
"The value of pct_accuracy should be higher than 0 and lower"
" or equal to 1, "
"pct_accuracy = {}".format(self.pct_accuracy))
if self.voting not in ['soft', 'hard']:
raise ValueError('Invalid value for parameter "voting".'
' "voting" should be one of these options '
'{selection, hybrid, weighting}')
if self.voting == 'soft':
self._check_predict_proba()
| 5,467 |
368 | /*
Plugin-SDK (Grand Theft Auto San Andreas) header file
Authors: GTA Community. See more here
https://github.com/DK22Pac/plugin-sdk
Do not delete this comment block. Respect others' work!
*/
#include "PluginBase.h"
namespace plugin {
META_BEGIN(CGangWars::InitAtStartOfGame)
static int address;
static int global_address;
static const int id = 0x443920;
static const bool is_virtual = false;
static const int vtable_index = -1;
using mv_addresses_t = MvAddresses<0x443920, 0, 0, 0, 0, 0>;
// total references count: 10us (2), 10ushl (0), 10eu (0), 11us (0), 11eu (0), sr2 (0), sr2lv (0)
using refs_t = RefList<
0x53BD02, GAME_10US_COMPACT, H_CALL, 0x53BCF0, 1,
0x5BF8D6, GAME_10US_COMPACT, H_CALL, 0x5BF840, 1>;
using def_t = void();
static const int cb_priority = PRIORITY_BEFORE;
using calling_convention_t = CallingConventions::Cdecl;
using args_t = ArgPick<ArgTypes<>>;
META_END
META_BEGIN(CGangWars::AddKillToProvocation)
static int address;
static int global_address;
static const int id = 0x443950;
static const bool is_virtual = false;
static const int vtable_index = -1;
using mv_addresses_t = MvAddresses<0x443950, 0, 0, 0, 0, 0>;
// total references count: 10us (1), 10ushl (0), 10eu (0), 11us (0), 11eu (0), sr2 (0), sr2lv (0)
using refs_t = RefList<
0x43DEE9, GAME_10US_COMPACT, H_CALL, 0x43DCD0, 1>;
using def_t = void(int);
static const int cb_priority = PRIORITY_BEFORE;
using calling_convention_t = CallingConventions::Cdecl;
using args_t = ArgPick<ArgTypes<int>, 0>;
META_END
META_BEGIN(CGangWars::DontCreateCivilians)
static int address;
static int global_address;
static const int id = 0x4439C0;
static const bool is_virtual = false;
static const int vtable_index = -1;
using mv_addresses_t = MvAddresses<0x4439C0, 0, 0, 0, 0, 0>;
// total references count: 10us (2), 10ushl (0), 10eu (0), 11us (0), 11eu (0), sr2 (0), sr2lv (0)
using refs_t = RefList<
0x4341D1, GAME_10US_COMPACT, H_CALL, 0x4341C0, 1,
0x61477A, GAME_10US_COMPACT, H_CALL, 0x614720, 1>;
using def_t = bool();
static const int cb_priority = PRIORITY_BEFORE;
using calling_convention_t = CallingConventions::Cdecl;
using args_t = ArgPick<ArgTypes<>>;
META_END
META_BEGIN(CGangWars::PedStreamedInForThisGang)
static int address;
static int global_address;
static const int id = 0x4439D0;
static const bool is_virtual = false;
static const int vtable_index = -1;
using mv_addresses_t = MvAddresses<0x4439D0, 0, 0, 0, 0, 0>;
// total references count: 10us (5), 10ushl (0), 10eu (0), 11us (0), 11eu (0), sr2 (0), sr2lv (0)
using refs_t = RefList<
0x4448BE, GAME_10US_COMPACT, H_CALL, 0x444810, 1,
0x4448FB, GAME_10US_COMPACT, H_CALL, 0x444810, 2,
0x444A53, GAME_10US_COMPACT, H_CALL, 0x444810, 3,
0x444A69, GAME_10US_COMPACT, H_CALL, 0x444810, 4,
0x4453F3, GAME_10US_COMPACT, H_CALL, 0x4453D0, 1>;
using def_t = bool(int);
static const int cb_priority = PRIORITY_BEFORE;
using calling_convention_t = CallingConventions::Cdecl;
using args_t = ArgPick<ArgTypes<int>, 0>;
META_END
META_BEGIN(CGangWars::PickStreamedInPedForThisGang)
static int address;
static int global_address;
static const int id = 0x443A20;
static const bool is_virtual = false;
static const int vtable_index = -1;
using mv_addresses_t = MvAddresses<0x443A20, 0, 0, 0, 0, 0>;
// total references count: 10us (2), 10ushl (0), 10eu (0), 11us (0), 11eu (0), sr2 (0), sr2lv (0)
using refs_t = RefList<
0x444D8A, GAME_10US_COMPACT, H_CALL, 0x444810, 1,
0x44554B, GAME_10US_COMPACT, H_CALL, 0x4453D0, 1>;
using def_t = bool(int, int *);
static const int cb_priority = PRIORITY_BEFORE;
using calling_convention_t = CallingConventions::Cdecl;
using args_t = ArgPick<ArgTypes<int,int *>, 0,1>;
META_END
META_BEGIN(CGangWars::GangWarGoingOn)
static int address;
static int global_address;
static const int id = 0x443AA0;
static const bool is_virtual = false;
static const int vtable_index = -1;
using mv_addresses_t = MvAddresses<0x443AA0, 0, 0, 0, 0, 0>;
// total references count: 10us (1), 10ushl (0), 10eu (0), 11us (0), 11eu (0), sr2 (0), sr2lv (0)
using refs_t = RefList<
0x471A66, GAME_10US_COMPACT, H_CALL, 0x470A90, 1>;
using def_t = bool();
static const int cb_priority = PRIORITY_BEFORE;
using calling_convention_t = CallingConventions::Cdecl;
using args_t = ArgPick<ArgTypes<>>;
META_END
META_BEGIN(CGangWars::GangWarFightingGoingOn)
static int address;
static int global_address;
static const int id = 0x443AC0;
static const bool is_virtual = false;
static const int vtable_index = -1;
using mv_addresses_t = MvAddresses<0x443AC0, 0, 0, 0, 0, 0>;
// total references count: 10us (9), 10ushl (0), 10eu (0), 11us (0), 11eu (0), sr2 (0), sr2lv (0)
using refs_t = RefList<
0x424DEE, GAME_10US_COMPACT, H_CALL, 0x424CE0, 1,
0x42F9D1, GAME_10US_COMPACT, H_CALL, 0x42F9C0, 1,
0x4301C1, GAME_10US_COMPACT, H_CALL, 0x430050, 1,
0x47B677, GAME_10US_COMPACT, H_CALL, 0x47A760, 1,
0x562167, GAME_10US_COMPACT, H_CALL, 0x562120, 1,
0x56218E, GAME_10US_COMPACT, H_CALL, 0x562120, 2,
0x60FCC2, GAME_10US_COMPACT, H_CALL, 0x60FBD0, 1,
0x612045, GAME_10US_COMPACT, H_CALL, 0x611FC0, 1,
0x6147F5, GAME_10US_COMPACT, H_CALL, 0x614720, 1>;
using def_t = bool();
static const int cb_priority = PRIORITY_BEFORE;
using calling_convention_t = CallingConventions::Cdecl;
using args_t = ArgPick<ArgTypes<>>;
META_END
META_BEGIN(CGangWars::DoesPlayerControlThisZone)
static int address;
static int global_address;
static const int id = 0x443AE0;
static const bool is_virtual = false;
static const int vtable_index = -1;
using mv_addresses_t = MvAddresses<0x443AE0, 0, 0, 0, 0, 0>;
// total references count: 10us (0), 10ushl (0), 10eu (0), 11us (0), 11eu (0), sr2 (0), sr2lv (0)
using refs_t = RefList<>;
using def_t = bool(CZoneInfo *);
static const int cb_priority = PRIORITY_BEFORE;
using calling_convention_t = CallingConventions::Cdecl;
using args_t = ArgPick<ArgTypes<CZoneInfo *>, 0>;
META_END
META_BEGIN(CGangWars::PickZoneToAttack)
static int address;
static int global_address;
static const int id = 0x443B00;
static const bool is_virtual = false;
static const int vtable_index = -1;
using mv_addresses_t = MvAddresses<0x443B00, 0, 0, 0, 0, 0>;
// total references count: 10us (1), 10ushl (0), 10eu (0), 11us (0), 11eu (0), sr2 (0), sr2lv (0)
using refs_t = RefList<
0x444303, GAME_10US_COMPACT, H_CALL, 0x444300, 1>;
using def_t = bool();
static const int cb_priority = PRIORITY_BEFORE;
using calling_convention_t = CallingConventions::Cdecl;
using args_t = ArgPick<ArgTypes<>>;
META_END
META_BEGIN(CGangWars::TellStreamingWhichGangsAreNeeded)
static int address;
static int global_address;
static const int id = 0x443D50;
static const bool is_virtual = false;
static const int vtable_index = -1;
using mv_addresses_t = MvAddresses<0x443D50, 0, 0, 0, 0, 0>;
// total references count: 10us (1), 10ushl (0), 10eu (0), 11us (0), 11eu (0), sr2 (0), sr2lv (0)
using refs_t = RefList<
0x40AABF, GAME_10US_COMPACT, H_CALL, 0x40AA10, 1>;
using def_t = void(int *);
static const int cb_priority = PRIORITY_BEFORE;
using calling_convention_t = CallingConventions::Cdecl;
using args_t = ArgPick<ArgTypes<int *>, 0>;
META_END
META_BEGIN(CGangWars::CalculateTimeTillNextAttack)
static int address;
static int global_address;
static const int id = 0x443DB0;
static const bool is_virtual = false;
static const int vtable_index = -1;
using mv_addresses_t = MvAddresses<0x443DB0, 0, 0, 0, 0, 0>;
// total references count: 10us (3), 10ushl (0), 10eu (0), 11us (0), 11eu (0), sr2 (0), sr2lv (0)
using refs_t = RefList<
0x446B25, GAME_10US_COMPACT, H_CALL, 0x446610, 1,
0x446BCB, GAME_10US_COMPACT, H_CALL, 0x446610, 2,
0x446D49, GAME_10US_COMPACT, H_CALL, 0x446610, 3>;
using def_t = unsigned int();
static const int cb_priority = PRIORITY_BEFORE;
using calling_convention_t = CallingConventions::Cdecl;
using args_t = ArgPick<ArgTypes<>>;
META_END
META_BEGIN(CGangWars::UpdateTerritoryUnderControlPercentage)
static int address;
static int global_address;
static const int id = 0x443DE0;
static const bool is_virtual = false;
static const int vtable_index = -1;
using mv_addresses_t = MvAddresses<0x443DE0, 0, 0, 0, 0, 0>;
// total references count: 10us (1), 10ushl (0), 10eu (0), 11us (0), 11eu (0), sr2 (0), sr2lv (0)
using refs_t = RefList<
0x44665D, GAME_10US_COMPACT, H_CALL, 0x446610, 1>;
using def_t = void();
static const int cb_priority = PRIORITY_BEFORE;
using calling_convention_t = CallingConventions::Cdecl;
using args_t = ArgPick<ArgTypes<>>;
META_END
META_BEGIN(CGangWars::CanPlayerStartAGangWarHere)
static int address;
static int global_address;
static const int id = 0x443F80;
static const bool is_virtual = false;
static const int vtable_index = -1;
using mv_addresses_t = MvAddresses<0x443F80, 0, 0, 0, 0, 0>;
// total references count: 10us (3), 10ushl (0), 10eu (0), 11us (0), 11eu (0), sr2 (0), sr2lv (0)
using refs_t = RefList<
0x4460A0, GAME_10US_COMPACT, H_CALL, 0x446050, 1,
0x5724F9, GAME_10US_COMPACT, H_CALL, 0x572440, 1,
0x5866F7, GAME_10US_COMPACT, H_CALL, 0x586650, 1>;
using def_t = bool(CZoneInfo *);
static const int cb_priority = PRIORITY_BEFORE;
using calling_convention_t = CallingConventions::Cdecl;
using args_t = ArgPick<ArgTypes<CZoneInfo *>, 0>;
META_END
META_BEGIN(CGangWars::ClearSpecificZonesToTriggerGangWar)
static int address;
static int global_address;
static const int id = 0x443FF0;
static const bool is_virtual = false;
static const int vtable_index = -1;
using mv_addresses_t = MvAddresses<0x443FF0, 0, 0, 0, 0, 0>;
// total references count: 10us (3), 10ushl (0), 10eu (0), 11us (0), 11eu (0), sr2 (0), sr2lv (0)
using refs_t = RefList<
0x468601, GAME_10US_COMPACT, H_CALL, 0x468560, 1,
0x476646, GAME_10US_COMPACT, H_CALL, 0x4762D0, 1,
0x618F26, GAME_10US_COMPACT, H_CALL, 0x618E90, 1>;
using def_t = void();
static const int cb_priority = PRIORITY_BEFORE;
using calling_convention_t = CallingConventions::Cdecl;
using args_t = ArgPick<ArgTypes<>>;
META_END
META_BEGIN(CGangWars::SetSpecificZoneToTriggerGangWar)
static int address;
static int global_address;
static const int id = 0x444010;
static const bool is_virtual = false;
static const int vtable_index = -1;
using mv_addresses_t = MvAddresses<0x444010, 0, 0, 0, 0, 0>;
// total references count: 10us (1), 10ushl (0), 10eu (0), 11us (0), 11eu (0), sr2 (0), sr2lv (0)
using refs_t = RefList<
0x476630, GAME_10US_COMPACT, H_CALL, 0x4762D0, 1>;
using def_t = void(int);
static const int cb_priority = PRIORITY_BEFORE;
using calling_convention_t = CallingConventions::Cdecl;
using args_t = ArgPick<ArgTypes<int>, 0>;
META_END
META_BEGIN(CGangWars::CheerVictory)
static int address;
static int global_address;
static const int id = 0x444040;
static const bool is_virtual = false;
static const int vtable_index = -1;
using mv_addresses_t = MvAddresses<0x444040, 0, 0, 0, 0, 0>;
// total references count: 10us (1), 10ushl (0), 10eu (0), 11us (0), 11eu (0), sr2 (0), sr2lv (0)
using refs_t = RefList<
0x446411, GAME_10US_COMPACT, H_CALL, 0x446400, 1>;
using def_t = void();
static const int cb_priority = PRIORITY_BEFORE;
using calling_convention_t = CallingConventions::Cdecl;
using args_t = ArgPick<ArgTypes<>>;
META_END
META_BEGIN(CGangWars::StartDefensiveGangWar)
static int address;
static int global_address;
static const int id = 0x444300;
static const bool is_virtual = false;
static const int vtable_index = -1;
using mv_addresses_t = MvAddresses<0x444300, 0, 0, 0, 0, 0>;
// total references count: 10us (1), 10ushl (0), 10eu (0), 11us (0), 11eu (0), sr2 (0), sr2lv (0)
using refs_t = RefList<
0x446E46, GAME_10US_COMPACT, H_CALL, 0x446610, 1>;
using def_t = void();
static const int cb_priority = PRIORITY_BEFORE;
using calling_convention_t = CallingConventions::Cdecl;
using args_t = ArgPick<ArgTypes<>>;
META_END
META_BEGIN(CGangWars::ClearTheStreets)
static int address;
static int global_address;
static const int id = 0x4444B0;
static const bool is_virtual = false;
static const int vtable_index = -1;
using mv_addresses_t = MvAddresses<0x4444B0, 0, 0, 0, 0, 0>;
// total references count: 10us (1), 10ushl (0), 10eu (0), 11us (0), 11eu (0), sr2 (0), sr2lv (0)
using refs_t = RefList<
0x4462E8, GAME_10US_COMPACT, H_CALL, 0x446050, 1>;
using def_t = void();
static const int cb_priority = PRIORITY_BEFORE;
using calling_convention_t = CallingConventions::Cdecl;
using args_t = ArgPick<ArgTypes<>>;
META_END
META_BEGIN(CGangWars::TellGangMembersTo)
static int address;
static int global_address;
static const int id = 0x444530;
static const bool is_virtual = false;
static const int vtable_index = -1;
using mv_addresses_t = MvAddresses<0x444530, 0, 0, 0, 0, 0>;
// total references count: 10us (2), 10ushl (0), 10eu (0), 11us (0), 11eu (0), sr2 (0), sr2lv (0)
using refs_t = RefList<
0x446395, GAME_10US_COMPACT, H_CALL, 0x446050, 1,
0x446470, GAME_10US_COMPACT, H_CALL, 0x446400, 1>;
using def_t = void(int);
static const int cb_priority = PRIORITY_BEFORE;
using calling_convention_t = CallingConventions::Cdecl;
using args_t = ArgPick<ArgTypes<int>, 0>;
META_END
META_BEGIN(CGangWars::CreateAttackWave)
static int address;
static int global_address;
static const int id = 0x444810;
static const bool is_virtual = false;
static const int vtable_index = -1;
using mv_addresses_t = MvAddresses<0x444810, 0, 0, 0, 0, 0>;
// total references count: 10us (3), 10ushl (0), 10eu (0), 11us (0), 11eu (0), sr2 (0), sr2lv (0)
using refs_t = RefList<
0x446710, GAME_10US_COMPACT, H_CALL, 0x446610, 1,
0x4467F4, GAME_10US_COMPACT, H_CALL, 0x446610, 2,
0x4468D3, GAME_10US_COMPACT, H_CALL, 0x446610, 3>;
using def_t = bool(int, int);
static const int cb_priority = PRIORITY_BEFORE;
using calling_convention_t = CallingConventions::Cdecl;
using args_t = ArgPick<ArgTypes<int,int>, 0,1>;
META_END
META_BEGIN(CGangWars::CreateDefendingGroup)
static int address;
static int global_address;
static const int id = 0x4453D0;
static const bool is_virtual = false;
static const int vtable_index = -1;
using mv_addresses_t = MvAddresses<0x4453D0, 0, 0, 0, 0, 0>;
// total references count: 10us (1), 10ushl (0), 10eu (0), 11us (0), 11eu (0), sr2 (0), sr2lv (0)
using refs_t = RefList<
0x446CA1, GAME_10US_COMPACT, H_CALL, 0x446610, 1>;
using def_t = bool(int);
static const int cb_priority = PRIORITY_BEFORE;
using calling_convention_t = CallingConventions::Cdecl;
using args_t = ArgPick<ArgTypes<int>, 0>;
META_END
META_BEGIN(CGangWars::AttackWaveOvercome)
static int address;
static int global_address;
static const int id = 0x445B30;
static const bool is_virtual = false;
static const int vtable_index = -1;
using mv_addresses_t = MvAddresses<0x445B30, 0, 0, 0, 0, 0>;
// total references count: 10us (4), 10ushl (0), 10eu (0), 11us (0), 11eu (0), sr2 (0), sr2lv (0)
using refs_t = RefList<
0x446739, GAME_10US_COMPACT, H_CALL, 0x446610, 1,
0x44681F, GAME_10US_COMPACT, H_CALL, 0x446610, 2,
0x4468F5, GAME_10US_COMPACT, H_CALL, 0x446610, 3,
0x446B12, GAME_10US_COMPACT, H_CALL, 0x446610, 4>;
using def_t = bool();
static const int cb_priority = PRIORITY_BEFORE;
using calling_convention_t = CallingConventions::Cdecl;
using args_t = ArgPick<ArgTypes<>>;
META_END
META_BEGIN(CGangWars::ReleasePedsInAttackWave)
static int address;
static int global_address;
static const int id = 0x445C30;
static const bool is_virtual = false;
static const int vtable_index = -1;
using mv_addresses_t = MvAddresses<0x445C30, 0, 0, 0, 0, 0>;
// total references count: 10us (8), 10ushl (0), 10eu (0), 11us (0), 11eu (0), sr2 (0), sr2lv (0)
using refs_t = RefList<
0x446404, GAME_10US_COMPACT, H_CALL, 0x446400, 1,
0x446524, GAME_10US_COMPACT, H_CALL, 0x4464C0, 1,
0x446554, GAME_10US_COMPACT, H_CALL, 0x4464C0, 2,
0x446748, GAME_10US_COMPACT, H_CALL, 0x446610, 1,
0x44682E, GAME_10US_COMPACT, H_CALL, 0x446610, 2,
0x446A32, GAME_10US_COMPACT, H_CALL, 0x446610, 3,
0x446B95, GAME_10US_COMPACT, H_CALL, 0x446610, 4,
0x446C2E, GAME_10US_COMPACT, H_CALL, 0x446610, 5>;
using def_t = int(bool, bool);
static const int cb_priority = PRIORITY_BEFORE;
using calling_convention_t = CallingConventions::Cdecl;
using args_t = ArgPick<ArgTypes<bool,bool>, 0,1>;
META_END
META_BEGIN(CGangWars::ReleaseCarsInAttackWave)
static int address;
static int global_address;
static const int id = 0x445E20;
static const bool is_virtual = false;
static const int vtable_index = -1;
using mv_addresses_t = MvAddresses<0x445E20, 0, 0, 0, 0, 0>;
// total references count: 10us (5), 10ushl (0), 10eu (0), 11us (0), 11eu (0), sr2 (0), sr2lv (0)
using refs_t = RefList<
0x44640C, GAME_10US_COMPACT, H_CALL, 0x446400, 1,
0x44655C, GAME_10US_COMPACT, H_JUMP, 0x4464C0, 1,
0x44674D, GAME_10US_COMPACT, H_CALL, 0x446610, 1,
0x446833, GAME_10US_COMPACT, H_CALL, 0x446610, 2,
0x446A37, GAME_10US_COMPACT, H_CALL, 0x446610, 3>;
using def_t = void();
static const int cb_priority = PRIORITY_BEFORE;
using calling_convention_t = CallingConventions::Cdecl;
using args_t = ArgPick<ArgTypes<>>;
META_END
META_BEGIN(CGangWars::MakePlayerGainInfluenceInZone)
static int address;
static int global_address;
static const int id = 0x445E80;
static const bool is_virtual = false;
static const int vtable_index = -1;
using mv_addresses_t = MvAddresses<0x445E80, 0, 0, 0, 0, 0>;
// total references count: 10us (3), 10ushl (0), 10eu (0), 11us (0), 11eu (0), sr2 (0), sr2lv (0)
using refs_t = RefList<
0x446757, GAME_10US_COMPACT, H_CALL, 0x446610, 1,
0x44683D, GAME_10US_COMPACT, H_CALL, 0x446610, 2,
0x446903, GAME_10US_COMPACT, H_CALL, 0x446610, 3>;
using def_t = bool(float);
static const int cb_priority = PRIORITY_BEFORE;
using calling_convention_t = CallingConventions::Cdecl;
using args_t = ArgPick<ArgTypes<float>, 0>;
META_END
META_BEGIN(CGangWars::StrengthenPlayerInfluenceInZone)
static int address;
static int global_address;
static const int id = 0x445F50;
static const bool is_virtual = false;
static const int vtable_index = -1;
using mv_addresses_t = MvAddresses<0x445F50, 0, 0, 0, 0, 0>;
// total references count: 10us (1), 10ushl (0), 10eu (0), 11us (0), 11eu (0), sr2 (0), sr2lv (0)
using refs_t = RefList<
0x446B87, GAME_10US_COMPACT, H_CALL, 0x446610, 1>;
using def_t = void(int);
static const int cb_priority = PRIORITY_BEFORE;
using calling_convention_t = CallingConventions::Cdecl;
using args_t = ArgPick<ArgTypes<int>, 0>;
META_END
META_BEGIN(CGangWars::MakeEnemyGainInfluenceInZone)
static int address;
static int global_address;
static const int id = 0x445FD0;
static const bool is_virtual = false;
static const int vtable_index = -1;
using mv_addresses_t = MvAddresses<0x445FD0, 0, 0, 0, 0, 0>;
// total references count: 10us (3), 10ushl (0), 10eu (0), 11us (0), 11eu (0), sr2 (0), sr2lv (0)
using refs_t = RefList<
0x446534, GAME_10US_COMPACT, H_CALL, 0x4464C0, 1,
0x446C3D, GAME_10US_COMPACT, H_CALL, 0x446610, 1,
0x446D3E, GAME_10US_COMPACT, H_CALL, 0x446610, 2>;
using def_t = void(int, int);
static const int cb_priority = PRIORITY_BEFORE;
using calling_convention_t = CallingConventions::Cdecl;
using args_t = ArgPick<ArgTypes<int,int>, 0,1>;
META_END
META_BEGIN(CGangWars::StartOffensiveGangWar)
static int address;
static int global_address;
static const int id = 0x446050;
static const bool is_virtual = false;
static const int vtable_index = -1;
using mv_addresses_t = MvAddresses<0x446050, 0, 0, 0, 0, 0>;
// total references count: 10us (1), 10ushl (0), 10eu (0), 11us (0), 11eu (0), sr2 (0), sr2lv (0)
using refs_t = RefList<
0x4466DC, GAME_10US_COMPACT, H_CALL, 0x446610, 1>;
using def_t = void();
static const int cb_priority = PRIORITY_BEFORE;
using calling_convention_t = CallingConventions::Cdecl;
using args_t = ArgPick<ArgTypes<>>;
META_END
META_BEGIN(CGangWars::DoStuffWhenPlayerVictorious)
static int address;
static int global_address;
static const int id = 0x446400;
static const bool is_virtual = false;
static const int vtable_index = -1;
using mv_addresses_t = MvAddresses<0x446400, 0, 0, 0, 0, 0>;
// total references count: 10us (1), 10ushl (0), 10eu (0), 11us (0), 11eu (0), sr2 (0), sr2lv (0)
using refs_t = RefList<
0x44690B, GAME_10US_COMPACT, H_CALL, 0x446610, 1>;
using def_t = void();
static const int cb_priority = PRIORITY_BEFORE;
using calling_convention_t = CallingConventions::Cdecl;
using args_t = ArgPick<ArgTypes<>>;
META_END
META_BEGIN(CGangWars::EndGangWar)
static int address;
static int global_address;
static const int id = 0x4464C0;
static const bool is_virtual = false;
static const int vtable_index = -1;
using mv_addresses_t = MvAddresses<0x4464C0, 0, 0, 0, 0, 0>;
// total references count: 10us (5), 10ushl (0), 10eu (0), 11us (0), 11eu (0), sr2 (0), sr2lv (0)
using refs_t = RefList<
0x4465D4, GAME_10US_COMPACT, H_CALL, 0x446570, 1,
0x446631, GAME_10US_COMPACT, H_CALL, 0x446610, 1,
0x56E5C3, GAME_10US_COMPACT, H_CALL, 0x56E580, 1,
0x56E5FE, GAME_10US_COMPACT, H_CALL, 0x56E5D0, 1,
0x618F87, GAME_10US_COMPACT, H_CALL, 0x618F50, 1>;
using def_t = void(bool);
static const int cb_priority = PRIORITY_BEFORE;
using calling_convention_t = CallingConventions::Cdecl;
using args_t = ArgPick<ArgTypes<bool>, 0>;
META_END
META_BEGIN(CGangWars::SetGangWarsActive)
static int address;
static int global_address;
static const int id = 0x446570;
static const bool is_virtual = false;
static const int vtable_index = -1;
using mv_addresses_t = MvAddresses<0x446570, 0, 0, 0, 0, 0>;
// total references count: 10us (3), 10ushl (0), 10eu (0), 11us (0), 11eu (0), sr2 (0), sr2lv (0)
using refs_t = RefList<
0x4465FC, GAME_10US_COMPACT, H_CALL, 0x4465F0, 1,
0x471A41, GAME_10US_COMPACT, H_CALL, 0x470A90, 1,
0x471A52, GAME_10US_COMPACT, H_CALL, 0x470A90, 2>;
using def_t = void(bool);
static const int cb_priority = PRIORITY_BEFORE;
using calling_convention_t = CallingConventions::Cdecl;
using args_t = ArgPick<ArgTypes<bool>, 0>;
META_END
META_BEGIN(CGangWars::SwitchGangWarsActive)
static int address;
static int global_address;
static const int id = 0x4465F0;
static const bool is_virtual = false;
static const int vtable_index = -1;
using mv_addresses_t = MvAddresses<0x4465F0, 0, 0, 0, 0, 0>;
// total references count: 10us (0), 10ushl (0), 10eu (0), 11us (0), 11eu (0), sr2 (0), sr2lv (0)
using refs_t = RefList<>;
using def_t = void();
static const int cb_priority = PRIORITY_BEFORE;
using calling_convention_t = CallingConventions::Cdecl;
using args_t = ArgPick<ArgTypes<>>;
META_END
META_BEGIN(CGangWars::Update)
static int address;
static int global_address;
static const int id = 0x446610;
static const bool is_virtual = false;
static const int vtable_index = -1;
using mv_addresses_t = MvAddresses<0x446610, 0, 0, 0, 0, 0>;
// total references count: 10us (1), 10ushl (0), 10eu (0), 11us (0), 11eu (0), sr2 (0), sr2lv (0)
using refs_t = RefList<
0x53C122, GAME_10US_COMPACT, H_CALL, 0x53BEE0, 1>;
using def_t = void();
static const int cb_priority = PRIORITY_BEFORE;
using calling_convention_t = CallingConventions::Cdecl;
using args_t = ArgPick<ArgTypes<>>;
META_END
META_BEGIN(CGangWars::Load)
static int address;
static int global_address;
static const int id = 0x5D3EB0;
static const bool is_virtual = false;
static const int vtable_index = -1;
using mv_addresses_t = MvAddresses<0x5D3EB0, 0, 0, 0, 0, 0>;
// total references count: 10us (1), 10ushl (0), 10eu (0), 11us (0), 11eu (0), sr2 (0), sr2lv (0)
using refs_t = RefList<
0x5D19B2, GAME_10US_COMPACT, H_CALL, 0x5D17B0, 1>;
using def_t = void();
static const int cb_priority = PRIORITY_BEFORE;
using calling_convention_t = CallingConventions::Cdecl;
using args_t = ArgPick<ArgTypes<>>;
META_END
META_BEGIN(CGangWars::Save)
static int address;
static int global_address;
static const int id = 0x5D5530;
static const bool is_virtual = false;
static const int vtable_index = -1;
using mv_addresses_t = MvAddresses<0x5D5530, 0, 0, 0, 0, 0>;
// total references count: 10us (1), 10ushl (0), 10eu (0), 11us (0), 11eu (0), sr2 (0), sr2lv (0)
using refs_t = RefList<
0x5D158A, GAME_10US_COMPACT, H_CALL, 0x5D13E0, 1>;
using def_t = void();
static const int cb_priority = PRIORITY_BEFORE;
using calling_convention_t = CallingConventions::Cdecl;
using args_t = ArgPick<ArgTypes<>>;
META_END
}
| 11,813 |
335 | {
"word": "Sentimentalize",
"definitions": [
"Treat, regard, or portray in a sentimental way."
],
"parts-of-speech": "Verb"
} | 65 |
8,451 | /*******************************************************************************
* ___ _ ____ ____
* / _ \ _ _ ___ ___| |_| _ \| __ )
* | | | | | | |/ _ \/ __| __| | | | _ \
* | |_| | |_| | __/\__ \ |_| |_| | |_) |
* \__\_\\__,_|\___||___/\__|____/|____/
*
* Copyright (c) 2014-2019 Appsicle
* Copyright (c) 2019-2020 QuestDB
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************/
package io.questdb.griffin.engine.functions.groupby;
import io.questdb.cairo.TableWriter;
import io.questdb.cairo.sql.Record;
import io.questdb.cairo.sql.RecordCursor;
import io.questdb.cairo.sql.RecordCursorFactory;
import io.questdb.griffin.AbstractGriffinTest;
import io.questdb.griffin.SqlException;
import io.questdb.griffin.engine.functions.rnd.SharedRandom;
import io.questdb.std.Rnd;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
public class LastDoubleGroupByFunctionFactoryTest extends AbstractGriffinTest {
@Before
public void setUp3() {
SharedRandom.RANDOM.set(new Rnd());
}
@Test
public void testLastDouble() throws Exception {
assertQuery(
"x\n" +
"10.0\n",
"select last(x) x from tab",
"create table tab as (select cast(x as double) x from long_sequence(10))",
null,
false,
true,
true
);
}
@Test
public void testLastDoubleNull() throws Exception {
assertQuery(
"y\n" +
"NaN\n",
"select last(y) y from tab",
"create table tab as (select cast(x as double) x, cast(null as double) y from long_sequence(100))",
null,
false,
true,
true
);
}
@Test
public void testAllNull() throws SqlException {
compiler.compile("create table tab (f double)", sqlExecutionContext);
try (TableWriter w = engine.getWriter(sqlExecutionContext.getCairoSecurityContext(), "tab", "testing")) {
for (int i = 100; i > 10; i--) {
TableWriter.Row r = w.newRow();
r.append();
}
w.commit();
}
try (RecordCursorFactory factory = compiler.compile("select last(f) from tab", sqlExecutionContext).getRecordCursorFactory()) {
try (RecordCursor cursor = factory.getCursor(sqlExecutionContext)) {
Record record = cursor.getRecord();
Assert.assertEquals(1, cursor.size());
Assert.assertTrue(cursor.hasNext());
Assert.assertTrue(Double.isNaN(record.getDouble(0)));
}
}
}
@Test
public void testNonNull() throws SqlException {
compiler.compile("create table tab (f double)", sqlExecutionContext);
final Rnd rnd = new Rnd();
try (TableWriter w = engine.getWriter(sqlExecutionContext.getCairoSecurityContext(), "tab", "testing")) {
for (int i = 100; i > 10; i--) {
TableWriter.Row r = w.newRow();
r.putDouble(0, rnd.nextDouble());
r.append();
}
w.commit();
}
try (RecordCursorFactory factory = compiler.compile("select last(f) from tab", sqlExecutionContext).getRecordCursorFactory()) {
try (RecordCursor cursor = factory.getCursor(sqlExecutionContext)) {
Record record = cursor.getRecord();
Assert.assertEquals(1, cursor.size());
Assert.assertTrue(cursor.hasNext());
Assert.assertEquals(0.3901731258748704, record.getDouble(0), 0.0001);
}
}
}
@Test
public void testSampleFill() throws Exception {
assertQuery("b\tlast\tk\n" +
"\t0.44804689668613573\t1970-01-03T00:00:00.000000Z\n" +
"VTJW\t0.8685154305419587\t1970-01-03T00:00:00.000000Z\n" +
"RXGZ\t0.5659429139861241\t1970-01-03T00:00:00.000000Z\n" +
"PEHN\t0.12105630273556178\t1970-01-03T00:00:00.000000Z\n" +
"HYRX\t0.49428905119584543\t1970-01-03T00:00:00.000000Z\n" +
"CPSW\t0.6752509547112409\t1970-01-03T00:00:00.000000Z\n" +
"\t0.05758228485190853\t1970-01-03T03:00:00.000000Z\n" +
"VTJW\t0.6697969295620055\t1970-01-03T03:00:00.000000Z\n" +
"CPSW\t0.6940904779678791\t1970-01-03T03:00:00.000000Z\n" +
"HYRX\t0.05158459929273784\t1970-01-03T03:00:00.000000Z\n" +
"RXGZ\t0.6590829275055244\t1970-01-03T03:00:00.000000Z\n" +
"PEHN\t0.7365115215570027\t1970-01-03T03:00:00.000000Z\n" +
"\t0.49153268154777974\t1970-01-03T06:00:00.000000Z\n" +
"VTJW\t0.8196554745841765\t1970-01-03T06:00:00.000000Z\n" +
"HYRX\t0.23493793601747937\t1970-01-03T06:00:00.000000Z\n" +
"RXGZ\t0.007985454958725269\t1970-01-03T06:00:00.000000Z\n" +
"PEHN\t0.4346135812930124\t1970-01-03T06:00:00.000000Z\n" +
"CPSW\t0.7129300012245174\t1970-01-03T06:00:00.000000Z\n" +
"\t0.7202789791127316\t1970-01-03T09:00:00.000000Z\n" +
"RXGZ\t0.03192108074989719\t1970-01-03T09:00:00.000000Z\n" +
"VTJW\t0.7732229848518976\t1970-01-03T09:00:00.000000Z\n" +
"PEHN\t0.13271564102902209\t1970-01-03T09:00:00.000000Z\n" +
"HYRX\t0.4182912727422209\t1970-01-03T09:00:00.000000Z\n" +
"CPSW\t0.7317695244811556\t1970-01-03T09:00:00.000000Z\n",
"select b, last(a), k from x sample by 3h fill(linear)",
"create table x as " +
"(" +
"select" +
" rnd_double(0) a," +
" rnd_symbol(5,4,4,1) b," +
" timestamp_sequence(172800000000, 360000000) k" +
" from" +
" long_sequence(100)" +
") timestamp(k) partition by NONE",
"k",
"insert into x select * from (" +
"select" +
" rnd_double(0) a," +
" rnd_symbol(5,4,4,1) b," +
" timestamp_sequence(277200000000, 360000000) k" +
" from" +
" long_sequence(35)" +
") timestamp(k)",
"b\tlast\tk\n" +
"\t0.44804689668613573\t1970-01-03T00:00:00.000000Z\n" +
"VTJW\t0.8685154305419587\t1970-01-03T00:00:00.000000Z\n" +
"RXGZ\t0.5659429139861241\t1970-01-03T00:00:00.000000Z\n" +
"PEHN\t0.12105630273556178\t1970-01-03T00:00:00.000000Z\n" +
"HYRX\t0.49428905119584543\t1970-01-03T00:00:00.000000Z\n" +
"CPSW\t0.6752509547112409\t1970-01-03T00:00:00.000000Z\n" +
"CGFN\t2.7171094533334066\t1970-01-03T00:00:00.000000Z\n" +
"NPIW\t4.115364146194077\t1970-01-03T00:00:00.000000Z\n" +
"PEVM\t-3.15429689776691\t1970-01-03T00:00:00.000000Z\n" +
"WGRM\tNaN\t1970-01-03T00:00:00.000000Z\n" +
"ZNFK\tNaN\t1970-01-03T00:00:00.000000Z\n" +
"\t0.05758228485190853\t1970-01-03T03:00:00.000000Z\n" +
"VTJW\t0.6697969295620055\t1970-01-03T03:00:00.000000Z\n" +
"CPSW\t0.6940904779678791\t1970-01-03T03:00:00.000000Z\n" +
"HYRX\t0.05158459929273784\t1970-01-03T03:00:00.000000Z\n" +
"RXGZ\t0.6590829275055244\t1970-01-03T03:00:00.000000Z\n" +
"PEHN\t0.7365115215570027\t1970-01-03T03:00:00.000000Z\n" +
"CGFN\t2.505608562668917\t1970-01-03T03:00:00.000000Z\n" +
"NPIW\t3.750106582628655\t1970-01-03T03:00:00.000000Z\n" +
"PEVM\t-2.7606061299772864\t1970-01-03T03:00:00.000000Z\n" +
"WGRM\tNaN\t1970-01-03T03:00:00.000000Z\n" +
"ZNFK\tNaN\t1970-01-03T03:00:00.000000Z\n" +
"\t0.49153268154777974\t1970-01-03T06:00:00.000000Z\n" +
"VTJW\t0.8196554745841765\t1970-01-03T06:00:00.000000Z\n" +
"HYRX\t0.23493793601747937\t1970-01-03T06:00:00.000000Z\n" +
"RXGZ\t0.007985454958725269\t1970-01-03T06:00:00.000000Z\n" +
"PEHN\t0.4346135812930124\t1970-01-03T06:00:00.000000Z\n" +
"CPSW\t0.7129300012245174\t1970-01-03T06:00:00.000000Z\n" +
"CGFN\t2.294107672004426\t1970-01-03T06:00:00.000000Z\n" +
"NPIW\t3.3848490190632345\t1970-01-03T06:00:00.000000Z\n" +
"PEVM\t-2.3669153621876635\t1970-01-03T06:00:00.000000Z\n" +
"WGRM\tNaN\t1970-01-03T06:00:00.000000Z\n" +
"ZNFK\tNaN\t1970-01-03T06:00:00.000000Z\n" +
"\t0.7202789791127316\t1970-01-03T09:00:00.000000Z\n" +
"RXGZ\t0.03192108074989719\t1970-01-03T09:00:00.000000Z\n" +
"VTJW\t0.7732229848518976\t1970-01-03T09:00:00.000000Z\n" +
"PEHN\t0.13271564102902209\t1970-01-03T09:00:00.000000Z\n" +
"HYRX\t0.4182912727422209\t1970-01-03T09:00:00.000000Z\n" +
"CPSW\t0.7317695244811556\t1970-01-03T09:00:00.000000Z\n" +
"CGFN\t2.0826067813399365\t1970-01-03T09:00:00.000000Z\n" +
"NPIW\t3.0195914554978125\t1970-01-03T09:00:00.000000Z\n" +
"PEVM\t-1.9732245943980409\t1970-01-03T09:00:00.000000Z\n" +
"WGRM\tNaN\t1970-01-03T09:00:00.000000Z\n" +
"ZNFK\tNaN\t1970-01-03T09:00:00.000000Z\n" +
"\t0.6914896391199901\t1970-01-03T12:00:00.000000Z\n" +
"VTJW\t0.7267904951196187\t1970-01-03T12:00:00.000000Z\n" +
"RXGZ\t0.055856706541069105\t1970-01-03T12:00:00.000000Z\n" +
"PEHN\t-0.1691822992349681\t1970-01-03T12:00:00.000000Z\n" +
"HYRX\t0.6016446094669624\t1970-01-03T12:00:00.000000Z\n" +
"CPSW\t0.7506090477377941\t1970-01-03T12:00:00.000000Z\n" +
"CGFN\t1.8711058906754459\t1970-01-03T12:00:00.000000Z\n" +
"NPIW\t2.6543338919323913\t1970-01-03T12:00:00.000000Z\n" +
"PEVM\t-1.5795338266084187\t1970-01-03T12:00:00.000000Z\n" +
"WGRM\tNaN\t1970-01-03T12:00:00.000000Z\n" +
"ZNFK\tNaN\t1970-01-03T12:00:00.000000Z\n" +
"\t0.6627002991272485\t1970-01-03T15:00:00.000000Z\n" +
"VTJW\t0.6803580053873398\t1970-01-03T15:00:00.000000Z\n" +
"RXGZ\t0.07979233233224103\t1970-01-03T15:00:00.000000Z\n" +
"PEHN\t-0.4710802394989586\t1970-01-03T15:00:00.000000Z\n" +
"HYRX\t0.7849979461917039\t1970-01-03T15:00:00.000000Z\n" +
"CPSW\t0.7694485709944322\t1970-01-03T15:00:00.000000Z\n" +
"CGFN\t1.6596050000109557\t1970-01-03T15:00:00.000000Z\n" +
"NPIW\t2.28907632836697\t1970-01-03T15:00:00.000000Z\n" +
"PEVM\t-1.1858430588187956\t1970-01-03T15:00:00.000000Z\n" +
"WGRM\tNaN\t1970-01-03T15:00:00.000000Z\n" +
"ZNFK\tNaN\t1970-01-03T15:00:00.000000Z\n" +
"\t0.6339109591345069\t1970-01-03T18:00:00.000000Z\n" +
"VTJW\t0.6339255156550605\t1970-01-03T18:00:00.000000Z\n" +
"RXGZ\t0.10372795812341296\t1970-01-03T18:00:00.000000Z\n" +
"PEHN\t-0.7729781797629487\t1970-01-03T18:00:00.000000Z\n" +
"HYRX\t0.9683512829164456\t1970-01-03T18:00:00.000000Z\n" +
"CPSW\t0.7882880942510704\t1970-01-03T18:00:00.000000Z\n" +
"CGFN\t1.4481041093464653\t1970-01-03T18:00:00.000000Z\n" +
"NPIW\t1.9238187648015488\t1970-01-03T18:00:00.000000Z\n" +
"PEVM\t-0.7921522910291726\t1970-01-03T18:00:00.000000Z\n" +
"WGRM\tNaN\t1970-01-03T18:00:00.000000Z\n" +
"ZNFK\tNaN\t1970-01-03T18:00:00.000000Z\n" +
"\t0.6051216191417653\t1970-01-03T21:00:00.000000Z\n" +
"VTJW\t0.5874930259227816\t1970-01-03T21:00:00.000000Z\n" +
"RXGZ\t0.12766358391458488\t1970-01-03T21:00:00.000000Z\n" +
"PEHN\t-1.0748761200269392\t1970-01-03T21:00:00.000000Z\n" +
"HYRX\t1.1517046196411869\t1970-01-03T21:00:00.000000Z\n" +
"CPSW\t0.8071276175077092\t1970-01-03T21:00:00.000000Z\n" +
"CGFN\t1.2366032186819753\t1970-01-03T21:00:00.000000Z\n" +
"NPIW\t1.5585612012361274\t1970-01-03T21:00:00.000000Z\n" +
"PEVM\t-0.3984615232395501\t1970-01-03T21:00:00.000000Z\n" +
"WGRM\tNaN\t1970-01-03T21:00:00.000000Z\n" +
"ZNFK\tNaN\t1970-01-03T21:00:00.000000Z\n" +
"\t0.5763322791490237\t1970-01-04T00:00:00.000000Z\n" +
"VTJW\t0.5410605361905028\t1970-01-04T00:00:00.000000Z\n" +
"RXGZ\t0.15159920970575683\t1970-01-04T00:00:00.000000Z\n" +
"PEHN\t-1.3767740602909293\t1970-01-04T00:00:00.000000Z\n" +
"HYRX\t1.3350579563659284\t1970-01-04T00:00:00.000000Z\n" +
"CPSW\t0.8259671407643474\t1970-01-04T00:00:00.000000Z\n" +
"CGFN\t1.025102328017485\t1970-01-04T00:00:00.000000Z\n" +
"NPIW\t1.1933036376707062\t1970-01-04T00:00:00.000000Z\n" +
"PEVM\t-0.004770755449927295\t1970-01-04T00:00:00.000000Z\n" +
"WGRM\tNaN\t1970-01-04T00:00:00.000000Z\n" +
"ZNFK\tNaN\t1970-01-04T00:00:00.000000Z\n" +
"\t0.5475429391562822\t1970-01-04T03:00:00.000000Z\n" +
"CGFN\t0.8136014373529948\t1970-01-04T03:00:00.000000Z\n" +
"NPIW\t0.8280460741052847\t1970-01-04T03:00:00.000000Z\n" +
"PEVM\t0.3889200123396954\t1970-01-04T03:00:00.000000Z\n" +
"VTJW\t0.4946280464582231\t1970-01-04T03:00:00.000000Z\n" +
"RXGZ\t0.1755348354969287\t1970-01-04T03:00:00.000000Z\n" +
"PEHN\t-1.6786720005549198\t1970-01-04T03:00:00.000000Z\n" +
"HYRX\t1.51841129309067\t1970-01-04T03:00:00.000000Z\n" +
"CPSW\t0.8448066640209855\t1970-01-04T03:00:00.000000Z\n" +
"WGRM\tNaN\t1970-01-04T03:00:00.000000Z\n" +
"ZNFK\tNaN\t1970-01-04T03:00:00.000000Z\n" +
"WGRM\t0.8387598218385978\t1970-01-04T06:00:00.000000Z\n" +
"CGFN\t0.6021005466885047\t1970-01-04T06:00:00.000000Z\n" +
"\t0.5364603752015349\t1970-01-04T06:00:00.000000Z\n" +
"PEVM\t0.7826107801293182\t1970-01-04T06:00:00.000000Z\n" +
"ZNFK\t0.7806183442034064\t1970-01-04T06:00:00.000000Z\n" +
"NPIW\t0.4627885105398635\t1970-01-04T06:00:00.000000Z\n" +
"VTJW\t0.44819555672594497\t1970-01-04T06:00:00.000000Z\n" +
"RXGZ\t0.19947046128810061\t1970-01-04T06:00:00.000000Z\n" +
"PEHN\t-1.9805699408189095\t1970-01-04T06:00:00.000000Z\n" +
"HYRX\t1.7017646298154117\t1970-01-04T06:00:00.000000Z\n" +
"CPSW\t0.8636461872776237\t1970-01-04T06:00:00.000000Z\n",
true,
true,
true
);
}
}
| 11,018 |
680 | <filename>tensorflow/core/framework/bfloat16.h
/* Copyright 2015 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#ifndef TENSORFLOW_FRAMEWORK_BFLOAT16_H_
#define TENSORFLOW_FRAMEWORK_BFLOAT16_H_
#include "third_party/eigen3/unsupported/Eigen/CXX11/Tensor"
#include "tensorflow/core/platform/types.h"
// Compact 16-bit encoding of floating point numbers. This representation uses
// 1 bit for the sign, 8 bits for the exponent and 7 bits for the mantissa. It
// is assumed that floats are in IEEE 754 format so the representation is just
// bits 16-31 of a single precision float.
//
// NOTE: The IEEE floating point standard defines a float16 format that
// is different than this format (it has fewer bits of exponent and more
// bits of mantissa). We don't use that format here because conversion
// to/from 32-bit floats is more complex for that format, and the
// conversion for this format is very simple.
//
// Because of the existing IEEE float16 type, we do not name our representation
// "float16" but just use "uint16".
//
// <-----our 16bits float------->
// s e e e e e e e e f f f f f f f f f f f f f f f f f f f f f f f
// <------------------------------float-------------------------->
// 3 3 2 2 1 1 0
// 1 0 3 2 5 4 0
//
//
// This type only supports conversion back and forth with float.
//
// This file must be compilable by nvcc.
namespace tensorflow {
struct bfloat16 {
EIGEN_DEVICE_FUNC bfloat16() {}
EIGEN_DEVICE_FUNC explicit bfloat16(const uint16_t v) : value(v) {}
uint16_t value;
};
// Conversion routines between an array of float and bfloat16 of
// "size".
void FloatToBFloat16(const float* src, bfloat16* dst, int64 size);
void BFloat16ToFloat(const bfloat16* src, float* dst, int64 size);
} // namespace tensorflow
namespace Eigen {
template <>
struct NumTraits<tensorflow::bfloat16> : GenericNumTraits<uint16_t> {};
EIGEN_STRONG_INLINE bool operator==(const tensorflow::bfloat16 a,
const tensorflow::bfloat16 b) {
return a.value == b.value;
}
} // namespace Eigen
#endif // TENSORFLOW_FRAMEWORK_BFLOAT16_H_
| 942 |
313 | //
// Copyright 2018 The Simons Foundation, 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.
//
#ifndef __ITENSOR_PRINT_H
#define __ITENSOR_PRINT_H
#include "itensor/util/tinyformat.h"
#include "itensor/util/stdx.h"
namespace itensor {
using tinyformat::format;
template <typename... VArgs>
void
printf(const char* fmt_string, VArgs&&... vargs)
{
tinyformat::printf(fmt_string,std::forward<VArgs>(vargs)...);
std::cout.flush();
}
template <typename... VArgs>
void
printfln(const char* fmt_string, VArgs&&... vargs)
{
tinyformat::printf(fmt_string,std::forward<VArgs>(vargs)...);
std::cout << std::endl;
}
void inline
println()
{
std::cout << std::endl;
}
template <typename T,
class = stdx::require_not<std::is_convertible<T,std::ostream const&>>>
void
println(const T& arg)
{
std::cout << arg << std::endl;
}
template <typename T, typename... VArgs,
class = stdx::require_not<std::is_convertible<T,std::ostream const&>>>
void
println(const T& arg1, VArgs&&... vargs)
{
std::cout << arg1;
println(std::forward<VArgs>(vargs)...);
}
template <typename T,
class = stdx::require_not<std::is_convertible<T,std::ostream const&>>>
void
print(const T& arg)
{
std::cout << arg;
std::cout.flush();
}
template <typename T, typename... VArgs,
class = stdx::require_not<std::is_convertible<T,std::ostream const&>>>
void
print(const T& arg1, VArgs&&... vargs)
{
std::cout << arg1;
print(std::forward<VArgs>(vargs)...);
}
////////////////////////////////
////////////////////////////////
////////////////////////////////
template <typename... VArgs>
void
printf(std::ostream & os, const char* fmt_string, VArgs&&... vargs)
{
tinyformat::format(os,fmt_string,std::forward<VArgs>(vargs)...);
std::cout.flush();
}
template <typename... VArgs>
void
printfln(std::ostream & os, const char* fmt_string, VArgs&&... vargs)
{
tinyformat::format(os,fmt_string,std::forward<VArgs>(vargs)...);
os << std::endl;
}
void inline
println(std::ostream & os)
{
os << std::endl;
}
template <typename T>
void
println(std::ostream & os, const T& arg)
{
os << arg << std::endl;
}
template <typename T, typename... VArgs>
void
println(std::ostream & os, const T& arg1, VArgs&&... vargs)
{
os << arg1;
println(os,std::forward<VArgs>(vargs)...);
}
template <typename T>
void
print(std::ostream & os, const T& arg)
{
os << arg;
os.flush();
}
template <typename T, typename... VArgs>
void
print(std::ostream & os, const T& arg1, VArgs&&... vargs)
{
os << arg1;
print(os,std::forward<VArgs>(vargs)...);
}
////////////////////////////////
////////////////////////////////
////////////////////////////////
template<typename T>
void
PrintNice(const char* tok,
T const& X)
{
auto pre = format("%s = ",tok);
auto str = format("%s",X);
//Put a newline after '=' if
//output is large or output contains
//newline character
bool put_newline = false;
if(pre.size() + str.size() > 60)
{
put_newline = true;
}
else
{
for(auto c : str)
if(c == '\n')
{
put_newline = true;
break;
}
}
if(put_newline) println(pre);
else print(pre);
println(str);
}
} //namespace itensor
#endif
| 1,640 |
413 | <reponame>ktts16/mini-caffe<filename>example/deeplandmark/main.cpp
#include <cassert>
#include <chrono>
#include <iostream>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <caffe/profiler.hpp>
#include "landmark.hpp"
using namespace cv;
using namespace std;
using namespace caffe;
void showLandmarks(Mat &image, Rect &bbox, vector<Point2f> &landmarks) {
Mat img;
image.copyTo(img);
rectangle(img, bbox, Scalar(0, 0, 255), 2);
for (int i = 0; i < landmarks.size(); i++) {
Point2f &point = landmarks[i];
circle(img, point, 2, Scalar(0, 255, 0), -1);
}
imwrite("./deeplandmark-result.jpg", image);
imshow("landmark", img);
waitKey(0);
}
int main(int argc, char *argv[]) {
FaceDetector fd;
Landmarker lder;
fd.LoadXML("../deeplandmark/haarcascade_frontalface_alt.xml");
lder.LoadModel("../models/deeplandmark");
Mat image;
Mat gray;
image = imread("../deeplandmark/test.jpg");
if (image.data == NULL) return -1;
cvtColor(image, gray, CV_BGR2GRAY);
vector<Rect> bboxes;
fd.DetectFace(gray, bboxes);
Profiler* profiler = Profiler::Get();
vector<Point2f> landmarks;
for (int i = 0; i < bboxes.size(); i++) {
BBox bbox_ = BBox(bboxes[i]).subBBox(0.1, 0.9, 0.2, 1);
const int kTestN = 1000;
double time = 0;
for (int j = 0; j < kTestN; j++) {
auto tic = profiler->Now();
landmarks = lder.DetectLandmark(gray, bbox_);
auto toc = profiler->Now();
time += double(toc - tic) / 1000;
}
cout << "costs " << time / kTestN << " ms" << endl;
showLandmarks(image, bbox_.rect, landmarks);
}
return 0;
}
| 700 |
1,428 | def make_burger(f):
def new_f():
print('/-----\\')
f()
print('\-----/')
return new_f
@make_burger
def chop():
print("-------")
chop() | 87 |
454 | {
"title": "破狼博客",
"question": {
"url": "https://api.github.com/repos/greengerong/rebirth-question/issues?callback=JSONP_CALLBACK&access_token=[set token]"
},
"article": {
"pageSize": 10
}
}
| 93 |
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.
*
*************************************************************/
#ifndef _SV_SALOBJ_H
#define _SV_SALOBJ_H
#include <salobj.hxx>
// -----------------
// - SalObjectData -
// -----------------
class Os2SalObject : public SalObject
{
public:
HWND mhWnd; // Window handle
HWND mhWndChild; // Child Window handle
HWND mhLastFocusWnd; // Child-Window, welches als letztes den Focus hatte
SystemChildData maSysData; // SystemEnvData
HWND mhLastClipWnd; // LastClip-Window
HWND mhOldLastClipWnd; // LastClip-Window befor BeginSetClipRegion
long mnHeight; // Fenster-Hoehe fuer Positionsumrechnung
Os2SalObject* mpNextObject; // pointer to next object
void* mpInst; // instance handle for callback
SALOBJECTPROC mpProc; // callback proc
Os2SalObject();
virtual ~Os2SalObject();
virtual void ResetClipRegion();
virtual USHORT GetClipRegionType();
virtual void BeginSetClipRegion( ULONG nRects );
virtual void UnionClipRegion( long nX, long nY, long nWidth, long nHeight );
virtual void EndSetClipRegion();
virtual void SetPosSize( long nX, long nY, long nWidth, long nHeight );
virtual void Show( sal_Bool bVisible );
virtual void Enable( sal_Bool nEnable );
virtual void GrabFocus();
virtual void SetBackground();
virtual void SetBackground( SalColor nSalColor );
virtual const SystemEnvData* GetSystemData() const;
virtual void InterceptChildWindowKeyDown( sal_Bool bIntercept );
};
#endif // _SV_SALOBJ_H
| 826 |
2,360 | # Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class XcursorThemes(Package, XorgPackage):
"""This is a default set of cursor themes for use with libXcursor,
originally created for the XFree86 Project, and now shipped as part
of the X.Org software distribution."""
homepage = "https://cgit.freedesktop.org/xorg/data/cursors"
xorg_mirror_path = "data/xcursor-themes-1.0.4.tar.gz"
version('1.0.4', sha256='8ed23bab13a4010fe4e95b37eefb634e31ac7cb8240b8b3b7d919c3a2db09503')
depends_on('libxcursor')
depends_on('xcursorgen', type='build')
depends_on('pkgconfig', type='build')
depends_on('util-macros', type='build')
def install(self, spec, prefix):
configure('--prefix={0}'.format(prefix))
make()
make('install')
# `make install` copies the files to the libxcursor installation.
# Create a fake directory to convince Spack that we actually
# installed something.
mkdir(prefix.lib)
| 436 |
32,544 | <filename>spring-4/src/main/java/com/baeldung/flips/model/Foo.java
package com.baeldung.flips.model;
import lombok.Data;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
@Data
@RequiredArgsConstructor
public class Foo {
@NonNull private final String name;
@NonNull private final int id;
}
| 114 |
310 | {
"name": "Dance Dance Revolution",
"description": "A ridiculous dancing game.",
"url": "https://en.wikipedia.org/wiki/Dance_Dance_Revolution"
} | 49 |
777 | <gh_stars>100-1000
// Copyright 2014 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 EXTENSIONS_RENDERER_API_TEST_BASE_H_
#define EXTENSIONS_RENDERER_API_TEST_BASE_H_
#include <map>
#include <string>
#include <utility>
#include "base/message_loop/message_loop.h"
#include "base/run_loop.h"
#include "extensions/renderer/module_system_test.h"
#include "extensions/renderer/v8_schema_registry.h"
#include "gin/handle.h"
#include "gin/modules/module_registry.h"
#include "gin/object_template_builder.h"
#include "gin/wrappable.h"
#include "mojo/public/cpp/bindings/interface_request.h"
#include "mojo/public/cpp/system/core.h"
namespace extensions {
class V8SchemaRegistry;
// An InterfaceProvider that provides access from JS modules to interfaces
// registered by AddInterface() calls.
class TestInterfaceProvider : public gin::Wrappable<TestInterfaceProvider> {
public:
static gin::Handle<TestInterfaceProvider> Create(v8::Isolate* isolate);
~TestInterfaceProvider() override;
gin::ObjectTemplateBuilder GetObjectTemplateBuilder(
v8::Isolate* isolate) override;
template <typename Interface>
void AddInterface(
const base::Callback<void(mojo::InterfaceRequest<Interface>)>
factory_callback) {
factories_.insert(std::make_pair(
Interface::Name_,
base::Bind(ForwardToInterfaceFactory<Interface>, factory_callback)));
}
// Ignore requests for Interface.
template <typename Interface>
void IgnoreInterfaceRequests() {
factories_.insert(std::make_pair(
Interface::Name_, base::Bind(&TestInterfaceProvider::IgnoreHandle)));
}
static gin::WrapperInfo kWrapperInfo;
private:
TestInterfaceProvider();
mojo::Handle GetInterface(const std::string& interface_name);
template <typename Interface>
static void ForwardToInterfaceFactory(
const base::Callback<void(mojo::InterfaceRequest<Interface>)>
factory_callback,
mojo::ScopedMessagePipeHandle handle) {
factory_callback.Run(mojo::MakeRequest<Interface>(std::move(handle)));
}
static void IgnoreHandle(mojo::ScopedMessagePipeHandle handle);
std::map<std::string, base::Callback<void(mojo::ScopedMessagePipeHandle)> >
factories_;
};
// An environment for unit testing apps/extensions API custom bindings
// implemented on Mojo interfaces. This augments a ModuleSystemTestEnvironment
// with a TestInterfaceProvider and other modules available in a real extensions
// environment.
class ApiTestEnvironment {
public:
explicit ApiTestEnvironment(ModuleSystemTestEnvironment* environment);
~ApiTestEnvironment();
void RunTest(const std::string& file_name, const std::string& test_name);
TestInterfaceProvider* interface_provider() { return interface_provider_; }
ModuleSystemTestEnvironment* env() { return env_; }
private:
void RegisterModules();
void InitializeEnvironment();
void RunTestInner(const std::string& test_name,
const base::Closure& quit_closure);
void RunPromisesAgain();
ModuleSystemTestEnvironment* env_;
TestInterfaceProvider* interface_provider_;
std::unique_ptr<V8SchemaRegistry> v8_schema_registry_;
};
// A base class for unit testing apps/extensions API custom bindings implemented
// on Mojo interfaces. To use:
// 1. Register test Mojo interface implementations on interface_provider().
// 2. Write JS tests in extensions/test/data/test_file.js.
// 3. Write one C++ test function for each JS test containing
// RunTest("test_file.js", "testFunctionName").
// See extensions/renderer/api_test_base_unittest.cc and
// extensions/test/data/api_test_base_unittest.js for sample usage.
class ApiTestBase : public ModuleSystemTest {
protected:
ApiTestBase();
~ApiTestBase() override;
void SetUp() override;
void RunTest(const std::string& file_name, const std::string& test_name);
ApiTestEnvironment* api_test_env() { return test_env_.get(); }
TestInterfaceProvider* interface_provider() {
return test_env_->interface_provider();
}
private:
base::MessageLoop message_loop_;
std::unique_ptr<ApiTestEnvironment> test_env_;
};
} // namespace extensions
#endif // EXTENSIONS_RENDERER_API_TEST_BASE_H_
| 1,348 |
434 | <gh_stars>100-1000
#!/usr/bin/python3
# EMACS settings: -*- tab-width: 2; indent-tabs-mode: t; python-indent-offset: 2 -*-
# vim: tabstop=2:shiftwidth=2:noexpandtab
# kate: tab-width 2; replace-tabs off; indent-width 2;
#
# ==============================================================================
# Authors: <NAME>
#
# License:
# ==============================================================================
# Copyright 2007-2016 Technische Universitaet Dresden - Germany
# Chair of VLSI-Design, Diagnostics and Architecture
#
# 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,
# distributed under the License is distributed on an "AS IS" BASIS,default
# 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.
# ==============================================================================
"""
[http://stackoverflow.com/questions/18673694/referencing-current-branch-in-github-readme-md]
Referencing current branch in github readme.md[1]
This pre-commit hook[2] updates the README.md file's
Travis badge with the current branch. Gist at[4].
[1] http://stackoverflow.com/questions/18673694/referencing-current-branch-in-github-readme-md
[2] http://www.git-scm.com/book/en/v2/Customizing-Git-Git-Hooks
[3] https://docs.travis-ci.com/user/status-images/
[4] https://gist.github.com/dandye/dfe0870a6a1151c89ed9
"""
from subprocess import check_output, check_call
import os
# Collecting values to substitute
substitutions = {}
substitutions["BRANCH"] = check_output(["git", "rev-parse", "--abbrev-ref", "HEAD"], universal_newlines=True).strip()
substitutions["GENERATED_HEADER"] = '<!--- DO NOT EDIT! This file is generated from .tpl --->'
# Patch templates .tpl to generate specialized .md files
git_root = check_output(['git', 'rev-parse', '--show-toplevel'], universal_newlines=True).strip()
for root, dirs, files in os.walk(git_root):
for file in files:
if file.endswith('.tpl'):
trgt = file[:-3]+'md'
print(' generate ' + file + ' -> ' + trgt);
tpl = open(os.path.join(root, file), 'r', encoding='utf-8')
md = open(os.path.join(root, trgt), 'w', encoding='utf-8')
for line in tpl:
for key in substitutions:
line = line.replace('{@'+key+'@}', substitutions[key])
md.write(line)
md .close()
tpl.close()
check_call(['git', 'add', trgt ])
| 936 |
12,347 | <filename>poetry/plugins/__init__.py
from .application_plugin import ApplicationPlugin
from .plugin import Plugin
__all__ = ["ApplicationPlugin", "Plugin"]
| 42 |
1,576 | <reponame>embix/WindowsInternals<filename>CPUSTRES/AffinityDlg.h<gh_stars>1000+
#pragma once
class CThread;
// CAffinityDlg dialog
class CAffinityDlg : public CDialogEx {
DECLARE_DYNAMIC(CAffinityDlg)
public:
CAffinityDlg(bool affinity, CThread* pThread, const CString& title, CWnd* pParent = nullptr);
CAffinityDlg(const CString& title, CWnd* pParent = nullptr);
virtual ~CAffinityDlg();
// Dialog Data
#ifdef AFX_DESIGN_TIME
enum { IDD = IDD_AFFINITY };
#endif
enum { IDC_FIRST = 100 };
DWORD_PTR GetSelectedAffinity() const {
return m_SelectedAfinity;
}
int GetSelectedCPU() const {
return m_IdealCPU;
}
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
DWORD_PTR CalcAffinity();
void DisableNonProcessAffinity();
bool m_Affinity;
bool m_Process = false;
CString m_Title;
CButton m_Buttons[64];
CThread* m_pThread;
DWORD_PTR m_SelectedAfinity;
int m_IdealCPU;
DECLARE_MESSAGE_MAP()
virtual BOOL OnInitDialog();
void OnOK() override;
public:
afx_msg void OnBnClickedSelectall();
afx_msg void OnBnClickedUnselectall();
};
| 450 |
395 | <reponame>jabader97/backpack
"""BatchGrad extension for Embedding."""
from backpack.core.derivatives.embedding import EmbeddingDerivatives
from backpack.extensions.firstorder.batch_grad.batch_grad_base import BatchGradBase
class BatchGradEmbedding(BatchGradBase):
"""BatchGrad extension for Embedding."""
def __init__(self):
"""Initialization."""
super().__init__(derivatives=EmbeddingDerivatives(), params=["weight"])
| 152 |
2,937 | <reponame>Mu-L/ogre<filename>Components/Volume/src/OgreVolumeTextureSource.cpp
/*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org
Copyright (c) 2000-2014 <NAME> Ltd
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.
-----------------------------------------------------------------------------
*/
#include "OgreVolumeTextureSource.h"
#include "OgreTextureManager.h"
#include "OgreHardwarePixelBuffer.h"
#include "OgreColourValue.h"
#include "OgreMemoryAllocatorConfig.h"
#include "OgreLogManager.h"
#include "OgreTimer.h"
namespace Ogre {
namespace Volume {
float TextureSource::getVolumeGridValue(size_t x, size_t y, size_t z) const
{
x = x >= mWidth ? mWidth - 1 : x;
y = y >= mHeight ? mHeight - 1 : y;
z = z >= mDepth ? mDepth - 1 : z;
return mData[(mDepth - z - 1) * mWidthTimesHeight + y * mWidth + x];
}
//-----------------------------------------------------------------------
void TextureSource::setVolumeGridValue(int x, int y, int z, float value)
{
mData[(mDepth - z - 1) * mWidthTimesHeight + y * mWidth + x] = value;
}
//-----------------------------------------------------------------------
TextureSource::TextureSource(const String &volumeTextureName, const Real worldWidth, const Real worldHeight, const Real worldDepth, const bool trilinearValue, const bool trilinearGradient, const bool sobelGradient) :
GridSource(trilinearValue, trilinearGradient, sobelGradient)
{
Timer t;
Image img;
img.load(volumeTextureName, ResourceGroupManager::getSingleton().getWorldResourceGroupName());
LogManager::getSingleton().stream() << "Loaded texture in " << t.getMilliseconds() << "ms.";
t.reset();
mWidth = img.getWidth();
mHeight= img.getHeight();
mWidthTimesHeight = mWidth * mHeight;
mDepth = img.getDepth();
mPosXScale = (Real)1.0 / (Real)worldWidth * (Real)mWidth;
mPosYScale = (Real)1.0 / (Real)worldHeight * (Real)mHeight;
mPosZScale = (Real)1.0 / (Real)worldDepth * (Real)mDepth;
mVolumeSpaceToWorldSpaceFactor = (Real)worldWidth * (Real)mWidth;
auto srcBox = img.getPixelBox();
mData = OGRE_ALLOC_T(float, mWidth * mHeight * mDepth, MEMCATEGORY_GENERAL);
auto dstBox = srcBox;
dstBox.data = (uchar*)mData;
dstBox.format = PF_FLOAT32_R;
PixelUtil::bulkPixelConversion(srcBox, dstBox);
LogManager::getSingleton().stream() << "Processed texture in " << t.getMilliseconds() << "ms.";
}
//-----------------------------------------------------------------------
TextureSource::~TextureSource(void)
{
OGRE_FREE(mData, MEMCATEGORY_GENERAL);
}
}
}
| 1,309 |
358 | <filename>messages/profile_retrieve.json<gh_stars>100-1000
{
"commandDescription": "Retrieve profiles from the salesforce org with all its associated permissions. Common use case for this command is to migrate profile changes from a integration environment to other higher environments [overcomes SFDX CLI Profile retrieve issue where it doesnt fetch the full profile unless the entire metadata is present in source], or retrieving profiles from production to lower environments for testing.",
"folderFlagDescription": "retrieve only updated versions of profiles found in this directory, If ignored, all profiles will be retrieved.",
"profileListFlagDescription": "comma separated list of profiles to be retrieved. Use it for selectively retrieving an existing profile or retrieving a new profile",
"deleteFlagDescription": "set this flag to delete profile files that does not exist in the org, when retrieving in bulk"
}
| 192 |
4,408 | /*
* Copyright 2016 WebAssembly Community Group participants
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef WABT_GENERATE_NAMES_H_
#define WABT_GENERATE_NAMES_H_
#include "src/common.h"
namespace wabt {
struct Module;
enum NameOpts {
None = 0,
AlphaNames = 1 << 0,
};
Result GenerateNames(struct Module*, NameOpts opts = NameOpts::None);
inline std::string IndexToAlphaName(Index index) {
std::string s;
do {
// For multiple chars, put most frequently changing char first.
s += 'a' + (index % 26);
index /= 26;
// Continue remaining sequence with 'a' rather than 'b'.
} while (index--);
return s;
}
} // namespace wabt
#endif /* WABT_GENERATE_NAMES_H_ */
| 386 |
649 | package net.serenitybdd.screenplay.actions;
import net.serenitybdd.core.pages.WebElementFacade;
import net.serenitybdd.screenplay.Actor;
import net.serenitybdd.screenplay.Interaction;
import net.serenitybdd.screenplay.abilities.BrowseTheWeb;
import net.thucydides.core.annotations.Step;
public class JSClickOnElement implements Interaction {
private final WebElementFacade element;
@Step("{0} clicks on #element")
public <T extends Actor> void performAs(T theUser) {
BrowseTheWeb.as(theUser).evaluateJavascript("arguments[0].click();", element);
}
public JSClickOnElement(WebElementFacade element) {
this.element = element;
}
}
| 236 |
4,812 | //===-- BPFRegisterInfo.h - BPF Register Information Impl -------*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This file contains the BPF implementation of the TargetRegisterInfo class.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_LIB_TARGET_BPF_BPFREGISTERINFO_H
#define LLVM_LIB_TARGET_BPF_BPFREGISTERINFO_H
#include "llvm/CodeGen/TargetRegisterInfo.h"
#define GET_REGINFO_HEADER
#include "BPFGenRegisterInfo.inc"
namespace llvm {
struct BPFRegisterInfo : public BPFGenRegisterInfo {
BPFRegisterInfo();
const MCPhysReg *getCalleeSavedRegs(const MachineFunction *MF) const override;
BitVector getReservedRegs(const MachineFunction &MF) const override;
void eliminateFrameIndex(MachineBasicBlock::iterator MI, int SPAdj,
unsigned FIOperandNum,
RegScavenger *RS = nullptr) const override;
Register getFrameRegister(const MachineFunction &MF) const override;
};
}
#endif
| 402 |
14,668 | // Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef NET_DNS_PUBLIC_SECURE_DNS_MODE_H_
#define NET_DNS_PUBLIC_SECURE_DNS_MODE_H_
#include "base/containers/fixed_flat_map.h"
#include "base/strings/string_piece.h"
namespace net {
// GENERATED_JAVA_ENUM_PACKAGE: org.chromium.net
// The SecureDnsMode specifies what types of lookups (secure/insecure) should
// be performed and in what order when resolving a specific query. The int
// values should not be changed as they are logged.
enum class SecureDnsMode : int {
// In OFF mode, no DoH lookups should be performed.
kOff = 0,
// In AUTOMATIC mode, DoH lookups should be performed first if DoH is
// available, and insecure DNS lookups should be performed as a fallback.
kAutomatic = 1,
// In SECURE mode, only DoH lookups should be performed.
kSecure = 2,
};
constexpr auto kSecureDnsModes =
base::MakeFixedFlatMap<SecureDnsMode, base::StringPiece>(
{{SecureDnsMode::kOff, "Off"},
{SecureDnsMode::kAutomatic, "Automatic"},
{SecureDnsMode::kSecure, "Secure"}});
} // namespace net
#endif // NET_DNS_PUBLIC_SECURE_DNS_MODE_H_
| 435 |
8,027 | <reponame>Unknoob/buck
void D();
void static_func_C();
void prebuilt_func_C();
void C() {
D();
static_func_C();
prebuilt_func_C();
}
| 61 |
2,151 | /*
* Copyright (C) 2014 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 android.support.v17.leanback.transition;
import android.R;
import android.app.Fragment;
import android.content.Context;
import android.transition.ChangeTransform;
import android.transition.Transition;
import android.transition.TransitionManager;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.animation.AnimationUtils;
final class TransitionHelperApi21 {
TransitionHelperApi21() {
}
public static void setEnterTransition(android.app.Fragment fragment, Object transition) {
fragment.setEnterTransition((Transition)transition);
}
public static void setExitTransition(android.app.Fragment fragment, Object transition) {
fragment.setExitTransition((Transition)transition);
}
public static void setSharedElementEnterTransition(android.app.Fragment fragment,
Object transition) {
fragment.setSharedElementEnterTransition((Transition)transition);
}
public static void addSharedElement(android.app.FragmentTransaction ft,
View view, String transitionName) {
ft.addSharedElement(view, transitionName);
}
public static Object getSharedElementEnterTransition(Window window) {
return window.getSharedElementEnterTransition();
}
public static Object getSharedElementReturnTransition(Window window) {
return window.getSharedElementReturnTransition();
}
public static Object getSharedElementExitTransition(Window window) {
return window.getSharedElementExitTransition();
}
public static Object getSharedElementReenterTransition(Window window) {
return window.getSharedElementReenterTransition();
}
public static Object getEnterTransition(Window window) {
return window.getEnterTransition();
}
public static Object getReturnTransition(Window window) {
return window.getReturnTransition();
}
public static Object getExitTransition(Window window) {
return window.getExitTransition();
}
public static Object getReenterTransition(Window window) {
return window.getReenterTransition();
}
public static Object createScale() {
return new ChangeTransform();
}
public static Object createDefaultInterpolator(Context context) {
return AnimationUtils.loadInterpolator(context, R.interpolator.fast_out_linear_in);
}
public static Object createChangeTransform() {
return new ChangeTransform();
}
public static Object createFadeAndShortSlide(int edge) {
return new FadeAndShortSlide(edge);
}
public static Object createFadeAndShortSlide(int edge, float distance) {
FadeAndShortSlide slide = new FadeAndShortSlide(edge);
slide.setDistance(distance);
return slide;
}
public static void beginDelayedTransition(ViewGroup sceneRoot, Object transitionObject) {
Transition transition = (Transition) transitionObject;
TransitionManager.beginDelayedTransition(sceneRoot, transition);
}
public static void setTransitionGroup(ViewGroup viewGroup, boolean transitionGroup) {
viewGroup.setTransitionGroup(transitionGroup);
}
}
| 1,196 |
2,313 | /*
* Copyright (c) 2021 Arm Limited.
*
* SPDX-License-Identifier: MIT
*
* 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.
*/
#include "tests/validation/fixtures/UNIT/ContextFixture.h"
#include "src/gpu/cl/ClContext.h"
using namespace arm_compute::mlgo;
namespace arm_compute
{
namespace test
{
namespace validation
{
TEST_SUITE(CL)
TEST_SUITE(UNIT)
TEST_SUITE(Context)
EMPTY_BODY_FIXTURE_TEST_CASE(SimpleContextCApi, SimpleContextCApiFixture<AclTarget::AclGpuOcl>, framework::DatasetMode::ALL)
EMPTY_BODY_FIXTURE_TEST_CASE(SimpleContextCppApi, SimpleContextCppApiFixture<acl::Target::GpuOcl>, framework::DatasetMode::ALL)
EMPTY_BODY_FIXTURE_TEST_CASE(MultipleContexts, MultipleContextsFixture<AclTarget::AclGpuOcl>, framework::DatasetMode::ALL)
/** Test-case for MLGO kernel configuration file
*
* Validate that CpuCapabilities are set correctly
*
* Test Steps:
* - Create a file with the MLGO configuration
* - Pass the kernel file to the Context during creation
* - Validate that the MLGO file has been parsed successfully
*/
TEST_CASE(CheckMLGO, framework::DatasetMode::ALL)
{
// Create test mlgo file
std::string mlgo_str = R"_(
<header>
gemm-version, [1,2,1]
ip-type,gpu
</header>
<heuristics-table>
0, g76 , 8, f32, best-performance, static, gemm-type, [m,n,k,n]
1, g76 , 8, f16, best-performance, static, gemm-config-reshaped, [m,n,k,n]
</heuristics-table>
<heuristic, 0>
b , 0, var, m, ==, num, 10., 1, 2
l , 1, gemm-type, reshaped
b , 2, var, r_mn, >=, num, 2., 3, 6
b , 3, var, n, >=, num, 200., 4, 5
l, 4, gemm-type, reshaped-only-rhs
l , 5, gemm-type, reshaped
l , 6, gemm-type, reshaped-only-rhs
</heuristic>
<heuristic, 1>
l ,0,gemm-config-reshaped,[4,2,4,2,8,1,0,1,0]
</heuristic>
)_";
const std::string mlgo_filename = "test.mlgo";
std::ofstream ofs(mlgo_filename, std::ofstream::trunc);
ARM_COMPUTE_EXPECT(ofs, framework::LogLevel::ERRORS);
ofs << mlgo_str;
ofs.close();
acl::Context::Options opts;
opts.copts.kernel_config_file = mlgo_filename.c_str();
arm_compute::gpu::opencl::ClContext ctx(&opts.copts);
const MLGOHeuristics &heuristics = ctx.mlgo();
ARM_COMPUTE_EXPECT(heuristics.query_gemm_type(Query{ "g76", DataType::F32, 10, 1024, 20, 1 }).second == GEMMType::RESHAPED,
framework::LogLevel::ERRORS);
ARM_COMPUTE_EXPECT((heuristics.query_gemm_config_reshaped(Query{ "g76", DataType::F16, 100, 100, 20, 32 }).second == GEMMConfigReshaped{ 4, 2, 4, 2, 8, true, false, true, false }),
framework::LogLevel::ERRORS);
}
TEST_SUITE_END() // Context
TEST_SUITE_END() // UNIT
TEST_SUITE_END() // CL
} // namespace validation
} // namespace test
} // namespace arm_compute
| 1,555 |
5,547 | /**
******************************************************************************
* @file flash.h
* @author YANDLD
* @version V3.0.0
* @date 2015.8.28
* @brief www.beyondcore.net http://upcmcu.taobao.com
******************************************************************************
*/
#ifndef __CH_LIB_IFLASH_H__
#define __CH_LIB_IFLASH_H__
#include <stdint.h>
/* function return type */
#define FLASH_OK 0x00
#define FLASH_OVERFLOW 0x01
#define FLASH_BUSY 0x02
#define FLASH_ERROR 0x04
#define FLASH_TIMEOUT 0x08
#define FLASH_NOT_ERASED 0x10
#define FLASH_CONTENTERR 0x11
//!< API functions
void FLASH_Init(void);
uint32_t FLASH_GetSectorSize(void);
uint8_t FLASH_WriteSector(uint32_t addr, const uint8_t *buf, uint32_t len);
uint8_t FLASH_EraseSector(uint32_t addr);
uint32_t FLASH_Test(uint32_t startAddr, uint32_t len);
#endif
| 428 |
816 | <gh_stars>100-1000
package com.jxtech.app.autokey;
import com.jxtech.jbo.Jbo;
import com.jxtech.jbo.JboSetIFace;
import com.jxtech.jbo.util.JxException;
/**
*
*
* @author <EMAIL>
* @date 2014.05
*/
public class AutoKey extends Jbo implements AutoKeyIFace {
/**
*
*/
private static final long serialVersionUID = -8946757743216221745L;
public AutoKey(JboSetIFace jboset) throws JxException {
super(jboset);
}
}
| 198 |
942 | <reponame>KatsutoshiOtogawa/treefrog-framework
#include "mongoc.h"
#include "mongoc-read-concern-private.h"
#include "mongoc-util-private.h"
#include "TestSuite.h"
#include "test-conveniences.h"
#include "test-libmongoc.h"
static void
test_read_concern_append (void)
{
mongoc_read_concern_t *rc;
bson_t *cmd;
cmd = tmp_bson ("{'foo': 1}");
/* append default readConcern */
rc = mongoc_read_concern_new ();
ASSERT (mongoc_read_concern_is_default (rc));
ASSERT_MATCH (cmd, "{'foo': 1, 'readConcern': {'$exists': false}}");
/* append readConcern with level */
mongoc_read_concern_set_level (rc, MONGOC_READ_CONCERN_LEVEL_LOCAL);
ASSERT (mongoc_read_concern_append (rc, cmd));
ASSERT_MATCH (cmd, "{'foo': 1, 'readConcern': {'level': 'local'}}");
mongoc_read_concern_destroy (rc);
}
static void
test_read_concern_basic (void)
{
mongoc_read_concern_t *read_concern;
read_concern = mongoc_read_concern_new ();
BEGIN_IGNORE_DEPRECATIONS;
/*
* Test defaults.
*/
ASSERT (read_concern);
ASSERT (mongoc_read_concern_is_default (read_concern));
ASSERT (!mongoc_read_concern_get_level (read_concern));
/*
* Test changes to level.
*/
mongoc_read_concern_set_level (read_concern,
MONGOC_READ_CONCERN_LEVEL_LOCAL);
ASSERT (!mongoc_read_concern_is_default (read_concern));
ASSERT_CMPSTR (mongoc_read_concern_get_level (read_concern),
MONGOC_READ_CONCERN_LEVEL_LOCAL);
/*
* Check generated bson.
*/
ASSERT_MATCH (_mongoc_read_concern_get_bson (read_concern),
"{'level': 'local'}");
mongoc_read_concern_destroy (read_concern);
}
static void
test_read_concern_bson_omits_defaults (void)
{
mongoc_read_concern_t *read_concern;
const bson_t *bson;
bson_iter_t iter;
read_concern = mongoc_read_concern_new ();
/*
* Check generated bson.
*/
ASSERT (read_concern);
bson = _mongoc_read_concern_get_bson (read_concern);
ASSERT (bson);
ASSERT (!bson_iter_init_find (&iter, bson, "level"));
mongoc_read_concern_destroy (read_concern);
}
static void
test_read_concern_always_mutable (void)
{
mongoc_read_concern_t *read_concern;
read_concern = mongoc_read_concern_new ();
ASSERT (read_concern);
mongoc_read_concern_set_level (read_concern,
MONGOC_READ_CONCERN_LEVEL_LOCAL);
ASSERT_MATCH (_mongoc_read_concern_get_bson (read_concern),
"{'level': 'local'}");
mongoc_read_concern_set_level (read_concern,
MONGOC_READ_CONCERN_LEVEL_MAJORITY);
ASSERT_MATCH (_mongoc_read_concern_get_bson (read_concern),
"{'level': 'majority'}");
mongoc_read_concern_set_level (read_concern,
MONGOC_READ_CONCERN_LEVEL_LINEARIZABLE);
ASSERT_MATCH (_mongoc_read_concern_get_bson (read_concern),
"{'level': 'linearizable'}");
mongoc_read_concern_destroy (read_concern);
}
void
test_read_concern_install (TestSuite *suite)
{
TestSuite_Add (suite, "/ReadConcern/append", test_read_concern_append);
TestSuite_Add (suite, "/ReadConcern/basic", test_read_concern_basic);
TestSuite_Add (suite,
"/ReadConcern/bson_omits_defaults",
test_read_concern_bson_omits_defaults);
TestSuite_Add (
suite, "/ReadConcern/always_mutable", test_read_concern_always_mutable);
}
| 1,614 |
362 | <reponame>yzqzss/reddit-android-appstore
package subreddit.android.appstore.backend.github;
import java.util.List;
import io.reactivex.Observable;
public interface GithubRepository {
Observable<GithubApi.Release> getLatestRelease();
Observable<List<GithubApi.Contributor>> getContributors();
}
| 103 |
1,144 | /******************************************************************************
* Product: Adempiere ERP & CRM Smart Business Solution *
* Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. *
* This program is free software; you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. This program is distributed in the hope *
* that it will be useful, but WITHOUT ANY WARRANTY; without even the implied *
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. *
* You should have received a copy of the GNU General Public License along *
* with this program; if not, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us *
* ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA *
* or via <EMAIL> or http://www.compiere.org/license.html *
*****************************************************************************/
package org.compiere.util;
import java.util.ListResourceBundle;
/**
* License Dialog Translation
*
* @author <NAME> - <EMAIL>
* @version $Id: IniRes.java,v 1.2 2006/07/30 00:52:23 jjanke Exp $
*/
public class IniRes_el extends ListResourceBundle
{
/** Translation Content */
static final Object[][] contents = new String[][]
{
{ "Adempiere_License", "\u03a3\u03c5\u03bc\u03c6\u03c9\u03bd\u03af\u03b1 \u0386\u03b4\u03b5\u03b9\u03b1\u03c2 \u03a7\u03c1\u03ae\u03c3\u03b7\u03c2" },
{ "Do_you_accept", "\u0391\u03c0\u03bf\u03b4\u03ad\u03c7\u03b5\u03c3\u03c4\u03b5 \u03c4\u03b7\u03bd \u0386\u03b4\u03b5\u03b9\u03b1 \u03a7\u03c1\u03ae\u03c3\u03b7\u03c2 ?" },
{ "No", "\u038c\u03c7\u03b9" },
{ "Yes_I_Understand", "\u039d\u03b1\u03b9, \u03c4\u03b7\u03bd \u03ba\u03b1\u03c4\u03ac\u03bb\u03b1\u03b2\u03b1 \u03ba\u03b1\u03b9 \u03c4\u03b7\u03bd \u0391\u03c0\u03bf\u03b4\u03ad\u03c7\u03bf\u03bc\u03b1\u03b9" },
{ "license_htm", "org/adempiere/license.htm" },
{ "License_rejected", "\u0397 \u0386\u03b4\u03b5\u03b9\u03b1 \u03a7\u03c1\u03ae\u03c3\u03b7\u03c2 \u03b1\u03c0\u03bf\u03c1\u03c1\u03af\u03c6\u03b8\u03b7\u03ba\u03b5 \u03ae \u03ad\u03bb\u03b7\u03be\u03b5" }
};
/**
* Get Content
* @return Content
*/
public Object[][] getContents()
{
return contents;
} // getContent
} // IniRes
| 1,193 |
4,200 | <reponame>kbens/rundeck
/*
* Copyright 2016 SimplifyOps, Inc. (http://simplifyops.com)
*
* 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.dtolabs.rundeck.core.execution.workflow;
import com.dtolabs.rundeck.core.common.INodeEntry;
import com.dtolabs.rundeck.core.execution.ExecutionContext;
import com.dtolabs.rundeck.core.execution.ExecutionListener;
import com.dtolabs.rundeck.core.execution.StatusResult;
import com.dtolabs.rundeck.core.execution.StepExecutionItem;
import com.dtolabs.rundeck.core.execution.workflow.state.ExecutionState;
import com.dtolabs.rundeck.core.execution.workflow.steps.StepExecutionResult;
import com.dtolabs.rundeck.core.execution.workflow.steps.StepExecutor;
import com.dtolabs.rundeck.core.execution.workflow.steps.node.NodeStepExecutionItem;
import com.dtolabs.rundeck.core.execution.workflow.steps.node.NodeStepResult;
import java.util.HashMap;
import java.util.Map;
/**
* Emits events to the logger for workflow step/node start and finish.
*/
public class WorkflowEventLoggerListener implements WorkflowExecutionListener{
private static final String STEP_START = "stepbegin";
private static final String STEP_HANDLER = "handlerbegin";
private static final String HANDLER_FINISH = "handlerend";
private static final String STEP_FINISH = "stepend";
private static final String NODE_START = "nodebegin";
private static final String NODE_FINISH = "nodeend";
ExecutionListener logger;
public WorkflowEventLoggerListener(ExecutionListener logger) {
this.logger = logger;
}
@Override
public void beginWorkflowExecution(StepExecutionContext executionContext, WorkflowExecutionItem item) {
}
@Override
public void finishWorkflowExecution(WorkflowExecutionResult result, StepExecutionContext executionContext,
WorkflowExecutionItem item) {
}
@Override
public void beginWorkflowItem(int step, StepExecutionItem item) {
logger.event(STEP_START, null, null);
}
@Override
public void beginWorkflowItemErrorHandler(int step, StepExecutionItem item) {
logger.event(STEP_HANDLER, null, null);
}
private static Map resultMap(StepExecutionResult result) {
if (null != result && result.isSuccess()) {
return null;
}
HashMap hashMap = new HashMap();
if (null != result && null != result.getFailureData()) {
hashMap.putAll(result.getFailureData());
}
hashMap.put("failureReason", null != result ? result.getFailureReason().toString() : "Unknown");
hashMap.put("executionState", null != result && result.isSuccess() ? ExecutionState.SUCCEEDED.toString() :
ExecutionState.FAILED.toString());
return hashMap;
}
@Override
public void finishWorkflowItem(int step, StepExecutionItem item, StepExecutionResult result) {
logger.event(STEP_FINISH,
null != result && null != result.getFailureMessage()
? result.getFailureMessage()
: null,
resultMap(result));
}
@Override
public void finishWorkflowItemErrorHandler(int step, StepExecutionItem item, StepExecutionResult result) {
logger.event(HANDLER_FINISH,
null != result && null != result.getFailureMessage()
? result.getFailureMessage()
: null, resultMap(result));
}
@Override
public void beginStepExecution(StepExecutor executor, StepExecutionContext context, StepExecutionItem item) {
}
@Override
public void finishStepExecution(StepExecutor executor, StatusResult result, StepExecutionContext context,
StepExecutionItem item) {
}
@Override
public void beginExecuteNodeStep(ExecutionContext context, NodeStepExecutionItem item, INodeEntry node) {
logger.event(NODE_START, null, null);
}
@Override
public void finishExecuteNodeStep(NodeStepResult result, ExecutionContext context, StepExecutionItem item, INodeEntry node) {
logger.event(NODE_FINISH, null != result && null != result.getFailureMessage() ? result.getFailureMessage() :
null,
resultMap(result));
}
}
| 1,696 |
1,217 | <filename>Modules/ego_planner/ego-planner-swarm/src/uav_simulator/so3_quadrotor_simulator/include/ode/libs/numeric/odeint/performance/phase_lattice.hpp
/*
* Copyright 2009-2012 <NAME>
* Copyright 2009-2012 <NAME>
*
* Distributed under the Boost Software License, Version 1.0.
* (See accompanying file LICENSE_1_0.txt or
* copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#include <cmath>
#include <boost/array.hpp>
template< size_t N >
struct phase_lattice
{
typedef double value_type;
typedef boost::array< value_type , N > state_type;
value_type m_epsilon;
state_type m_omega;
phase_lattice() : m_epsilon( 6.0/(N*N) ) // should be < 8/N^2 to see phase locking
{
for( size_t i=1 ; i<N-1 ; ++i )
m_omega[i] = m_epsilon*(N-i);
}
void inline operator()( const state_type &x , state_type &dxdt , const double t ) const
{
double c = 0.0;
for( size_t i=0 ; i<N-1 ; ++i )
{
dxdt[i] = m_omega[i] + c;
c = ( x[i+1] - x[i] );
dxdt[i] += c;
}
//dxdt[N-1] = m_omega[N-1] + sin( x[N-1] - x[N-2] );
}
};
| 562 |
680 | package org.ff4j.property.multi;
/*
* #%L
* ff4j-core
* %%
* Copyright (C) 2013 - 2016 FF4J
* %%
* 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.
* #L%
*/
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import org.ff4j.property.Property;
/**
*
* @author <NAME> (@clunven)</a>
*
* @param <T>
* myultliva
* @param <M>
*/
public abstract class AbstractPropertyMap < T, M extends Map<String, ? extends T>> extends Property < M > implements Map< String, T > {
/** serial. */
private static final long serialVersionUID = 2612494170643655559L;
/**
* Default constructor.
*/
public AbstractPropertyMap() {
}
/**
* Constructor by property name.
*
* @param name
* property name
*/
@SuppressWarnings("unchecked")
public AbstractPropertyMap(String name) {
super(name);
value = (M) new HashMap<String, T>();
}
/**
* Constructor by T expression.
*
* @param uid
* unique name
* @param lvl
* current double value
*/
public AbstractPropertyMap(String uid, M value) {
super(uid, value);
}
/**
* Access Internal value.
*
* @return
* target value.
*/
protected M value() {
if (value == null) {
throw new IllegalStateException("Value should not be null nor empty");
}
return value;
}
/** {@inheritDoc} */
public int size() {
return value().size();
}
/** {@inheritDoc} */
public boolean isEmpty() {
return value().isEmpty();
}
/** {@inheritDoc} */
public boolean containsKey(Object key) {
return value().containsKey(key);
}
/** {@inheritDoc} */
public boolean containsValue(Object obj) {
return value().containsValue(obj);
}
/** {@inheritDoc} */
public T get(Object key) {
return value().get(key);
}
/** {@inheritDoc} */
public T remove(Object key) {
return value().remove(key);
}
/** {@inheritDoc} */
public void clear() {
value().clear();
}
/** {@inheritDoc} */
public Set<String> keySet() {
return value().keySet();
}
}
| 1,106 |
634 | <reponame>halotroop2288/consulo<filename>modules/base/platform-impl/src/main/java/consulo/actionSystem/impl/UnifiedActionPopupMenuImpl.java
/*
* Copyright 2013-2021 consulo.io
*
* 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 consulo.actionSystem.impl;
import com.intellij.ide.DataManager;
import com.intellij.openapi.actionSystem.ActionGroup;
import com.intellij.openapi.actionSystem.ActionPopupMenu;
import com.intellij.openapi.actionSystem.DataContext;
import com.intellij.openapi.actionSystem.impl.ActionManagerImpl;
import com.intellij.openapi.actionSystem.impl.PresentationFactory;
import consulo.ui.Component;
import consulo.ui.PopupMenu;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.function.Supplier;
/**
* @author VISTALL
* @since 17/08/2021
* <p>
* Simple ActionPopupMenu implementation
*/
public class UnifiedActionPopupMenuImpl implements ActionPopupMenu {
private final String myPlace;
@Nonnull
private final ActionGroup myGroup;
private final ActionManagerImpl myManager;
@Nullable
private final PresentationFactory myPresentationFactory;
@Nullable
private Supplier<DataContext> myDataContextProvider;
public UnifiedActionPopupMenuImpl(String place, @Nonnull ActionGroup group, ActionManagerImpl actionManager, @Nullable PresentationFactory factory) {
myPlace = place;
myGroup = group;
myManager = actionManager;
myPresentationFactory = factory;
}
@Nonnull
@Override
public String getPlace() {
return myPlace;
}
@Nonnull
@Override
public ActionGroup getActionGroup() {
return myGroup;
}
@Override
public void setTargetComponent(@Nonnull Component component) {
myDataContextProvider = () -> DataManager.getInstance().getDataContext(component);
}
@Override
public void show(Component component, int x, int y) {
DataContext context = myDataContextProvider == null ? DataManager.getInstance().getDataContext(component) : myDataContextProvider.get();
PresentationFactory presentationFactory = myPresentationFactory == null ? new PresentationFactory() : myPresentationFactory;
PopupMenu popupMenu = PopupMenu.create(component);
UnifiedActionUtil.expandActionGroup(myGroup, context, myManager, presentationFactory, popupMenu::add);
myManager.addActionPopup(this);
popupMenu.show(x, y);
}
}
| 836 |
1,775 | package com.threedr3am.bug.compile.javac;
import java.nio.charset.Charset;
import java.util.List;
import java.util.Locale;
import javax.tools.Diagnostic;
import javax.tools.DiagnosticCollector;
import javax.tools.JavaCompiler;
import javax.tools.JavaCompiler.CompilationTask;
import javax.tools.JavaFileObject;
import javax.tools.StandardJavaFileManager;
import javax.tools.ToolProvider;
/**
* @author threedr3am
*/
public class ByJavaFileObject {
//使用了JavaFileObject指定java文件进行编译
public static void d() {
JavaCompiler javaCompiler = ToolProvider.getSystemJavaCompiler();
ClassLoader classLoader = ByJavaFileObject.class.getClassLoader();
DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector();
StandardJavaFileManager standardJavaFileManager = javaCompiler
.getStandardFileManager(diagnostics, Locale.CHINA, Charset.forName("utf-8"));
// FileManagerImpl fileManager = new FileManagerImpl(standardJavaFileManager);
Iterable<? extends JavaFileObject> javaFileObjects = standardJavaFileManager.getJavaFileObjects("/tmp/ccc/CCC.java", "/tmp/Main.java");
// 编译任务
CompilationTask task = javaCompiler.getTask(null, standardJavaFileManager, diagnostics, null, null, javaFileObjects);
Boolean result = task.call();
System.out.println(result);
List list = diagnostics.getDiagnostics();
for (Object object : list) {
Diagnostic d = (Diagnostic) object;
System.out.println(d.getMessage(Locale.ENGLISH));
}
}
public static void main(String[] args) {
d();
}
}
| 634 |
1,085 | <gh_stars>1000+
/*
* Copyright (C) 2020 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 org.conscrypt;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.FileDescriptor;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.junit.AfterClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
@RunWith(JUnit4.class)
public class NativeCryptoArgTest {
// Null value passed in for a long which represents a native address
private static final long NULL = 0L;
/*
* Non-null value passed in for a long which represents a native address. Shouldn't
* ever get de-referenced but we make it a multiple of 4 to avoid any alignment errors.
* Used in the case where there are multiple checks we want to test in a native method,
* so we can get past the first check and test the second one.
*/
private static final long NOT_NULL = 4L;
private static final String CONSCRYPT_PACKAGE = NativeCryptoArgTest.class.getCanonicalName()
.substring(0, NativeCryptoArgTest.class.getCanonicalName().lastIndexOf('.') + 1);
private static final Set<String> testedMethods = new HashSet<>();
private final Map<String, Class<?>> classCache = new HashMap<>();
private final Map<String, Method> methodMap = buildMethodMap();
@AfterClass
public static void after() {
// TODO(prb): Temporary hacky check - remove
assertTrue(testedMethods.size() >= 190);
}
@Test
public void ecMethods() throws Throwable {
String[] illegalArgMethods = new String[] {
"EC_GROUP_new_arbitrary"
};
String[] ioExMethods = new String[] {
"EC_KEY_parse_curve_name",
"EC_KEY_marshal_curve_name"
};
// All of the EC_* methods apart from the exceptions below throw NPE if their
// first argument is null.
MethodFilter filter = MethodFilter.newBuilder("EC_ methods")
.hasPrefix("EC_")
.except(illegalArgMethods)
.except(ioExMethods)
.expectSize(16)
.build();
testMethods(filter, NullPointerException.class);
filter = MethodFilter.nameFilter("EC_ methods (IllegalArgument)", illegalArgMethods);
testMethods(filter, IllegalArgumentException.class);
filter = MethodFilter.nameFilter("EC_ methods (IOException)", ioExMethods);
testMethods(filter, IOException.class);
}
@Test
public void macMethods() throws Throwable {
// All of the non-void HMAC and CMAC methods throw NPE when passed a null pointer
MethodFilter filter = MethodFilter.newBuilder("HMAC methods")
.hasPrefix("HMAC_")
.takesArguments()
.expectSize(5)
.build();
testMethods(filter, NullPointerException.class);
filter = MethodFilter.newBuilder("CMAC methods")
.hasPrefix("CMAC_")
.takesArguments()
.expectSize(5)
.build();
testMethods(filter, NullPointerException.class);
}
@Test
public void sslMethods() throws Throwable {
// These methods don't throw on a null first arg as they can get called before the
// connection is fully initialised. However if the first arg is non-NULL, any subsequent
// null args should throw NPE.
String[] nonThrowingMethods = new String[] {
"SSL_interrupt",
"SSL_shutdown",
"ENGINE_SSL_shutdown",
};
// Most of the NativeSsl methods take a long holding a pointer to the native
// object followed by a {@code NativeSsl} holder object. However the second arg
// is unused(!) so we don't need to test it.
MethodFilter filter = MethodFilter.newBuilder("NativeSsl methods")
.hasArg(0, long.class)
.hasArg(1, conscryptClass("NativeSsl"))
.except(nonThrowingMethods)
.expectSize(60)
.build();
testMethods(filter, NullPointerException.class);
// Many of the SSL_* methods take a single long which points
// to a native object.
filter = MethodFilter.newBuilder("1-arg SSL methods")
.hasPrefix("SSL_")
.hasArgLength(1)
.hasArg(0, long.class)
.expectSize(10)
.build();
testMethods(filter, NullPointerException.class);
filter = MethodFilter.nameFilter("Non throwing NativeSsl methods", nonThrowingMethods);
testMethods(filter, null);
expectVoid("SSL_shutdown", NOT_NULL, null, null, null);
expectNPE("SSL_shutdown", NOT_NULL, null, new FileDescriptor(), null);
expectNPE("ENGINE_SSL_shutdown", NOT_NULL, null, null);
expectVoid("SSL_set_session", NOT_NULL, null, NULL);
}
@Test
public void evpMethods() throws Throwable {
String[] illegalArgMethods = new String[] {
"EVP_AEAD_CTX_open_buf",
"EVP_AEAD_CTX_seal_buf",
"EVP_PKEY_new_RSA"
};
String[] nonThrowingMethods = new String[] {
"EVP_MD_CTX_destroy",
"EVP_PKEY_CTX_free",
"EVP_PKEY_free",
"EVP_CIPHER_CTX_free"
};
// All of the non-void EVP_ methods apart from the above should throw on a null
// first argument.
MethodFilter filter = MethodFilter.newBuilder("EVP methods")
.hasPrefix("EVP_")
.takesArguments()
.except(illegalArgMethods)
.except(nonThrowingMethods)
.expectSize(45)
.build();
testMethods(filter, NullPointerException.class);
filter = MethodFilter.nameFilter("EVP methods (IllegalArgument)", illegalArgMethods);
testMethods(filter, IllegalArgumentException.class);
filter = MethodFilter.nameFilter("EVP methods (non-throwing)", nonThrowingMethods);
testMethods(filter, null);
}
@Test
public void x509Methods() throws Throwable {
// A number of X509 methods have a native pointer as arg 0 and an
// OpenSSLX509Certificate or OpenSSLX509CRL as arg 1.
MethodFilter filter = MethodFilter.newBuilder("X509 methods")
.hasArgLength(2)
.hasArg(0, long.class)
.hasArg(1, conscryptClass("OpenSSLX509Certificate"),
conscryptClass("OpenSSLX509CRL"))
.expectSize(32)
.build();
// TODO(prb): test null second argument
testMethods(filter, NullPointerException.class);
// The rest of the X509 methods are somewhat ad hoc.
expectNPE("d2i_X509", (Object) null);
invokeAndExpect( conscryptThrowable("OpenSSLX509CertificateFactory$ParsingException"),
"d2i_X509", new byte[]{0, 0, 0, 0, 0, 0, 0, 0, 0});
expectNPE("d2i_X509_bio", NULL);
expectNPE("PEM_read_bio_X509", NULL);
expectNPE("ASN1_seq_pack_X509", (Object) null);
// TODO(prb): Check what this should really throw
// expectNPE("ASN1_seq_pack_X509", (Object) new long[] { NULL });
expectNPE("ASN1_seq_unpack_X509_bio", NULL);
//
expectNPE("X509_cmp", NULL, null, NULL, null);
expectNPE("X509_cmp", NOT_NULL, null, NULL, null);
expectNPE("X509_cmp", NULL, null, NOT_NULL, null);
expectNPE("X509_print_ex", NULL, NULL, null, NULL, NULL);
expectNPE("X509_print_ex", NOT_NULL, NULL, null, NULL, NULL);
expectNPE("X509_print_ex", NULL, NOT_NULL, null, NULL, NULL);
}
private void testMethods(MethodFilter filter, Class<? extends Throwable> exceptionClass)
throws Throwable {
List<Method> methods = filter.filter(methodMap.values());
for (Method method : methods) {
List<Object[]> argsLists = permuteArgs(method);
for (Object[] args : argsLists) {
invokeAndExpect(exceptionClass, method, args);
}
}
}
private List<Object[]> permuteArgs(Method method) {
// For now just supply 0 for integral types and null for everything else
// TODO: allow user defined strategy, e.g. if two longs passed as native refs,
// generate {NULL,NULL}, {NULL,NOT_NULL}, {NOT_NULL,NULL} to test both null checks
List<Object[]> result = new ArrayList<>(1);
Class<?>[] argTypes = method.getParameterTypes();
int argCount = argTypes.length;
assertTrue(argCount > 0);
Object[] args = new Object[argCount];
for (int arg = 0; arg < argCount; arg++) {
if (argTypes[arg] == int.class) {
args[arg] = 0;
} else if (argTypes[arg] == long.class) {
args[arg] = NULL;
} else if (argTypes[arg] == boolean.class) {
args[arg] = false;
} else {
args[arg] = null;
}
}
result.add(args);
return result;
}
private void expectVoid(String methodName, Object... args) throws Throwable {
invokeAndExpect(null, methodName, args);
}
private void expectNPE(String methodName, Object... args) throws Throwable {
invokeAndExpect(NullPointerException.class, methodName, args);
}
private void invokeAndExpect(Class<? extends Throwable> expectedThrowable, String methodName,
Object... args) throws Throwable {
Method method = methodMap.get(methodName);
assertNotNull(method);
assertEquals(methodName, method.getName());
invokeAndExpect(expectedThrowable, method, args);
}
private void invokeAndExpect(Class<? extends Throwable> expectedThrowable, Method method,
Object... args) throws Throwable {
try {
method.invoke(null, args);
if (expectedThrowable != null) {
fail("No exception thrown by method " + method.getName());
}
} catch (IllegalAccessException e) {
throw new AssertionError("Illegal access", e);
} catch (InvocationTargetException e) {
Throwable cause = e.getCause();
if (expectedThrowable != null) {
assertEquals("Method: " + method.getName(), expectedThrowable, cause.getClass());
} else {
throw cause;
}
}
testedMethods.add(method.getName());
}
@SuppressWarnings("unchecked")
private Class<? extends Throwable> conscryptThrowable(String name) {
Class<?> klass = conscryptClass(name);
assertNotNull(klass);
assertTrue(Throwable.class.isAssignableFrom(klass));
return (Class<? extends Throwable>) klass;
}
private Class<?> conscryptClass(String className) {
return classCache.computeIfAbsent(className, s -> {
try {
return Class.forName(CONSCRYPT_PACKAGE + className);
} catch (ClassNotFoundException e) {
return null;
}
});
}
private Map<String, Method> buildMethodMap() {
Map<String, Method> classMap = new HashMap<>();
assertNotNull(classMap);
Class<?> nativeCryptoClass = conscryptClass("NativeCrypto");
assertNotNull(nativeCryptoClass);
for (Method method : nativeCryptoClass.getDeclaredMethods()) {
int modifiers = method.getModifiers();
if (!Modifier.isNative(modifiers)) {
continue;
}
method.setAccessible(true);
classMap.put(method.getName(), method);
}
return classMap;
}
}
| 5,451 |
4,392 | <filename>kernel/x86_64/saxpy_microk_skylakex-2.c
/***************************************************************************
Copyright (c) 2014, The OpenBLAS Project
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the
distribution.
3. Neither the name of the OpenBLAS project 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 OPENBLAS PROJECT 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.
*****************************************************************************/
/* need a new enough GCC for avx512 support */
#if (( defined(__GNUC__) && __GNUC__ > 6 && defined(__AVX2__)) || (defined(__clang__) && __clang_major__ >= 6))
#define HAVE_KERNEL_16 1
#include <immintrin.h>
static void saxpy_kernel_16( BLASLONG n, FLOAT *x, FLOAT *y, FLOAT *alpha)
{
BLASLONG i = 0;
__m256 __alpha;
__alpha = _mm256_broadcastss_ps(_mm_load_ss(alpha));
#ifdef __AVX512CD__
BLASLONG n64;
__m512 __alpha5;
__alpha5 = _mm512_broadcastss_ps(_mm_load_ss(alpha));
n64 = n & ~63;
for (; i < n64; i+= 64) {
_mm512_storeu_ps(&y[i + 0], _mm512_loadu_ps(&y[i + 0]) + __alpha5 * _mm512_loadu_ps(&x[i + 0]));
_mm512_storeu_ps(&y[i + 16], _mm512_loadu_ps(&y[i + 16]) + __alpha5 * _mm512_loadu_ps(&x[i + 16]));
_mm512_storeu_ps(&y[i + 32], _mm512_loadu_ps(&y[i + 32]) + __alpha5 * _mm512_loadu_ps(&x[i + 32]));
_mm512_storeu_ps(&y[i + 48], _mm512_loadu_ps(&y[i + 48]) + __alpha5 * _mm512_loadu_ps(&x[i + 48]));
}
#endif
for (; i < n; i+= 32) {
_mm256_storeu_ps(&y[i + 0], _mm256_loadu_ps(&y[i + 0]) + __alpha * _mm256_loadu_ps(&x[i + 0]));
_mm256_storeu_ps(&y[i + 8], _mm256_loadu_ps(&y[i + 8]) + __alpha * _mm256_loadu_ps(&x[i + 8]));
_mm256_storeu_ps(&y[i + 16], _mm256_loadu_ps(&y[i + 16]) + __alpha * _mm256_loadu_ps(&x[i + 16]));
_mm256_storeu_ps(&y[i + 24], _mm256_loadu_ps(&y[i + 24]) + __alpha * _mm256_loadu_ps(&x[i + 24]));
}
}
#else
#include "saxpy_microk_haswell-2.c"
#endif
| 1,163 |
777 | // 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 "components/proximity_auth/remote_device_loader.h"
#include <algorithm>
#include <utility>
#include "base/base64url.h"
#include "base/bind.h"
#include "components/cryptauth/secure_message_delegate.h"
#include "components/proximity_auth/logging/logging.h"
#include "components/proximity_auth/proximity_auth_pref_manager.h"
namespace proximity_auth {
RemoteDeviceLoader::RemoteDeviceLoader(
const std::vector<cryptauth::ExternalDeviceInfo>& unlock_keys,
const std::string& user_id,
const std::string& user_private_key,
std::unique_ptr<cryptauth::SecureMessageDelegate> secure_message_delegate,
ProximityAuthPrefManager* pref_manager)
: remaining_unlock_keys_(unlock_keys),
user_id_(user_id),
user_private_key_(user_private_key),
secure_message_delegate_(std::move(secure_message_delegate)),
pref_manager_(pref_manager),
weak_ptr_factory_(this) {}
RemoteDeviceLoader::~RemoteDeviceLoader() {}
void RemoteDeviceLoader::Load(const RemoteDeviceCallback& callback) {
DCHECK(callback_.is_null());
callback_ = callback;
PA_LOG(INFO) << "Loading " << remaining_unlock_keys_.size()
<< " remote devices";
if (remaining_unlock_keys_.empty()) {
callback_.Run(remote_devices_);
return;
}
std::vector<cryptauth::ExternalDeviceInfo> all_unlock_keys =
remaining_unlock_keys_;
for (const auto& unlock_key : all_unlock_keys) {
secure_message_delegate_->DeriveKey(
user_private_key_, unlock_key.public_key(),
base::Bind(&RemoteDeviceLoader::OnPSKDerived,
weak_ptr_factory_.GetWeakPtr(), unlock_key));
}
}
void RemoteDeviceLoader::OnPSKDerived(
const cryptauth::ExternalDeviceInfo& unlock_key,
const std::string& psk) {
std::string public_key = unlock_key.public_key();
auto iterator = std::find_if(
remaining_unlock_keys_.begin(), remaining_unlock_keys_.end(),
[&public_key](const cryptauth::ExternalDeviceInfo& unlock_key) {
return unlock_key.public_key() == public_key;
});
DCHECK(iterator != remaining_unlock_keys_.end());
remaining_unlock_keys_.erase(iterator);
PA_LOG(INFO) << "Derived PSK for " << unlock_key.friendly_device_name()
<< ", " << remaining_unlock_keys_.size() << " keys remaining.";
// TODO(tengs): We assume that devices without a |bluetooth_address| field are
// BLE devices. Ideally, we should have a separate field for this information.
cryptauth::RemoteDevice::BluetoothType bluetooth_type =
unlock_key.bluetooth_address().empty()
? cryptauth::RemoteDevice::BLUETOOTH_LE
: cryptauth::RemoteDevice::BLUETOOTH_CLASSIC;
std::string bluetooth_address = unlock_key.bluetooth_address();
if (bluetooth_address.empty() && pref_manager_) {
std::string b64_public_key;
base::Base64UrlEncode(unlock_key.public_key(),
base::Base64UrlEncodePolicy::INCLUDE_PADDING,
&b64_public_key);
bluetooth_address = pref_manager_->GetDeviceAddress(b64_public_key);
PA_LOG(INFO) << "The BLE address of " << unlock_key.friendly_device_name()
<< " is " << bluetooth_address;
}
remote_devices_.push_back(cryptauth::RemoteDevice(
user_id_, unlock_key.friendly_device_name(), unlock_key.public_key(),
bluetooth_type, bluetooth_address, psk, std::string()));
if (remaining_unlock_keys_.empty())
callback_.Run(remote_devices_);
}
} // namespace proximity_auth
| 1,365 |
3,093 | import webview
import pytest
from .util import run_test
def test_bg_color():
window = webview.create_window('Background color test', 'https://www.example.org', background_color='#0000FF')
run_test(webview, window)
def test_invalid_bg_color():
with pytest.raises(ValueError):
webview.create_window('Background color test', 'https://www.example.org', background_color='#dsg0000FF')
with pytest.raises(ValueError):
webview.create_window('Background color test', 'https://www.example.org', background_color='FF00FF')
with pytest.raises(ValueError):
webview.create_window('Background color test', 'https://www.example.org', background_color='#ac')
with pytest.raises(ValueError):
webview.create_window('Background color test', 'https://www.example.org', background_color='#EFEFEH')
with pytest.raises(ValueError):
webview.create_window('Background color test', 'https://www.example.org', background_color='#0000000')
| 337 |
403 | <gh_stars>100-1000
/*
* Camunda Platform REST API
* OpenApi Spec for Camunda Platform REST API.
*
* The version of the OpenAPI document: 7.16.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package com.camunda.consulting.openapi.client.model;
import java.util.Objects;
import java.util.Arrays;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonTypeName;
import com.fasterxml.jackson.annotation.JsonValue;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
/**
* ExecutionDto
*/
@JsonPropertyOrder({
ExecutionDto.JSON_PROPERTY_ID,
ExecutionDto.JSON_PROPERTY_PROCESS_INSTANCE_ID,
ExecutionDto.JSON_PROPERTY_ENDED,
ExecutionDto.JSON_PROPERTY_TENANT_ID
})
@JsonTypeName("ExecutionDto")
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2021-11-19T11:53:20.948992+01:00[Europe/Berlin]")
public class ExecutionDto {
public static final String JSON_PROPERTY_ID = "id";
private String id;
public static final String JSON_PROPERTY_PROCESS_INSTANCE_ID = "processInstanceId";
private String processInstanceId;
public static final String JSON_PROPERTY_ENDED = "ended";
private Boolean ended;
public static final String JSON_PROPERTY_TENANT_ID = "tenantId";
private String tenantId;
public ExecutionDto id(String id) {
this.id = id;
return this;
}
/**
* The id of the Execution.
* @return id
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "The id of the Execution.")
@JsonProperty(JSON_PROPERTY_ID)
@JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public ExecutionDto processInstanceId(String processInstanceId) {
this.processInstanceId = processInstanceId;
return this;
}
/**
* The id of the root of the execution tree representing the process instance.
* @return processInstanceId
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "The id of the root of the execution tree representing the process instance.")
@JsonProperty(JSON_PROPERTY_PROCESS_INSTANCE_ID)
@JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)
public String getProcessInstanceId() {
return processInstanceId;
}
public void setProcessInstanceId(String processInstanceId) {
this.processInstanceId = processInstanceId;
}
public ExecutionDto ended(Boolean ended) {
this.ended = ended;
return this;
}
/**
* Indicates if the execution is ended.
* @return ended
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "Indicates if the execution is ended.")
@JsonProperty(JSON_PROPERTY_ENDED)
@JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)
public Boolean getEnded() {
return ended;
}
public void setEnded(Boolean ended) {
this.ended = ended;
}
public ExecutionDto tenantId(String tenantId) {
this.tenantId = tenantId;
return this;
}
/**
* The id of the tenant this execution belongs to. Can be `null` if the execution belongs to no single tenant.
* @return tenantId
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "The id of the tenant this execution belongs to. Can be `null` if the execution belongs to no single tenant.")
@JsonProperty(JSON_PROPERTY_TENANT_ID)
@JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
ExecutionDto executionDto = (ExecutionDto) o;
return Objects.equals(this.id, executionDto.id) &&
Objects.equals(this.processInstanceId, executionDto.processInstanceId) &&
Objects.equals(this.ended, executionDto.ended) &&
Objects.equals(this.tenantId, executionDto.tenantId);
}
@Override
public int hashCode() {
return Objects.hash(id, processInstanceId, ended, tenantId);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class ExecutionDto {\n");
sb.append(" id: ").append(toIndentedString(id)).append("\n");
sb.append(" processInstanceId: ").append(toIndentedString(processInstanceId)).append("\n");
sb.append(" ended: ").append(toIndentedString(ended)).append("\n");
sb.append(" tenantId: ").append(toIndentedString(tenantId)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
| 1,893 |
5,169 | <filename>Specs/0/6/8/TFImageBrowser/0.1.0/TFImageBrowser.podspec.json
{
"name": "TFImageBrowser",
"version": "0.1.0",
"summary": "图片大图浏览器",
"description": "图片浏览器,字符串、PHAsset等多种图片来源,双击缩放、过场动画、图片缓存.",
"homepage": "https://github.com/ToFind1991/TFImageBrowser",
"license": "MIT",
"authors": {
"shiwei": "<EMAIL>"
},
"platforms": {
"ios": "8.0"
},
"source": {
"git": "https://github.com/ToFind1991/TFImageBrowser.git",
"tag": "0.1.0"
},
"source_files": [
"TFImageBrowser/PhotoBrowser",
"TFImageBrowser/PhotoBrowser/ImageUri",
"TFImageBrowser/PhotoBrowser/Resolver",
"TFImageBrowser/PhotoBrowser/Utilities"
],
"exclude_files": "Classes/Exclude",
"frameworks": "UIKit",
"requires_arc": true
}
| 383 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.