hexsha stringlengths 40 40 | size int64 22 2.4M | ext stringclasses 5
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 3 260 | max_stars_repo_name stringlengths 5 109 | max_stars_repo_head_hexsha stringlengths 40 78 | max_stars_repo_licenses listlengths 1 9 | max_stars_count float64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 3 260 | max_issues_repo_name stringlengths 5 109 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses listlengths 1 9 | max_issues_count float64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 3 260 | max_forks_repo_name stringlengths 5 109 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses listlengths 1 9 | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 22 2.4M | avg_line_length float64 5 169k | max_line_length int64 5 786k | alphanum_fraction float64 0.06 0.95 | matches listlengths 1 11 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
64b18e90febcf2c1a0788ffd2adc1516b88be482 | 2,608 | h | C | include/tvm/utils/sch.h | mmurooka/tvm | 9098ad443d059ed4d216afb5bcc41655afdc34e0 | [
"BSD-3-Clause"
] | 2 | 2021-03-15T00:54:58.000Z | 2022-02-01T20:15:47.000Z | include/tvm/utils/sch.h | mmurooka/tvm | 9098ad443d059ed4d216afb5bcc41655afdc34e0 | [
"BSD-3-Clause"
] | null | null | null | include/tvm/utils/sch.h | mmurooka/tvm | 9098ad443d059ed4d216afb5bcc41655afdc34e0 | [
"BSD-3-Clause"
] | null | null | null | /* Copyright 2017-2018 CNRS-AIST JRL and CNRS-UM LIRMM
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its contributors
* may be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#pragma once
/** @name SCH utilities
*
* These functions make it easier to work with sch-core
*
* @{
*/
#include <tvm/api.h>
#include <sch/S_Polyhedron/S_Polyhedron.h>
#include <sch/CD/CD_Pair.h>
#include <SpaceVecAlg/SpaceVecAlg>
#include <memory>
namespace tvm
{
namespace utils
{
/** Set \p obj pose to \p t */
TVM_DLLAPI void transform(sch::S_Object& obj, const sva::PTransformd& t);
/** Loads an sch::S_Polyhedron object using \p filename */
TVM_DLLAPI std::unique_ptr<sch::S_Polyhedron> Polyhedron(const std::string& filename);
/** Compute distance between two objects
*
* \param pair pair of SCH objects
*
* \param p1 will be the closest point in the first object
*
* \param p2 will be the closes point in the second object
*
* \returns The squared distance between the two objects, returns a negative
* distance in case of inter-penetration
*
*/
TVM_DLLAPI double distance(sch::CD_Pair& pair, Eigen::Vector3d& p1, Eigen::Vector3d& p2);
} // utils
} // namespace tvm
/** @} */
/* End of SCH utilities */
| 33.012658 | 91 | 0.744632 | [
"object",
"transform"
] |
64b3969539ddfff8cfa570e1067c7904cf71cb2d | 7,410 | h | C | Conch/source/common/downloadMgr/JCDownloadMgr.h | waitingchange/ModifyLayanative2.0 | 05370d79a14f5b85367251c8ea846da4316f60f3 | [
"Apache-2.0"
] | null | null | null | Conch/source/common/downloadMgr/JCDownloadMgr.h | waitingchange/ModifyLayanative2.0 | 05370d79a14f5b85367251c8ea846da4316f60f3 | [
"Apache-2.0"
] | null | null | null | Conch/source/common/downloadMgr/JCDownloadMgr.h | waitingchange/ModifyLayanative2.0 | 05370d79a14f5b85367251c8ea846da4316f60f3 | [
"Apache-2.0"
] | null | null | null | /**
@file JCDownloadMgr.h
@brief
@author hugao
@version 1.0
@date 2016_5_11
*/
#ifndef __JCDownloadMgr_H__
#define __JCDownloadMgr_H__
#include "../buffer/JCBuffer.h"
#include <functional>
#include <thread>
#include <mutex>
#include <map>
#include <atomic>
#include "../misc/JCLayaThreadPool.h"
namespace laya{
#ifndef THIN_COMMON_WITHOUT_DOWNLOAD
class Curl;
#endif
struct _QueryBase;
class __Buffer;
/**
* @brief 只负责从网络下载资源。post数据。不管缓存。更新。
* 同时做转换层的工作:替换扩展名解密
*/
class JCDownloadMgr{
public:
struct maskinfo {
unsigned int key;
int len;
};
//回调
typedef std::function<int(unsigned int, unsigned int, float)> onProgressFunc; //返回1表示终止下载
//数据,localip,svip,curlret,httpret,header
typedef std::function<void(JCBuffer& buff, const std::string& localip,
const std::string& svip, int curlret, int httpret,
const std::string& httpresheader)> onEndFunc;
public:
static void defCompleteFunc(JCBuffer&, const std::string&, const std::string&,
int, int, const std::string&);
static int defProgressFunc(unsigned int, unsigned int,float);
~JCDownloadMgr();
static JCDownloadMgr* getInstance();
static void delInstance();
//初始化。p_nWorkThreadNum 表示开启几个下载线程。
void init( int p_nWorkThreadNum );
//设置操作超时
void setOpt_optTimeout( int p_nTimeout);
//设置超时后的重试次数。第一个是操作超时后的重试次数,第二个是连接超时后的重试次数。
void setOpt_tryNumOnTimeout(int p_nOptTry, int p_nConnTry){ m_nTryNumConn = p_nConnTry; m_nTryNumOpt=p_nOptTry;};
void getOpt_tryNumOnTimeout(int& p_nOptTry, int& p_nConnTry){ p_nConnTry=m_nTryNumConn ; p_nOptTry= m_nTryNumOpt;};
void setOpt_progCB(onProgressFunc p_ProgCb);
void setOpt_completeCB(onEndFunc p_CompleteCb);
/*
* @brief 完整参数的下载请求
* @prame p_nOptTimeout 下载超时。单位是秒, 要求>2, 如果为0,则使用缺省的。
*/
void download(const char *p_pszUrl,int p_nPriority,
onProgressFunc p_ProgCb, onEndFunc p_CompleteCb,
const char* p_pPostData, int p_nPostLen, //可以为0
bool p_bOnlyHeader, //一般是false
int p_nTimeout, int p_nConnTimeout, //为0则缺省
std::vector<std::string> p_vHeaders, //size()==0则忽略
const char* p_pLocalFile, //一边下载,一边保存,一般用在大文件下载,0则忽略
bool p_bChkRemoteChange=false //检查远端文件是否改变了,大文件用
);
void download(const char* p_pszURL);
virtual void download(const char* p_pszURL,int p_nPriority, onProgressFunc p_ProgCb,
onEndFunc p_CompleteCb ,int p_nOptTimeout);
virtual void download(const char* p_pszURL, int p_nPriority, onProgressFunc p_ProgCb,
onEndFunc p_CompleteCb, int p_nOptTimeout,int p_nConnTimeout);
virtual void download(const char* p_pszURL,int p_nPriority, onProgressFunc p_ProgCb,
onEndFunc p_CompleteCb , int p_nOptTimeout,
std::vector<std::string>& p_headers);
/*
* @brief
* 下载大文件,如果失败,回自动断点续传。
* 中间过程会直接写文件,而普通的下载是下载到内存中。
* @pram p_pszLocal 本地文件位置,包括文件名,要求目录必须存在,且有写的权限。
*/
void downloadBigFile(const char* p_pszURL, const char* p_pszLocal, onProgressFunc p_ProgCb, onEndFunc p_CompleteCb, int p_nTryNum, int p_nOptTimeout);
void getHeader(const char* p_pszUrl, onEndFunc p_CompleteCb, int p_nTryNum, int p_nOptTimeout);
void postData(const char* p_pszURL,const char* p_Buffer, int p_nLength, onEndFunc p_completeCb);
void postData(const char* p_pszURL,const char* p_Buffer, int p_nLength, onEndFunc p_completeCb,
std::vector<std::string>& p_headers);
//删除所有挂起的任务
void clearAllAsyncTask();
//结束当前的任务
void stopCurTask();
//设置代理
void setProxyString(const char* pProxy);
/*
* @brief 替换某个路径。
* 这个是为了解决有些cdn实在不好用而做的。如果路径中存在p_pstrPath(必须完全匹配), 则用p_pszReplace替换。
* 这样可以导致一个动态目录,从而规避cdn问题。
* 注意替换后url的长度不要增加太多。与下面的tail结合不许比原始大小大512
*/
void setFinalReplacePath(const char* p_pstrPath, const char* p_pszReplace);
/*
* @brief 设置下载的时候附加的东西。
* 注意不要让url的长度增加太多。与上面的替换结合不许比原始大小大512
* @param type
* 0表示不附加
* 1随机数,形式为rnd=xxxx
* 2外面设置的字符串
* @param p_strTail
*/
void setDownloadTail(int type, const char* p_strTail);
//根据替换和添加规则,得到一个新的url,内部会重新分配空间,所以需要外部delete
char* getFinalUrl(const char* p_pszUrl);
void resetFinalReplacePath(){
m_strStubPath=""; m_strStubReplace="";
}
void resetDownloadTail(){ m_nDownloadTailType=0; m_strDownloadTail="";};
//下载的时候修改文件的扩展名,以防止中间路途被修改。
//由于没有进行多线程保护。这个必须要保证在程序刚开始的时候设置。
void setDownloadReplaceExt(const char* p_pszOrigin, const char* p_pszNew );
void resetDownloadReplaceExt();
//凡是扩展名为p_pszExt的文件,用key来进行异或操作,操作长度为p_nLen
void setDownloadUnmask(const char* p_pszExt, unsigned char p_nKey, int p_nLen );
void resetDownloadUnmask();
//如果不存在,则key为0
maskinfo getMaskInfo(const char* p_pszExt );
//如果buffer长度太小,则mask整个buffer
void maskBuffer( maskinfo& p_mask, char* p_pBuff, int p_nLen );
int getThreadNum(){ return m_nThreadNum; }
void setCookieFile( const char* p_pszCookieFile );
//优先级最低的给一个独立的线程
void postToDownloadThread(std::function<int(void*, unsigned char **,size_t*)> task, int p_nPriority);
protected:
//这是一个单件,不允许直接构造
JCDownloadMgr();
int __DownloadBigFile(void *p_pCurl, const char *p_pszUrl, const char* p_pszLocal, bool p_bHaveQuery, int p_nOptTimeout, int p_nTryNum);
int __DownloadHeader(void *p_pCurl, const char *p_pszUrl, unsigned char **p_ppBuff, size_t *p_piSize, bool p_bHaveQuery, int p_nOptTimeout, int p_nTryNum);
public://不对外的
void __WorkThread();
//下载完数据的处理。
bool postDownload(const char* p_pszUrl, unsigned char*& p_pBuff, int& p_nLen);
//返回错误代码。实际使用的是 Curl::ErrorCode
//p_bHaveQuery 是表示是否已经有Query了,因为需要决定添加?rnd=xx还是&rnd=xx
int __Download(void *p_pCurl, const char *p_pszUrl, unsigned char **p_ppBuff, size_t *p_piSize, bool p_bHaveQuery);
static bool m_bCancelTask;
public:
char** m_pCurDownloadingUrl; //正在下载的文件。调试用。如果某一个为0则表示正在空闲
static int s_nNoResponseTimeout; //如果下载中途没有数据了,则超过这么长时间之后就重来。
static std::string s_curlProxyString;
static int s_nConnTimeout;//超时的全局设置
static int s_nOptTimeout;
static bool s_bEncodeURI;
protected:
short m_nTryNumOpt;
short m_nTryNumConn;
short m_nThreadNum;
JCThreadPool<_QueryBase *> m_ThreadPool;
std::recursive_mutex m_CancelMutex;
#ifdef WIN32
std::atomic_uint32_t m_nStopNum; //完成个数
#else
std::atomic_uint m_nStopNum; //完成个数
#endif
std::string m_strStubPath;
std::string m_strStubReplace;
int m_nDownloadTailType;
std::string m_strDownloadTail;
std::vector<std::string> m_vExtReplace; //所有需要替换的扩展名。两个一对,第一个是原始的,第二个是新的
int m_nTimeout;
onProgressFunc m_funcProgress;
onEndFunc m_funcComplete;
std::string m_strCookieFile;
typedef std::map<std::string, maskinfo> maskMap;
maskMap m_maskInfo;
};
std::string encodeURI(const char* url);
}
//------------------------------------------------------------------------------
#endif //__JCDownloadMgr_H__
| 35.797101 | 157 | 0.670175 | [
"vector"
] |
64b5dc244b37146acc3776c1ef650b51c1de9ef5 | 7,805 | h | C | content/services/auction_worklet/seller_worklet.h | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 76 | 2020-09-02T03:05:41.000Z | 2022-03-30T04:40:55.000Z | content/services/auction_worklet/seller_worklet.h | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 45 | 2020-09-02T03:21:37.000Z | 2022-03-31T22:19:45.000Z | content/services/auction_worklet/seller_worklet.h | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 8 | 2020-07-22T18:49:18.000Z | 2022-02-08T10:27:16.000Z | // Copyright 2021 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CONTENT_SERVICES_AUCTION_WORKLET_SELLER_WORKLET_H_
#define CONTENT_SERVICES_AUCTION_WORKLET_SELLER_WORKLET_H_
#include <stdint.h>
#include <memory>
#include <string>
#include "base/callback.h"
#include "base/sequence_checker.h"
#include "content/services/auction_worklet/public/mojom/auction_worklet_service.mojom-forward.h"
#include "content/services/auction_worklet/public/mojom/auction_worklet_service.mojom.h"
#include "content/services/auction_worklet/public/mojom/seller_worklet.mojom.h"
#include "content/services/auction_worklet/worklet_loader.h"
#include "mojo/public/cpp/bindings/pending_remote.h"
#include "services/network/public/mojom/url_loader_factory.mojom-forward.h"
#include "third_party/abseil-cpp/absl/types/optional.h"
#include "third_party/blink/public/mojom/interest_group/interest_group_types.mojom-forward.h"
#include "url/gurl.h"
#include "url/origin.h"
#include "v8/include/v8-persistent-handle.h"
namespace v8 {
class UnboundScript;
} // namespace v8
namespace auction_worklet {
class AuctionV8Helper;
// Represents a seller worklet for FLEDGE
// (https://github.com/WICG/turtledove/blob/main/FLEDGE.md). Loads and runs the
// seller worklet's Javascript.
class SellerWorklet : public mojom::SellerWorklet {
public:
// Starts loading the worklet script on construction. Callback will be invoked
// asynchronously once the data has been fetched or an error has occurred.
SellerWorklet(scoped_refptr<AuctionV8Helper> v8_helper,
bool pause_for_debugger_on_start,
mojo::PendingRemote<network::mojom::URLLoaderFactory>
pending_url_loader_factory,
const GURL& script_source_url,
mojom::AuctionWorkletService::LoadSellerWorkletCallback
load_worklet_callback);
explicit SellerWorklet(const SellerWorklet&) = delete;
SellerWorklet& operator=(const SellerWorklet&) = delete;
~SellerWorklet() override;
// Warning: The caller may need to spin the event loop for this to get
// initialized to a value different from kNoDebugContextGroupId.
int context_group_id_for_testing() const { return context_group_id_; }
// mojom::SellerWorklet implementation:
void ScoreAd(const std::string& ad_metadata_json,
double bid,
blink::mojom::AuctionAdConfigPtr auction_config,
const url::Origin& browser_signal_top_window_origin,
const url::Origin& browser_signal_interest_group_owner,
const std::string& browser_signal_ad_render_fingerprint,
uint32_t browser_signal_bidding_duration_msecs,
ScoreAdCallback callback) override;
void ReportResult(blink::mojom::AuctionAdConfigPtr auction_config,
const url::Origin& browser_signal_top_window_origin,
const url::Origin& browser_signal_interest_group_owner,
const GURL& browser_signal_render_url,
const std::string& browser_signal_ad_render_fingerprint,
double browser_signal_bid,
double browser_signal_desirability,
ReportResultCallback callback) override;
void ConnectDevToolsAgent(
mojo::PendingReceiver<blink::mojom::DevToolsAgent> agent) override;
private:
// Portion of SellerWorklet that deals with V8 execution, and therefore lives
// on the v8 thread --- everything except the constructor must be run there.
class V8State {
public:
V8State(scoped_refptr<AuctionV8Helper> v8_helper,
GURL script_source_url,
base::WeakPtr<SellerWorklet> parent);
void SetWorkletScript(WorkletLoader::Result worklet_script);
void ScoreAd(const std::string& ad_metadata_json,
double bid,
blink::mojom::AuctionAdConfigPtr auction_config,
const url::Origin& browser_signal_top_window_origin,
const url::Origin& browser_signal_interest_group_owner,
const std::string& browser_signal_ad_render_fingerprint,
uint32_t browser_signal_bidding_duration_msecs,
ScoreAdCallback callback);
void ReportResult(blink::mojom::AuctionAdConfigPtr auction_config,
const url::Origin& browser_signal_top_window_origin,
const url::Origin& browser_signal_interest_group_owner,
const GURL& browser_signal_render_url,
const std::string& browser_signal_ad_render_fingerprint,
double browser_signal_bid,
double browser_signal_desirability,
ReportResultCallback callback);
void ConnectDevToolsAgent(
mojo::PendingReceiver<blink::mojom::DevToolsAgent> agent);
private:
friend class base::DeleteHelper<V8State>;
~V8State();
void FinishInit();
void PostScoreAdCallbackToUserThread(ScoreAdCallback callback,
double score,
std::vector<std::string> errors);
void PostReportResultCallbackToUserThread(
ReportResultCallback callback,
absl::optional<std::string> signals_for_winner,
absl::optional<GURL> report_url,
std::vector<std::string> errors);
static void PostResumeToUserThread(
base::WeakPtr<SellerWorklet> parent,
scoped_refptr<base::SequencedTaskRunner> user_thread);
const scoped_refptr<AuctionV8Helper> v8_helper_;
const base::WeakPtr<SellerWorklet> parent_;
const scoped_refptr<base::SequencedTaskRunner> user_thread_;
// Compiled script, not bound to any context. Can be repeatedly bound to
// different context and executed, without persisting any state.
v8::Global<v8::UnboundScript> worklet_script_;
const GURL script_source_url_;
int context_group_id_;
SEQUENCE_CHECKER(v8_sequence_checker_);
};
void ResumeIfPaused();
void StartIfReady();
void OnDownloadComplete(WorkletLoader::Result worklet_script,
absl::optional<std::string> error_msg);
void DeliverContextGroupIdOnUserThread(int context_group_id);
void DeliverScoreAdCallbackOnUserThread(ScoreAdCallback callback,
double score,
std::vector<std::string> errors);
void DeliverReportResultCallbackOnUserThread(
ReportResultCallback callback,
absl::optional<std::string> signals_for_winner,
absl::optional<GURL> report_url,
std::vector<std::string> errors);
scoped_refptr<base::SequencedTaskRunner> v8_runner_;
// Kept around until Start().
scoped_refptr<AuctionV8Helper> v8_helper_;
mojo::PendingRemote<network::mojom::URLLoaderFactory>
pending_url_loader_factory_;
const GURL script_source_url_;
bool paused_;
// `context_group_id_` starts at kNoDebugContextGroupId, but then gets
// initialized after some thread hops.
int context_group_id_;
std::unique_ptr<WorkletLoader> worklet_loader_;
// Lives on `v8_runner_`. Since it's deleted there, tasks can be safely
// posted from main thread to it with an Unretained pointer.
std::unique_ptr<V8State, base::OnTaskRunnerDeleter> v8_state_;
mojom::AuctionWorkletService::LoadSellerWorkletCallback
load_worklet_callback_;
SEQUENCE_CHECKER(user_sequence_checker_);
// Used when posting callbacks back from V8State.
base::WeakPtrFactory<SellerWorklet> weak_ptr_factory_{this};
};
} // namespace auction_worklet
#endif // CONTENT_SERVICES_AUCTION_WORKLET_SELLER_WORKLET_H_
| 40.231959 | 96 | 0.712108 | [
"vector"
] |
64b882388219307c06f7a4301a1975873902525d | 350 | h | C | LYProjectKit/PopModule/LYPayPopViewController.h | LYManager/LYProjectKit | b8755c91bb2c26b8091fbe6246506ae118b2837d | [
"MIT"
] | 1 | 2019-03-19T05:50:30.000Z | 2019-03-19T05:50:30.000Z | LYProjectKit/PopModule/LYPayPopViewController.h | LYManager/LYProjectKit | b8755c91bb2c26b8091fbe6246506ae118b2837d | [
"MIT"
] | null | null | null | LYProjectKit/PopModule/LYPayPopViewController.h | LYManager/LYProjectKit | b8755c91bb2c26b8091fbe6246506ae118b2837d | [
"MIT"
] | null | null | null | // LYPayPopViewController.h
// LYProjectKit
//
// Created by Sunshie on 2019/10/20.
// Copyright © 2019 Sunshie. All rights reserved.
//
#import "LYBaseViewController.h"
NS_ASSUME_NONNULL_BEGIN
@interface LYPayPopViewController : LYBaseViewController
/**< ly*/
@property(nonatomic,strong)LYTaskCardModel * model;
@end
NS_ASSUME_NONNULL_END
| 19.444444 | 56 | 0.765714 | [
"model"
] |
64bb2203de7bff736eb15ebba38db5f0978d1f25 | 3,335 | h | C | aws-cpp-sdk-migrationhubstrategy/include/aws/migrationhubstrategy/model/NoManagementPreference.h | perfectrecall/aws-sdk-cpp | fb8cbebf2fd62720b65aeff841ad2950e73d8ebd | [
"Apache-2.0"
] | 1 | 2022-01-05T18:20:03.000Z | 2022-01-05T18:20:03.000Z | aws-cpp-sdk-migrationhubstrategy/include/aws/migrationhubstrategy/model/NoManagementPreference.h | perfectrecall/aws-sdk-cpp | fb8cbebf2fd62720b65aeff841ad2950e73d8ebd | [
"Apache-2.0"
] | 1 | 2022-01-03T23:59:37.000Z | 2022-01-03T23:59:37.000Z | aws-cpp-sdk-migrationhubstrategy/include/aws/migrationhubstrategy/model/NoManagementPreference.h | ravindra-wagh/aws-sdk-cpp | 7d5ff01b3c3b872f31ca98fb4ce868cd01e97696 | [
"Apache-2.0"
] | 1 | 2021-11-09T11:58:03.000Z | 2021-11-09T11:58:03.000Z | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#pragma once
#include <aws/migrationhubstrategy/MigrationHubStrategyRecommendations_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSVector.h>
#include <aws/migrationhubstrategy/model/NoPreferenceTargetDestination.h>
#include <utility>
namespace Aws
{
namespace Utils
{
namespace Json
{
class JsonValue;
class JsonView;
} // namespace Json
} // namespace Utils
namespace MigrationHubStrategyRecommendations
{
namespace Model
{
/**
* <p> Object containing the choice of application destination that you specify.
* </p><p><h3>See Also:</h3> <a
* href="http://docs.aws.amazon.com/goto/WebAPI/migrationhubstrategy-2020-02-19/NoManagementPreference">AWS
* API Reference</a></p>
*/
class AWS_MIGRATIONHUBSTRATEGYRECOMMENDATIONS_API NoManagementPreference
{
public:
NoManagementPreference();
NoManagementPreference(Aws::Utils::Json::JsonView jsonValue);
NoManagementPreference& operator=(Aws::Utils::Json::JsonView jsonValue);
Aws::Utils::Json::JsonValue Jsonize() const;
/**
* <p> The choice of application destination that you specify. </p>
*/
inline const Aws::Vector<NoPreferenceTargetDestination>& GetTargetDestination() const{ return m_targetDestination; }
/**
* <p> The choice of application destination that you specify. </p>
*/
inline bool TargetDestinationHasBeenSet() const { return m_targetDestinationHasBeenSet; }
/**
* <p> The choice of application destination that you specify. </p>
*/
inline void SetTargetDestination(const Aws::Vector<NoPreferenceTargetDestination>& value) { m_targetDestinationHasBeenSet = true; m_targetDestination = value; }
/**
* <p> The choice of application destination that you specify. </p>
*/
inline void SetTargetDestination(Aws::Vector<NoPreferenceTargetDestination>&& value) { m_targetDestinationHasBeenSet = true; m_targetDestination = std::move(value); }
/**
* <p> The choice of application destination that you specify. </p>
*/
inline NoManagementPreference& WithTargetDestination(const Aws::Vector<NoPreferenceTargetDestination>& value) { SetTargetDestination(value); return *this;}
/**
* <p> The choice of application destination that you specify. </p>
*/
inline NoManagementPreference& WithTargetDestination(Aws::Vector<NoPreferenceTargetDestination>&& value) { SetTargetDestination(std::move(value)); return *this;}
/**
* <p> The choice of application destination that you specify. </p>
*/
inline NoManagementPreference& AddTargetDestination(const NoPreferenceTargetDestination& value) { m_targetDestinationHasBeenSet = true; m_targetDestination.push_back(value); return *this; }
/**
* <p> The choice of application destination that you specify. </p>
*/
inline NoManagementPreference& AddTargetDestination(NoPreferenceTargetDestination&& value) { m_targetDestinationHasBeenSet = true; m_targetDestination.push_back(std::move(value)); return *this; }
private:
Aws::Vector<NoPreferenceTargetDestination> m_targetDestination;
bool m_targetDestinationHasBeenSet;
};
} // namespace Model
} // namespace MigrationHubStrategyRecommendations
} // namespace Aws
| 36.648352 | 199 | 0.736132 | [
"object",
"vector",
"model"
] |
d3a4515114fce14213c07ce357d18b5d9c280ff8 | 2,711 | h | C | src/TNL/Operators/fdm/CentralFiniteDifference.h | GregTheMadMonk/tnl-noa | d7d57962decf579a89797816e7d564350157cbf2 | [
"MIT"
] | null | null | null | src/TNL/Operators/fdm/CentralFiniteDifference.h | GregTheMadMonk/tnl-noa | d7d57962decf579a89797816e7d564350157cbf2 | [
"MIT"
] | null | null | null | src/TNL/Operators/fdm/CentralFiniteDifference.h | GregTheMadMonk/tnl-noa | d7d57962decf579a89797816e7d564350157cbf2 | [
"MIT"
] | null | null | null | // Copyright (c) 2004-2022 Tomáš Oberhuber et al.
//
// This file is part of TNL - Template Numerical Library (https://tnl-project.org/)
//
// SPDX-License-Identifier: MIT
#pragma once
#include <noa/3rdparty/tnl-noa/src/TNL/Operators/fdm/FiniteDifferences.h>
#include <noa/3rdparty/tnl-noa/src/TNL/Operators/fdm/ExactDifference.h>
#include <noa/3rdparty/tnl-noa/src/TNL/Operators/Operator.h>
namespace noa::TNL {
namespace Operators {
template< typename Mesh,
int Xdifference = 0,
int YDifference = 0,
int ZDifference = 0,
typename RealType = typename Mesh::RealType,
typename IndexType = typename Mesh::GlobalIndexType >
class CentralFiniteDifference
{};
template< int Dimension,
typename MeshReal,
typename MeshDevice,
typename MeshIndex,
int XDifference,
int YDifference,
int ZDifference,
typename Real,
typename Index >
class CentralFiniteDifference< Meshes::Grid< Dimension, MeshReal, MeshDevice, MeshIndex >,
XDifference,
YDifference,
ZDifference,
Real,
Index > : public Operator< Meshes::Grid< Dimension, MeshReal, MeshDevice, MeshIndex >,
Functions::MeshInteriorDomain,
Dimension,
Dimension,
Real,
Index >
{
public:
typedef Meshes::Grid< Dimension, MeshReal, MeshDevice, MeshIndex > MeshType;
typedef Real RealType;
typedef MeshDevice DeviceType;
typedef Index IndexType;
typedef ExactDifference< Dimension, XDifference, YDifference, ZDifference > ExactOperatorType;
// static constexpr int getMeshDimension() { return Dimension; }
template< typename MeshFunction, typename MeshEntity >
__cuda_callable__
inline Real
operator()( const MeshFunction& u, const MeshEntity& entity, const RealType& time = 0.0 ) const
{
static_assert( MeshFunction::getEntitiesDimension() == Dimension,
"Finite differences can be evaluate only on mesh cells, i.e. the dimensions count of the mesh entities of "
"mesh function must be the same as mesh dimensions count." );
return FiniteDifferences< MeshType, Real, Index, XDifference, YDifference, ZDifference, 0, 0, 0 >::getValue( u, entity );
};
};
} // namespace Operators
} // namespace noa::TNL
| 39.289855 | 128 | 0.585393 | [
"mesh"
] |
d3a7a93ec057f8132b586f013cea8ec8dc6e9bb2 | 6,309 | c | C | cdkl-2.09/lib/cpc_async.c | ezifra/nifti_arm | 31423268a9172d06d3f04d0f0419de31ad0477ad | [
"BSD-3-Clause"
] | 2 | 2019-09-15T08:36:06.000Z | 2019-12-10T01:58:47.000Z | cdkl-2.09/lib/cpc_async.c | ezifra/nifti_arm | 31423268a9172d06d3f04d0f0419de31ad0477ad | [
"BSD-3-Clause"
] | null | null | null | cdkl-2.09/lib/cpc_async.c | ezifra/nifti_arm | 31423268a9172d06d3f04d0f0419de31ad0477ad | [
"BSD-3-Clause"
] | 1 | 2019-09-15T08:36:07.000Z | 2019-09-15T08:36:07.000Z | /*
* CPCLIB
*
* Copyright (C) 2000-2008 EMS Dr. Thomas Wuensche
*
* 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.
*
*/
#include <sys/types.h>
#include <sys/dir.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/file.h>
#include <sys/time.h>
#include <errno.h>
#include <unistd.h>
#include <poll.h>
#include "../include/cpc.h"
#include "../include/cpclib.h"
#include "../include/cpc_common.h"
/*********************************************************************************/
/* Functions to handle CPC messages in an asynchronous programming model */
/*********************************************************************************/
extern unsigned int CPCHandlerCnt[CAN_MAX_DEVICE];
extern CPC_INIT_PARAMS_T CPCInitParams[CAN_MAX_DEVICE];
extern CPC_LIB_PARAMS_T CPCLibParams[CAN_MAX_DEVICE];
#define CPC_HANDLER_CNT 50
typedef enum {
HDLR_STANDARD = 0,
HDLR_EXTENDED
} EN_HDLR_T;
struct CPC_HANDLER {
EN_HDLR_T type;
/* standard handler */
void (*cpc_handler) (int, const CPC_MSG_T *);
/* extended handler */
void (*cpc_handlerEx) (int, const CPC_MSG_T *, void *);
void *customPointer;
};
struct CPC_HANDLER CPCHandlers[CAN_MAX_DEVICE][CPC_HANDLER_CNT];
int CPC_WaitForEvent(int handle, int timeout, unsigned char event)
{
struct pollfd fds;
int result = 0;
if (CPCInitParams[handle].chanparams.fd < 0)
return CPC_ERR_CHANNEL_NOT_ACTIVE;
fds.fd = CPCInitParams[handle].chanparams.fd;
fds.events = event & EVENT_READ ? POLLIN : 0;
fds.events |= event & EVENT_WRITE ? POLLOUT : 0;
fds.revents = 0;
if(poll(&fds, 1, timeout) >= 0) {
result = fds.revents & POLLIN ? EVENT_READ : 0;
result |= fds.revents & POLLOUT ? EVENT_WRITE : 0;
}
return result; // No events
}
/*********************************************************************************/
/* add a handler to the list */
int CPC_AddHandlerEx(int handle,
void (*handlerEx) (int handle, const CPC_MSG_T *, void *customPointer),
void *customPointer)
{
if (CPCInitParams[handle].chanparams.fd < 0)
return CPC_ERR_CHANNEL_NOT_ACTIVE;
if (CPCHandlerCnt[handle] < CPC_HANDLER_CNT) {
CPCHandlers[handle][CPCHandlerCnt[handle]].cpc_handlerEx =
handlerEx;
CPCHandlers[handle][CPCHandlerCnt[handle]].customPointer =
customPointer;
CPCHandlers[handle][CPCHandlerCnt[handle]].type =
HDLR_EXTENDED;
CPCHandlerCnt[handle]++;
return 0;
}
return -1;
}
/*********************************************************************************/
/* remove a handler from the list */
int CPC_RemoveHandlerEx(int handle,
void (*handlerEx) (int handle, const CPC_MSG_T *,
void *customPointer))
{
signed int i;
if (CPCInitParams[handle].chanparams.fd < 0)
return CPC_ERR_CHANNEL_NOT_ACTIVE;
for (i = CPCHandlerCnt[handle] - 1; i >= 0; i--) {
if (CPCHandlers[handle][i].cpc_handlerEx == handlerEx) {
for (; i < CPCHandlerCnt[handle]; i++) {
CPCHandlers[handle][i].cpc_handler = CPCHandlers[handle][i + 1].cpc_handler;
CPCHandlers[handle][i].cpc_handlerEx = CPCHandlers[handle][i + 1].cpc_handlerEx;
CPCHandlers[handle][i].type = CPCHandlers[handle][i + 1].type;
CPCHandlers[handle][i].customPointer =
CPCHandlers[handle][i + 1].customPointer;
}
CPCHandlerCnt[handle]--;
return 0;
}
}
return -1;
}
/*********************************************************************************/
/* add a handler to the list */
int CPC_AddHandler(int handle,
void (*handler) (int handle, const CPC_MSG_T *))
{
if (CPCInitParams[handle].chanparams.fd < 0)
return CPC_ERR_CHANNEL_NOT_ACTIVE;
if (CPCHandlerCnt[handle] < CPC_HANDLER_CNT) {
CPCHandlers[handle][CPCHandlerCnt[handle]].cpc_handler =
handler;
CPCHandlers[handle][CPCHandlerCnt[handle]].type =
HDLR_STANDARD;
CPCHandlerCnt[handle]++;
return 0;
}
return -1;
}
/*********************************************************************************/
/* remove a handler from the list */
int CPC_RemoveHandler(int handle,
void (*handler) (int handle, const CPC_MSG_T *))
{
signed int i;
if (CPCInitParams[handle].chanparams.fd < 0)
return CPC_ERR_CHANNEL_NOT_ACTIVE;
for (i = CPCHandlerCnt[handle] - 1; i >= 0; i--) {
if (CPCHandlers[handle][i].cpc_handler == handler) {
for (; i < CPCHandlerCnt[handle]; i++) {
CPCHandlers[handle][i].cpc_handler =
CPCHandlers[handle][i + 1].cpc_handler;
CPCHandlers[handle][i].cpc_handlerEx =
CPCHandlers[handle][i +
1].cpc_handlerEx;
CPCHandlers[handle][i].type =
CPCHandlers[handle][i + 1].type;
CPCHandlers[handle][i].customPointer =
CPCHandlers[handle][i +
1].customPointer;
}
CPCHandlerCnt[handle]--;
return 0;
}
}
return -1;
}
/*********************************************************************************/
/* execute all handlers in the list */
CPC_MSG_T *CPC_Handle(int handle)
{
unsigned int i;
ssize_t retval;
int fd = CPCInitParams[handle].chanparams.fd;
if (fd < 0)
return NULL;
errno = 0;
retval = CPCLibParams[handle].read(fd, &CPCLibParams[handle].handleMessage, sizeof(CPC_MSG_T));
if (-errno == CPC_ERR_NO_INTERFACE_PRESENT
|| retval == CPC_ERR_NO_INTERFACE_PRESENT) {
CPCLibParams[handle].handleMessage.type = CPC_MSG_T_DISCONNECTED;
CPCLibParams[handle].handleMessage.length = 1;
/* sh 07.03.2005
* device has been disconnected inform application
* via handlers
*/
retval = sizeof(CPC_MSG_T);
}
if (retval > 0) {
for (i = 0; i < CPCHandlerCnt[handle]; i++) {
if (CPCHandlers[handle][i].type == HDLR_STANDARD)
CPCHandlers[handle][i].cpc_handler(handle,
&CPCLibParams[handle].handleMessage);
else
CPCHandlers[handle][i].
cpc_handlerEx(handle, &CPCLibParams[handle].handleMessage,
CPCHandlers[handle][i].
customPointer);
}
return &CPCLibParams[handle].handleMessage;
}
return NULL;
}
| 28.418919 | 96 | 0.600412 | [
"model"
] |
d3abbca68ef877824e91fa743ee0c6af734433c7 | 19,507 | c | C | src/bin/e_comp_wl_input.c | FlorentRevest/Enlightenment | 0b614b8d66c1f1d71b83ea04ae5014c1f66bfc6e | [
"BSD-2-Clause"
] | null | null | null | src/bin/e_comp_wl_input.c | FlorentRevest/Enlightenment | 0b614b8d66c1f1d71b83ea04ae5014c1f66bfc6e | [
"BSD-2-Clause"
] | null | null | null | src/bin/e_comp_wl_input.c | FlorentRevest/Enlightenment | 0b614b8d66c1f1d71b83ea04ae5014c1f66bfc6e | [
"BSD-2-Clause"
] | null | null | null | #define EXECUTIVE_MODE_ENABLED
#define E_COMP_WL
#include "e.h"
#include <sys/mman.h>
static void
_e_comp_wl_input_update_seat_caps(void)
{
Eina_List *l;
struct wl_resource *res;
enum wl_seat_capability caps = 0;
if (e_comp->wl_comp_data->ptr.enabled)
caps |= WL_SEAT_CAPABILITY_POINTER;
if (e_comp->wl_comp_data->kbd.enabled)
caps |= WL_SEAT_CAPABILITY_KEYBOARD;
if (e_comp->wl_comp_data->touch.enabled)
caps |= WL_SEAT_CAPABILITY_TOUCH;
EINA_LIST_FOREACH(e_comp->wl_comp_data->seat.resources, l, res)
wl_seat_send_capabilities(res, caps);
}
static void
_e_comp_wl_input_cb_resource_destroy(struct wl_client *client EINA_UNUSED, struct wl_resource *resource)
{
wl_resource_destroy(resource);
}
static void
_e_comp_wl_input_pointer_cb_cursor_set(struct wl_client *client, struct wl_resource *resource EINA_UNUSED, uint32_t serial EINA_UNUSED, struct wl_resource *surface_resource, int32_t x, int32_t y)
{
E_Client *ec;
Eina_Bool got_mouse = EINA_FALSE;
E_CLIENT_FOREACH(ec)
{
if (e_pixmap_type_get(ec->pixmap) != E_PIXMAP_TYPE_WL) continue;
if (!ec->comp_data->surface) continue;
if (client != wl_resource_get_client(ec->comp_data->surface)) continue;
if (ec->mouse.in)
{
got_mouse = EINA_TRUE;
break;
}
}
if (!got_mouse) return;
if (!surface_resource)
{
e_pointer_object_set(e_comp->pointer, NULL, x, y);
return;
}
ec = wl_resource_get_user_data(surface_resource);
if (!ec->re_manage)
{
ec->re_manage = 1;
ec->ignored = 0;
ec->lock_focus_out = ec->layer_block = ec->visible = ec->override = 1;
ec->icccm.title = eina_stringshare_add("noshadow");
evas_object_pass_events_set(ec->frame, 1);
e_client_focus_stack_set(eina_list_remove(e_client_focus_stack_get(), ec));
EC_CHANGED(ec);
}
/* ignore cursor changes during resize/move I guess */
if (e_client_action_get()) return;
e_pointer_object_set(e_comp->pointer, ec->frame, x, y);
}
static const struct wl_pointer_interface _e_pointer_interface =
{
_e_comp_wl_input_pointer_cb_cursor_set,
_e_comp_wl_input_cb_resource_destroy
};
static const struct wl_keyboard_interface _e_keyboard_interface =
{
_e_comp_wl_input_cb_resource_destroy
};
static const struct wl_touch_interface _e_touch_interface =
{
_e_comp_wl_input_cb_resource_destroy
};
static void
_e_comp_wl_input_cb_pointer_unbind(struct wl_resource *resource)
{
e_comp->wl_comp_data->ptr.resources =
eina_list_remove(e_comp->wl_comp_data->ptr.resources, resource);
}
static void
_e_comp_wl_input_cb_pointer_get(struct wl_client *client, struct wl_resource *resource, uint32_t id)
{
struct wl_resource *res;
/* try to create pointer resource */
res = wl_resource_create(client, &wl_pointer_interface,
wl_resource_get_version(resource), id);
if (!res)
{
ERR("Could not create pointer on seat %s: %m",
e_comp->wl_comp_data->seat.name);
wl_client_post_no_memory(client);
return;
}
e_comp->wl_comp_data->ptr.resources =
eina_list_append(e_comp->wl_comp_data->ptr.resources, res);
wl_resource_set_implementation(res, &_e_pointer_interface,
e_comp->wl_comp_data,
_e_comp_wl_input_cb_pointer_unbind);
}
static void
_e_comp_wl_input_cb_keyboard_unbind(struct wl_resource *resource)
{
Eina_List *l, *ll;
struct wl_resource *res;
e_comp->wl_comp_data->kbd.resources =
eina_list_remove(e_comp->wl_comp_data->kbd.resources, resource);
EINA_LIST_FOREACH_SAFE(e_comp->wl_comp_data->kbd.focused, l, ll, res)
if (res == resource)
e_comp->wl_comp_data->kbd.focused =
eina_list_remove_list(e_comp->wl_comp_data->kbd.resources, l);
}
void
e_comp_wl_input_keyboard_enter_send(E_Client *ec)
{
struct wl_resource *res;
Eina_List *l;
uint32_t serial;
if (!ec->comp_data->surface) return;
if (!e_comp->wl_comp_data->kbd.focused) return;
e_comp_wl_input_keyboard_modifiers_serialize();
serial = wl_display_next_serial(e_comp->wl_comp_data->wl.disp);
EINA_LIST_FOREACH(e_comp->wl_comp_data->kbd.focused, l, res)
{
wl_keyboard_send_enter(res, serial, ec->comp_data->surface,
&e_comp->wl_comp_data->kbd.keys);
wl_keyboard_send_modifiers(res, serial,
e_comp->wl_comp_data->kbd.mod_depressed,
e_comp->wl_comp_data->kbd.mod_latched,
e_comp->wl_comp_data->kbd.mod_locked,
e_comp->wl_comp_data->kbd.mod_group);
}
}
static void
_e_comp_wl_input_cb_keyboard_get(struct wl_client *client, struct wl_resource *resource, uint32_t id)
{
E_Client *focused;
struct wl_resource *res;
/* try to create keyboard resource */
res = wl_resource_create(client, &wl_keyboard_interface,
wl_resource_get_version(resource), id);
if (!res)
{
ERR("Could not create keyboard on seat %s: %m",
e_comp->wl_comp_data->seat.name);
wl_client_post_no_memory(client);
return;
}
e_comp->wl_comp_data->kbd.resources =
eina_list_append(e_comp->wl_comp_data->kbd.resources, res);
wl_resource_set_implementation(res, &_e_keyboard_interface,
e_comp->wl_comp_data,
_e_comp_wl_input_cb_keyboard_unbind);
/* FIXME: These values should be configurable */
if (wl_resource_get_version(res) >= WL_KEYBOARD_REPEAT_INFO_SINCE_VERSION)
wl_keyboard_send_repeat_info(res, 25, 400);
/* send current keymap */
wl_keyboard_send_keymap(res, WL_KEYBOARD_KEYMAP_FORMAT_XKB_V1,
e_comp->wl_comp_data->xkb.fd,
e_comp->wl_comp_data->xkb.size);
/* if the client owns the focused surface, we need to send an enter */
focused = e_client_focused_get();
if (!focused) return;
e_comp_wl_input_keyboard_enter_send(focused);
}
static void
_e_comp_wl_input_cb_touch_unbind(struct wl_resource *resource)
{
e_comp->wl_comp_data->touch.resources =
eina_list_remove(e_comp->wl_comp_data->touch.resources, resource);
}
static void
_e_comp_wl_input_cb_touch_get(struct wl_client *client EINA_UNUSED, struct wl_resource *resource, uint32_t id EINA_UNUSED)
{
struct wl_resource *res;
/* try to create pointer resource */
res = wl_resource_create(client, &wl_touch_interface,
wl_resource_get_version(resource), id);
if (!res)
{
ERR("Could not create touch on seat %s: %m",
e_comp->wl_comp_data->seat.name);
wl_client_post_no_memory(client);
return;
}
e_comp->wl_comp_data->touch.resources =
eina_list_append(e_comp->wl_comp_data->touch.resources, res);
wl_resource_set_implementation(res, &_e_touch_interface,
e_comp->wl_comp_data,
_e_comp_wl_input_cb_touch_unbind);
}
static const struct wl_seat_interface _e_seat_interface =
{
_e_comp_wl_input_cb_pointer_get,
_e_comp_wl_input_cb_keyboard_get,
_e_comp_wl_input_cb_touch_get,
};
static void
_e_comp_wl_input_cb_unbind_seat(struct wl_resource *resource)
{
e_comp->wl_comp_data->seat.resources =
eina_list_remove(e_comp->wl_comp_data->seat.resources, resource);
}
static void
_e_comp_wl_input_cb_bind_seat(struct wl_client *client, void *data EINA_UNUSED, uint32_t version, uint32_t id)
{
struct wl_resource *res;
res = wl_resource_create(client, &wl_seat_interface, MIN(version, 4), id);
if (!res)
{
ERR("Could not create seat resource: %m");
return;
}
/* store version of seat interface for reuse in updating capabilities */
e_comp->wl_comp_data->seat.version = version;
e_comp->wl_comp_data->seat.resources =
eina_list_append(e_comp->wl_comp_data->seat.resources, res);
wl_resource_set_implementation(res, &_e_seat_interface,
e_comp->wl_comp_data,
_e_comp_wl_input_cb_unbind_seat);
_e_comp_wl_input_update_seat_caps();
if (e_comp->wl_comp_data->seat.version >= WL_SEAT_NAME_SINCE_VERSION)
wl_seat_send_name(res, e_comp->wl_comp_data->seat.name);
}
static int
_e_comp_wl_input_keymap_fd_get(off_t size)
{
int fd = 0, blen = 0, len = 0;
const char *path;
char tmp[PATH_MAX];
long flags;
blen = sizeof(tmp) - 1;
if (!(path = getenv("XDG_RUNTIME_DIR")))
return -1;
len = strlen(path);
if (len < blen)
{
strcpy(tmp, path);
strcat(tmp, "/e-wl-keymap-XXXXXX");
}
else
return -1;
if ((fd = mkstemp(tmp)) < 0) return -1;
flags = fcntl(fd, F_GETFD);
if (flags < 0)
{
close(fd);
return -1;
}
if (fcntl(fd, F_SETFD, (flags | FD_CLOEXEC)) == -1)
{
close(fd);
return -1;
}
if (ftruncate(fd, size) < 0)
{
close(fd);
return -1;
}
unlink(tmp);
return fd;
}
static void
_e_comp_wl_input_keymap_update(struct xkb_keymap *keymap)
{
char *tmp;
xkb_mod_mask_t latched = 0, locked = 0, group = 0;
struct wl_resource *res;
Eina_List *l;
/* unreference any existing keymap */
if (e_comp->wl_comp_data->xkb.keymap)
xkb_map_unref(e_comp->wl_comp_data->xkb.keymap);
/* unmap any existing keyboard area */
if (e_comp->wl_comp_data->xkb.area)
munmap(e_comp->wl_comp_data->xkb.area, e_comp->wl_comp_data->xkb.size);
if (e_comp->wl_comp_data->xkb.fd >= 0) close(e_comp->wl_comp_data->xkb.fd);
/* unreference any existing keyboard state */
if (e_comp->wl_comp_data->xkb.state)
{
latched =
xkb_state_serialize_mods(e_comp->wl_comp_data->xkb.state,
XKB_STATE_MODS_LATCHED);
locked =
xkb_state_serialize_mods(e_comp->wl_comp_data->xkb.state,
XKB_STATE_MODS_LOCKED);
group =
xkb_state_serialize_layout(e_comp->wl_comp_data->xkb.state,
XKB_STATE_LAYOUT_EFFECTIVE);
xkb_state_unref(e_comp->wl_comp_data->xkb.state);
}
/* create a new xkb state */
e_comp->wl_comp_data->xkb.state = xkb_state_new(keymap);
if ((latched) || (locked) || (group))
xkb_state_update_mask(e_comp->wl_comp_data->xkb.state, 0,
latched, locked, 0, 0, group);
/* increment keymap reference */
e_comp->wl_comp_data->xkb.keymap = xkb_map_ref(keymap);
/* fetch updated modifiers */
e_comp->wl_comp_data->kbd.mod_shift =
xkb_map_mod_get_index(keymap, XKB_MOD_NAME_SHIFT);
e_comp->wl_comp_data->kbd.mod_caps =
xkb_map_mod_get_index(keymap, XKB_MOD_NAME_CAPS);
e_comp->wl_comp_data->kbd.mod_ctrl =
xkb_map_mod_get_index(keymap, XKB_MOD_NAME_CTRL);
e_comp->wl_comp_data->kbd.mod_alt =
xkb_map_mod_get_index(keymap, XKB_MOD_NAME_ALT);
e_comp->wl_comp_data->kbd.mod_super =
xkb_map_mod_get_index(keymap, XKB_MOD_NAME_LOGO);
if (!(tmp = xkb_map_get_as_string(keymap)))
{
ERR("Could not get keymap string");
return;
}
e_comp->wl_comp_data->xkb.size = strlen(tmp) + 1;
e_comp->wl_comp_data->xkb.fd =
_e_comp_wl_input_keymap_fd_get(e_comp->wl_comp_data->xkb.size);
if (e_comp->wl_comp_data->xkb.fd < 0)
{
ERR("Could not create keymap file");
free(tmp);
return;
}
e_comp->wl_comp_data->xkb.area =
mmap(NULL, e_comp->wl_comp_data->xkb.size, (PROT_READ | PROT_WRITE),
MAP_SHARED, e_comp->wl_comp_data->xkb.fd, 0);
if (e_comp->wl_comp_data->xkb.area == MAP_FAILED)
{
ERR("Failed to mmap keymap area: %m");
free(tmp);
return;
}
strcpy(e_comp->wl_comp_data->xkb.area, tmp);
free(tmp);
/* send updated keymap */
EINA_LIST_FOREACH(e_comp->wl_comp_data->kbd.resources, l, res)
wl_keyboard_send_keymap(res, WL_KEYBOARD_KEYMAP_FORMAT_XKB_V1,
e_comp->wl_comp_data->xkb.fd,
e_comp->wl_comp_data->xkb.size);
/* update modifiers */
e_comp_wl_input_keyboard_modifiers_update();
}
EINTERN Eina_Bool
e_comp_wl_input_init(void)
{
/* set default seat name */
if (!e_comp->wl_comp_data->seat.name)
e_comp->wl_comp_data->seat.name = "default";
e_comp->wl_comp_data->xkb.fd = -1;
/* create the global resource for input seat */
e_comp->wl_comp_data->seat.global =
wl_global_create(e_comp->wl_comp_data->wl.disp, &wl_seat_interface, 4,
e_comp->wl_comp_data, _e_comp_wl_input_cb_bind_seat);
if (!e_comp->wl_comp_data->seat.global)
{
ERR("Could not create global for seat: %m");
return EINA_FALSE;
}
wl_array_init(&e_comp->wl_comp_data->kbd.keys);
return EINA_TRUE;
}
EINTERN void
e_comp_wl_input_shutdown(void)
{
struct wl_resource *res;
/* destroy pointer resources */
EINA_LIST_FREE(e_comp->wl_comp_data->ptr.resources, res)
wl_resource_destroy(res);
/* destroy keyboard resources */
EINA_LIST_FREE(e_comp->wl_comp_data->kbd.resources, res)
wl_resource_destroy(res);
e_comp->wl_comp_data->kbd.resources = eina_list_free(e_comp->wl_comp_data->kbd.resources);
/* destroy touch resources */
EINA_LIST_FREE(e_comp->wl_comp_data->touch.resources, res)
wl_resource_destroy(res);
/* destroy e_comp->wl_comp_data->kbd.keys array */
wl_array_release(&e_comp->wl_comp_data->kbd.keys);
/* unmap any existing keyboard area */
if (e_comp->wl_comp_data->xkb.area)
munmap(e_comp->wl_comp_data->xkb.area, e_comp->wl_comp_data->xkb.size);
if (e_comp->wl_comp_data->xkb.fd >= 0) close(e_comp->wl_comp_data->xkb.fd);
/* unreference any existing keyboard state */
if (e_comp->wl_comp_data->xkb.state)
xkb_state_unref(e_comp->wl_comp_data->xkb.state);
/* unreference any existing keymap */
if (e_comp->wl_comp_data->xkb.keymap)
xkb_map_unref(e_comp->wl_comp_data->xkb.keymap);
/* unreference any existing context */
if (e_comp->wl_comp_data->xkb.context)
xkb_context_unref(e_comp->wl_comp_data->xkb.context);
/* destroy the global seat resource */
if (e_comp->wl_comp_data->seat.global)
wl_global_destroy(e_comp->wl_comp_data->seat.global);
e_comp->wl_comp_data->seat.global = NULL;
}
EINTERN Eina_Bool
e_comp_wl_input_pointer_check(struct wl_resource *res)
{
return wl_resource_instance_of(res, &wl_pointer_interface,
&_e_pointer_interface);
}
EINTERN Eina_Bool
e_comp_wl_input_keyboard_check(struct wl_resource *res)
{
return wl_resource_instance_of(res, &wl_keyboard_interface,
&_e_keyboard_interface);
}
EINTERN Eina_Bool
e_comp_wl_input_keyboard_modifiers_serialize(void)
{
Eina_Bool changed = EINA_FALSE;
xkb_mod_mask_t mod;
xkb_layout_index_t grp;
mod = xkb_state_serialize_mods(e_comp->wl_comp_data->xkb.state,
XKB_STATE_DEPRESSED);
changed |= mod != e_comp->wl_comp_data->kbd.mod_depressed;
e_comp->wl_comp_data->kbd.mod_depressed = mod;
mod = xkb_state_serialize_mods(e_comp->wl_comp_data->xkb.state,
XKB_STATE_MODS_LATCHED);
changed |= mod != e_comp->wl_comp_data->kbd.mod_latched;
e_comp->wl_comp_data->kbd.mod_latched = mod;
mod = xkb_state_serialize_mods(e_comp->wl_comp_data->xkb.state,
XKB_STATE_MODS_LOCKED);
changed |= mod != e_comp->wl_comp_data->kbd.mod_locked;
e_comp->wl_comp_data->kbd.mod_locked = mod;
grp = xkb_state_serialize_layout(e_comp->wl_comp_data->xkb.state,
XKB_STATE_LAYOUT_EFFECTIVE);
changed |= grp != e_comp->wl_comp_data->kbd.mod_group;
e_comp->wl_comp_data->kbd.mod_group = grp;
return changed;
}
EINTERN void
e_comp_wl_input_keyboard_modifiers_update(void)
{
uint32_t serial;
struct wl_resource *res;
Eina_List *l;
if (!e_comp_wl_input_keyboard_modifiers_serialize()) return;
if (!e_comp->wl_comp_data->kbd.focused) return;
serial = wl_display_next_serial(e_comp->wl_comp_data->wl.disp);
EINA_LIST_FOREACH(e_comp->wl_comp_data->kbd.resources, l, res)
wl_keyboard_send_modifiers(res, serial,
e_comp->wl_comp_data->kbd.mod_depressed,
e_comp->wl_comp_data->kbd.mod_latched,
e_comp->wl_comp_data->kbd.mod_locked,
e_comp->wl_comp_data->kbd.mod_group);
}
EINTERN void
e_comp_wl_input_keyboard_state_update(uint32_t keycode, Eina_Bool pressed)
{
enum xkb_key_direction dir;
if (!e_comp->wl_comp_data->xkb.state) return;
if (pressed) dir = XKB_KEY_DOWN;
else dir = XKB_KEY_UP;
e_comp->wl_comp_data->kbd.mod_changed =
xkb_state_update_key(e_comp->wl_comp_data->xkb.state, keycode + 8, dir);
e_comp_wl_input_keyboard_modifiers_update();
}
E_API void
e_comp_wl_input_pointer_enabled_set(Eina_Bool enabled)
{
/* check for valid compositor data */
if (!e_comp->wl_comp_data)
{
ERR("No compositor data");
return;
}
e_comp->wl_comp_data->ptr.enabled = !!enabled;
_e_comp_wl_input_update_seat_caps();
}
E_API void
e_comp_wl_input_keyboard_enabled_set(Eina_Bool enabled)
{
/* check for valid compositor data */
if (!e_comp->wl_comp_data)
{
ERR("No compositor data");
return;
}
e_comp->wl_comp_data->kbd.enabled = !!enabled;
_e_comp_wl_input_update_seat_caps();
}
E_API void
e_comp_wl_input_keymap_set(const char *rules, const char *model, const char *layout)
{
struct xkb_keymap *keymap;
struct xkb_rule_names names;
/* DBG("COMP_WL: Keymap Set: %s %s %s", rules, model, layout); */
/* assemble xkb_rule_names so we can fetch keymap */
memset(&names, 0, sizeof(names));
if (rules) names.rules = strdup(rules);
else names.rules = strdup("evdev");
if (model) names.model = strdup(model);
else names.model = strdup("pc105");
if (layout) names.layout = strdup(layout);
else names.layout = strdup("us");
/* unreference any existing context */
if (e_comp->wl_comp_data->xkb.context)
xkb_context_unref(e_comp->wl_comp_data->xkb.context);
/* create a new xkb context */
e_comp->wl_comp_data->xkb.context = xkb_context_new(0);
/* fetch new keymap based on names */
keymap = xkb_map_new_from_names(e_comp->wl_comp_data->xkb.context, &names, 0);
if (keymap)
{
/* update compositor keymap */
_e_comp_wl_input_keymap_update(keymap);
}
/* cleanup */
free((char *)names.rules);
free((char *)names.model);
free((char *)names.layout);
}
EAPI void
e_comp_wl_input_touch_enabled_set(Eina_Bool enabled)
{
/* check for valid compositor data */
if (!e_comp->wl_comp_data)
{
ERR("No compositor data");
return;
}
e_comp->wl_comp_data->touch.enabled = !!enabled;
_e_comp_wl_input_update_seat_caps();
}
EINTERN Eina_Bool
e_comp_wl_input_touch_check(struct wl_resource *res)
{
return wl_resource_instance_of(res, &wl_touch_interface,
&_e_touch_interface);
}
| 30.432137 | 195 | 0.669196 | [
"model"
] |
d3b35fc6cf962ba99cfc90a8a6ae563c430e5c25 | 294 | h | C | swalib_example/Code/Game/Entities/Boss.h | MariaRoman96/Minijuego | 83a6a8d736c33fd866ff37a18633940b75d19b40 | [
"BSD-2-Clause"
] | 1 | 2020-07-20T17:57:27.000Z | 2020-07-20T17:57:27.000Z | swalib_example/Code/Game/Entities/Boss.h | MariaRoman96/Minijuego | 83a6a8d736c33fd866ff37a18633940b75d19b40 | [
"BSD-2-Clause"
] | null | null | null | swalib_example/Code/Game/Entities/Boss.h | MariaRoman96/Minijuego | 83a6a8d736c33fd866ff37a18633940b75d19b40 | [
"BSD-2-Clause"
] | null | null | null | #pragma once
#include <vector>
#include "Entity.h"
#include "../../../../common/core.h"
#include "../Entities/Components/render_comp.h"
#include "../Graphics/sprite.h"
#include "Enemy.h"
class Boss : public cEntity {
public:
static Boss* create();
void finishLogic();
private:
Boss() {};
}; | 19.6 | 47 | 0.670068 | [
"vector"
] |
d3ba5cf460b05d6455b10b2d013c9d33b41a474e | 9,535 | h | C | include/itkMultigridAnisotropicDiffusionImageFilter.h | nellogrb/MultigridAnisotropicDiffusion | 9f476c24bd296d801884c6786374adc63f03cabd | [
"Apache-2.0"
] | 1 | 2016-07-26T14:32:35.000Z | 2016-07-26T14:32:35.000Z | include/itkMultigridAnisotropicDiffusionImageFilter.h | nellogrb/MultigridAnisotropicDiffusion | 9f476c24bd296d801884c6786374adc63f03cabd | [
"Apache-2.0"
] | null | null | null | include/itkMultigridAnisotropicDiffusionImageFilter.h | nellogrb/MultigridAnisotropicDiffusion | 9f476c24bd296d801884c6786374adc63f03cabd | [
"Apache-2.0"
] | null | null | null | /*=========================================================================
*
* Copyright Insight Software Consortium
*
* 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.txt
*
* 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 __itkMultigridAnisotropicDiffusionImageFilter_h
#define __itkMultigridAnisotropicDiffusionImageFilter_h
#include "itkImageToImageFilter.h"
#include "itkMacro.h"
#include "mad/itkStencilImage.h"
#include "mad/itkGridsHierarchy.h"
#include "mad/itkInterGridOperators.h"
//#include "mad/itkCoarseGridOperatorsGenerator.h"
#include "mad/itkMultigridGaussSeidelSmoother.h"
#include "mad/itkDirectSolver.h"
#ifdef BENCHMARK
#include <fstream>
#include <ctime>
#endif
namespace itk
{
/** \class MultigridAnisotropicDiffusionImageFilter
*
* \brief This class embodies, in the form of an ImageToImageFilter class,
* an implementation of a multigrid method to solve a generic anisotropic
* diffusion problem:
*
* \f[
* \partial_t I(\mathbf{x}, t) - \mathrm{div} \left( M(\mathbf{x}) \nabla I(\mathbf{x}, t) \right) = 0
* \f]
*
* The filter is templated, in addition to the input and output image
* types, over the smoother type; the latter should be a derived class
* of the pure virtual base class MultigridSmoother. The smoothers
* MultigridGaussSeidel (which is the default one if not specified)
* and MultigridWeightedJacobi have already been implemented, and can
* be found in the subdirectory .mad/ .
*
* The minimum inputs required for the filter to work are:
*
* -# The image to be diffused
* -# A diffusion tensor in the form of an image with a
* SymmetricSecondRankTensor as pixel type
*
* The image and the tensor must be defined on the same ImageRegion.
* Optional parameters are:
*
* -# The time step (defaults to 0.01)
* -# The number of time steps (defaults to 1)
* -# The type of coarse grid operator to build, the options being
* Direct Coarse Approximation (DCA) and Galerkin Coarse Approximation
* (GCA) (defaults to DCA)
* -# The type of cycle to be executed: FMG, VCYCLE and SMOOTHER
* (in the last two cases, the initial guess is the image at the
* previous step). FMG and VCYCLE are well-known multigrid cycles.
* The SMOOTHER mode solves the problem using the chosen smoother
* only, and is mainly intended as a baseline for comparison with
* the first two. (defaults to VCYCLE).
* -# The number of smoother iterations for each level (defaults to 2)
* -# The maximum relative residual tolerance (defaults to 1e-6)
* -# The maximum number of VCycles (defaults to 100)
* -# The verbosity (defaults to 0 = quiet)
*
* The filter works with double type as internal precision. The coefficients
* of the SymmetricSecondRankTensor elements composing the diffusion
* tensor are expected to have the same type as the input image.
*
* \author Antonello Gerbi
*
* \ingroup ITKMultigridAnisotropicDiffusion
*/
template < class TInputImage, class TOutputImage,
class TSmootherType = mad::MultigridGaussSeidelSmoother< TInputImage::ImageDimension > >
class MultigridAnisotropicDiffusionImageFilter :
public ImageToImageFilter< TInputImage, TOutputImage >
{
public:
/** Standard and useful class typedefs. */
typedef MultigridAnisotropicDiffusionImageFilter Self;
typedef ImageToImageFilter< TInputImage, TOutputImage > SuperClass;
typedef SmartPointer< Self > Pointer;
typedef SmartPointer< const Self > ConstPointer;
typedef TInputImage InputImageType;
typedef typename TInputImage::PixelType InputPixelType;
typedef TOutputImage OutputImageType;
typedef typename TOutputImage::PixelType OutputPixelType;
typedef double InternalPixelType;
typedef Image< InternalPixelType, TInputImage::ImageDimension > InternalImageType;
typedef Image< SymmetricSecondRankTensor< InputPixelType, TInputImage::ImageDimension >,
TInputImage::ImageDimension > InputTensorImageType;
typedef Image< SymmetricSecondRankTensor< InternalPixelType, TInputImage::ImageDimension >,
TInputImage::ImageDimension > InternalTensorImageType;
typedef mad::StencilImage< InternalPixelType, TInputImage::ImageDimension > StencilImageType;
typedef typename mad::GridsHierarchy< TInputImage::ImageDimension > GridsHierarchyType;
typedef typename mad::InterGridOperators< TInputImage::ImageDimension > InterGridOperatorsType;
typedef typename mad::DirectSolver< TInputImage::ImageDimension > DirectSolverType;
typedef InternalPixelType Precision;
enum CycleType { VCYCLE, FMG, SMOOTHER };
/** Method for creation through the object factory. */
itkNewMacro( Self );
/** Run-time type information (and related methods). */
itkTypeMacro( MultigridAnisotropicDiffusionImageFilter, ImageToImageFilter );
/** Sets the type of cycle to be executed. CycleType is
* an enum with VCYCLE, FMG and SMOOTHER as possible values */
itkSetMacro( Cycle, CycleType );
/** Sets the number of iterations that should be executed each time
* on both the ascending and descending legs of the VCycle. */
itkSetMacro( IterationsPerGrid, unsigned int );
/** Sets the maximum number of VCycle to be executed for each
* time step if the residual tolerance is not reached before. */
itkSetMacro( MaxCycles, unsigned int );
/** Sets the number of time steps. All of the data required
* to solve the problem is calculated just once, before the
* first step. */
itkSetMacro( NumberOfSteps, unsigned int );
/** Sets the time step. */
itkSetMacro( TimeStep, Precision );
/** Sets the tolerance for the residual, for each time step. */
itkSetMacro( Tolerance, Precision );
/** Sets wether the filter should produce textual output containing
* informations on the current status. */
itkSetMacro( Verbose, bool );
/** Sets the diffusion tensor, whose elements are internally casted to
* InternalPixelPrecision. */
void SetDiffusionTensor( const InputTensorImageType * inputTensor );
protected:
/** Class constructor. */
MultigridAnisotropicDiffusionImageFilter();
/** Class destructor. */
~MultigridAnisotropicDiffusionImageFilter();
/** Generates the output, which is then accessed by method GetOuput(). */
virtual void GenerateData();
private:
typename InternalTensorImageType::Pointer m_DiffusionTensor;
Precision m_TimeStep;
unsigned int m_NumberOfSteps;
CycleType m_Cycle;
unsigned int m_IterationsPerGrid;
Precision m_Tolerance;
unsigned int m_MaxCycles;
bool m_Verbose;
unsigned int m_CurrentLevel;
unsigned int m_CoarsestLevel;
GridsHierarchyType * m_Grids;
DirectSolverType * m_DirectSolver;
#ifdef BENCHMARK
std::ofstream m_BenchmarkOutput;
clock_t m_Time;
#endif
/** Returns the approximated solution after a Full Multigrid Cycle. */
typename InternalImageType::Pointer FullMultiGrid( const InternalImageType * rhsImage );
/** Returns the L2-Norm of inputImage. */
Precision L2Norm( const InternalImageType * inputImage ) const;
/** Returns the approximated solution after a single VCycle. */
typename InternalImageType::Pointer VCycle( const InternalImageType * inputImage,
const InternalImageType * rhsImage );
/** Purposely not implemented */
MultigridAnisotropicDiffusionImageFilter( const Self & );
void operator=( const Self & );
};
} // end namespace itk
#ifndef ITK_MANUAL_INSTANTIATION
#include "itkMultigridAnisotropicDiffusionImageFilter.hxx"
#endif
#endif // __itkMultigridAnisotropicDiffusionImageFilter_h
| 43.538813 | 125 | 0.626953 | [
"object"
] |
d3c324d45ea4a419b6f2e6e7da73910cb660fae7 | 5,174 | h | C | Common/Misc/vtkResourceFileLocator.h | lfmc/VTK | 9999969f67745e9c1e2e0d606b637f1d7af21649 | [
"BSD-3-Clause"
] | null | null | null | Common/Misc/vtkResourceFileLocator.h | lfmc/VTK | 9999969f67745e9c1e2e0d606b637f1d7af21649 | [
"BSD-3-Clause"
] | 2 | 2018-05-04T02:00:02.000Z | 2018-05-04T02:15:19.000Z | Common/Misc/vtkResourceFileLocator.h | lfmc/VTK | 9999969f67745e9c1e2e0d606b637f1d7af21649 | [
"BSD-3-Clause"
] | 1 | 2021-05-03T23:51:31.000Z | 2021-05-03T23:51:31.000Z | /*=========================================================================
Program: Visualization Toolkit
Module: vtkResourceFileLocator.h
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
/**
* @class vtkResourceFileLocator
* @brief utility to locate resource files.
*
* VTK based application often need to locate resource files, such configuration
* files, Python modules, etc. vtkResourceFileLocator provides methods that can
* be used to locate such resource files at runtime.
*
* Using `Locate`, one can locate files relative to an
* anchor directory such as the executable directory, or the library directory.
*
* `GetLibraryPathForSymbolUnix` and `GetLibraryPathForSymbolWin32` methods can
* be used to locate the library that provides a particular symbol. For example,
* this is used by `vtkPythonInterpreter` to ensure that the `vtk` Python package
* is located relative the VTK libraries, irrespective of the application location.
*/
#ifndef vtkResourceFileLocator_h
#define vtkResourceFileLocator_h
#include "vtkCommonMiscModule.h" // For export macro
#include "vtkDeprecation.h" // For VTK_DEPRECATED_IN_9_0_0
#include "vtkObject.h"
#include <string> // needed for std::string
#include <vector> // needed for std::vector
class VTKCOMMONMISC_EXPORT vtkResourceFileLocator : public vtkObject
{
public:
static vtkResourceFileLocator* New();
vtkTypeMacro(vtkResourceFileLocator, vtkObject);
void PrintSelf(ostream& os, vtkIndent indent) override;
///@{
/**
* Enable/disable printing of testing of various path during `Locate`
* to `stdout`.
*
* @deprecated Instead use `SetLogVerbosity` to specify the verbosity at which
* this instance should log trace information. Default is
* `vtkLogger::VERBOSITY_TRACE`.
*/
VTK_DEPRECATED_IN_9_0_0("Use vtkResourceFileLocator::SetLogVerbosity")
void SetPrintDebugInformation(bool);
VTK_DEPRECATED_IN_9_0_0("Use vtkResourceFileLocator::GetLogVerbosity")
bool GetPrintDebugInformation();
VTK_DEPRECATED_IN_9_0_0("Use vtkResourceFileLocator::SetLogVerbosity")
void PrintDebugInformationOn();
VTK_DEPRECATED_IN_9_0_0("Use vtkResourceFileLocator::SetLogVerbosity")
void PrintDebugInformationOff();
///@}
///@{
/**
* The log verbosity to use when logging information about the resource
* searching. Default is `vtkLogger::VERBOSITY_TRACE`.
*/
vtkSetMacro(LogVerbosity, int);
vtkGetMacro(LogVerbosity, int);
///@}
///@{
/**
* Given a starting anchor directory, look for the landmark file relative to
* the anchor. If found return the anchor. If not found, go one directory up
* and then look the landmark file again.
*/
virtual std::string Locate(const std::string& anchor, const std::string& landmark,
const std::string& defaultDir = std::string());
///@}
///@{
/**
* This variant is used to look for landmark relative to the anchor using
* additional prefixes for the landmark file. For example, if you're looking for
* `vtk/__init__.py`, but it can be placed relative to your anchor location
* (let's say the executable directory), under "lib" or "lib/python", then
* use this variant with "lib", and "lib/python" passed in as the landmark
* prefixes. On success, the returned value will be anchor + matching prefix.
*/
virtual std::string Locate(const std::string& anchor,
const std::vector<std::string>& landmark_prefixes, const std::string& landmark,
const std::string& defaultDir = std::string());
///@}
///@{
/**
* Returns the name of the library providing the symbol. For example, if you
* want to locate where the VTK libraries located call
* `GetLibraryPathForSymbolUnix("GetVTKVersion")` on Unixes and
* `GetLibraryPathForSymbolWin32(GetVTKVersion)` on Windows. Alternatively, you
* can simply use the `vtkGetLibraryPathForSymbol(GetVTKVersion)` macro
* that makes the appropriate call as per the current platform.
*/
static std::string GetLibraryPathForSymbolUnix(const char* symbolname);
static std::string GetLibraryPathForSymbolWin32(const void* fptr);
///@}
protected:
vtkResourceFileLocator();
~vtkResourceFileLocator() override;
private:
vtkResourceFileLocator(const vtkResourceFileLocator&) = delete;
void operator=(const vtkResourceFileLocator&) = delete;
int LogVerbosity;
};
#if defined(_WIN32) && !defined(__CYGWIN__)
#define vtkGetLibraryPathForSymbol(function) \
vtkResourceFileLocator::GetLibraryPathForSymbolWin32(reinterpret_cast<const void*>(&function))
#else
#define vtkGetLibraryPathForSymbol(function) \
vtkResourceFileLocator::GetLibraryPathForSymbolUnix(#function)
#endif
#endif
| 38.61194 | 100 | 0.711828 | [
"vector"
] |
d3c7fd2b0eb4cfd76f295498d177852c4738e877 | 66,655 | h | C | Source/GeneratedServices/Directory/GTLRDirectoryObjects.h | mealdy/google-api-objectivec-client-for-rest | 88c5af3f3fa283191bda728b251befc657c09f19 | [
"Apache-2.0"
] | null | null | null | Source/GeneratedServices/Directory/GTLRDirectoryObjects.h | mealdy/google-api-objectivec-client-for-rest | 88c5af3f3fa283191bda728b251befc657c09f19 | [
"Apache-2.0"
] | null | null | null | Source/GeneratedServices/Directory/GTLRDirectoryObjects.h | mealdy/google-api-objectivec-client-for-rest | 88c5af3f3fa283191bda728b251befc657c09f19 | [
"Apache-2.0"
] | 1 | 2018-09-26T08:17:07.000Z | 2018-09-26T08:17:07.000Z | // NOTE: This file was generated by the ServiceGenerator.
// ----------------------------------------------------------------------------
// API:
// Admin Directory API (admin/directory_v1)
// Description:
// The Admin SDK Directory API lets you view and manage enterprise resources
// such as users and groups, administrative notifications, security features,
// and more.
// Documentation:
// https://developers.google.com/admin-sdk/directory/
#if GTLR_BUILT_AS_FRAMEWORK
#import "GTLR/GTLRObject.h"
#else
#import "GTLRObject.h"
#endif
#if GTLR_RUNTIME_VERSION != 3000
#error This file was generated by a different version of ServiceGenerator which is incompatible with this GTLR library source.
#endif
@class GTLRDirectory_Asp;
@class GTLRDirectory_CalendarResource;
@class GTLRDirectory_Channel_Params;
@class GTLRDirectory_ChromeOsDevice;
@class GTLRDirectory_ChromeOsDevice_ActiveTimeRanges_Item;
@class GTLRDirectory_ChromeOsDevice_RecentUsers_Item;
@class GTLRDirectory_CustomerPostalAddress;
@class GTLRDirectory_DomainAlias;
@class GTLRDirectory_Domains;
@class GTLRDirectory_Group;
@class GTLRDirectory_Member;
@class GTLRDirectory_MobileDevice;
@class GTLRDirectory_MobileDevice_Applications_Item;
@class GTLRDirectory_Notification;
@class GTLRDirectory_OrgUnit;
@class GTLRDirectory_Privilege;
@class GTLRDirectory_Role;
@class GTLRDirectory_Role_RolePrivileges_Item;
@class GTLRDirectory_RoleAssignment;
@class GTLRDirectory_Schema;
@class GTLRDirectory_SchemaFieldSpec;
@class GTLRDirectory_SchemaFieldSpec_NumericIndexingSpec;
@class GTLRDirectory_Token;
@class GTLRDirectory_User;
@class GTLRDirectory_User_CustomSchemas;
@class GTLRDirectory_UserCustomProperties;
@class GTLRDirectory_UserName;
@class GTLRDirectory_VerificationCode;
NS_ASSUME_NONNULL_BEGIN
/**
* JSON template for Alias object in Directory API.
*/
@interface GTLRDirectory_Alias : GTLRObject
/** A alias email */
@property(nonatomic, copy, nullable) NSString *alias;
/** ETag of the resource. */
@property(nonatomic, copy, nullable) NSString *ETag;
/**
* Unique id of the group (Read-only) Unique id of the user (Read-only)
*
* identifier property maps to 'id' in JSON (to avoid Objective C's 'id').
*/
@property(nonatomic, copy, nullable) NSString *identifier;
/** Kind of resource this is. */
@property(nonatomic, copy, nullable) NSString *kind;
/** Group's primary email (Read-only) User's primary email (Read-only) */
@property(nonatomic, copy, nullable) NSString *primaryEmail;
@end
/**
* JSON response template to list aliases in Directory API.
*/
@interface GTLRDirectory_Aliases : GTLRObject
/**
* List of alias objects.
*
* Can be any valid JSON type.
*/
@property(nonatomic, strong, nullable) NSArray *aliases;
/** ETag of the resource. */
@property(nonatomic, copy, nullable) NSString *ETag;
/** Kind of resource this is. */
@property(nonatomic, copy, nullable) NSString *kind;
@end
/**
* The template that returns individual ASP (Access Code) data.
*/
@interface GTLRDirectory_Asp : GTLRObject
/**
* The unique ID of the ASP.
*
* Uses NSNumber of intValue.
*/
@property(nonatomic, strong, nullable) NSNumber *codeId;
/**
* The time when the ASP was created. Expressed in Unix time format.
*
* Uses NSNumber of longLongValue.
*/
@property(nonatomic, strong, nullable) NSNumber *creationTime;
/** ETag of the ASP. */
@property(nonatomic, copy, nullable) NSString *ETag;
/** The type of the API resource. This is always admin#directory#asp. */
@property(nonatomic, copy, nullable) NSString *kind;
/**
* The time when the ASP was last used. Expressed in Unix time format.
*
* Uses NSNumber of longLongValue.
*/
@property(nonatomic, strong, nullable) NSNumber *lastTimeUsed;
/**
* The name of the application that the user, represented by their userId,
* entered when the ASP was created.
*/
@property(nonatomic, copy, nullable) NSString *name;
/** The unique ID of the user who issued the ASP. */
@property(nonatomic, copy, nullable) NSString *userKey;
@end
/**
* GTLRDirectory_Asps
*
* @note This class supports NSFastEnumeration and indexed subscripting over
* its "items" property.
*/
@interface GTLRDirectory_Asps : GTLRCollectionObject
/** ETag of the resource. */
@property(nonatomic, copy, nullable) NSString *ETag;
/**
* A list of ASP resources.
*
* @note This property is used to support NSFastEnumeration and indexed
* subscripting on this class.
*/
@property(nonatomic, strong, nullable) NSArray<GTLRDirectory_Asp *> *items;
/** The type of the API resource. This is always admin#directory#aspList. */
@property(nonatomic, copy, nullable) NSString *kind;
@end
/**
* JSON template for Calendar Resource object in Directory API.
*/
@interface GTLRDirectory_CalendarResource : GTLRObject
/** ETag of the resource. */
@property(nonatomic, copy, nullable) NSString *etags;
/**
* The type of the resource. For calendar resources, the value is
* admin#directory#resources#calendars#CalendarResource.
*/
@property(nonatomic, copy, nullable) NSString *kind;
/** The brief description of the calendar resource. */
@property(nonatomic, copy, nullable) NSString *resourceDescription;
/**
* The read-only email ID for the calendar resource. Generated as part of
* creating a new calendar resource.
*/
@property(nonatomic, copy, nullable) NSString *resourceEmail;
/** The unique ID for the calendar resource. */
@property(nonatomic, copy, nullable) NSString *resourceId;
/** The name of the calendar resource. For example, Training Room 1A */
@property(nonatomic, copy, nullable) NSString *resourceName;
/**
* The type of the calendar resource. Used for grouping resources in the
* calendar user interface.
*/
@property(nonatomic, copy, nullable) NSString *resourceType;
@end
/**
* JSON template for Calendar Resource List Response object in Directory API.
*
* @note This class supports NSFastEnumeration and indexed subscripting over
* its "items" property. If returned as the result of a query, it should
* support automatic pagination (when @c shouldFetchNextPages is
* enabled).
*/
@interface GTLRDirectory_CalendarResources : GTLRCollectionObject
/** ETag of the resource. */
@property(nonatomic, copy, nullable) NSString *ETag;
/**
* The CalendarResources in this page of results.
*
* @note This property is used to support NSFastEnumeration and indexed
* subscripting on this class.
*/
@property(nonatomic, strong, nullable) NSArray<GTLRDirectory_CalendarResource *> *items;
/**
* Identifies this as a collection of CalendarResources. This is always
* admin#directory#resources#calendars#calendarResourcesList.
*/
@property(nonatomic, copy, nullable) NSString *kind;
/**
* The continuation token, used to page through large result sets. Provide this
* value in a subsequent request to return the next page of results.
*/
@property(nonatomic, copy, nullable) NSString *nextPageToken;
@end
/**
* An notification channel used to watch for resource changes.
*/
@interface GTLRDirectory_Channel : GTLRObject
/** The address where notifications are delivered for this channel. */
@property(nonatomic, copy, nullable) NSString *address;
/**
* Date and time of notification channel expiration, expressed as a Unix
* timestamp, in milliseconds. Optional.
*
* Uses NSNumber of longLongValue.
*/
@property(nonatomic, strong, nullable) NSNumber *expiration;
/**
* A UUID or similar unique string that identifies this channel.
*
* identifier property maps to 'id' in JSON (to avoid Objective C's 'id').
*/
@property(nonatomic, copy, nullable) NSString *identifier;
/**
* Identifies this as a notification channel used to watch for changes to a
* resource. Value: the fixed string "api#channel".
*/
@property(nonatomic, copy, nullable) NSString *kind;
/** Additional parameters controlling delivery channel behavior. Optional. */
@property(nonatomic, strong, nullable) GTLRDirectory_Channel_Params *params;
/**
* A Boolean value to indicate whether payload is wanted. Optional.
*
* Uses NSNumber of boolValue.
*/
@property(nonatomic, strong, nullable) NSNumber *payload;
/**
* An opaque ID that identifies the resource being watched on this channel.
* Stable across different API versions.
*/
@property(nonatomic, copy, nullable) NSString *resourceId;
/** A version-specific identifier for the watched resource. */
@property(nonatomic, copy, nullable) NSString *resourceUri;
/**
* An arbitrary string delivered to the target address with each notification
* delivered over this channel. Optional.
*/
@property(nonatomic, copy, nullable) NSString *token;
/** The type of delivery mechanism used for this channel. */
@property(nonatomic, copy, nullable) NSString *type;
@end
/**
* Additional parameters controlling delivery channel behavior. Optional.
*
* @note This class is documented as having more properties of NSString. Use @c
* -additionalJSONKeys and @c -additionalPropertyForName: to get the list
* of properties and then fetch them; or @c -additionalProperties to
* fetch them all at once.
*/
@interface GTLRDirectory_Channel_Params : GTLRObject
@end
/**
* JSON template for Chrome Os Device resource in Directory API.
*/
@interface GTLRDirectory_ChromeOsDevice : GTLRObject
/** List of active time ranges (Read-only) */
@property(nonatomic, strong, nullable) NSArray<GTLRDirectory_ChromeOsDevice_ActiveTimeRanges_Item *> *activeTimeRanges;
/** AssetId specified during enrollment or through later annotation */
@property(nonatomic, copy, nullable) NSString *annotatedAssetId;
/** Address or location of the device as noted by the administrator */
@property(nonatomic, copy, nullable) NSString *annotatedLocation;
/** User of the device */
@property(nonatomic, copy, nullable) NSString *annotatedUser;
/** Chromebook boot mode (Read-only) */
@property(nonatomic, copy, nullable) NSString *bootMode;
/** Unique identifier of Chrome OS Device (Read-only) */
@property(nonatomic, copy, nullable) NSString *deviceId;
/** ETag of the resource. */
@property(nonatomic, copy, nullable) NSString *ETag;
/** Chromebook Mac Address on ethernet network interface (Read-only) */
@property(nonatomic, copy, nullable) NSString *ethernetMacAddress;
/** Chromebook firmware version (Read-only) */
@property(nonatomic, copy, nullable) NSString *firmwareVersion;
/** Kind of resource this is. */
@property(nonatomic, copy, nullable) NSString *kind;
/** Date and time the device was last enrolled (Read-only) */
@property(nonatomic, strong, nullable) GTLRDateTime *lastEnrollmentTime;
/**
* Date and time the device was last synchronized with the policy settings in
* the Google Apps administrator control panel (Read-only)
*/
@property(nonatomic, strong, nullable) GTLRDateTime *lastSync;
/** Chromebook Mac Address on wifi network interface (Read-only) */
@property(nonatomic, copy, nullable) NSString *macAddress;
/**
* Mobile Equipment identifier for the 3G mobile card in the Chromebook
* (Read-only)
*/
@property(nonatomic, copy, nullable) NSString *meid;
/** Chromebook Model (Read-only) */
@property(nonatomic, copy, nullable) NSString *model;
/** Notes added by the administrator */
@property(nonatomic, copy, nullable) NSString *notes;
/** Chromebook order number (Read-only) */
@property(nonatomic, copy, nullable) NSString *orderNumber;
/** OrgUnit of the device */
@property(nonatomic, copy, nullable) NSString *orgUnitPath;
/** Chromebook Os Version (Read-only) */
@property(nonatomic, copy, nullable) NSString *osVersion;
/** Chromebook platform version (Read-only) */
@property(nonatomic, copy, nullable) NSString *platformVersion;
/**
* List of recent device users, in descending order by last login time
* (Read-only)
*/
@property(nonatomic, strong, nullable) NSArray<GTLRDirectory_ChromeOsDevice_RecentUsers_Item *> *recentUsers;
/** Chromebook serial number (Read-only) */
@property(nonatomic, copy, nullable) NSString *serialNumber;
/** status of the device (Read-only) */
@property(nonatomic, copy, nullable) NSString *status;
/** Final date the device will be supported (Read-only) */
@property(nonatomic, strong, nullable) GTLRDateTime *supportEndDate;
/**
* Will Chromebook auto renew after support end date (Read-only)
*
* Uses NSNumber of boolValue.
*/
@property(nonatomic, strong, nullable) NSNumber *willAutoRenew;
@end
/**
* GTLRDirectory_ChromeOsDevice_ActiveTimeRanges_Item
*/
@interface GTLRDirectory_ChromeOsDevice_ActiveTimeRanges_Item : GTLRObject
/**
* Duration in milliseconds
*
* Uses NSNumber of intValue.
*/
@property(nonatomic, strong, nullable) NSNumber *activeTime;
/**
* Date of usage
*
* Date only (yyyy-mm-dd).
*/
@property(nonatomic, strong, nullable) GTLRDateTime *date;
@end
/**
* GTLRDirectory_ChromeOsDevice_RecentUsers_Item
*/
@interface GTLRDirectory_ChromeOsDevice_RecentUsers_Item : GTLRObject
/** Email address of the user. Present only if the user type is managed */
@property(nonatomic, copy, nullable) NSString *email;
/** The type of the user */
@property(nonatomic, copy, nullable) NSString *type;
@end
/**
* JSON request template for firing actions on ChromeOs Device in Directory
* Devices API.
*/
@interface GTLRDirectory_ChromeOsDeviceAction : GTLRObject
/** Action to be taken on the ChromeOs Device */
@property(nonatomic, copy, nullable) NSString *action;
@property(nonatomic, copy, nullable) NSString *deprovisionReason;
@end
/**
* JSON response template for List Chrome OS Devices operation in Directory
* API.
*
* @note This class supports NSFastEnumeration and indexed subscripting over
* its "chromeosdevices" property. If returned as the result of a query,
* it should support automatic pagination (when @c shouldFetchNextPages
* is enabled).
*/
@interface GTLRDirectory_ChromeOsDevices : GTLRCollectionObject
/**
* List of Chrome OS Device objects.
*
* @note This property is used to support NSFastEnumeration and indexed
* subscripting on this class.
*/
@property(nonatomic, strong, nullable) NSArray<GTLRDirectory_ChromeOsDevice *> *chromeosdevices;
/** ETag of the resource. */
@property(nonatomic, copy, nullable) NSString *ETag;
/** Kind of resource this is. */
@property(nonatomic, copy, nullable) NSString *kind;
/** Token used to access next page of this result. */
@property(nonatomic, copy, nullable) NSString *nextPageToken;
@end
/**
* JSON template for Customer Resource object in Directory API.
*/
@interface GTLRDirectory_Customer : GTLRObject
/**
* The customer's secondary contact email address. This email address cannot be
* on the same domain as the customerDomain
*/
@property(nonatomic, copy, nullable) NSString *alternateEmail;
/** The customer's creation time (Readonly) */
@property(nonatomic, strong, nullable) GTLRDateTime *customerCreationTime;
/**
* The customer's primary domain name string. Do not include the www prefix
* when creating a new customer.
*/
@property(nonatomic, copy, nullable) NSString *customerDomain;
/** ETag of the resource. */
@property(nonatomic, copy, nullable) NSString *ETag;
/**
* The unique ID for the customer's Google account. (Readonly)
*
* identifier property maps to 'id' in JSON (to avoid Objective C's 'id').
*/
@property(nonatomic, copy, nullable) NSString *identifier;
/** Identifies the resource as a customer. Value: admin#directory#customer */
@property(nonatomic, copy, nullable) NSString *kind;
/** The customer's ISO 639-2 language code. The default value is en-US */
@property(nonatomic, copy, nullable) NSString *language;
/** The customer's contact phone number in E.164 format. */
@property(nonatomic, copy, nullable) NSString *phoneNumber;
/** The customer's postal address information. */
@property(nonatomic, strong, nullable) GTLRDirectory_CustomerPostalAddress *postalAddress;
@end
/**
* JSON template for postal address of a customer.
*/
@interface GTLRDirectory_CustomerPostalAddress : GTLRObject
/**
* A customer's physical address. The address can be composed of one to three
* lines.
*/
@property(nonatomic, copy, nullable) NSString *addressLine1;
/** Address line 2 of the address. */
@property(nonatomic, copy, nullable) NSString *addressLine2;
/** Address line 3 of the address. */
@property(nonatomic, copy, nullable) NSString *addressLine3;
/** The customer contact's name. */
@property(nonatomic, copy, nullable) NSString *contactName;
/**
* This is a required property. For countryCode information see the ISO 3166
* country code elements.
*/
@property(nonatomic, copy, nullable) NSString *countryCode;
/**
* Name of the locality. An example of a locality value is the city of San
* Francisco.
*/
@property(nonatomic, copy, nullable) NSString *locality;
/** The company or company division name. */
@property(nonatomic, copy, nullable) NSString *organizationName;
/**
* The postal code. A postalCode example is a postal zip code such as 10009.
* This is in accordance with -
* http://portablecontacts.net/draft-spec.html#address_element.
*/
@property(nonatomic, copy, nullable) NSString *postalCode;
/**
* Name of the region. An example of a region value is NY for the state of New
* York.
*/
@property(nonatomic, copy, nullable) NSString *region;
@end
/**
* JSON template for Domain Alias object in Directory API.
*/
@interface GTLRDirectory_DomainAlias : GTLRObject
/**
* The creation time of the domain alias. (Read-only).
*
* Uses NSNumber of longLongValue.
*/
@property(nonatomic, strong, nullable) NSNumber *creationTime;
/** The domain alias name. */
@property(nonatomic, copy, nullable) NSString *domainAliasName;
/** ETag of the resource. */
@property(nonatomic, copy, nullable) NSString *ETag;
/** Kind of resource this is. */
@property(nonatomic, copy, nullable) NSString *kind;
/**
* The parent domain name that the domain alias is associated with. This can
* either be a primary or secondary domain name within a customer.
*/
@property(nonatomic, copy, nullable) NSString *parentDomainName;
/**
* Indicates the verification state of a domain alias. (Read-only)
*
* Uses NSNumber of boolValue.
*/
@property(nonatomic, strong, nullable) NSNumber *verified;
@end
/**
* JSON response template to list domain aliases in Directory API.
*/
@interface GTLRDirectory_DomainAliases : GTLRObject
/** List of domain alias objects. */
@property(nonatomic, strong, nullable) NSArray<GTLRDirectory_DomainAlias *> *domainAliases;
/** ETag of the resource. */
@property(nonatomic, copy, nullable) NSString *ETag;
/** Kind of resource this is. */
@property(nonatomic, copy, nullable) NSString *kind;
@end
/**
* JSON template for Domain object in Directory API.
*/
@interface GTLRDirectory_Domains : GTLRObject
/**
* Creation time of the domain. (Read-only).
*
* Uses NSNumber of longLongValue.
*/
@property(nonatomic, strong, nullable) NSNumber *creationTime;
/** List of domain alias objects. (Read-only) */
@property(nonatomic, strong, nullable) NSArray<GTLRDirectory_DomainAlias *> *domainAliases;
/** The domain name of the customer. */
@property(nonatomic, copy, nullable) NSString *domainName;
/** ETag of the resource. */
@property(nonatomic, copy, nullable) NSString *ETag;
/**
* Indicates if the domain is a primary domain (Read-only).
*
* Uses NSNumber of boolValue.
*/
@property(nonatomic, strong, nullable) NSNumber *isPrimary;
/** Kind of resource this is. */
@property(nonatomic, copy, nullable) NSString *kind;
/**
* Indicates the verification state of a domain. (Read-only).
*
* Uses NSNumber of boolValue.
*/
@property(nonatomic, strong, nullable) NSNumber *verified;
@end
/**
* JSON response template to list Domains in Directory API.
*/
@interface GTLRDirectory_Domains2 : GTLRObject
/** List of domain objects. */
@property(nonatomic, strong, nullable) NSArray<GTLRDirectory_Domains *> *domains;
/** ETag of the resource. */
@property(nonatomic, copy, nullable) NSString *ETag;
/** Kind of resource this is. */
@property(nonatomic, copy, nullable) NSString *kind;
@end
/**
* JSON template for Group resource in Directory API.
*/
@interface GTLRDirectory_Group : GTLRObject
/**
* Is the group created by admin (Read-only) *
*
* Uses NSNumber of boolValue.
*/
@property(nonatomic, strong, nullable) NSNumber *adminCreated;
/** List of aliases (Read-only) */
@property(nonatomic, strong, nullable) NSArray<NSString *> *aliases;
/**
* Description of the group
*
* Remapped to 'descriptionProperty' to avoid NSObject's 'description'.
*/
@property(nonatomic, copy, nullable) NSString *descriptionProperty;
/**
* Group direct members count
*
* Uses NSNumber of longLongValue.
*/
@property(nonatomic, strong, nullable) NSNumber *directMembersCount;
/** Email of Group */
@property(nonatomic, copy, nullable) NSString *email;
/** ETag of the resource. */
@property(nonatomic, copy, nullable) NSString *ETag;
/**
* Unique identifier of Group (Read-only)
*
* identifier property maps to 'id' in JSON (to avoid Objective C's 'id').
*/
@property(nonatomic, copy, nullable) NSString *identifier;
/** Kind of resource this is. */
@property(nonatomic, copy, nullable) NSString *kind;
/** Group name */
@property(nonatomic, copy, nullable) NSString *name;
/** List of non editable aliases (Read-only) */
@property(nonatomic, strong, nullable) NSArray<NSString *> *nonEditableAliases;
@end
/**
* JSON response template for List Groups operation in Directory API.
*
* @note This class supports NSFastEnumeration and indexed subscripting over
* its "groups" property. If returned as the result of a query, it should
* support automatic pagination (when @c shouldFetchNextPages is
* enabled).
*/
@interface GTLRDirectory_Groups : GTLRCollectionObject
/** ETag of the resource. */
@property(nonatomic, copy, nullable) NSString *ETag;
/**
* List of group objects.
*
* @note This property is used to support NSFastEnumeration and indexed
* subscripting on this class.
*/
@property(nonatomic, strong, nullable) NSArray<GTLRDirectory_Group *> *groups;
/** Kind of resource this is. */
@property(nonatomic, copy, nullable) NSString *kind;
/** Token used to access next page of this result. */
@property(nonatomic, copy, nullable) NSString *nextPageToken;
@end
/**
* JSON template for Member resource in Directory API.
*/
@interface GTLRDirectory_Member : GTLRObject
/** Email of member (Read-only) */
@property(nonatomic, copy, nullable) NSString *email;
/** ETag of the resource. */
@property(nonatomic, copy, nullable) NSString *ETag;
/**
* Unique identifier of customer member (Read-only) Unique identifier of group
* (Read-only) Unique identifier of member (Read-only)
*
* identifier property maps to 'id' in JSON (to avoid Objective C's 'id').
*/
@property(nonatomic, copy, nullable) NSString *identifier;
/** Kind of resource this is. */
@property(nonatomic, copy, nullable) NSString *kind;
/** Role of member */
@property(nonatomic, copy, nullable) NSString *role;
/** Status of member (Immutable) */
@property(nonatomic, copy, nullable) NSString *status;
/** Type of member (Immutable) */
@property(nonatomic, copy, nullable) NSString *type;
@end
/**
* JSON response template for List Members operation in Directory API.
*
* @note This class supports NSFastEnumeration and indexed subscripting over
* its "members" property. If returned as the result of a query, it
* should support automatic pagination (when @c shouldFetchNextPages is
* enabled).
*/
@interface GTLRDirectory_Members : GTLRCollectionObject
/** ETag of the resource. */
@property(nonatomic, copy, nullable) NSString *ETag;
/** Kind of resource this is. */
@property(nonatomic, copy, nullable) NSString *kind;
/**
* List of member objects.
*
* @note This property is used to support NSFastEnumeration and indexed
* subscripting on this class.
*/
@property(nonatomic, strong, nullable) NSArray<GTLRDirectory_Member *> *members;
/** Token used to access next page of this result. */
@property(nonatomic, copy, nullable) NSString *nextPageToken;
@end
/**
* JSON template for Mobile Device resource in Directory API.
*/
@interface GTLRDirectory_MobileDevice : GTLRObject
/**
* Adb (USB debugging) enabled or disabled on device (Read-only)
*
* Uses NSNumber of boolValue.
*/
@property(nonatomic, strong, nullable) NSNumber *adbStatus;
/** List of applications installed on Mobile Device */
@property(nonatomic, strong, nullable) NSArray<GTLRDirectory_MobileDevice_Applications_Item *> *applications;
/** Mobile Device Baseband version (Read-only) */
@property(nonatomic, copy, nullable) NSString *basebandVersion;
/** Mobile Device Bootloader version (Read-only) */
@property(nonatomic, copy, nullable) NSString *bootloaderVersion;
/** Mobile Device Brand (Read-only) */
@property(nonatomic, copy, nullable) NSString *brand;
/** Mobile Device Build number (Read-only) */
@property(nonatomic, copy, nullable) NSString *buildNumber;
/** The default locale used on the Mobile Device (Read-only) */
@property(nonatomic, copy, nullable) NSString *defaultLanguage;
/**
* Developer options enabled or disabled on device (Read-only)
*
* Uses NSNumber of boolValue.
*/
@property(nonatomic, strong, nullable) NSNumber *developerOptionsStatus;
/** Mobile Device compromised status (Read-only) */
@property(nonatomic, copy, nullable) NSString *deviceCompromisedStatus;
/** Mobile Device serial number (Read-only) */
@property(nonatomic, copy, nullable) NSString *deviceId;
/** DevicePasswordStatus (Read-only) */
@property(nonatomic, copy, nullable) NSString *devicePasswordStatus;
/** List of owner user's email addresses (Read-only) */
@property(nonatomic, strong, nullable) NSArray<NSString *> *email;
/** Mobile Device Encryption Status (Read-only) */
@property(nonatomic, copy, nullable) NSString *encryptionStatus;
/** ETag of the resource. */
@property(nonatomic, copy, nullable) NSString *ETag;
/**
* Date and time the device was first synchronized with the policy settings in
* the Google Apps administrator control panel (Read-only)
*/
@property(nonatomic, strong, nullable) GTLRDateTime *firstSync;
/** Mobile Device Hardware (Read-only) */
@property(nonatomic, copy, nullable) NSString *hardware;
/** Mobile Device Hardware Id (Read-only) */
@property(nonatomic, copy, nullable) NSString *hardwareId;
/** Mobile Device IMEI number (Read-only) */
@property(nonatomic, copy, nullable) NSString *imei;
/** Mobile Device Kernel version (Read-only) */
@property(nonatomic, copy, nullable) NSString *kernelVersion;
/** Kind of resource this is. */
@property(nonatomic, copy, nullable) NSString *kind;
/**
* Date and time the device was last synchronized with the policy settings in
* the Google Apps administrator control panel (Read-only)
*/
@property(nonatomic, strong, nullable) GTLRDateTime *lastSync;
/**
* Boolean indicating if this account is on owner/primary profile or not
* (Read-only)
*
* Uses NSNumber of boolValue.
*/
@property(nonatomic, strong, nullable) NSNumber *managedAccountIsOnOwnerProfile;
/** Mobile Device manufacturer (Read-only) */
@property(nonatomic, copy, nullable) NSString *manufacturer;
/** Mobile Device MEID number (Read-only) */
@property(nonatomic, copy, nullable) NSString *meid;
/** Name of the model of the device */
@property(nonatomic, copy, nullable) NSString *model;
/** List of owner user's names (Read-only) */
@property(nonatomic, strong, nullable) NSArray<NSString *> *name;
/** Mobile Device mobile or network operator (if available) (Read-only) */
@property(nonatomic, copy, nullable) NSString *networkOperator;
/** Name of the mobile operating system */
@property(nonatomic, copy, nullable) NSString *os;
/** List of accounts added on device (Read-only) */
@property(nonatomic, strong, nullable) NSArray<NSString *> *otherAccountsInfo;
/** DMAgentPermission (Read-only) */
@property(nonatomic, copy, nullable) NSString *privilege;
/** Mobile Device release version version (Read-only) */
@property(nonatomic, copy, nullable) NSString *releaseVersion;
/** Unique identifier of Mobile Device (Read-only) */
@property(nonatomic, copy, nullable) NSString *resourceId;
/**
* Mobile Device Security patch level (Read-only)
*
* Uses NSNumber of longLongValue.
*/
@property(nonatomic, strong, nullable) NSNumber *securityPatchLevel;
/** Mobile Device SSN or Serial Number (Read-only) */
@property(nonatomic, copy, nullable) NSString *serialNumber;
/** Status of the device (Read-only) */
@property(nonatomic, copy, nullable) NSString *status;
/**
* Work profile supported on device (Read-only)
*
* Uses NSNumber of boolValue.
*/
@property(nonatomic, strong, nullable) NSNumber *supportsWorkProfile;
/** The type of device (Read-only) */
@property(nonatomic, copy, nullable) NSString *type;
/**
* Unknown sources enabled or disabled on device (Read-only)
*
* Uses NSNumber of boolValue.
*/
@property(nonatomic, strong, nullable) NSNumber *unknownSourcesStatus;
/** Mobile Device user agent */
@property(nonatomic, copy, nullable) NSString *userAgent;
/** Mobile Device WiFi MAC address (Read-only) */
@property(nonatomic, copy, nullable) NSString *wifiMacAddress;
@end
/**
* GTLRDirectory_MobileDevice_Applications_Item
*/
@interface GTLRDirectory_MobileDevice_Applications_Item : GTLRObject
/** Display name of application */
@property(nonatomic, copy, nullable) NSString *displayName;
/** Package name of application */
@property(nonatomic, copy, nullable) NSString *packageName;
/** List of Permissions for application */
@property(nonatomic, strong, nullable) NSArray<NSString *> *permission;
/**
* Version code of application
*
* Uses NSNumber of intValue.
*/
@property(nonatomic, strong, nullable) NSNumber *versionCode;
/** Version name of application */
@property(nonatomic, copy, nullable) NSString *versionName;
@end
/**
* JSON request template for firing commands on Mobile Device in Directory
* Devices API.
*/
@interface GTLRDirectory_MobileDeviceAction : GTLRObject
/** Action to be taken on the Mobile Device */
@property(nonatomic, copy, nullable) NSString *action;
@end
/**
* JSON response template for List Mobile Devices operation in Directory API.
*
* @note This class supports NSFastEnumeration and indexed subscripting over
* its "mobiledevices" property. If returned as the result of a query, it
* should support automatic pagination (when @c shouldFetchNextPages is
* enabled).
*/
@interface GTLRDirectory_MobileDevices : GTLRCollectionObject
/** ETag of the resource. */
@property(nonatomic, copy, nullable) NSString *ETag;
/** Kind of resource this is. */
@property(nonatomic, copy, nullable) NSString *kind;
/**
* List of Mobile Device objects.
*
* @note This property is used to support NSFastEnumeration and indexed
* subscripting on this class.
*/
@property(nonatomic, strong, nullable) NSArray<GTLRDirectory_MobileDevice *> *mobiledevices;
/** Token used to access next page of this result. */
@property(nonatomic, copy, nullable) NSString *nextPageToken;
@end
/**
* Template for a notification resource.
*/
@interface GTLRDirectory_Notification : GTLRObject
/** Body of the notification (Read-only) */
@property(nonatomic, copy, nullable) NSString *body;
/** ETag of the resource. */
@property(nonatomic, copy, nullable) NSString *ETag;
/** Address from which the notification is received (Read-only) */
@property(nonatomic, copy, nullable) NSString *fromAddress;
/**
* Boolean indicating whether the notification is unread or not.
*
* Uses NSNumber of boolValue.
*/
@property(nonatomic, strong, nullable) NSNumber *isUnread;
/** The type of the resource. */
@property(nonatomic, copy, nullable) NSString *kind;
@property(nonatomic, copy, nullable) NSString *notificationId;
/** Time at which notification was sent (Read-only) */
@property(nonatomic, strong, nullable) GTLRDateTime *sendTime;
/** Subject of the notification (Read-only) */
@property(nonatomic, copy, nullable) NSString *subject;
@end
/**
* Template for notifications list response.
*
* @note This class supports NSFastEnumeration and indexed subscripting over
* its "items" property. If returned as the result of a query, it should
* support automatic pagination (when @c shouldFetchNextPages is
* enabled).
*/
@interface GTLRDirectory_Notifications : GTLRCollectionObject
/** ETag of the resource. */
@property(nonatomic, copy, nullable) NSString *ETag;
/**
* List of notifications in this page.
*
* @note This property is used to support NSFastEnumeration and indexed
* subscripting on this class.
*/
@property(nonatomic, strong, nullable) NSArray<GTLRDirectory_Notification *> *items;
/** The type of the resource. */
@property(nonatomic, copy, nullable) NSString *kind;
/** Token for fetching the next page of notifications. */
@property(nonatomic, copy, nullable) NSString *nextPageToken;
/**
* Number of unread notification for the domain.
*
* Uses NSNumber of intValue.
*/
@property(nonatomic, strong, nullable) NSNumber *unreadNotificationsCount;
@end
/**
* JSON template for Org Unit resource in Directory API.
*/
@interface GTLRDirectory_OrgUnit : GTLRObject
/**
* Should block inheritance
*
* Uses NSNumber of boolValue.
*/
@property(nonatomic, strong, nullable) NSNumber *blockInheritance;
/**
* Description of OrgUnit
*
* Remapped to 'descriptionProperty' to avoid NSObject's 'description'.
*/
@property(nonatomic, copy, nullable) NSString *descriptionProperty;
/** ETag of the resource. */
@property(nonatomic, copy, nullable) NSString *ETag;
/** Kind of resource this is. */
@property(nonatomic, copy, nullable) NSString *kind;
/** Name of OrgUnit */
@property(nonatomic, copy, nullable) NSString *name;
/** Id of OrgUnit */
@property(nonatomic, copy, nullable) NSString *orgUnitId;
/** Path of OrgUnit */
@property(nonatomic, copy, nullable) NSString *orgUnitPath;
/** Id of parent OrgUnit */
@property(nonatomic, copy, nullable) NSString *parentOrgUnitId;
/** Path of parent OrgUnit */
@property(nonatomic, copy, nullable) NSString *parentOrgUnitPath;
@end
/**
* JSON response template for List Organization Units operation in Directory
* API.
*/
@interface GTLRDirectory_OrgUnits : GTLRObject
/** ETag of the resource. */
@property(nonatomic, copy, nullable) NSString *ETag;
/** Kind of resource this is. */
@property(nonatomic, copy, nullable) NSString *kind;
/** List of user objects. */
@property(nonatomic, strong, nullable) NSArray<GTLRDirectory_OrgUnit *> *organizationUnits;
@end
/**
* JSON template for privilege resource in Directory API.
*/
@interface GTLRDirectory_Privilege : GTLRObject
/**
* A list of child privileges. Privileges for a service form a tree. Each
* privilege can have a list of child privileges; this list is empty for a leaf
* privilege.
*/
@property(nonatomic, strong, nullable) NSArray<GTLRDirectory_Privilege *> *childPrivileges;
/** ETag of the resource. */
@property(nonatomic, copy, nullable) NSString *ETag;
/**
* If the privilege can be restricted to an organization unit.
*
* Uses NSNumber of boolValue.
*/
@property(nonatomic, strong, nullable) NSNumber *isOuScopable;
/** The type of the API resource. This is always admin#directory#privilege. */
@property(nonatomic, copy, nullable) NSString *kind;
/** The name of the privilege. */
@property(nonatomic, copy, nullable) NSString *privilegeName;
/** The obfuscated ID of the service this privilege is for. */
@property(nonatomic, copy, nullable) NSString *serviceId;
/** The name of the service this privilege is for. */
@property(nonatomic, copy, nullable) NSString *serviceName;
@end
/**
* JSON response template for List privileges operation in Directory API.
*
* @note This class supports NSFastEnumeration and indexed subscripting over
* its "items" property.
*/
@interface GTLRDirectory_Privileges : GTLRCollectionObject
/** ETag of the resource. */
@property(nonatomic, copy, nullable) NSString *ETag;
/**
* A list of Privilege resources.
*
* @note This property is used to support NSFastEnumeration and indexed
* subscripting on this class.
*/
@property(nonatomic, strong, nullable) NSArray<GTLRDirectory_Privilege *> *items;
/**
* The type of the API resource. This is always admin#directory#privileges.
*/
@property(nonatomic, copy, nullable) NSString *kind;
@end
/**
* JSON template for role resource in Directory API.
*/
@interface GTLRDirectory_Role : GTLRObject
/** ETag of the resource. */
@property(nonatomic, copy, nullable) NSString *ETag;
/**
* Returns true if the role is a super admin role.
*
* Uses NSNumber of boolValue.
*/
@property(nonatomic, strong, nullable) NSNumber *isSuperAdminRole;
/**
* Returns true if this is a pre-defined system role.
*
* Uses NSNumber of boolValue.
*/
@property(nonatomic, strong, nullable) NSNumber *isSystemRole;
/** The type of the API resource. This is always admin#directory#role. */
@property(nonatomic, copy, nullable) NSString *kind;
/** A short description of the role. */
@property(nonatomic, copy, nullable) NSString *roleDescription;
/**
* ID of the role.
*
* Uses NSNumber of longLongValue.
*/
@property(nonatomic, strong, nullable) NSNumber *roleId;
/** Name of the role. */
@property(nonatomic, copy, nullable) NSString *roleName;
/** The set of privileges that are granted to this role. */
@property(nonatomic, strong, nullable) NSArray<GTLRDirectory_Role_RolePrivileges_Item *> *rolePrivileges;
@end
/**
* GTLRDirectory_Role_RolePrivileges_Item
*/
@interface GTLRDirectory_Role_RolePrivileges_Item : GTLRObject
/** The name of the privilege. */
@property(nonatomic, copy, nullable) NSString *privilegeName;
/** The obfuscated ID of the service this privilege is for. */
@property(nonatomic, copy, nullable) NSString *serviceId;
@end
/**
* JSON template for roleAssignment resource in Directory API.
*/
@interface GTLRDirectory_RoleAssignment : GTLRObject
/** The unique ID of the user this role is assigned to. */
@property(nonatomic, copy, nullable) NSString *assignedTo;
/** ETag of the resource. */
@property(nonatomic, copy, nullable) NSString *ETag;
/**
* The type of the API resource. This is always admin#directory#roleAssignment.
*/
@property(nonatomic, copy, nullable) NSString *kind;
/**
* If the role is restricted to an organization unit, this contains the ID for
* the organization unit the exercise of this role is restricted to.
*/
@property(nonatomic, copy, nullable) NSString *orgUnitId;
/**
* ID of this roleAssignment.
*
* Uses NSNumber of longLongValue.
*/
@property(nonatomic, strong, nullable) NSNumber *roleAssignmentId;
/**
* The ID of the role that is assigned.
*
* Uses NSNumber of longLongValue.
*/
@property(nonatomic, strong, nullable) NSNumber *roleId;
/**
* The scope in which this role is assigned. Possible values are:
* - CUSTOMER
* - ORG_UNIT
*/
@property(nonatomic, copy, nullable) NSString *scopeType;
@end
/**
* JSON response template for List roleAssignments operation in Directory API.
*
* @note This class supports NSFastEnumeration and indexed subscripting over
* its "items" property. If returned as the result of a query, it should
* support automatic pagination (when @c shouldFetchNextPages is
* enabled).
*/
@interface GTLRDirectory_RoleAssignments : GTLRCollectionObject
/** ETag of the resource. */
@property(nonatomic, copy, nullable) NSString *ETag;
/**
* A list of RoleAssignment resources.
*
* @note This property is used to support NSFastEnumeration and indexed
* subscripting on this class.
*/
@property(nonatomic, strong, nullable) NSArray<GTLRDirectory_RoleAssignment *> *items;
/**
* The type of the API resource. This is always
* admin#directory#roleAssignments.
*/
@property(nonatomic, copy, nullable) NSString *kind;
@property(nonatomic, copy, nullable) NSString *nextPageToken;
@end
/**
* JSON response template for List roles operation in Directory API.
*
* @note This class supports NSFastEnumeration and indexed subscripting over
* its "items" property. If returned as the result of a query, it should
* support automatic pagination (when @c shouldFetchNextPages is
* enabled).
*/
@interface GTLRDirectory_Roles : GTLRCollectionObject
/** ETag of the resource. */
@property(nonatomic, copy, nullable) NSString *ETag;
/**
* A list of Role resources.
*
* @note This property is used to support NSFastEnumeration and indexed
* subscripting on this class.
*/
@property(nonatomic, strong, nullable) NSArray<GTLRDirectory_Role *> *items;
/** The type of the API resource. This is always admin#directory#roles. */
@property(nonatomic, copy, nullable) NSString *kind;
@property(nonatomic, copy, nullable) NSString *nextPageToken;
@end
/**
* JSON template for Schema resource in Directory API.
*/
@interface GTLRDirectory_Schema : GTLRObject
/** ETag of the resource. */
@property(nonatomic, copy, nullable) NSString *ETag;
/** Fields of Schema */
@property(nonatomic, strong, nullable) NSArray<GTLRDirectory_SchemaFieldSpec *> *fields;
/** Kind of resource this is. */
@property(nonatomic, copy, nullable) NSString *kind;
/** Unique identifier of Schema (Read-only) */
@property(nonatomic, copy, nullable) NSString *schemaId;
/** Schema name */
@property(nonatomic, copy, nullable) NSString *schemaName;
@end
/**
* JSON template for FieldSpec resource for Schemas in Directory API.
*/
@interface GTLRDirectory_SchemaFieldSpec : GTLRObject
/** ETag of the resource. */
@property(nonatomic, copy, nullable) NSString *ETag;
/** Unique identifier of Field (Read-only) */
@property(nonatomic, copy, nullable) NSString *fieldId;
/** Name of the field. */
@property(nonatomic, copy, nullable) NSString *fieldName;
/** Type of the field. */
@property(nonatomic, copy, nullable) NSString *fieldType;
/**
* Boolean specifying whether the field is indexed or not.
*
* Uses NSNumber of boolValue.
*/
@property(nonatomic, strong, nullable) NSNumber *indexed;
/** Kind of resource this is. */
@property(nonatomic, copy, nullable) NSString *kind;
/**
* Boolean specifying whether this is a multi-valued field or not.
*
* Uses NSNumber of boolValue.
*/
@property(nonatomic, strong, nullable) NSNumber *multiValued;
/**
* Indexing spec for a numeric field. By default, only exact match queries will
* be supported for numeric fields. Setting the numericIndexingSpec allows
* range queries to be supported.
*/
@property(nonatomic, strong, nullable) GTLRDirectory_SchemaFieldSpec_NumericIndexingSpec *numericIndexingSpec;
/**
* Read ACLs on the field specifying who can view values of this field. Valid
* values are "ALL_DOMAIN_USERS" and "ADMINS_AND_SELF".
*/
@property(nonatomic, copy, nullable) NSString *readAccessType;
@end
/**
* Indexing spec for a numeric field. By default, only exact match queries will
* be supported for numeric fields. Setting the numericIndexingSpec allows
* range queries to be supported.
*/
@interface GTLRDirectory_SchemaFieldSpec_NumericIndexingSpec : GTLRObject
/**
* Maximum value of this field. This is meant to be indicative rather than
* enforced. Values outside this range will still be indexed, but search may
* not be as performant.
*
* Uses NSNumber of doubleValue.
*/
@property(nonatomic, strong, nullable) NSNumber *maxValue;
/**
* Minimum value of this field. This is meant to be indicative rather than
* enforced. Values outside this range will still be indexed, but search may
* not be as performant.
*
* Uses NSNumber of doubleValue.
*/
@property(nonatomic, strong, nullable) NSNumber *minValue;
@end
/**
* JSON response template for List Schema operation in Directory API.
*/
@interface GTLRDirectory_Schemas : GTLRObject
/** ETag of the resource. */
@property(nonatomic, copy, nullable) NSString *ETag;
/** Kind of resource this is. */
@property(nonatomic, copy, nullable) NSString *kind;
/** List of UserSchema objects. */
@property(nonatomic, strong, nullable) NSArray<GTLRDirectory_Schema *> *schemas;
@end
/**
* JSON template for token resource in Directory API.
*/
@interface GTLRDirectory_Token : GTLRObject
/**
* Whether the application is registered with Google. The value is true if the
* application has an anonymous Client ID.
*
* Uses NSNumber of boolValue.
*/
@property(nonatomic, strong, nullable) NSNumber *anonymous;
/** The Client ID of the application the token is issued to. */
@property(nonatomic, copy, nullable) NSString *clientId;
/** The displayable name of the application the token is issued to. */
@property(nonatomic, copy, nullable) NSString *displayText;
/** ETag of the resource. */
@property(nonatomic, copy, nullable) NSString *ETag;
/** The type of the API resource. This is always admin#directory#token. */
@property(nonatomic, copy, nullable) NSString *kind;
/**
* Whether the token is issued to an installed application. The value is true
* if the application is installed to a desktop or mobile device.
*
* Uses NSNumber of boolValue.
*/
@property(nonatomic, strong, nullable) NSNumber *nativeApp;
/** A list of authorization scopes the application is granted. */
@property(nonatomic, strong, nullable) NSArray<NSString *> *scopes;
/** The unique ID of the user that issued the token. */
@property(nonatomic, copy, nullable) NSString *userKey;
@end
/**
* JSON response template for List tokens operation in Directory API.
*
* @note This class supports NSFastEnumeration and indexed subscripting over
* its "items" property.
*/
@interface GTLRDirectory_Tokens : GTLRCollectionObject
/** ETag of the resource. */
@property(nonatomic, copy, nullable) NSString *ETag;
/**
* A list of Token resources.
*
* @note This property is used to support NSFastEnumeration and indexed
* subscripting on this class.
*/
@property(nonatomic, strong, nullable) NSArray<GTLRDirectory_Token *> *items;
/** The type of the API resource. This is always admin#directory#tokenList. */
@property(nonatomic, copy, nullable) NSString *kind;
@end
/**
* JSON template for User object in Directory API.
*/
@interface GTLRDirectory_User : GTLRObject
/**
* addresses
*
* Can be any valid JSON type.
*/
@property(nonatomic, strong, nullable) id addresses;
/**
* Indicates if user has agreed to terms (Read-only)
*
* Uses NSNumber of boolValue.
*/
@property(nonatomic, strong, nullable) NSNumber *agreedToTerms;
/** List of aliases (Read-only) */
@property(nonatomic, strong, nullable) NSArray<NSString *> *aliases;
/**
* Boolean indicating if the user should change password in next login
*
* Uses NSNumber of boolValue.
*/
@property(nonatomic, strong, nullable) NSNumber *changePasswordAtNextLogin;
/** User's Google account creation time. (Read-only) */
@property(nonatomic, strong, nullable) GTLRDateTime *creationTime;
/** CustomerId of User (Read-only) */
@property(nonatomic, copy, nullable) NSString *customerId;
/** Custom fields of the user. */
@property(nonatomic, strong, nullable) GTLRDirectory_User_CustomSchemas *customSchemas;
@property(nonatomic, strong, nullable) GTLRDateTime *deletionTime;
/**
* emails
*
* Can be any valid JSON type.
*/
@property(nonatomic, strong, nullable) id emails;
/** ETag of the resource. */
@property(nonatomic, copy, nullable) NSString *ETag;
/**
* externalIds
*
* Can be any valid JSON type.
*/
@property(nonatomic, strong, nullable) id externalIds;
/** Hash function name for password. Supported are MD5, SHA-1 and crypt */
@property(nonatomic, copy, nullable) NSString *hashFunction;
/**
* Unique identifier of User (Read-only)
*
* identifier property maps to 'id' in JSON (to avoid Objective C's 'id').
*/
@property(nonatomic, copy, nullable) NSString *identifier;
/**
* ims
*
* Can be any valid JSON type.
*/
@property(nonatomic, strong, nullable) id ims;
/**
* Boolean indicating if user is included in Global Address List
*
* Uses NSNumber of boolValue.
*/
@property(nonatomic, strong, nullable) NSNumber *includeInGlobalAddressList;
/**
* Boolean indicating if ip is whitelisted
*
* Uses NSNumber of boolValue.
*/
@property(nonatomic, strong, nullable) NSNumber *ipWhitelisted;
/**
* Boolean indicating if the user is admin (Read-only)
*
* Uses NSNumber of boolValue.
*/
@property(nonatomic, strong, nullable) NSNumber *isAdmin;
/**
* Boolean indicating if the user is delegated admin (Read-only)
*
* Uses NSNumber of boolValue.
*/
@property(nonatomic, strong, nullable) NSNumber *isDelegatedAdmin;
/**
* Is 2-step verification enforced (Read-only)
*
* Uses NSNumber of boolValue.
*/
@property(nonatomic, strong, nullable) NSNumber *isEnforcedIn2Sv;
/**
* Is enrolled in 2-step verification (Read-only)
*
* Uses NSNumber of boolValue.
*/
@property(nonatomic, strong, nullable) NSNumber *isEnrolledIn2Sv;
/**
* Is mailbox setup (Read-only)
*
* Uses NSNumber of boolValue.
*/
@property(nonatomic, strong, nullable) NSNumber *isMailboxSetup;
/** Kind of resource this is. */
@property(nonatomic, copy, nullable) NSString *kind;
/** User's last login time. (Read-only) */
@property(nonatomic, strong, nullable) GTLRDateTime *lastLoginTime;
/** User's name */
@property(nonatomic, strong, nullable) GTLRDirectory_UserName *name;
/** List of non editable aliases (Read-only) */
@property(nonatomic, strong, nullable) NSArray<NSString *> *nonEditableAliases;
/**
* notes
*
* Can be any valid JSON type.
*/
@property(nonatomic, strong, nullable) id notes;
/**
* organizations
*
* Can be any valid JSON type.
*/
@property(nonatomic, strong, nullable) id organizations;
/** OrgUnit of User */
@property(nonatomic, copy, nullable) NSString *orgUnitPath;
/** User's password */
@property(nonatomic, copy, nullable) NSString *password;
/**
* phones
*
* Can be any valid JSON type.
*/
@property(nonatomic, strong, nullable) id phones;
/**
* posixAccounts
*
* Can be any valid JSON type.
*/
@property(nonatomic, strong, nullable) id posixAccounts;
/** username of User */
@property(nonatomic, copy, nullable) NSString *primaryEmail;
/**
* relations
*
* Can be any valid JSON type.
*/
@property(nonatomic, strong, nullable) id relations;
/**
* sshPublicKeys
*
* Can be any valid JSON type.
*/
@property(nonatomic, strong, nullable) id sshPublicKeys;
/**
* Indicates if user is suspended
*
* Uses NSNumber of boolValue.
*/
@property(nonatomic, strong, nullable) NSNumber *suspended;
/** Suspension reason if user is suspended (Read-only) */
@property(nonatomic, copy, nullable) NSString *suspensionReason;
/** ETag of the user's photo (Read-only) */
@property(nonatomic, copy, nullable) NSString *thumbnailPhotoEtag;
/** Photo Url of the user (Read-only) */
@property(nonatomic, copy, nullable) NSString *thumbnailPhotoUrl;
/**
* websites
*
* Can be any valid JSON type.
*/
@property(nonatomic, strong, nullable) id websites;
@end
/**
* Custom fields of the user.
*
* @note This class is documented as having more properties of
* GTLRDirectory_UserCustomProperties. Use @c -additionalJSONKeys and @c
* -additionalPropertyForName: to get the list of properties and then
* fetch them; or @c -additionalProperties to fetch them all at once.
*/
@interface GTLRDirectory_User_CustomSchemas : GTLRObject
@end
/**
* JSON template for About (notes) of a user in Directory API.
*/
@interface GTLRDirectory_UserAbout : GTLRObject
/**
* About entry can have a type which indicates the content type. It can either
* be plain or html. By default, notes contents are assumed to contain plain
* text.
*/
@property(nonatomic, copy, nullable) NSString *contentType;
/** Actual value of notes. */
@property(nonatomic, copy, nullable) NSString *value;
@end
/**
* JSON template for address.
*/
@interface GTLRDirectory_UserAddress : GTLRObject
/** Country. */
@property(nonatomic, copy, nullable) NSString *country;
/** Country code. */
@property(nonatomic, copy, nullable) NSString *countryCode;
/** Custom type. */
@property(nonatomic, copy, nullable) NSString *customType;
/** Extended Address. */
@property(nonatomic, copy, nullable) NSString *extendedAddress;
/** Formatted address. */
@property(nonatomic, copy, nullable) NSString *formatted;
/** Locality. */
@property(nonatomic, copy, nullable) NSString *locality;
/** Other parts of address. */
@property(nonatomic, copy, nullable) NSString *poBox;
/** Postal code. */
@property(nonatomic, copy, nullable) NSString *postalCode;
/**
* If this is user's primary address. Only one entry could be marked as
* primary.
*
* Uses NSNumber of boolValue.
*/
@property(nonatomic, strong, nullable) NSNumber *primary;
/** Region. */
@property(nonatomic, copy, nullable) NSString *region;
/**
* User supplied address was structured. Structured addresses are NOT supported
* at this time. You might be able to write structured addresses, but any
* values will eventually be clobbered.
*
* Uses NSNumber of boolValue.
*/
@property(nonatomic, strong, nullable) NSNumber *sourceIsStructured;
/** Street. */
@property(nonatomic, copy, nullable) NSString *streetAddress;
/**
* Each entry can have a type which indicates standard values of that entry.
* For example address could be of home, work etc. In addition to the standard
* type, an entry can have a custom type and can take any value. Such type
* should have the CUSTOM value as type and also have a customType value.
*/
@property(nonatomic, copy, nullable) NSString *type;
@end
/**
* JSON template for a set of custom properties (i.e. all fields in a
* particular schema)
*
* @note This class is documented as having more properties of any valid JSON
* type. Use @c -additionalJSONKeys and @c -additionalPropertyForName: to
* get the list of properties and then fetch them; or @c
* -additionalProperties to fetch them all at once.
*/
@interface GTLRDirectory_UserCustomProperties : GTLRObject
@end
/**
* JSON template for an email.
*/
@interface GTLRDirectory_UserEmail : GTLRObject
/** Email id of the user. */
@property(nonatomic, copy, nullable) NSString *address;
/** Custom Type. */
@property(nonatomic, copy, nullable) NSString *customType;
/**
* If this is user's primary email. Only one entry could be marked as primary.
*
* Uses NSNumber of boolValue.
*/
@property(nonatomic, strong, nullable) NSNumber *primary;
/**
* Each entry can have a type which indicates standard types of that entry. For
* example email could be of home, work etc. In addition to the standard type,
* an entry can have a custom type and can take any value Such types should
* have the CUSTOM value as type and also have a customType value.
*/
@property(nonatomic, copy, nullable) NSString *type;
@end
/**
* JSON template for an externalId entry.
*/
@interface GTLRDirectory_UserExternalId : GTLRObject
/** Custom type. */
@property(nonatomic, copy, nullable) NSString *customType;
/** The type of the Id. */
@property(nonatomic, copy, nullable) NSString *type;
/** The value of the id. */
@property(nonatomic, copy, nullable) NSString *value;
@end
/**
* JSON template for instant messenger of an user.
*/
@interface GTLRDirectory_UserIm : GTLRObject
/** Custom protocol. */
@property(nonatomic, copy, nullable) NSString *customProtocol;
/** Custom type. */
@property(nonatomic, copy, nullable) NSString *customType;
/** Instant messenger id. */
@property(nonatomic, copy, nullable) NSString *im;
/**
* If this is user's primary im. Only one entry could be marked as primary.
*
* Uses NSNumber of boolValue.
*/
@property(nonatomic, strong, nullable) NSNumber *primary;
/**
* Protocol used in the instant messenger. It should be one of the values from
* ImProtocolTypes map. Similar to type, it can take a CUSTOM value and specify
* the custom name in customProtocol field.
*/
@property(nonatomic, copy, nullable) NSString *protocol;
/**
* Each entry can have a type which indicates standard types of that entry. For
* example instant messengers could be of home, work etc. In addition to the
* standard type, an entry can have a custom type and can take any value. Such
* types should have the CUSTOM value as type and also have a customType value.
*/
@property(nonatomic, copy, nullable) NSString *type;
@end
/**
* JSON request template for setting/revoking admin status of a user in
* Directory API.
*/
@interface GTLRDirectory_UserMakeAdmin : GTLRObject
/**
* Boolean indicating new admin status of the user
*
* Uses NSNumber of boolValue.
*/
@property(nonatomic, strong, nullable) NSNumber *status;
@end
/**
* JSON template for name of a user in Directory API.
*/
@interface GTLRDirectory_UserName : GTLRObject
/** Last Name */
@property(nonatomic, copy, nullable) NSString *familyName;
/** Full Name */
@property(nonatomic, copy, nullable) NSString *fullName;
/** First Name */
@property(nonatomic, copy, nullable) NSString *givenName;
@end
/**
* JSON template for an organization entry.
*/
@interface GTLRDirectory_UserOrganization : GTLRObject
/** The cost center of the users department. */
@property(nonatomic, copy, nullable) NSString *costCenter;
/** Custom type. */
@property(nonatomic, copy, nullable) NSString *customType;
/** Department within the organization. */
@property(nonatomic, copy, nullable) NSString *department;
/**
* Description of the organization.
*
* Remapped to 'descriptionProperty' to avoid NSObject's 'description'.
*/
@property(nonatomic, copy, nullable) NSString *descriptionProperty;
/** The domain to which the organization belongs to. */
@property(nonatomic, copy, nullable) NSString *domain;
/** Location of the organization. This need not be fully qualified address. */
@property(nonatomic, copy, nullable) NSString *location;
/** Name of the organization */
@property(nonatomic, copy, nullable) NSString *name;
/**
* If it user's primary organization.
*
* Uses NSNumber of boolValue.
*/
@property(nonatomic, strong, nullable) NSNumber *primary;
/** Symbol of the organization. */
@property(nonatomic, copy, nullable) NSString *symbol;
/** Title (designation) of the user in the organization. */
@property(nonatomic, copy, nullable) NSString *title;
/**
* Each entry can have a type which indicates standard types of that entry. For
* example organization could be of school, work etc. In addition to the
* standard type, an entry can have a custom type and can give it any name.
* Such types should have the CUSTOM value as type and also have a CustomType
* value.
*/
@property(nonatomic, copy, nullable) NSString *type;
@end
/**
* JSON template for a phone entry.
*/
@interface GTLRDirectory_UserPhone : GTLRObject
/** Custom Type. */
@property(nonatomic, copy, nullable) NSString *customType;
/**
* If this is user's primary phone or not.
*
* Uses NSNumber of boolValue.
*/
@property(nonatomic, strong, nullable) NSNumber *primary;
/**
* Each entry can have a type which indicates standard types of that entry. For
* example phone could be of home_fax, work, mobile etc. In addition to the
* standard type, an entry can have a custom type and can give it any name.
* Such types should have the CUSTOM value as type and also have a customType
* value.
*/
@property(nonatomic, copy, nullable) NSString *type;
/** Phone number. */
@property(nonatomic, copy, nullable) NSString *value;
@end
/**
* JSON template for Photo object in Directory API.
*/
@interface GTLRDirectory_UserPhoto : GTLRObject
/** ETag of the resource. */
@property(nonatomic, copy, nullable) NSString *ETag;
/**
* Height in pixels of the photo
*
* Uses NSNumber of intValue.
*/
@property(nonatomic, strong, nullable) NSNumber *height;
/**
* Unique identifier of User (Read-only)
*
* identifier property maps to 'id' in JSON (to avoid Objective C's 'id').
*/
@property(nonatomic, copy, nullable) NSString *identifier;
/** Kind of resource this is. */
@property(nonatomic, copy, nullable) NSString *kind;
/** Mime Type of the photo */
@property(nonatomic, copy, nullable) NSString *mimeType;
/**
* Base64 encoded photo data
*
* Contains encoded binary data; GTLRBase64 can encode/decode (probably
* web-safe format).
*/
@property(nonatomic, copy, nullable) NSString *photoData;
/** Primary email of User (Read-only) */
@property(nonatomic, copy, nullable) NSString *primaryEmail;
/**
* Width in pixels of the photo
*
* Uses NSNumber of intValue.
*/
@property(nonatomic, strong, nullable) NSNumber *width;
@end
/**
* JSON template for a POSIX account entry. Description of the field family:
* go/fbs-posix.
*/
@interface GTLRDirectory_UserPosixAccount : GTLRObject
/** The GECOS (user information) entry for this account. */
@property(nonatomic, copy, nullable) NSString *gecos;
/**
* The default group ID.
*
* Uses NSNumber of intValue.
*/
@property(nonatomic, strong, nullable) NSNumber *gid;
/** The path to the home directory for this account. */
@property(nonatomic, copy, nullable) NSString *homeDirectory;
/**
* If this is user's primary account within the SystemId.
*
* Uses NSNumber of boolValue.
*/
@property(nonatomic, strong, nullable) NSNumber *primary;
/** The path to the login shell for this account. */
@property(nonatomic, copy, nullable) NSString *shell;
/** System identifier for which account Username or Uid apply to. */
@property(nonatomic, copy, nullable) NSString *systemId;
/**
* The user ID.
*
* Uses NSNumber of intValue.
*/
@property(nonatomic, strong, nullable) NSNumber *uid;
/** The username of the account. */
@property(nonatomic, copy, nullable) NSString *username;
@end
/**
* JSON template for a relation entry.
*/
@interface GTLRDirectory_UserRelation : GTLRObject
/** Custom Type. */
@property(nonatomic, copy, nullable) NSString *customType;
/**
* The relation of the user. Some of the possible values are mother, father,
* sister, brother, manager, assistant, partner.
*/
@property(nonatomic, copy, nullable) NSString *type;
/** The name of the relation. */
@property(nonatomic, copy, nullable) NSString *value;
@end
/**
* JSON response template for List Users operation in Apps Directory API.
*
* @note This class supports NSFastEnumeration and indexed subscripting over
* its "users" property. If returned as the result of a query, it should
* support automatic pagination (when @c shouldFetchNextPages is
* enabled).
*/
@interface GTLRDirectory_Users : GTLRCollectionObject
/** ETag of the resource. */
@property(nonatomic, copy, nullable) NSString *ETag;
/** Kind of resource this is. */
@property(nonatomic, copy, nullable) NSString *kind;
/** Token used to access next page of this result. */
@property(nonatomic, copy, nullable) NSString *nextPageToken;
/** Event that triggered this response (only used in case of Push Response) */
@property(nonatomic, copy, nullable) NSString *triggerEvent;
/**
* List of user objects.
*
* @note This property is used to support NSFastEnumeration and indexed
* subscripting on this class.
*/
@property(nonatomic, strong, nullable) NSArray<GTLRDirectory_User *> *users;
@end
/**
* JSON template for a POSIX account entry.
*/
@interface GTLRDirectory_UserSshPublicKey : GTLRObject
/**
* An expiration time in microseconds since epoch.
*
* Uses NSNumber of longLongValue.
*/
@property(nonatomic, strong, nullable) NSNumber *expirationTimeUsec;
/** A SHA-256 fingerprint of the SSH public key. (Read-only) */
@property(nonatomic, copy, nullable) NSString *fingerprint;
/** An SSH public key. */
@property(nonatomic, copy, nullable) NSString *key;
@end
/**
* JSON request template to undelete a user in Directory API.
*/
@interface GTLRDirectory_UserUndelete : GTLRObject
/** OrgUnit of User */
@property(nonatomic, copy, nullable) NSString *orgUnitPath;
@end
/**
* JSON template for a website entry.
*/
@interface GTLRDirectory_UserWebsite : GTLRObject
/** Custom Type. */
@property(nonatomic, copy, nullable) NSString *customType;
/**
* If this is user's primary website or not.
*
* Uses NSNumber of boolValue.
*/
@property(nonatomic, strong, nullable) NSNumber *primary;
/**
* Each entry can have a type which indicates standard types of that entry. For
* example website could be of home, work, blog etc. In addition to the
* standard type, an entry can have a custom type and can give it any name.
* Such types should have the CUSTOM value as type and also have a customType
* value.
*/
@property(nonatomic, copy, nullable) NSString *type;
/** Website. */
@property(nonatomic, copy, nullable) NSString *value;
@end
/**
* JSON template for verification codes in Directory API.
*/
@interface GTLRDirectory_VerificationCode : GTLRObject
/** ETag of the resource. */
@property(nonatomic, copy, nullable) NSString *ETag;
/**
* The type of the resource. This is always admin#directory#verificationCode.
*/
@property(nonatomic, copy, nullable) NSString *kind;
/** The obfuscated unique ID of the user. */
@property(nonatomic, copy, nullable) NSString *userId;
/**
* A current verification code for the user. Invalidated or used verification
* codes are not returned as part of the result.
*/
@property(nonatomic, copy, nullable) NSString *verificationCode;
@end
/**
* JSON response template for List verification codes operation in Directory
* API.
*
* @note This class supports NSFastEnumeration and indexed subscripting over
* its "items" property.
*/
@interface GTLRDirectory_VerificationCodes : GTLRCollectionObject
/** ETag of the resource. */
@property(nonatomic, copy, nullable) NSString *ETag;
/**
* A list of verification code resources.
*
* @note This property is used to support NSFastEnumeration and indexed
* subscripting on this class.
*/
@property(nonatomic, strong, nullable) NSArray<GTLRDirectory_VerificationCode *> *items;
/**
* The type of the resource. This is always
* admin#directory#verificationCodesList.
*/
@property(nonatomic, copy, nullable) NSString *kind;
@end
NS_ASSUME_NONNULL_END
| 27.669157 | 126 | 0.728317 | [
"object",
"model"
] |
d3cef5b06c88a9be0980da413d74435c33283234 | 34,083 | c | C | src/lio/bin/lio_warm.c | tacketar/lstore | 45ce7fdca6e3aa63b1b160697d8ee2f46ddea147 | [
"Apache-2.0"
] | 1 | 2016-09-06T13:36:37.000Z | 2016-09-06T13:36:37.000Z | src/lio/bin/lio_warm.c | tacketar/lstore | 45ce7fdca6e3aa63b1b160697d8ee2f46ddea147 | [
"Apache-2.0"
] | null | null | null | src/lio/bin/lio_warm.c | tacketar/lstore | 45ce7fdca6e3aa63b1b160697d8ee2f46ddea147 | [
"Apache-2.0"
] | 1 | 2016-09-06T13:50:48.000Z | 2016-09-06T13:50:48.000Z | /*
Copyright 2016 Vanderbilt University
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.
*/
#define _log_module_index 207
#include <rocksdb/c.h>
#include <apr.h>
#include <apr_hash.h>
#include <apr_pools.h>
#include <gop/gop.h>
#include <gop/opque.h>
#include <gop/tp.h>
#include <gop/types.h>
#include <ibp/types.h>
#include <lio/authn.h>
#include <lio/ds.h>
#include <lio/ex3.h>
#include <lio/lio.h>
#include <lio/os.h>
#include <lio/rs.h>
#include <stdio.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <tbx/apr_wrapper.h>
#include <tbx/assert_result.h>
#include <tbx/iniparse.h>
#include <tbx/list.h>
#include <tbx/log.h>
#include <tbx/que.h>
#include <tbx/stdinarray_iter.h>
#include <tbx/string_token.h>
#include <tbx/type_malloc.h>
#include "warmer_helpers.h"
typedef struct {
char *fname;
char *exnode;
ex_id_t inode;
int write_err;
int n_left;
int n_good;
int n_bad;
} inode_entry_t;
typedef struct {
int n_used;
int curr_slot;
int n_running;
int running_slot;
int n_failed;
int serial_max;
int *failed;
char **cap;
inode_entry_t **inode;
ex_off_t *nbytes;
char *key;
ibp_depot_t depot;
gop_op_generic_t *gop;
} rid_warm_t;
typedef struct {
char *rid_key;
ex_off_t good;
ex_off_t bad;
ex_off_t nbytes;
ex_off_t dtime;
rid_warm_t *warm;
} warm_hash_entry_t;
typedef struct {
char *cap;
ex_off_t nbytes;
} warm_cap_info_t;
typedef struct {
apr_thread_t *thread;
tbx_que_t *que;
tbx_que_t *que_setattr;
apr_hash_t *hash;
apr_pool_t *mpool;
inode_entry_t **inode;
gop_opque_t *q;
int write_err;
ex_off_t good;
ex_off_t bad;
ex_off_t werr;
int n_bulk;
} warm_thread_t;
typedef struct {
lio_path_tuple_t tuple;
warm_cap_info_t *cap;
char *fname;
char *exnode;
ibp_context_t *ic;
apr_hash_t *hash;
apr_pool_t *mpool;
int n;
ex_id_t inode;
int write_err;
} warm_t;
apr_hash_t *tagged_rids = NULL;
apr_pool_t *tagged_pool = NULL;
tbx_stack_t *tagged_keys = NULL;
warm_db_t *db_rid = NULL;
warm_db_t *db_inode = NULL;
int verbose = 0;
ibp_context_t *ic = NULL;
int bulk_mode = 1;
static int dt = 86400;
//*************************************************************************
// parse_tag_file - Parse the file contianing the RID's for tagging
//*************************************************************************
void parse_tag_file(char *fname)
{
tbx_inip_file_t *fd;
tbx_inip_group_t *g;
tbx_inip_element_t *ele;
char *key, *value, *v;
fd = tbx_inip_file_read(fname, 1);
if (fd == NULL) return;
apr_pool_create(&tagged_pool, NULL);
tagged_rids = apr_hash_make(tagged_pool);
tagged_keys = tbx_stack_new();
//** Cycle through the blocks storing both the segment block information and also the cap blocks
g = tbx_inip_group_find(fd, "tag");
ele = tbx_inip_ele_first(g);
while (ele != NULL) {
key = tbx_inip_ele_get_key(ele);
if (strcmp(key, "rid_key") == 0) {
v = tbx_inip_ele_get_value(ele);
value = strdup(v);
info_printf(lio_ifd, 0, "Tagging RID %s\n", value);
apr_hash_set(tagged_rids, value, APR_HASH_KEY_STRING, value);
tbx_stack_push(tagged_keys, value);
}
ele = tbx_inip_ele_next(ele);
}
tbx_inip_destroy(fd);
if (apr_hash_count(tagged_rids) == 0) {
tbx_stack_free(tagged_keys, 0);
apr_pool_destroy(tagged_pool);
tagged_pool = NULL;
tagged_rids = NULL;
} else {
info_printf(lio_ifd, 0, "\n");
}
}
//*************************************************************************
// object_warm_finish - Does the final steps in warming a file
//*************************************************************************
void object_warm_finish(warm_thread_t *w, inode_entry_t *inode)
{
int state;
state = (inode->write_err == 0) ? 0 : WFE_WRITE_ERR;
if (inode->n_bad == 0) {
w->good++;
state |= WFE_SUCCESS;
if (verbose == 1) info_printf(lio_ifd, 0, "Succeeded with file %s with %d allocations\n", inode->fname, inode->n_good);
} else {
w->bad++;
state |= WFE_FAIL;
info_printf(lio_ifd, 0, "Failed with file %s on %d out of %d allocations\n", inode->fname, inode->n_bad, inode->n_good+inode->n_bad);
}
warm_put_inode(db_inode, inode->inode, state, inode->n_bad, inode->fname);
tbx_que_put(w->que_setattr, &(inode->fname), TBX_QUE_BLOCK);
free(inode);
}
//*************************************************************************
// process_warm_op - Processes the results of the warming op
//*************************************************************************
void process_warm_op(warm_hash_entry_t *wr, warm_thread_t *w)
{
rid_warm_t *r = wr->warm;
int i, j;
int *failed;
ex_off_t *nbytes;
inode_entry_t **inode;
char **cap;
gop_op_status_t status;
//** Set up all the pointers
failed = r->failed + r->running_slot;
nbytes = r->nbytes + r->running_slot;
cap = r->cap + r->running_slot;
inode = r->inode + r->running_slot;
//** Update the time
wr->dtime += gop_time_exec(r->gop);
//** First handle all the failed allocations
//** Since the next step after this assumes all the allocations are good we
//** do some odd inc/dec to account for that
status = gop_get_status(r->gop);
if (status.op_status == OP_STATE_SUCCESS) {
for (i=0; i<r->n_failed; i++) {
j = failed[i];
info_printf(lio_ifd, 1, "ERROR: %s cap=%s\n", inode[j]->fname, cap[j]);
inode[j]->n_bad++;
free(cap[j]);
cap[j] = NULL; //** Flag that it's bad
wr->bad++;
}
} else { //** Everything failed
for (i=0; i<r->n_running; i++) {
info_printf(lio_ifd, 1, "ERROR: %s cap=%s\n", inode[i]->fname, cap[i]);
inode[i]->n_bad++;
free(cap[i]);
cap[i] = NULL; //** Flag that it's bad
wr->bad++;
}
}
//** Now process all the allocations and clean up as we go
for (i=0; i<r->n_running; i++) {
if (cap[i] != NULL) {
free(cap[i]);
wr->good++;
inode[i]->n_good++;
warm_put_rid(db_rid, wr->rid_key, inode[i]->inode, nbytes[i], WFE_SUCCESS);
} else {
warm_put_rid(db_rid, wr->rid_key, inode[i]->inode, nbytes[i], WFE_FAIL);
}
inode[i]->n_left--;
if (inode[i]->n_left == 0) object_warm_finish(w, inode[i]);
}
gop_free(r->gop, OP_DESTROY);
r->gop = NULL;
}
//*************************************************************************
// warm_serial_fn - Performs the serial warming
//*************************************************************************
gop_op_status_t warm_serial_fn(void *arg, int id)
{
warm_hash_entry_t *wr = (warm_hash_entry_t *)arg;
rid_warm_t *r = wr->warm;
int i, slot, nbad;
gop_op_status_t status = gop_success_status;
gop_op_status_t gs;
gop_op_generic_t *gop;
gop_opque_t *q = gop_opque_new();
//** Submit tasks and process them as needed
nbad = 0;
opque_start_execution(q);
for (i=0; i<r->n_running; i++) {
gop = ibp_modify_alloc_gop(ic, r->cap[r->running_slot + i], -1, dt, -1, lio_gc->timeout);
gop_set_myid(gop, i);
gop_opque_add(q, gop);
if (i>r->serial_max) { //** Reap a task
gop = opque_waitany(q);
slot = gop_get_myid(gop);
gs = gop_get_status(gop);
if (gs.op_status != OP_STATE_SUCCESS) {
r->failed[r->running_slot + nbad] = slot;
nbad++;
}
gop_free(gop, OP_DESTROY);
}
}
//** Finish the processing
while ((gop = opque_waitany(q)) != NULL) {
slot = gop_get_myid(gop);
gs = gop_get_status(gop);
if (gs.op_status != OP_STATE_SUCCESS) {
r->failed[r->running_slot + nbad] = slot;
nbad++;
}
gop_free(gop, OP_DESTROY);
}
r->n_failed = nbad;
if (nbad == r->n_running) status = gop_failure_status;
gop_opque_free(q, OP_DESTROY);
return(status);
}
//*************************************************************************
// submit_warm_op - Warming op
//*************************************************************************
void submit_warm_op(warm_hash_entry_t *wr, warm_thread_t *w)
{
rid_warm_t *r = wr->warm;
r->n_running = r->n_used;
r->running_slot = r->curr_slot;
if (bulk_mode == 1) {
r->gop = ibp_rid_bulk_warm_gop(ic, &(r->depot), dt, r->n_running, &(r->cap[r->curr_slot]), &(r->n_failed), &(r->failed[r->curr_slot]), lio_gc->timeout);
} else {
r->gop = gop_tp_op_new(lio_gc->tpc_unlimited, NULL, warm_serial_fn, (void *)wr, NULL, 1);
}
r->curr_slot = (r->curr_slot == 0) ? w->n_bulk : 0;
r->n_used = 0; //** Reset the todo count
gop_set_private(r->gop, wr);
gop_opque_add(w->q, r->gop);
}
//*************************************************************************
// warm_rid_wait - Waits for the current warming gop fo rthe rid to complete and cleans up
//*************************************************************************
void warm_rid_wait(warm_thread_t *w, rid_warm_t *r)
{
warm_hash_entry_t *wr2;
gop_op_generic_t *gop;
while (r->gop) { //** Already have a task running so we have to wait
gop = opque_waitany(w->q);
wr2 = gop_get_private(gop);
process_warm_op(wr2, w);
}
}
//*************************************************************************
// rid_todo_slot - Gets the next free slot to use
// If needed the routine will force a warming call if needed.
//*************************************************************************
int rid_todo_slot(warm_hash_entry_t *wr, warm_thread_t *w)
{
rid_warm_t *r = wr->warm;
int slot;
if (r->n_used == w->n_bulk) { //** Generate a warm task
warm_rid_wait(w, r); //** Already have a task running so we have to wait
//** Generate the new operation and submit it
submit_warm_op(wr, w);
}
slot = r->curr_slot + r->n_used;
r->n_used++;
return(slot);
}
//*************************************************************************
// rid_todo_create - Creates a todo structure for the RID
//*************************************************************************
rid_warm_t *rid_todo_create(char *rid_key, int n, char *cap)
{
rid_warm_t *rid;
tbx_type_malloc_clear(rid, rid_warm_t, 1);
tbx_type_malloc_clear(rid->cap, char *, 2*n);
tbx_type_malloc_clear(rid->inode, inode_entry_t *, 2*n);
tbx_type_malloc_clear(rid->nbytes, ex_off_t, 2*n);
tbx_type_malloc_clear(rid->failed, int, 2*n);
rid->curr_slot = 0;
rid->n_running = 0;
rid->n_used = 0;
rid->serial_max = 20;
rid->key = rid_key;
ibp_cap2depot(cap, &(rid->depot));
return(rid);
}
//*************************************************************************
// rid_todo_destroy - Destroys the RID todo structure
//*************************************************************************
void rid_todo_destroy(rid_warm_t *rid)
{
free(rid->cap);
free(rid->inode);
free(rid->nbytes);
free(rid->failed);
free(rid);
}
//*************************************************************************
// gen_warm_task
//*************************************************************************
int total_gen_caps=0;
void gen_warm_tasks(warm_thread_t *w, inode_entry_t *inode)
{
tbx_inip_file_t *fd;
warm_hash_entry_t *wrid = NULL;
rid_warm_t *r;
char *etext, *mcap;
int slot, cnt;
char *exnode = inode->exnode; //** We save this just in case the blocks are all warmed and the inode is destroyed during the call
log_printf(15, "warming fname=%s, dt=%d\n", inode->fname, dt);
fd = tbx_inip_string_read(exnode, 1);
tbx_inip_group_t *g;
cnt = 0;
g = tbx_inip_group_first(fd);
inode->n_left = 1; //** Offset it to keep it from getting reaped during the processing
while (g) {
if (strncmp(tbx_inip_group_get(g), "block-", 6) == 0) { //** Got a data block
//** Get the manage cap first
etext = tbx_inip_get_string(fd, tbx_inip_group_get(g), "manage_cap", NULL);
if (!etext) {
info_printf(lio_ifd, 1, "MISSING_MCAP_ERROR: fname=%s block=%s\n", inode->fname, tbx_inip_group_get(g));
goto next;
}
mcap = tbx_stk_unescape_text('\\', etext);
free(etext);
//** Get the RID key
etext = tbx_inip_get_string(fd, tbx_inip_group_get(g), "rid_key", NULL);
if (etext != NULL) {
wrid = apr_hash_get(w->hash, etext, APR_HASH_KEY_STRING);
if (wrid == NULL) { //** 1st time so need to make an entry
tbx_type_malloc_clear(wrid, warm_hash_entry_t, 1);
wrid->rid_key = etext;
apr_hash_set(w->hash, wrid->rid_key, APR_HASH_KEY_STRING, wrid);
wrid->warm = rid_todo_create(etext, w->n_bulk, mcap);
} else {
free(etext);
}
}
r = wrid->warm;
//** Get the data size and update the counts
wrid->nbytes += tbx_inip_get_integer(fd, tbx_inip_group_get(g), "max_size", 0);
inode->n_left++; //** Incr this before the todo_slot call in case we flush all the existing caps so it won't be reaped
cnt++;
//** Get the slot
slot = rid_todo_slot(wrid, w);
//** Fill in the rest of the fields
r->inode[slot] = inode;
r->cap[slot] = mcap;
//** Check if it was tagged
if (tagged_rids != NULL) {
if (apr_hash_get(tagged_rids, wrid->rid_key, APR_HASH_KEY_STRING) != NULL) {
info_printf(lio_ifd, 0, "RID_TAG: %s rid_key=%s\n", inode->fname, wrid->rid_key);
}
}
}
next:
g = tbx_inip_group_next(g);
}
inode->n_left--; //** Undo our offset so we can reap the inode
tbx_inip_destroy(fd);
free(exnode);
//** Check if there was nothing to do. If so go ahead and mark the inode as complete
if (cnt == 0) object_warm_finish(w, inode);
}
//*************************************************************************
// setattr_thread - Sets the warming attribute
//*************************************************************************
void *setattr_thread(apr_thread_t *th, void *data)
{
tbx_que_t *que = (tbx_que_t *)data;
gop_opque_t *q = gop_opque_new();
gop_op_generic_t *gop;
int i, n, running;
int running_max = 1000;
int n_max = 1000;
char *fname[n_max];
char *etext, *fn;
etext = NULL;
opque_start_execution(q);
running = 0;
while (!tbx_que_is_finished(que)) {
n = tbx_que_bulk_get(que, n_max, fname, TBX_QUE_BLOCK);
//** Clean up any oustanding setattr calls
while ((gop = opque_get_next_finished(q)) != NULL) {
running--;
fn = gop_get_private(gop);
free(fn);
gop_free(gop, OP_DESTROY);
}
if (n <= 0) continue; //** Loop back if we got nothing
//** process the next round
for (i=0; i<n; i++) {
//** Make sure we don't flood the system
while (running > running_max) {
gop = opque_waitany(q);
running--;
fn = gop_get_private(gop);
free(fn);
gop_free(gop, OP_DESTROY);
}
running++;
gop = lio_setattr_gop(lio_gc, lio_gc->creds, fname[i], NULL, "os.timestamp.system.warm", (void *)etext, 0);
gop_set_private(gop, fname[i]);
gop_opque_add(q, gop);
}
}
//** Wait for the rest to complete
opque_finished_submission(q);
while ((gop = opque_waitany(q)) != NULL) {
fn = gop_get_private(gop);
free(fn);
gop_free(gop, OP_DESTROY);
}
gop_opque_free(q, OP_DESTROY);
return(NULL);
}
//*************************************************************************
// warming_thread - Main work thread for submitting warming operations
//*************************************************************************
void *warming_thread(apr_thread_t *th, void *data)
{
warm_thread_t *w = (warm_thread_t *)data;
int n, i;
gop_op_generic_t *gop;
warm_hash_entry_t *wr;
w->q = gop_opque_new();
while (!tbx_que_is_finished(w->que)) {
n = tbx_que_bulk_get(w->que, w->n_bulk, w->inode, TBX_QUE_BLOCK);
//** Process any submitted tasks that occurred during the warming
while ((gop = opque_get_next_finished(w->q)) != NULL) {
wr = gop_get_private(gop);
process_warm_op(wr, w);
}
if (n <= 0) continue; //** Loop back if we got nothing
//** Submit all the tasks
for (i=0; i<n; i++) {
gen_warm_tasks(w, w->inode[i]);
}
}
//** Flush all remaining RIDs to be warmed
apr_ssize_t hlen;
apr_hash_index_t *hi;
i = 0;
for (hi=apr_hash_first(NULL, w->hash); hi != NULL; hi = apr_hash_next(hi)) {
apr_hash_this(hi, NULL, &hlen, (void **)&wr);
if (wr->warm->n_used > 0) {
if (wr->warm->gop) warm_rid_wait(w, wr->warm); //** Already have a task running so we have to wait
submit_warm_op(wr, w);
i++;
if (i > 20) {
gop = opque_waitany(w->q);
wr = gop_get_private(gop);
process_warm_op(wr, w);
}
}
}
//** Process the results
opque_finished_submission(w->q);
while ((gop = opque_waitany(w->q)) != NULL) {
wr = gop_get_private(gop);
process_warm_op(wr, w);
}
//** And clean up
for (hi=apr_hash_first(NULL, w->hash); hi != NULL; hi = apr_hash_next(hi)) {
apr_hash_this(hi, NULL, &hlen, (void **)&wr);
rid_todo_destroy(wr->warm);
}
gop_opque_free(w->q, OP_DESTROY);
free(w->inode);
return(NULL);
}
//*************************************************************************
//*************************************************************************
int main(int argc, char **argv)
{
int i, j, start_option, rg_mode, ftype, prefix_len, return_code, n_warm, n_bulk, n_put, n, nleft;
char *fname, *path;
inode_entry_t *inode;
inode_entry_t **inode_list;
tbx_que_t *que, *que_setattr;
apr_thread_t *sa_thread;
char *keys[] = { "system.exnode", "system.inode", "system.write_errors" };
char *vals[3];
char *db_base = "/lio/log/warm";
int slot, v_size[3];
os_object_iter_t *it;
lio_os_regex_table_t *rp_single, *ro_single;
tbx_list_t *master;
apr_hash_index_t *hi;
apr_ssize_t klen;
char *rkey, *config, *value;
char *line_end;
warm_hash_entry_t *mrid, *wrid;
tbx_inip_file_t *ifd;
tbx_inip_group_t *ig;
tbx_inip_element_t *ele;
void *piter;
char ppbuf[128], ppbuf2[128], ppbuf3[128];
lio_path_tuple_t tuple;
ex_off_t total, good, bad, nbytes, submitted, werr, missing_err;
tbx_list_iter_t lit;
tbx_stack_t *stack;
int recurse_depth = 10000;
int summary_mode;
warm_thread_t *w;
double dtime, dtime_total;
n_bulk = 1000;
n_warm = 2;
n_put = 1000;
if (argc < 2) {
printf("\n");
printf("lio_warm LIO_COMMON_OPTIONS [-db DB_output_dir] [-t tag.cfg] [-rd recurse_depth] [-serial] [-dt time] [-sb] [-sf] [-v] LIO_PATH_OPTIONS\n");
lio_print_options(stdout);
lio_print_path_options(stdout);
printf(" -db DB_output_dir - Output Directory for the DBes. Default is %s\n", db_base);
printf(" -t tag.cfg - INI file with RID to tag by printing any files usign the RIDs\n");
printf(" -rd recurse_depth - Max recursion depth on directories. Defaults to %d\n", recurse_depth);
printf(" -serial - Use the IBP individual warming operation.\n");
printf(" -n_bulk - Number of allocations to warn at a time for bulk operations.\n");
printf(" NOTE: This is evenly divided among the warming threads. Default is %d\n", n_bulk);
printf(" -n_warm - Number of warming threads. Default is %d\n", n_warm);
printf(" -dt time - Duration time in sec. Default is %d sec\n", dt);
printf(" -sb - Print the summary but only list the bad RIDs\n");
printf(" -sf - Print the the full summary\n");
printf(" -v - Print all Success/Fail messages instead of just errors\n");
printf(" - - If no file is given but a single dash is used the files are taken from stdin\n");
return(1);
}
lio_init(&argc, &argv);
//*** Parse the path args
rp_single = ro_single = NULL;
rg_mode = lio_parse_path_options(&argc, argv, lio_gc->auto_translate, &tuple, &rp_single, &ro_single);
i=1;
summary_mode = 0;
verbose = 0;
do {
start_option = i;
if (strcmp(argv[i], "-db") == 0) { //** DB output base directory
i++;
db_base = argv[i];
i++;
} else if (strcmp(argv[i], "-serial") == 0) { //** Serial warming mode
i++;
bulk_mode = 0;
} else if (strcmp(argv[i], "-dt") == 0) { //** Time
i++;
dt = atoi(argv[i]);
i++;
} else if (strcmp(argv[i], "-n_bulk") == 0) { //** Time
i++;
n_bulk = atoi(argv[i]);
i++;
} else if (strcmp(argv[i], "-n_warm") == 0) { //** Time
i++;
n_warm = atoi(argv[i]);
i++;
} else if (strcmp(argv[i], "-rd") == 0) { //** Recurse depth
i++;
recurse_depth = atoi(argv[i]);
i++;
} else if (strcmp(argv[i], "-sb") == 0) { //** Print only bad RIDs
i++;
summary_mode = 1;
} else if (strcmp(argv[i], "-sf") == 0) { //** Print the full summary
i++;
summary_mode = 2;
} else if (strcmp(argv[i], "-v") == 0) { //** Verbose printing
i++;
verbose = 1;
} else if (strcmp(argv[i], "-t") == 0) { //** Got a list of RIDs to tag
i++;
parse_tag_file(argv[i]);
i++;
}
} while ((start_option < i) && (i<argc));
start_option = i;
if (rg_mode == 0) {
if (i>=argc) {
info_printf(lio_ifd, 0, "Missing directory!\n");
return(2);
}
} else {
start_option--; //** Ther 1st entry will be the rp created in lio_parse_path_options
}
piter = tbx_stdinarray_iter_create(argc-start_option, (const char **)&(argv[start_option]));
create_warm_db(db_base, &db_inode, &db_rid); //** Create the DB
ic = hack_ds_ibp_context_get(lio_gc->ds);
n_bulk = n_bulk / n_warm; //** Rescale the # of bulk caps to warn at a time
tbx_type_malloc(inode_list, inode_entry_t *, n_put);
//** Launch the warming threads
que = tbx_que_create(4*n_bulk*n_warm, sizeof(inode_entry_t *));
que_setattr = tbx_que_create(10000, sizeof(char *));
tbx_type_malloc_clear(w, warm_thread_t, n_warm);
for (j=0; j<n_warm; j++) {
w[j].n_bulk = n_bulk;
apr_pool_create(&(w[j].mpool), NULL);
w[j].hash = apr_hash_make(w[j].mpool);
w[j].que = que;
w[j].que_setattr = que_setattr;
tbx_type_malloc(w[j].inode, inode_entry_t *, w[j].n_bulk);
// ** Launch the backend thread
tbx_thread_create_assert(&(w[j].thread), NULL, warming_thread,
(void *)(&w[j]), lio_gc->mpool);
}
//** And the setattr thread
tbx_thread_create_assert(&sa_thread, NULL, setattr_thread,
(void *)que_setattr, lio_gc->mpool);
//** Process all the files
submitted = good = bad = werr = missing_err = 0;
slot = 0;
return_code = 0;
while ((path = tbx_stdinarray_iter_next(piter)) != NULL) {
if (rg_mode == 0) {
//** Create the simple path iterator
tuple = lio_path_resolve(lio_gc->auto_translate, path);
if (tuple.is_lio < 0) {
fprintf(stderr, "Unable to parse path: %s\n", path);
free(path);
return_code = EINVAL;
continue;
}
lio_path_wildcard_auto_append(&tuple);
rp_single = lio_os_path_glob2regex(tuple.path);
} else {
rg_mode = 0; //** Use the initial rp
}
free(path); //** No longer needed. lio_path_resolve will strdup
v_size[0] = v_size[1] = -tuple.lc->max_attr; v_size[2] = -tuple.lc->max_attr;
it = lio_create_object_iter_alist(tuple.lc, tuple.creds, rp_single, ro_single, OS_OBJECT_FILE_FLAG, recurse_depth, keys, (void **)vals, v_size, 3);
if (it == NULL) {
info_printf(lio_ifd, 0, "ERROR: Failed with object_iter creation\n");
goto finished;
}
while ((ftype = lio_next_object(tuple.lc, it, &fname, &prefix_len)) > 0) {
if ((ftype & OS_OBJECT_SYMLINK) || (v_size[0] == -1)) { //** We skip symlinked files and files missing exnodes
info_printf(lio_ifd, 0, "MISSING_EXNODE_ERROR for file %s\n", fname);
missing_err++;
free(fname);
for (i=-0; i<3; i++) {
if (v_size[i] > 0) free(vals[i]);
}
continue;
}
tbx_type_malloc(inode, inode_entry_t, 1);
inode_list[slot] = inode;
slot++;
inode->fname = fname;
inode->exnode = vals[0];
inode->write_err = 0;
if (v_size[2] != -1) {
werr++;
inode->write_err = 1;
info_printf(lio_ifd, 0, "WRITE_ERROR for file %s\n", fname);
if (vals[2] != NULL) {
free(vals[2]);
vals[2] = NULL;
}
}
inode->inode = 0;
if (v_size[1] > 0) {
sscanf(vals[1], XIDT, &(inode->inode));
free(vals[1]);
vals[1] = NULL;
}
vals[0] = NULL;
fname = NULL;
submitted++;
if (slot == n_put) {
nleft = slot;
do {
n = tbx_que_bulk_put(que, nleft, inode_list + slot - nleft, TBX_QUE_BLOCK);
if (n > 0) nleft = nleft - n;
} while (nleft > 0);
slot = 0;
}
}
lio_destroy_object_iter(lio_gc, it);
if (ftype < 0) {
fprintf(stderr, "ERROR getting the next object!\n");
return_code = EIO;
}
lio_path_release(&tuple);
if (rp_single != NULL) {
lio_os_regex_table_destroy(rp_single);
rp_single = NULL;
}
if (ro_single != NULL) {
lio_os_regex_table_destroy(ro_single);
ro_single = NULL;
}
}
//** dump any remaining files to be processed
if (slot > 0) {
nleft = slot;
do {
n = tbx_que_bulk_put(que, nleft, inode_list + slot - nleft, TBX_QUE_BLOCK);
if (n > 0) nleft = nleft - n;
} while (nleft > 0);
}
tbx_que_set_finished(que); //** Let the warming threads know we are done
//** and wait for them to complete
apr_status_t val;
good = bad = 0;
for (i=0; i<n_warm; i++) {
apr_thread_join(&val, w[i].thread);
good += w[i].good;
bad += w[i].bad;
}
tbx_que_set_finished(que_setattr); //** Let the setattr thread know we are done
apr_thread_join(&val, sa_thread);
//** Cleanup the que's
tbx_que_destroy(que);
tbx_que_destroy(que_setattr);
info_printf(lio_ifd, 0, "--------------------------------------------------------------------\n");
info_printf(lio_ifd, 0, "Submitted: " XOT " Success: " XOT " Fail: " XOT " Write Errors: " XOT " Missing Exnodes: " XOT "\n", submitted, good, bad, werr, missing_err);
if (submitted != (good+bad)) {
fprintf(stderr, "ERROR FAILED self-consistency check! Submitted != Success+Fail\n");
return_code = EFAULT;
}
if (bad > 0) {
fprintf(stderr, "ERROR Some files failed to warm!\n");
return_code = EIO;
}
if (submitted == 0) goto cleanup;
//** Merge the data from all the tables
master = tbx_list_create(0, &tbx_list_string_compare, tbx_list_string_dup, tbx_list_simple_free, tbx_list_no_data_free);
for (i=0; i<n_warm; i++) {
hi = apr_hash_first(NULL, w[i].hash);
while (hi != NULL) {
apr_hash_this(hi, (const void **)&rkey, &klen, (void **)&wrid);
mrid = tbx_list_search(master, wrid->rid_key);
if (mrid == NULL) {
tbx_list_insert(master, wrid->rid_key, wrid);
} else {
mrid->good += wrid->good;
mrid->bad += wrid->bad;
mrid->nbytes += wrid->nbytes;
mrid->dtime += wrid->dtime;
apr_hash_set(w[i].hash, wrid->rid_key, APR_HASH_KEY_STRING, NULL);
free(wrid->rid_key);
free(wrid);
}
hi = apr_hash_next(hi);
}
}
//** Get the RID config which is used in the summary
config = rs_get_rid_config(lio_gc->rs);
ifd = tbx_inip_string_read(config, 1); FATAL_UNLESS(ifd);
//** Convert it for easier lookup
ig = tbx_inip_group_first(ifd);
while (ig != NULL) {
rkey = tbx_inip_group_get(ig);
if (strcmp("rid", rkey) == 0) { //** Found a resource
//** Now cycle through the attributes
ele = tbx_inip_ele_first(ig);
while (ele != NULL) {
rkey = tbx_inip_ele_get_key(ele);
value = tbx_inip_ele_get_value(ele);
if (strcmp(rkey, "rid_key") == 0) {
tbx_inip_group_free(ig);
tbx_inip_group_set(ig, strdup(value));
}
ele = tbx_inip_ele_next(ele);
}
}
ig = tbx_inip_group_next(ig);
}
//** Print the summary
info_printf(lio_ifd, 0, "\n");
info_printf(lio_ifd, 0, " Allocations\n");
info_printf(lio_ifd, 0, " RID Key Size Avg Time(us) Total Good Bad\n");
info_printf(lio_ifd, 0, "---------------------------------------- --------- --------- ---------- ---------- ----------\n");
nbytes = good = bad = j = i = 0;
stack = tbx_stack_new();
dtime_total = 0;
lit = tbx_list_iter_search(master, NULL, 0);
while (tbx_list_next(&lit, (tbx_list_key_t **)&rkey, (tbx_list_data_t **)&mrid) == 0) {
j++;
nbytes += mrid->nbytes;
good += mrid->good;
bad += mrid->bad;
total = mrid->good + mrid->bad;
if (mrid->bad > 0) i++;
tbx_stack_push(stack, mrid);
if ((summary_mode == 0) || ((summary_mode == 1) && (mrid->bad == 0))) continue;
dtime_total += mrid->dtime;
dtime = mrid->dtime / (double)total;
line_end = (mrid->bad == 0) ? "\n" : " RID_ERR\n";
rkey = tbx_inip_get_string(ifd, mrid->rid_key, "ds_key", mrid->rid_key);
info_printf(lio_ifd, 0, "%-40s %s %s %10" PXOT " %10" PXOT " %10" PXOT "%s", rkey,
tbx_stk_pretty_print_double_with_scale_full(1024, (double)mrid->nbytes, ppbuf, 1), tbx_stk_pretty_print_double_with_scale_full(1024, dtime, ppbuf2, 1),
total, mrid->good, mrid->bad, line_end);
free(rkey);
}
if (summary_mode != 0) info_printf(lio_ifd, 0, "---------------------------------------- --------- --------- ---------- ---------- ----------\n");
snprintf(ppbuf2, sizeof(ppbuf2), "SUM (%d RIDs, %d bad)", j, i);
total = good + bad;
dtime_total = dtime_total / (double)total;
info_printf(lio_ifd, 0, "%-40s %s %s %10" PXOT " %10" PXOT " %10" PXOT "\n", ppbuf2,
tbx_stk_pretty_print_double_with_scale_full(1024, (double)nbytes, ppbuf, 1), tbx_stk_pretty_print_double_with_scale_full(1024, dtime_total, ppbuf3, 1), total, good, bad);
tbx_list_destroy(master);
tbx_inip_destroy(ifd);
free(config);
while ((mrid = tbx_stack_pop(stack)) != NULL) {
free(mrid->rid_key);
free(mrid);
}
tbx_stack_free(stack, 0);
cleanup:
for (j=0; j<n_warm; j++) {
apr_pool_destroy(w[j].mpool);
}
free(w);
finished:
if (tagged_rids != NULL) {
tbx_stack_free(tagged_keys, 1);
apr_pool_destroy(tagged_pool);
}
close_warm_db(db_inode, db_rid); //** Close the DBs
free(inode_list);
tbx_stdinarray_iter_destroy(piter);
lio_shutdown();
return(return_code);
}
| 32.962282 | 186 | 0.527682 | [
"object"
] |
d3d8b82507d33d7e9c126dcfedeb008b2c4c2442 | 3,045 | c | C | math_parallel/testEquation.c | anonymity1/parallel-homework | cf6a4d4ac172e86f3134745f7a0cccb39963b24f | [
"Apache-2.0"
] | null | null | null | math_parallel/testEquation.c | anonymity1/parallel-homework | cf6a4d4ac172e86f3134745f7a0cccb39963b24f | [
"Apache-2.0"
] | null | null | null | math_parallel/testEquation.c | anonymity1/parallel-homework | cf6a4d4ac172e86f3134745f7a0cccb39963b24f | [
"Apache-2.0"
] | null | null | null | //
// created by shs on 2019/4/20
// Copyright (c) 2019 shs. All rights reserved
//
#include "testing.h"
static inline void outputInfo() {
printf("Now please choose the alogorithm you want to use: \n");
}
extern void outputMainInfo() {
printf("This is a program of mathematics computing. \n");
printf(" input \'1\' to use gauss elimination. \n");
printf(" input \'2\' to use LU decomposition. \n");
printf(" input \'3\' to use sqr decomposition. \n");
printf(" input \'4\' to use chase decomposition. \n");
printf(" input \'a\' to use lagrange interpolation. \n");
printf(" input \'b\' to use newton interpolation. \n");
printf(" input \'c\' to use spline1 interpolation. \n");
printf(" input \'d\' to use spline2 interpolation. \n");
printf(" ...... \n");
printf(" input \'q\' to quit. \n");
outputInfo();
}
extern void outputEquRes(int dim, float res[MAXN]) {
printf("The answer is: ");
for (int i = 0; i < dim; i++) {
printf("%f ", res[i]);
}
printf("\n");
outputInfo();
}
extern void outputError() {
printf("Your input is illegal!\n");
outputInfo();
}
extern void GaussInfo(int* pdim, float a[][MAXN], float b[MAXN]) {
int var, equ;
printf("Please input the number of the variables: ");
scanf("%d", &var);
printf("Please input the number of the equations: ");
scanf("%d", &equ);
printf("Please input matrix a: \n");
*pdim = var;
for (int i = 0; i < equ; i++) {
for (int j = 0; j < var; j++) {
scanf("%f", &a[i][j]);
}
}
printf("Please input vector b: \n");
for (int i = 0; i < equ; i++) {
scanf("%f", &b[i]);
}
}
extern void luInfo(int* pdim, float a[][MAXN], float b[MAXN]) {
int dim;
printf("Please input the dimensional of the matrix: ");
scanf("%d", &dim);
printf("Please input matrix a: \n");
*pdim = dim;
for (int i = 0; i < dim; i++) {
for (int j = 0; j < dim; j++) {
scanf("%f", &a[i][j]);
}
}
printf("Please input vector b: \n");
for (int i = 0; i < dim; i++) {
scanf("%f", &b[i]);
}
}
extern void sqrInfo(int* pdim, float a[][MAXN], float b[MAXN]) {
int dim;
printf("Please input the dimensional of the matrix: ");
scanf("%d", &dim);
printf("Please input the down triangle of matrix a: \n");
*pdim = dim;
for (int i = 0; i < dim; i++) {
for (int j = 0; j <= i; j++) {
scanf("%f", &a[i][j]);
a[j][i] = a[i][j];
}
}
printf("Please input vector b: \n");
for (int i = 0; i < dim; i++) {
scanf("%f", &b[i]);
}
}
extern void chaseInfo(int* pdim, float a[][MAXN], float b[MAXN]) {
int dim;
printf("Please input the dimensional of the matrix: ");
scanf("%d", &dim);
*pdim = dim;
printf("Please input the diagonal vector of matrix a: \n");
for (int i = 0; i < dim; i++) {
scanf("%f", &a[i][i]);
}
printf("Please input the vector l of matrix a: \n");
for (int i = 1; i < dim; i++) {
scanf("%f", &a[i][i-1]);
}
printf("Please input the vector l of matrix a: \n");
for (int i = 1; i < dim; i++) {
scanf("%f", &a[i-1][i]);
}
printf("Please input vector b: \n");
for (int i = 0; i < dim; i++) {
scanf("%f", &b[i]);
}
} | 26.478261 | 66 | 0.573071 | [
"vector"
] |
d3d9f4e03b5b49912d121e04b4eb5f80e0abcf3f | 4,788 | h | C | net/base/network_interfaces.h | metux/chromium-deb | 3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 5 | 2018-07-12T06:46:46.000Z | 2021-11-01T00:53:42.000Z | net/base/network_interfaces.h | metux/chromium-deb | 3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | net/base/network_interfaces.h | metux/chromium-deb | 3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 2 | 2018-02-27T17:33:38.000Z | 2019-01-17T12:59:06.000Z | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef NET_BASE_NETWORK_INTERFACES_H_
#define NET_BASE_NETWORK_INTERFACES_H_
#include <stdint.h>
#include <memory>
#include <string>
#include <vector>
#include "base/macros.h"
#include "net/base/ip_address.h"
#include "net/base/net_export.h"
#include "net/base/network_change_notifier.h"
namespace net {
// A subset of IP address attributes which are actionable by the
// application layer. Currently unimplemented for all hosts;
// IP_ADDRESS_ATTRIBUTE_NONE is always returned.
enum IPAddressAttributes {
IP_ADDRESS_ATTRIBUTE_NONE = 0,
// A temporary address is dynamic by nature and will not contain MAC
// address. Presence of MAC address in IPv6 addresses can be used to
// track an endpoint and cause privacy concern. Please refer to
// RFC4941.
IP_ADDRESS_ATTRIBUTE_TEMPORARY = 1 << 0,
// A temporary address could become deprecated once the preferred
// lifetime is reached. It is still valid but shouldn't be used to
// create new connections.
IP_ADDRESS_ATTRIBUTE_DEPRECATED = 1 << 1,
// Anycast address.
IP_ADDRESS_ATTRIBUTE_ANYCAST = 1 << 2,
// Tentative address.
IP_ADDRESS_ATTRIBUTE_TENTATIVE = 1 << 3,
// DAD detected duplicate.
IP_ADDRESS_ATTRIBUTE_DUPLICATED = 1 << 4,
// May be detached from the link.
IP_ADDRESS_ATTRIBUTE_DETACHED = 1 << 5,
};
// struct that is used by GetNetworkList() to represent a network
// interface.
struct NET_EXPORT NetworkInterface {
NetworkInterface();
NetworkInterface(const std::string& name,
const std::string& friendly_name,
uint32_t interface_index,
NetworkChangeNotifier::ConnectionType type,
const IPAddress& address,
uint32_t prefix_length,
int ip_address_attributes);
NetworkInterface(const NetworkInterface& other);
~NetworkInterface();
std::string name;
std::string friendly_name; // Same as |name| on non-Windows.
uint32_t interface_index; // Always 0 on Android.
NetworkChangeNotifier::ConnectionType type;
IPAddress address;
uint32_t prefix_length;
int ip_address_attributes; // Combination of |IPAddressAttributes|.
};
typedef std::vector<NetworkInterface> NetworkInterfaceList;
// Policy settings to include/exclude network interfaces.
enum HostAddressSelectionPolicy {
INCLUDE_HOST_SCOPE_VIRTUAL_INTERFACES = 0x0,
EXCLUDE_HOST_SCOPE_VIRTUAL_INTERFACES = 0x1,
};
// Returns list of network interfaces except loopback interface. If an
// interface has more than one address, a separate entry is added to
// the list for each address.
// Can be called only on a thread that allows IO.
NET_EXPORT bool GetNetworkList(NetworkInterfaceList* networks,
int policy);
// Gets the SSID of the currently associated WiFi access point if there is one.
// Otherwise, returns empty string.
// Currently only implemented on Linux, ChromeOS, Android and Windows.
NET_EXPORT std::string GetWifiSSID();
// General category of the IEEE 802.11 (wifi) physical layer operating mode.
enum WifiPHYLayerProtocol {
// No wifi support or no associated AP.
WIFI_PHY_LAYER_PROTOCOL_NONE,
// An obsolete modes introduced by the original 802.11, e.g. IR, FHSS.
WIFI_PHY_LAYER_PROTOCOL_ANCIENT,
// 802.11a, OFDM-based rates.
WIFI_PHY_LAYER_PROTOCOL_A,
// 802.11b, DSSS or HR DSSS.
WIFI_PHY_LAYER_PROTOCOL_B,
// 802.11g, same rates as 802.11a but compatible with 802.11b.
WIFI_PHY_LAYER_PROTOCOL_G,
// 802.11n, HT rates.
WIFI_PHY_LAYER_PROTOCOL_N,
// Unclassified mode or failure to identify.
WIFI_PHY_LAYER_PROTOCOL_UNKNOWN
};
// Characterize the PHY mode of the currently associated access point.
// Currently only available on Windows.
NET_EXPORT WifiPHYLayerProtocol GetWifiPHYLayerProtocol();
enum WifiOptions {
// Disables background SSID scans.
WIFI_OPTIONS_DISABLE_SCAN = 1 << 0,
// Enables media streaming mode.
WIFI_OPTIONS_MEDIA_STREAMING_MODE = 1 << 1
};
class NET_EXPORT ScopedWifiOptions {
public:
ScopedWifiOptions() {}
virtual ~ScopedWifiOptions();
private:
DISALLOW_COPY_AND_ASSIGN(ScopedWifiOptions);
};
// Set temporary options on all wifi interfaces.
// |options| is an ORed bitfield of WifiOptions.
// Options are automatically disabled when the scoped pointer
// is freed. Currently only available on Windows.
NET_EXPORT std::unique_ptr<ScopedWifiOptions> SetWifiOptions(int options);
// Returns the hostname of the current system. Returns empty string on failure.
NET_EXPORT std::string GetHostName();
} // namespace net
#endif // NET_BASE_NETWORK_INTERFACES_H_
| 33.25 | 79 | 0.743525 | [
"vector"
] |
d3e2871650c9d835542f1a6a865c641dcf88dd67 | 23,713 | h | C | include/codegen/CppGenerator.h | makemebitter/LMFAO | a68cf7dfdba2e519b04b8f4702f0aa1ed15213e0 | [
"Apache-2.0"
] | 14 | 2020-10-09T09:47:56.000Z | 2022-02-28T21:12:37.000Z | include/codegen/CppGenerator.h | makemebitter/LMFAO | a68cf7dfdba2e519b04b8f4702f0aa1ed15213e0 | [
"Apache-2.0"
] | null | null | null | include/codegen/CppGenerator.h | makemebitter/LMFAO | a68cf7dfdba2e519b04b8f4702f0aa1ed15213e0 | [
"Apache-2.0"
] | 1 | 2021-06-18T16:29:19.000Z | 2021-06-18T16:29:19.000Z | //--------------------------------------------------------------------
//
// CppGenerator.h
//
// Created on: 16 Dec 2017
// Author: Max
//
//--------------------------------------------------------------------
#ifndef INCLUDE_CODEGEN_CPPGENERATOR_H_
#define INCLUDE_CODEGEN_CPPGENERATOR_H_
#include <boost/dynamic_bitset.hpp>
#include <cstring>
#include <CodeGenerator.hpp>
#include <Launcher.h>
#include <QueryCompiler.h>
#include <TreeDecomposition.h>
// #define PREVIOUS
const size_t LOOPIFY_THRESHOLD = 2;
namespace std
{
/**
* Custom hash function for vector of pairs.
*/
template<> struct hash<vector<pair<size_t,size_t>>>
{
HOT inline size_t operator()(const vector<pair<size_t,size_t>>& p) const
{
size_t seed = 0;
hash<size_t> h;
for (const pair<size_t,size_t>& d : p)
{
seed ^= h(d.first) + 0x9e3779b9 + (seed << 6) + (seed >> 2);
seed ^= h(d.second) + 0x9e3779b9 + (seed << 6) + (seed >> 2);
}
return seed;
}
};
}
struct ProductAggregate
{
prod_bitset product;
std::vector<std::pair<size_t,size_t>> viewAggregate;
std::pair<size_t,size_t> previous;
std::pair<size_t,size_t> correspondingLoopAgg;
bool multiplyByCount = false;
bool operator==(const ProductAggregate &other) const
{
return this->product == other.product &&
this->viewAggregate == other.viewAggregate &&
this->previous == other.previous &&
this->multiplyByCount == other.multiplyByCount;
}
};
struct ProductAggregate_hash
{
size_t operator()(const ProductAggregate &key ) const
{
size_t h = 0;
h ^= std::hash<prod_bitset>()(key.product)+ 0x9e3779b9 + (h<<6) + (h>>2);
h ^= std::hash<size_t>()(key.previous.first)+ 0x9e3779b9 + (h<<6) + (h>>2);
h ^= std::hash<size_t>()(key.previous.second)+ 0x9e3779b9 + (h<<6) + (h>>2);
h ^= std::hash<std::vector<std::pair<size_t,size_t>>>()(key.viewAggregate)+
0x9e3779b9 + (h<<6) + (h>>2);
h ^= std::hash<bool>()(key.multiplyByCount)+0x9e3779b9 + (h<<6) + (h>>2);
return h;
}
};
struct PostLoopAgg
{
std::pair<size_t,size_t> local;
std::pair<size_t,size_t> post;
bool operator==(const PostLoopAgg &other) const
{
return this->local == other.local &&
this->post == other.post;
}
};
struct PostLoopAgg_hash
{
size_t operator()(const PostLoopAgg &key ) const
{
size_t h = 0;
h ^= std::hash<size_t>()(key.local.first)+ 0x9e3779b9 + (h<<6) + (h>>2);
h ^= std::hash<size_t>()(key.local.second)+ 0x9e3779b9 + (h<<6) + (h>>2);
h ^= std::hash<size_t>()(key.post.first)+ 0x9e3779b9 + (h<<6) + (h>>2);
h ^= std::hash<size_t>()(key.post.second)+ 0x9e3779b9 + (h<<6) + (h>>2);
return h;
}
};
struct DependentComputation
{
prod_bitset product;
std::vector<std::pair<size_t,size_t>> view;
};
struct AggRegTuple
{
// bool hasPreviousComputation = false;
std::pair<size_t,size_t> previous;
std::pair<bool,size_t> product;
std::pair<bool,size_t> view;
std::pair<size_t,size_t> postLoop;
bool postLoopAgg = false;
bool preLoopAgg = false;
size_t prevDepth = multifaq::params::NUM_OF_VARIABLES;
bool newViewProduct = false;
bool singleViewAgg = false;
std::pair<size_t,size_t> viewAgg;
bool multiplyByCount = false;
// size_t view;
// size_t loopID;
// std::pair<size_t,size_t> localAgg;
bool operator==(const AggRegTuple &other) const
{
return this->product == other.product &&
this->view == other.view &&
this->viewAgg == other.viewAgg &&
this->previous == other.previous &&
// this->localAgg == other.localAgg &&
this->postLoop == other.postLoop &&
this->preLoopAgg == other.preLoopAgg &&
this->postLoopAgg == other.postLoopAgg;
}
};
struct AggRegTuple_hash
{
size_t operator()(const AggRegTuple &key ) const
{
size_t h = 0;
h ^= std::hash<size_t>()(key.previous.first)+ 0x9e3779b9 + (h<<6) + (h>>2);
h ^= std::hash<size_t>()(key.previous.second)+ 0x9e3779b9 + (h<<6) + (h>>2);
h ^= std::hash<bool>()(key.product.first)+ 0x9e3779b9 + (h<<6) + (h>>2);
h ^= std::hash<size_t>()(key.product.second)+ 0x9e3779b9 + (h<<6) + (h>>2);
h ^= std::hash<bool>()(key.view.first)+ 0x9e3779b9 + (h<<6) + (h>>2);
h ^= std::hash<size_t>()(key.view.second)+ 0x9e3779b9 + (h<<6) + (h>>2);
h ^= std::hash<size_t>()(key.viewAgg.first)+ 0x9e3779b9 + (h<<6) + (h>>2);
h ^= std::hash<size_t>()(key.viewAgg.second)+ 0x9e3779b9 + (h<<6) + (h>>2);
// h ^= std::hash<size_t>()(key.localAgg.first)+ 0x9e3779b9 + (h<<6) + (h>>2);
// h ^= std::hash<size_t>()(key.localAgg.second)+ 0x9e3779b9 + (h<<6) + (h>>2);
h ^= std::hash<size_t>()(key.postLoop.first)+ 0x9e3779b9 + (h<<6) + (h>>2);
h ^= std::hash<size_t>()(key.postLoop.second)+ 0x9e3779b9 + (h<<6) + (h>>2);
return h;
}
};
struct PostAggRegTuple
{
std::pair<size_t,size_t> local = {0,0};
std::pair<size_t,size_t> post = {0,0};
bool operator==(const PostAggRegTuple &other) const
{
return this->local == other.local &&
this->post == other.post;
}
};
struct PostAggRegTuple_hash
{
size_t operator()(const PostAggRegTuple &key ) const
{
size_t h = 0;
h ^= std::hash<size_t>()(key.local.first)+ 0x9e3779b9 + (h<<6) + (h>>2);
h ^= std::hash<size_t>()(key.local.second)+ 0x9e3779b9 + (h<<6) + (h>>2);
h ^= std::hash<size_t>()(key.post.first)+ 0x9e3779b9 + (h<<6) + (h>>2);
h ^= std::hash<size_t>()(key.post.second)+ 0x9e3779b9 + (h<<6) + (h>>2);
return h;
}
};
struct AggregateTuple
{
size_t viewID;
size_t aggID;
std::pair<size_t,size_t> local;
std::pair<size_t,size_t> post;
std::pair<bool, size_t> dependentProduct;
std::pair<bool, size_t> dependentView;
size_t loopID;
DependentComputation dependentComputation;
bool hasDependentComputation = false;
ProductAggregate dependentProdAgg;
};
struct DependentLoop
{
std::vector<std::pair<size_t,prod_bitset>> functionMask;
std::vector<size_t> next;
boost::dynamic_bitset<> outView;
boost::dynamic_bitset<> loopFactors;
size_t loopVariable;
prod_bitset branchFunctions; // TODO: These need to be specific for the
// actual view!!
DependentLoop(size_t numOfViews)
{
outView.resize(numOfViews + 1);
outView.reset();
}
};
struct AggregateIndexes
{
std::bitset<7> present;
size_t indexes[8];
void reset()
{
present.reset();
memset(&indexes[0], 0, 8*sizeof(size_t));
}
bool isIncrement(const AggregateIndexes& bench, const size_t& offset,
std::bitset<7>& increasing)
{
if (present != bench.present)
return false;
// If offset is zero we didn't compare any two tuples yet
if (offset==0)
{
// compare this and bench
increasing.reset();
for (size_t i = 0; i < 7; i++)
{
if (present[i])
{
if (indexes[i] == bench.indexes[i] + 1)
{
increasing.set(i);
}
else if (indexes[i] != bench.indexes[i])
{
return false;
}
}
}
return true;
}
for (size_t i = 0; i < 7; i++)
{
if (present[i])
{
if (increasing[i])
{
if (indexes[i] != bench.indexes[i] + offset + 1)
return false;
}
else
{
if (indexes[i] != bench.indexes[i])
return false;
}
}
}
return true;
}
};
class CppGenerator: public CodeGenerator
{
public:
CppGenerator(std::shared_ptr<Launcher> launcher);
~CppGenerator();
void generateCode(bool hasApplicationHandler, bool hasDynamicFunctions);
size_t numberOfGroups()
{
return viewGroups.size();
};
const std::vector<size_t>& getGroup(size_t group_id)
{
return viewGroups[group_id];
}
private:
std::string _pathToData;
std::string _outputDirectory;
std::string _datasetName;
std::shared_ptr<TreeDecomposition> _td;
std::shared_ptr<QueryCompiler> _qc;
std::vector<size_t>* variableOrder = nullptr;
std::vector<var_bitset> variableOrderBitset;
//TODO: this could be part of the view
std::vector<size_t>* incomingViews = nullptr;
// keeps track of where we can output tuples to the view
size_t* viewLevelRegister;
std::vector<size_t>* groupVariableOrder = nullptr;
std::vector<size_t>* groupIncomingViews = nullptr;
std::vector<size_t>* groupViewsPerVarInfo = nullptr;
std::vector<var_bitset> groupVariableOrderBitset;
bool* _requireHashing = nullptr;
// For groups of views that can be computed together
std::vector<std::vector<size_t>> viewGroups;
// For sorting
size_t** sortOrders = nullptr;
std::string* viewName = nullptr;
size_t* viewToGroupMapping = nullptr;
bool* _parallelizeGroup = nullptr;
size_t* _threadsPerGroup = nullptr;
// TODO: MAKE SURE WE SET THESE TO CORRECT SIZE;
std::unordered_map<std::string, std::pair<size_t,size_t>> aggregateMap;
std::vector<std::vector<std::string>> aggregateRegister;
std::vector<std::vector<boost::dynamic_bitset<>>> loopRegister;
std::vector<boost::dynamic_bitset<>> preAggregateIndexes;
std::vector<boost::dynamic_bitset<>> postAggregateIndexes;
std::vector<boost::dynamic_bitset<>> dependentAggregateIndexes;
std::vector<std::vector<size_t>> runningSumIndexesComplete;
// std::vector<boost::dynamic_bitset<>> runningSumIndexesPartial;
std::vector<std::vector<size_t>> finalAggregateIndexes;
std::vector<std::vector<size_t>> newFinalAggregates;
std::vector<std::string> finalAggregateString;
std::vector<std::string> localAggregateString;
std::string aggregateHeader;
std::vector<boost::dynamic_bitset<>> viewLoopFactors;
// std::vector<std::vector<size_t>> postAggregateIndexes;
size_t* numAggregateIndexes = nullptr;
std::vector<var_bitset> variableDependency;
std::vector<var_bitset> coveredVariables;
boost::dynamic_bitset<> addableViews;
bool _hasApplicationHandler;
bool _hasDynamicFunctions;
// std::unordered_map<std::string, std::pair<size_t,size_t>> deferredAggregateMap;
// std::vector<std::vector<std::string>> deferredAggregateRegister;
// std::vector<std::vector<boost::dynamic_bitset<>>> deferredLoopRegister;
/**************************************************************************/
/**************************************************************************/
std::vector<std::vector<AggRegTuple>> newAggregateRegister;
std::vector<std::unordered_map<
AggRegTuple, size_t, AggRegTuple_hash>> aggregateRegisterMap;
std::vector<std::vector<size_t>> aggregateRemapping;
std::vector<std::vector<std::vector<size_t>>> newAggregateRemapping;
size_t aggregateCounter;
std::vector<std::unordered_map<ProductAggregate,size_t,ProductAggregate_hash>>
productToVariableMap;
std::vector<std::vector<ProductAggregate>> productToVariableRegister;
std::vector<std::unordered_map<prod_bitset,size_t>> localProductMap;
std::vector<std::vector<prod_bitset>> localProductList;
std::vector<std::vector<size_t>> localProductRemapping;
// std::vector<std::vector<size_t>> newLocalProductRemapping;
size_t productCounter;
std::vector<std::map<std::vector<std::pair<size_t,size_t>>,size_t>> viewProductMap;
std::vector<std::vector<std::vector<std::pair<size_t,size_t>>>> viewProductList;
std::vector<std::vector<size_t>> viewProductRemapping;
// std::vector<std::vector<size_t>> newViewProductRemapping;
size_t viewCounter;
std::vector<std::vector<size_t>> postRemapping;
size_t postCounter;
std::vector<std::unordered_map<
PostAggRegTuple,size_t,PostAggRegTuple_hash>>postRegisterMap;
std::vector<std::vector<PostAggRegTuple>> postRegisterList;
std::vector<std::vector<boost::dynamic_bitset<>>> contributingViewList;
// std::vector<std::vector<dyn_bitset>> productLoopFactors;
std::vector<std::map<boost::dynamic_bitset<>, size_t>> totalLoopFactors;
std::vector<std::vector<boost::dynamic_bitset<>>> totalLoopFactorList;
std::vector<std::vector<size_t>> productLoopID;
std::vector<std::vector<size_t>> incViewLoopID;
std::vector<size_t> outViewLoopID;
std::vector<std::vector<size_t>> aggRegLoopID;
std::vector<std::vector<AggregateTuple>> aggregateComputation;
std::vector<DependentComputation> dependentComputation;
std::vector<boost::dynamic_bitset<>> listOfLoops;
std::vector<prod_bitset> functionsPerLoop;
std::vector<prod_bitset> functionsPerLoopBranch;
std::vector<boost::dynamic_bitset<>> viewsPerLoop;
std::vector<std::vector<size_t>> nextLoopsPerLoop;
std::vector<DependentLoop> depListOfLoops;
std::vector<boost::dynamic_bitset<>> outViewLoop;
std::vector<boost::dynamic_bitset<>> outputLoops;
std::vector<std::vector<size_t>> outputNextLoops;
std::vector<boost::dynamic_bitset<>> outputViewsPerLoop;
std::vector<std::vector<ProductAggregate>> outProductToVariableRegister;
std::vector<std::vector<prod_bitset>> outLocalProductRegister;
std::vector<std::vector<std::vector<std::pair<size_t,size_t>>>>
outViewProductRegister;
std::vector<std::vector<AggRegTuple>> outAggregateRegister;
std::vector<std::vector<size_t>> depAggregateRemapping;
std::vector<std::vector<size_t>> depLocalProductRemapping;
/**************************************************************************/
/**************************************************************************/
/* TODO: Technically there is no need to pre-materialise this! */
void createGroupVariableOrder();
void createRelationSortingOrder(TDNode* node, const size_t& parent_id);
void computeViewOrdering();
void computeParallelizeGroup(bool paralleize_groups);
void genDataHandler();
void genComputeGroupFiles(size_t group);
void genMakeFile();
void genMainFunction(bool parallelize);
prod_bitset computeLoopMasks(
prod_bitset presentFunctions, boost::dynamic_bitset<> consideredLoops,
const var_bitset& varOrderBitset, const var_bitset& relationBag,
const boost::dynamic_bitset<>& contributingViews,
boost::dynamic_bitset<>& nextVariable,
const boost::dynamic_bitset<>& prefixLoops);
void registerAggregatesToLoops(size_t depth, size_t group_id);
void registerDependentComputationToLoops(size_t view_id, size_t group_id);
std::pair<size_t,size_t> addProductToLoop(
ProductAggregate& prodAgg, size_t& currentLoop, bool& loopsOverRelation,
const size_t& maxDepth);
inline std::string offset(size_t off);
std::string typeToStr(Type t);
std::string genHeader();
std::string genTupleStructs();
std::string genTupleStructConstructors();
std::string genCaseIdentifiers();
std::string genLoadRelationFunction();
// std::string genComputeViewFunction(size_t view_id);
std::string genComputeGroupFunction(size_t view_id);
std::string genMaxMinValues(const std::vector<size_t>& view_id);
std::string genPointerArrays(const std::string& rel, std::string& numOfJoinVars,
bool parallelize);
std::string genGroupRelationOrdering(const std::string& rel_name,
const size_t& depth,
const size_t& group_id);
std::string genGroupLeapfrogJoinCode(size_t group_id, const TDNode& node,
size_t depth);
std::string genGroupGenericJoinCode(size_t group_id, const TDNode& node,
size_t depth);
// One Generic Case for Seek Value
std::string seekValueCase(size_t depth, const std::string& rel_name,
const std::string& attr_name, bool parallel);
// One Generic Case for Seek Value
std::string seekValueGenericJoin(size_t depth, const std::string& rel_name,
const std::string& attr_name, bool parallel, bool first);
std::string updateMaxCase(size_t depth, const std::string& rel_name,
const std::string& attr_name, bool parallelize);
std::string getUpperPointer(
const std::string rel_name, size_t depth, bool parallel);
std::string getLowerPointer(const std::string rel_name, size_t depth);
std::string updateRanges(size_t depth, const std::string& rel_name,
const std::string& attr_name, bool parallel);
std::string genProductString(
const TDNode& node, const boost::dynamic_bitset<>& contributingViews,
const prod_bitset& product);
std::string getFunctionString(Function* f, std::string& fvars);
std::string genSortFunction(const size_t& rel_id);
std::string genFindUpperBound(const std::string& rel_name,
const std::string& attrName,
size_t depth, bool parallel);
std::string genRunFunction(bool parallelize);
// std::string genRunMultithreadedFunction();
std::string genTestFunction();
std::string genDumpFunction();
bool resortRelation(const size_t& rel, const size_t& view);
bool resortView(const size_t& incView, const size_t& view);
// This can be removed ...
bool requireHash(const size_t& rel, const size_t& view);
void aggregateGenerator(size_t group_id, const TDNode& node);
void computeViewLevel(size_t group_id, const TDNode& node);
// void computeAggregateRegister(
// const size_t group_id, const size_t view_id, const size_t agg_id,
// std::vector<prod_bitset>& productSum, std::vector<size_t>& incoming,
// std::vector<std::pair<size_t, size_t>>& localAggReg,
// // std::vector<std::pair<size_t, size_t>>& viewAggReg,
// bool splitViewAggSummation, size_t depth);
// void computeAggregateRegister( Aggregate* aggregate,
// const size_t group_id, const size_t view_id,const size_t agg_id,
// const size_t depth, std::vector<std::pair<size_t, size_t>>& localAggReg);
void registerAggregatesToVariables(Aggregate* aggregate,
const size_t group_id, const size_t view_id,const size_t agg_id,
const size_t depth, std::vector<std::pair<size_t, size_t>>& localAggReg);
// TODO: This can be savely removed!
// void updateAggregateRegister(
// std::pair<size_t,size_t>& outputIndex, const std::string& aggString,
// size_t depth, const boost::dynamic_bitset<>& loopFactor, bool pre);
// std::string newgenAggregateString(
// const TDNode& node, boost::dynamic_bitset<> consideredLoops,
// size_t depth, size_t group_id);
// std::string newgenFinalAggregateString(
// const TDNode* node, boost::dynamic_bitset<> consideredLoops,
// size_t depth, size_t group_id);
// template<typename T>
// std::string resetRegisterArray(
// const size_t& depth, std::vector<std::vector<T>>& registerList,
// std::string registerName);
prod_bitset computeDependentLoops(
size_t view_id, prod_bitset presentFunctions, var_bitset relationBag,
boost::dynamic_bitset<> contributingViews, var_bitset varOrderBitset,
boost::dynamic_bitset<> addedOutLoops, size_t thisLoopID);
std::pair<size_t,size_t> addDependentProductToLoop(
ProductAggregate& prodAgg, const size_t view_id, size_t& currentLoop,
const size_t& maxDepth, std::pair<size_t,size_t>& prevAgg);
std::string genDependentAggLoopString(
const TDNode& node, const size_t currentLoop, size_t depth,
const boost::dynamic_bitset<>& contributingViews, const size_t maxDepth,
std::string& resetString);
void mapAggregateToIndexes(AggregateIndexes& index, const AggRegTuple& aggregate,
const size_t& depth, const size_t& loopID);
void mapAggregateToIndexes(AggregateIndexes& index,const PostAggRegTuple& aggregate,
const size_t& depth, const size_t& loopID);
void mapAggregateToIndexes(AggregateIndexes& index, const AggregateTuple& aggregate,
const size_t& viewID, const size_t& loopID);
std::string outputAggRegTupleString(
AggregateIndexes& first, size_t offset,const std::bitset<7>& increasing,
size_t stringOffset, bool postLoop);
std::string outputPostRegTupleString(
AggregateIndexes& first, size_t offset,const std::bitset<7>& increasing,
size_t stringOffset);
std::string outputFinalRegTupleString(
AggregateIndexes& first, size_t offset,const std::bitset<7>& increasing,
size_t stringOffset);
// // TODO: We should really only keep one
// std::string genAggLoopString(
// const TDNode& node, const size_t loop, size_t depth,
// const boost::dynamic_bitset<>& contributingViews,
// const size_t numOfOutViewLoops);
std::string genAggLoopStringCompressed(
const TDNode& node, const size_t loop, size_t depth,
const boost::dynamic_bitset<>& contributingViews,
const size_t numOfOutViewLoops, std::string& resetString);
#ifdef OLD
// TODO: RENAME
std::vector<size_t>* viewsPerVarInfo = nullptr;
// For topological order
std::vector<size_t>* viewsPerNode = nullptr;
template<typename T>
std::string resetRegisterArray(
const size_t& depth, std::vector<std::vector<T>>& registerList,
std::string registerName);
std::string genComputeViewFunction(size_t view_id);
std::string genRelationOrdering(const std::string& rel_name,
const size_t& depth,
const size_t& view_id);
std::string genAggregateString(
const std::vector<std::string>& aggRegister,
const std::vector<boost::dynamic_bitset<>>& loopReg,
boost::dynamic_bitset<> consideredLoops,
boost::dynamic_bitset<>& addedAggs, size_t depth);
std::string genFinalAggregateString(
const std::vector<std::string>& aggRegister,
const std::vector<boost::dynamic_bitset<>>& loopReg,
boost::dynamic_bitset<> consideredLoops,
boost::dynamic_bitset<>& addedAggs, size_t depth,
std::vector<size_t>& includableViews,
boost::dynamic_bitset<>& addedViews,size_t offDepth);
std::string genLeapfrogJoinCode(size_t view_id, size_t depth);
void createVariableOrder();
#endif
};
#endif /* INCLUDE_CODEGEN_CPPGENERATOR_HPP_ */
| 34.217893 | 94 | 0.621937 | [
"vector"
] |
d3e565b8f7ef3d52b1162348fa78f49a37ab5ed7 | 1,871 | h | C | code/render/characters/gpuskinnedmeshrenderer.h | gscept/nebula-trifid | e7c0a0acb05eedad9ed37a72c1bdf2d658511b42 | [
"BSD-2-Clause"
] | 67 | 2015-03-30T19:56:16.000Z | 2022-03-11T13:52:17.000Z | code/render/characters/gpuskinnedmeshrenderer.h | gscept/nebula-trifid | e7c0a0acb05eedad9ed37a72c1bdf2d658511b42 | [
"BSD-2-Clause"
] | 5 | 2015-04-15T17:17:33.000Z | 2016-02-11T00:40:17.000Z | code/render/characters/gpuskinnedmeshrenderer.h | gscept/nebula-trifid | e7c0a0acb05eedad9ed37a72c1bdf2d658511b42 | [
"BSD-2-Clause"
] | 34 | 2015-03-30T15:08:00.000Z | 2021-09-23T05:55:10.000Z | #pragma once
//------------------------------------------------------------------------------
/**
@class Characters::GPUSkinnedMeshRenderer
GPU implemention of SkinnedMeshRenderer.
(C) 2008 Radon Labs GmbH
(C) 2013-2016 Individual contributors, see AUTHORS file
*/
#include "characters/base/skinnedmeshrendererbase.h"
#include "util/stack.h"
#include "coregraphics/texture.h"
//------------------------------------------------------------------------------
namespace Characters
{
class GPUSkinnedMeshRenderer : public Base::SkinnedMeshRendererBase
{
__DeclareClass(GPUSkinnedMeshRenderer);
__DeclareSingleton(GPUSkinnedMeshRenderer);
public:
/// constructor
GPUSkinnedMeshRenderer();
/// destructor
virtual ~GPUSkinnedMeshRenderer();
/// get the skinning technique used by the renderer
Characters::SkinningTechnique::Code GetSkinningTechnique() const;
private:
friend class Characters::CharacterServer;
/// updates a skinned mesh
void UpdateGPUSkinnedJointPalette(const Ptr<Characters::CharacterInstance>& charInst, const Util::Array<IndexT>& jointPalette, const Ptr<CoreGraphics::ShaderVariable>& jointPaletteShdVar);
/// draw a skinned mesh
void DrawGPUSkinnedMesh(const Ptr<CoreGraphics::Mesh>& mesh, IndexT primGroupIndex);
/// draw skinned mesh instanced
void DrawGPUSkinnedMeshInstanced(const Ptr<CoreGraphics::Mesh>& mesh, IndexT primGroupIndex, SizeT instances);
static const SizeT ConstantBufferMaxJoints = 96;
};
//------------------------------------------------------------------------------
/**
*/
inline Characters::SkinningTechnique::Code
GPUSkinnedMeshRenderer::GetSkinningTechnique() const
{
return Characters::SkinningTechnique::GPUSkinning;
}
} // namespace Characters
//------------------------------------------------------------------------------
| 33.410714 | 192 | 0.628541 | [
"mesh"
] |
d3e8710548d9c4ca8e9f4123fde1175c631479af | 2,214 | h | C | FEM/rf_node.h | renchao-lu/ogs5 | ecfc987e5b5b9d95d383b0e92fc21f0a4170289f | [
"BSD-4-Clause"
] | 1 | 2021-02-24T12:25:31.000Z | 2021-02-24T12:25:31.000Z | FEM/rf_node.h | renchao-lu/ogs5 | ecfc987e5b5b9d95d383b0e92fc21f0a4170289f | [
"BSD-4-Clause"
] | null | null | null | FEM/rf_node.h | renchao-lu/ogs5 | ecfc987e5b5b9d95d383b0e92fc21f0a4170289f | [
"BSD-4-Clause"
] | null | null | null | /**
* \copyright
* Copyright (c) 2018, OpenGeoSys Community (http://www.opengeosys.org)
* Distributed under a Modified BSD License.
* See accompanying file LICENSE.txt or
* http://www.opengeosys.org/project/license
*
*/
/**************************************************************************
FEMLib - Object: Node
Task: class implementation
Programing:
04/2004 OK Implementation
last modified
02/2005 MB node parameter....
**************************************************************************/
#ifndef rf_node_INC
#define rf_node_INC
// C++ STL
//#include <list>
#include <iostream>
//#include <fstream>
//#include <string>
#include <vector>
// FEM
#include "FEMEnums.h"
class CNodeValue
{
public:
CNodeValue(void);
~CNodeValue(void);
void setProcessDistributionType(FiniteElement::DistributionType distype)
{
_node_distype = distype;
}
FiniteElement::DistributionType getProcessDistributionType() const
{
return _node_distype;
}
//
long geo_node_number;
long msh_node_number;
double node_value;
double node_area;
// int node_distype;
double node_parameterA;
double node_parameterB;
double node_parameterC;
double node_parameterD;
double node_parameterE;
int CurveIndex;
int conditional;
// std::vector<double>history_value;
long msh_node_number_conditional;
// JOD st-coupling 4.7.10
std::vector<long> msh_node_numbers_averaging;
// JOD
std::vector<double> msh_node_weights_averaging;
std::string tim_type_name;
// WW
void Write(std::ostream& os = std::cout) const;
void Read(std::istream& is = std::cin); // WW
bool check_me; // OK
bool _isConstrainedSTNode;
std::size_t getSTVectorIndex() const { return _st_vector_index; }
void setSTVectorIndex(int index) { _st_vector_index = index; }
std::size_t getSTVectorGroup() const { return _st_vector_group; }
void setSTVectorGroup(int group) { _st_vector_group = group; }
private:
FiniteElement::DistributionType _node_distype;
std::size_t _st_vector_index;
std::size_t _st_vector_group;
};
#endif
| 26.674699 | 76 | 0.635501 | [
"object",
"vector"
] |
d3e9568f3cd8b095b76f55d2316ce5f2527ca151 | 18,854 | h | C | WRK-V1.2/TOOLS/include/yvals.h | intj-t/openvmsft | 0d17fbce8607ab2b880be976c2e86d8cfc3e83bb | [
"Intel"
] | null | null | null | WRK-V1.2/TOOLS/include/yvals.h | intj-t/openvmsft | 0d17fbce8607ab2b880be976c2e86d8cfc3e83bb | [
"Intel"
] | null | null | null | WRK-V1.2/TOOLS/include/yvals.h | intj-t/openvmsft | 0d17fbce8607ab2b880be976c2e86d8cfc3e83bb | [
"Intel"
] | null | null | null | /* yvals.h values header for Microsoft C/C++ */
#pragma once
#ifndef _YVALS
#define _YVALS
#include <crtdefs.h>
#ifdef _MSC_VER
#pragma pack(push,_CRT_PACKING)
#endif /* _MSC_VER */
#define _CPPLIB_VER 405
#define __PURE_APPDOMAIN_GLOBAL
#ifndef __CRTDECL
#if defined(_M_CEE_PURE) || defined(MRTDLL)
#define __CRTDECL __clrcall
#else
#define __CRTDECL __cdecl
#endif
#endif
#ifndef __CLR_OR_THIS_CALL
#if defined(MRTDLL) || defined(_M_CEE_PURE)
#define __CLR_OR_THIS_CALL __clrcall
#else
#define __CLR_OR_THIS_CALL
#endif
#endif
#ifndef __CLRCALL_OR_CDECL
#if defined(MRTDLL) || defined(_M_CEE_PURE)
#define __CLRCALL_OR_CDECL __clrcall
#else
#define __CLRCALL_OR_CDECL __cdecl
#endif
#endif
#ifndef __CLRCALL_PURE_OR_CDECL
#if defined(_M_CEE_PURE)
#define __CLRCALL_PURE_OR_CDECL __clrcall
#else
#define __CLRCALL_PURE_OR_CDECL __cdecl
#endif
#endif
/* NAMING PROPERTIES */
#define _WIN32_C_LIB 1
/* THREAD AND LOCALE CONTROL */
#define _MULTI_THREAD 1 /* nontrivial locks if multithreaded */
#define _IOSTREAM_OP_LOCKS 1 /* lock iostream operations */
#define _GLOBAL_LOCALE 0 /* 0 for per-thread locales, 1 for shared */
/* THREAD-LOCAL STORAGE */
#define _COMPILER_TLS 1 /* 1 if compiler supports TLS directly */
#if _MULTI_THREAD
#define _TLS_QUAL __declspec(thread) /* TLS qualifier, if any */
#else /* _MULTI_THREAD */
#define _TLS_QUAL
#endif /* _MULTI_THREAD */
#ifndef _HAS_EXCEPTIONS
#define _HAS_EXCEPTIONS 1 /* predefine as 0 to disable exceptions */
#endif /* _HAS_EXCEPTIONS */
#ifndef _HAS_NAMESPACE
#define _HAS_NAMESPACE 1 /* predefine as 0 to disable exceptions */
#endif /* _HAS_NAMESPACE */
#ifndef _HAS_IMMUTABLE_SETS
#define _HAS_IMMUTABLE_SETS 0
#endif /* _HAS_IMMUTABLE_SETS */
#ifndef _HAS_STRICT_CONFORMANCE
#define _HAS_STRICT_CONFORMANCE 0
#endif /* _HAS_STRICT_CONFORMANCE */
#define _GLOBAL_USING 1
#if !defined (_HAS_ITERATOR_DEBUGGING)
#if defined (_DEBUG)
#define _HAS_ITERATOR_DEBUGGING 1 /* for range checks, etc. */
#else
#define _HAS_ITERATOR_DEBUGGING 0
#endif /* defined (_DEBUG) */
#else
#if !defined (_DEBUG) && _HAS_ITERATOR_DEBUGGING != 0
#include <crtwrn.h>
#pragma _CRT_WARNING( _NO_ITERATOR_DEBUGGING )
#undef _HAS_ITERATOR_DEBUGGING
#define _HAS_ITERATOR_DEBUGGING 0
#endif
#endif /* !defined (_HAS_ITERATOR_DEBUGGING) */
/* _SECURE_CRT definitions */
#define __STR2WSTR(str) L##str
#define _STR2WSTR(str) __STR2WSTR(str)
#define __FILEW__ _STR2WSTR(__FILE__)
#define __FUNCTIONW__ _STR2WSTR(__FUNCTION__)
/* _SECURE_SCL switches: default values */
#if !defined (_SECURE_SCL)
#define _SECURE_SCL 1
#endif
#if !defined (_SECURE_SCL_DEPRECATE)
#if defined(_SCL_SECURE_NO_DEPRECATE)
#define _SECURE_SCL_DEPRECATE 0
#else
#define _SECURE_SCL_DEPRECATE 1
#endif
#endif
#if !defined (_SECURE_SCL_THROWS)
#define _SECURE_SCL_THROWS 0
#endif
/* _SECURE_SCL switches: helper macros */
#if _SECURE_SCL && _SECURE_SCL_DEPRECATE
#define _SCL_INSECURE_DEPRECATE _CRT_DEPRECATE_TEXT("You have used a std:: construct that is not safe. See documentation on how to use the Safe Standard C++ Library")
#else
#define _SCL_INSECURE_DEPRECATE
#endif
/*
* Assert in debug builds.
* set errno and return
*
*/
#ifdef _DEBUG
#define _SCL_SECURE_INVALID_PARAMETER(expr) ::_invalid_parameter(__STR2WSTR(#expr), __FUNCTIONW__, __FILEW__, __LINE__, 0)
#else
#define _SCL_SECURE_INVALID_PARAMETER(expr) ::_invalid_parameter_noinfo()
#endif
#if _SECURE_SCL_THROWS
#define _SCL_SECURE_INVALID_ARGUMENT_NO_ASSERT _Xinvarg()
#define _SCL_SECURE_OUT_OF_RANGE_NO_ASSERT _Xran()
#else /* _SECURE_SCL_THROWS */
#define _SCL_SECURE_INVALID_ARGUMENT_NO_ASSERT _SCL_SECURE_INVALID_PARAMETER("invalid argument")
#define _SCL_SECURE_OUT_OF_RANGE_NO_ASSERT _SCL_SECURE_INVALID_PARAMETER("out of range")
#endif /* _SECURE_SCL_THROWS */
#define _SCL_SECURE_ALWAYS_VALIDATE(cond) \
{ \
if (!(cond)) \
{ \
_ASSERTE((#cond, 0)); \
_SCL_SECURE_INVALID_ARGUMENT_NO_ASSERT; \
} \
}
#define _SCL_SECURE_ALWAYS_VALIDATE_RANGE(cond) \
{ \
if (!(cond)) \
{ \
_ASSERTE((#cond, 0)); \
_SCL_SECURE_OUT_OF_RANGE_NO_ASSERT; \
} \
}
// validation a la Secure CRT
#define _SCL_SECURE_CRT_VALIDATE(cond, retvalue) \
{ \
if (!(cond)) \
{ \
_ASSERTE((#cond, 0)); \
_SCL_SECURE_INVALID_PARAMETER(cond); \
return (retvalue); \
} \
}
#if _SECURE_SCL
#define _SCL_SECURE_VALIDATE(cond) \
{ \
if (!(cond)) \
{ \
_ASSERTE((#cond, 0)); \
_SCL_SECURE_INVALID_ARGUMENT_NO_ASSERT; \
} \
__analysis_assume(cond); \
}
#define _SCL_SECURE_VALIDATE_RANGE(cond) \
{ \
if (!(cond)) \
{ \
_ASSERTE((#cond, 0)); \
_SCL_SECURE_OUT_OF_RANGE_NO_ASSERT; \
} \
__analysis_assume(cond); \
}
#define _SCL_SECURE_INVALID_ARGUMENT \
{ \
_ASSERTE(("Standard C++ Libraries Invalid Argument", 0)); \
_SCL_SECURE_INVALID_ARGUMENT_NO_ASSERT; \
}
#define _SCL_SECURE_OUT_OF_RANGE \
{ \
_ASSERTE(("Standard C++ Libraries Out of Range", 0)); \
_SCL_SECURE_OUT_OF_RANGE_NO_ASSERT; \
}
#define _SCL_SECURE_MOVE(func, dst, size, src, count) func((dst), (size), (src), (count))
#define _SCL_SECURE_COPY(func, dst, size, src, count) func((dst), (size), (src), (count))
#else /* _SECURE_SCL */
/* when users disable _SECURE_SCL to get performance, we don't want analysis warnings from SCL headers */
#if _HAS_ITERATOR_DEBUGGING
#define _SCL_SECURE_VALIDATE(cond) __analysis_assume(cond)
#define _SCL_SECURE_VALIDATE_RANGE(cond) __analysis_assume(cond)
#else
#define _SCL_SECURE_VALIDATE(cond)
#define _SCL_SECURE_VALIDATE_RANGE(cond)
#endif
#define _SCL_SECURE_INVALID_ARGUMENT
#define _SCL_SECURE_OUT_OF_RANGE
#define _SCL_SECURE_MOVE(func, dst, size, src, count) func((dst), (src), (count))
#define _SCL_SECURE_COPY(func, dst, size, src, count) func((dst), (src), (count))
#endif /* _SECURE_SCL */
/* _SECURE_VALIDATION is the name of the bool template argument used to define iterators
with secure validation selectively turned on or off (for an example, see the std::list
iterators). Notice that all the _SCL_SECURE_TRAITS_* validation macros are almost identical
to the _SCL_SECURE_* macros defined above. The only difference is the:
if (_SECURE_VALIDATION) { }
statement, which will statically evaluate to true or false. With optimizations on, the
compiler will optimize the check away.
*/
#define _SECURE_VALIDATION _Secure_validation
#if _SECURE_SCL
#define _SECURE_VALIDATION_DEFAULT true
#define _SCL_SECURE_TRAITS_VALIDATE(cond) \
{ \
__pragma(warning(push)); \
__pragma(warning(disable: 4127)); \
if (_SECURE_VALIDATION) \
{ \
_SCL_SECURE_VALIDATE(cond) \
} \
__pragma(warning(pop)); \
}
#define _SCL_SECURE_TRAITS_VALIDATE_RANGE(cond) \
{ \
__pragma(warning(push)); \
__pragma(warning(disable: 4127)); \
if (_SECURE_VALIDATION) \
{ \
_SCL_SECURE_VALIDATE_RANGE(cond) \
} \
__pragma(warning(pop)); \
}
#define _SCL_SECURE_TRAITS_INVALID_ARGUMENT \
{ \
__pragma(warning(push)); \
__pragma(warning(disable: 4127)); \
if (_SECURE_VALIDATION) \
{ \
_SCL_SECURE_INVALID_ARGUMENT \
} \
__pragma(warning(pop)); \
}
#define _SCL_SECURE_TRAITS_OUT_OF_RANGE \
{ \
__pragma(warning(push)); \
__pragma(warning(disable: 4127)); \
if (_SECURE_VALIDATION) \
{ \
_SCL_SECURE_OUT_OF_RANGE \
} \
__pragma(warning(pop)); \
}
#else
#define _SECURE_VALIDATION_DEFAULT false
#define _SCL_SECURE_TRAITS_VALIDATE(cond)
#define _SCL_SECURE_TRAITS_VALIDATE_RANGE(cond)
#define _SCL_SECURE_TRAITS_INVALID_ARGUMENT
#define _SCL_SECURE_TRAITS_OUT_OF_RANGE
#endif
#if __STDC_WANT_SECURE_LIB__
#define _CRT_SECURE_MEMCPY(dest, destsize, source, count) ::memcpy_s((dest), (destsize), (source), (count))
#define _CRT_SECURE_MEMMOVE(dest, destsize, source, count) ::memmove_s((dest), (destsize), (source), (count))
#define _CRT_SECURE_WMEMCPY(dest, destsize, source, count) ::wmemcpy_s((dest), (destsize), (source), (count))
#define _CRT_SECURE_WMEMMOVE(dest, destsize, source, count) ::wmemmove_s((dest), (destsize), (source), (count))
#else
#define _CRT_SECURE_MEMCPY(dest, destsize, source, count) ::memcpy((dest), (source), (count))
#define _CRT_SECURE_MEMMOVE(dest, destsize, source, count) ::memmove((dest), (source), (count))
#define _CRT_SECURE_WMEMCPY(dest, destsize, source, count) ::wmemcpy((dest), (source), (count))
#define _CRT_SECURE_WMEMMOVE(dest, destsize, source, count) ::wmemmove((dest), (source), (count))
#endif
#include <use_ansi.h>
#ifndef _VC6SP2
#define _VC6SP2 0 /* define as 1 to fix linker errors with V6.0 SP2 */
#endif /* _VC6SP2 */
/* Define _CRTIMP2 */
#ifndef _CRTIMP2
#if defined(_DLL) && !defined(_STATIC_CPPLIB)
#define _CRTIMP2 __declspec(dllimport)
#else /* ndef _DLL && !STATIC_CPPLIB */
#define _CRTIMP2
#endif /* _DLL && !STATIC_CPPLIB */
#endif /* _CRTIMP2 */
/* Define _CRTIMP2_NCEEPURE */
#ifndef _CRTIMP2_NCEEPURE
#if defined(_M_CEE_PURE)
#define _CRTIMP2_NCEEPURE
#else
#define _CRTIMP2_NCEEPURE _CRTIMP2
#endif
#endif
#ifndef _MRTIMP
#define _MRTIMP __declspec(dllimport)
#endif /* _MRTIMP */
/* Define _MRTIMP2 */
#ifndef _MRTIMP2
#if defined(_DLL) && !defined(_STATIC_CPPLIB)
#define _MRTIMP2 __declspec(dllimport)
#else /* ndef _DLL && !STATIC_CPPLIB */
#define _MRTIMP2
#endif /* _DLL && !STATIC_CPPLIB */
#endif /* _MRTIMP2 */
/* Define _MRTIMP2_NPURE */
#ifndef _MRTIMP2_NPURE
#if defined(_DLL) && defined(_M_CEE_PURE)
#define _MRTIMP2_NPURE __declspec(dllimport)
#else
#define _MRTIMP2_NPURE
#endif
#endif /* _MRTIMP2_NPURE */
/* Define _MRTIMP2_NCEE */
#ifndef _MRTIMP2_NCEE
#if defined(_M_CEE)
#define _MRTIMP2_NCEE
#else
#define _MRTIMP2_NCEE _MRTIMP2
#endif
#endif
/* Define _MRTIMP2_NCEEPURE */
#ifndef _MRTIMP2_NCEEPURE
#if defined(_M_CEE_PURE)
#define _MRTIMP2_NCEEPURE
#else
#define _MRTIMP2_NCEEPURE _MRTIMP2
#endif
#endif
/* Define _MRTIMP2_NPURE_NCEEPURE */
#ifndef _MRTIMP2_NPURE_NCEEPURE
#if defined(_M_CEE_PURE)
#define _MRTIMP2_NPURE_NCEEPURE
#else
#define _MRTIMP2_NPURE_NCEEPURE _MRTIMP2_NPURE
#endif
#endif
#if defined(_DLL) && !defined(_STATIC_CPPLIB) && !defined(_M_CEE_PURE)
#define _DLL_CPPLIB
#endif
#ifndef _CRTIMP2_PURE
#ifdef _M_CEE_PURE
#define _CRTIMP2_PURE
#else
#define _CRTIMP2_PURE _CRTIMP2
#endif
#endif
#if !defined(_CRTDATA2)
#define _CRTDATA2 _CRTIMP2
#endif
#define _DEPRECATED _CRT_DEPRECATE_TEXT("This is an obsolete part of the Standard C++ Library Implementation. Do not use it.")
/* NAMESPACE */
#if defined(__cplusplus)
#define _STD_BEGIN namespace std {
#define _STD_END }
#define _STD ::std::
/*
We use the stdext (standard extension) namespace to contain extensions that are not part of the current standard
*/
#define _STDEXT_BEGIN namespace stdext {
#define _STDEXT_END }
#define _STDEXT ::stdext::
#ifdef _STD_USING
#define _C_STD_BEGIN namespace std { /* only if *.c compiled as C++ */
#define _C_STD_END }
#define _CSTD ::std::
#else /* _STD_USING */
/* #define _GLOBAL_USING *.h in global namespace, c* imports to std */
#define _C_STD_BEGIN
#define _C_STD_END
#define _CSTD ::
#endif /* _STD_USING */
#define _C_LIB_DECL extern "C" { /* C has extern "C" linkage */
#define _END_C_LIB_DECL }
#define _EXTERN_C extern "C" {
#define _END_EXTERN_C }
#else /* __cplusplus */
#define _STD_BEGIN
#define _STD_END
#define _STD
#define _C_STD_BEGIN
#define _C_STD_END
#define _CSTD
#define _C_LIB_DECL
#define _END_C_LIB_DECL
#define _EXTERN_C
#define _END_EXTERN_C
#endif /* __cplusplus */
#define _Restrict restrict
#ifdef __cplusplus
_STD_BEGIN
typedef bool _Bool;
_STD_END
#endif /* __cplusplus */
/* VC++ COMPILER PARAMETERS */
#define _LONGLONG __int64
#define _ULONGLONG unsigned __int64
#define _LLONG_MAX 0x7fffffffffffffff
#define _ULLONG_MAX 0xffffffffffffffff
/* INTEGER PROPERTIES */
#define _C2 1 /* 0 if not 2's complement */
#define _MAX_EXP_DIG 8 /* for parsing numerics */
#define _MAX_INT_DIG 32
#define _MAX_SIG_DIG 36
typedef _LONGLONG _Longlong;
typedef _ULONGLONG _ULonglong;
/* STDIO PROPERTIES */
#define _Filet _iobuf
#ifndef _FPOS_T_DEFINED
#define _FPOSOFF(fp) ((long)(fp))
#endif /* _FPOS_T_DEFINED */
#define _IOBASE _base
#define _IOPTR _ptr
#define _IOCNT _cnt
/* MULTITHREAD PROPERTIES */
/* LOCK MACROS */
#define _LOCK_LOCALE 0
#define _LOCK_MALLOC 1
#define _LOCK_STREAM 2
#define _LOCK_DEBUG 3
#define _MAX_LOCK 4 /* one more than highest lock number */
#ifdef __cplusplus
_STD_BEGIN
// CLASS _Lockit
// warning 4412 is benign here
#pragma warning(push)
#pragma warning(disable:4412)
class _CRTIMP2_PURE _Lockit
{ // lock while object in existence -- MUST NEST
public:
#if _MULTI_THREAD
#if defined(_M_CEE_PURE) || defined(MRTDLL)
explicit __CLR_OR_THIS_CALL _Lockit() // set default lock
: _Locktype(0)
{
_Lockit_ctor(this);
}
explicit __CLR_OR_THIS_CALL _Lockit(int _Kind) // set the lock
{
_Lockit_ctor(this, _Kind);
}
__CLR_OR_THIS_CALL ~_Lockit() // clear the lock
{
_Lockit_dtor(this);
}
#else
explicit __thiscall _Lockit(); // set default lock
explicit __thiscall _Lockit(int); // set the lock
__thiscall ~_Lockit(); // clear the lock
#endif
static _MRTIMP2_NPURE void __cdecl _Lockit_ctor(int);
static _MRTIMP2_NPURE void __cdecl _Lockit_dtor(int);
private:
static _MRTIMP2_NPURE void __cdecl _Lockit_ctor(_Lockit *);
static _MRTIMP2_NPURE void __cdecl _Lockit_ctor(_Lockit *, int);
static _MRTIMP2_NPURE void __cdecl _Lockit_dtor(_Lockit *);
__CLR_OR_THIS_CALL _Lockit(const _Lockit&); // not defined
_Lockit& __CLR_OR_THIS_CALL operator=(const _Lockit&); // not defined
int _Locktype;
#else /* _MULTI_THREAD */
explicit _Lockit()
{ // do nothing
}
explicit _Lockit(int)
{ // do nothing
}
~_Lockit()
{ // do nothing
}
#endif /* _MULTI_THREAD */
};
#ifdef _M_CEE
class _CRTIMP2_PURE _EmptyLockit
{ // empty lock class used for bin compat
public:
#if _MULTI_THREAD
private:
int _Locktype;
#else /* _MULTI_THREAD */
#endif /* _MULTI_THREAD */
};
#if defined(__cplusplus_cli)
#define _M_CEE_FINALLY finally
#else
#define _M_CEE_FINALLY __finally
#endif
#define _BEGIN_LOCK(_Kind) \
{ \
typedef int _TmpTestType; \
__if_exists(_TmpTestType::ToString) \
{ \
bool _MustReleaseLock = false; \
int _LockKind = _Kind; \
System::Runtime::CompilerServices::RuntimeHelpers::PrepareConstrainedRegions(); \
try \
} \
{ \
__if_exists(_TmpTestType::ToString) \
{ \
System::Runtime::CompilerServices::RuntimeHelpers::PrepareConstrainedRegions(); \
try { } _M_CEE_FINALLY \
{ \
_STD _Lockit::_Lockit_ctor(_LockKind); \
_MustReleaseLock = true; \
} \
} \
__if_not_exists(_TmpTestType::ToString) \
{ \
_STD _Lockit _Lock(_Kind); \
}
#define _END_LOCK() \
} \
__if_exists(_TmpTestType::ToString) \
{ \
_M_CEE_FINALLY \
{ \
if (_MustReleaseLock) \
{ \
_STD _Lockit::_Lockit_dtor(_LockKind); \
} \
} \
} \
}
#define _BEGIN_LOCINFO(_VarName) \
_BEGIN_LOCK(_LOCK_LOCALE) \
_Locinfo _VarName;
#define _END_LOCINFO() \
_END_LOCK() \
#define _RELIABILITY_CONTRACT \
[System::Runtime::ConstrainedExecution::ReliabilityContract( \
System::Runtime::ConstrainedExecution::Consistency::WillNotCorruptState, \
System::Runtime::ConstrainedExecution::Cer::Success)]
#else
#define _BEGIN_LOCK(_Kind) \
{ \
_STD _Lockit _Lock(_Kind);
#define _END_LOCK() \
}
#define _BEGIN_LOCINFO(_VarName) \
{ \
_Locinfo _VarName;
#define _END_LOCINFO() \
}
#define _RELIABILITY_CONTRACT
#endif
class _CRTIMP2_PURE _Mutex
{ // lock under program control
public:
#if _MULTI_THREAD
#if defined(_M_CEE_PURE) || defined(MRTDLL)
__CLR_OR_THIS_CALL _Mutex()
{
_Mutex_ctor(this);
}
__CLR_OR_THIS_CALL ~_Mutex()
{
_Mutex_dtor(this);
}
void __CLR_OR_THIS_CALL _Lock()
{
_Mutex_Lock(this);
}
void __CLR_OR_THIS_CALL _Unlock()
{
_Mutex_Unlock(this);
}
#else
__thiscall _Mutex();
__thiscall ~_Mutex();
void __thiscall _Lock();
void __thiscall _Unlock();
#endif
private:
static _MRTIMP2_NPURE_NCEEPURE void __CLRCALL_PURE_OR_CDECL _Mutex_ctor(_Mutex *);
static _MRTIMP2_NPURE_NCEEPURE void __CLRCALL_PURE_OR_CDECL _Mutex_dtor(_Mutex *);
static _MRTIMP2_NPURE_NCEEPURE void __CLRCALL_PURE_OR_CDECL _Mutex_Lock(_Mutex *);
static _MRTIMP2_NPURE_NCEEPURE void __CLRCALL_PURE_OR_CDECL _Mutex_Unlock(_Mutex *);
__CLR_OR_THIS_CALL _Mutex(const _Mutex&); // not defined
_Mutex& __CLR_OR_THIS_CALL operator=(const _Mutex&); // not defined
void *_Mtx;
#else /* _MULTI_THREAD */
void _Lock()
{ // do nothing
}
void _Unlock()
{ // do nothing
}
#endif /* _MULTI_THREAD */
};
class _CRTIMP2_PURE _Init_locks
{ // initialize mutexes
public:
#if _MULTI_THREAD
#if defined(_M_CEE_PURE) || defined(MRTDLL)
__CLR_OR_THIS_CALL _Init_locks()
{
_Init_locks_ctor(this);
}
__CLR_OR_THIS_CALL ~_Init_locks()
{
_Init_locks_dtor(this);
}
#else
__thiscall _Init_locks();
__thiscall ~_Init_locks();
#endif
private:
static _MRTIMP2_NPURE void __cdecl _Init_locks_ctor(_Init_locks *);
static _MRTIMP2_NPURE void __cdecl _Init_locks_dtor(_Init_locks *);
#else /* _MULTI_THREAD */
_Init_locks()
{ // do nothing
}
~_Init_locks()
{ // do nothing
}
#endif /* _MULTI_THREAD */
};
#pragma warning(pop)
_STD_END
#endif /* __cplusplus */
#ifndef _RELIABILITY_CONTRACT
#define _RELIABILITY_CONTRACT
#endif
/* MISCELLANEOUS MACROS AND TYPES */
_C_STD_BEGIN
_MRTIMP2 void __cdecl _Atexit(void (__cdecl *)(void));
typedef int _Mbstatet;
#define _ATEXIT_T void
#define _Mbstinit(x) mbstate_t x = {0}
_C_STD_END
#define _EXTERN_TEMPLATE template
#define _THROW_BAD_ALLOC _THROW1(...)
#ifdef _MSC_VER
#pragma pack(pop)
#endif /* _MSC_VER */
#endif /* _YVALS */
/*
* Copyright (c) 1992-2005 by P.J. Plauger. ALL RIGHTS RESERVED.
* Consult your license regarding permissions and restrictions.
V4.05:0009 */
| 23.775536 | 166 | 0.699586 | [
"object"
] |
d3eb8e657089d0d611017dacfc06cfa67a28f3de | 612 | h | C | Fase4/engine/src/headers/pontos.h | 47Balboa/CG | 1398ae37fe8d52248efd2534848f51fe15a19f96 | [
"MIT"
] | 1 | 2020-11-14T20:10:52.000Z | 2020-11-14T20:10:52.000Z | Fase4/engine/src/headers/pontos.h | 47Balboa/CG | 1398ae37fe8d52248efd2534848f51fe15a19f96 | [
"MIT"
] | null | null | null | Fase4/engine/src/headers/pontos.h | 47Balboa/CG | 1398ae37fe8d52248efd2534848f51fe15a19f96 | [
"MIT"
] | 1 | 2021-05-30T16:55:35.000Z | 2021-05-30T16:55:35.000Z | #ifndef __PONTOS_H__
#define __PONTOS_H__
#include <vector>
#include <string>
#include <stdlib.h>
#include <GL/glew.h>
#include <GL/glut.h>
#include <IL/il.h>
#include "../../../src/headers/Point.h"
#include "headers/material.h"
using namespace std;
class pontos{
GLuint buffer[3], size_buffer[3];
Material* colour;
GLuint texture;
public:
pontos();
pontos(string s, vector<Point*>, vector<Point*> , vector<Point*>, Material*);
Material* getColour();
void setColour(Material*);
void loadTexture(string s);
void prepare(vector<Point*>, vector<Point*>, vector<Point*>);
void draw();
};
#endif
| 16.540541 | 78 | 0.694444 | [
"vector"
] |
d3ed7d2b8a30328c38b49b3f736fe3b70cb3f652 | 4,474 | h | C | Common/PlatformBase/Services/PrintLayoutService/MapViewportBase.h | achilex/MgDev | f7baf680a88d37659af32ee72b9a2046910b00d8 | [
"PHP-3.0"
] | 2 | 2017-04-19T01:38:30.000Z | 2020-07-31T03:05:32.000Z | Common/PlatformBase/Services/PrintLayoutService/MapViewportBase.h | achilex/MgDev | f7baf680a88d37659af32ee72b9a2046910b00d8 | [
"PHP-3.0"
] | null | null | null | Common/PlatformBase/Services/PrintLayoutService/MapViewportBase.h | achilex/MgDev | f7baf680a88d37659af32ee72b9a2046910b00d8 | [
"PHP-3.0"
] | 1 | 2021-12-29T10:46:12.000Z | 2021-12-29T10:46:12.000Z | //
// Copyright (C) 2004-2011 by Autodesk, Inc.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of version 2.1 of the GNU Lesser
// General Public License as published by the Free Software Foundation.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
//
#ifndef MGMAPVIEWPORTBASE_H_
#define MGMAPVIEWPORTBASE_H_
#include "PrintLayoutElementBase.h"
class MgMapView;
////////////////////////////////////////////////////////////
/// \brief
/// Defines the MgMapViewportBase object.
///
class MG_PLATFORMBASE_API MgMapViewportBase : public MgPrintLayoutElementBase
{
MG_DECL_DYNCREATE()
DECLARE_CLASSNAME(MgMapViewportBase)
INTERNAL_API:
///////////////////////////////////////////////////////////////////////////
/// \brief
/// Constructs an MgMapViewportBase object.
///
MgMapViewportBase();
///////////////////////////////////////////////////////////////////////////
/// \brief
/// Destroys an MgMapViewportBase object.
///
~MgMapViewportBase();
///////////////////////////////////////////////////////////////////////////
/// \brief
/// Gets the name of the map.
///
/// \return
/// Returns the name of the map.
///
virtual STRING GetMapName();
///////////////////////////////////////////////////////////////////////////
/// \brief
/// Gets the names of the hidden layers.
///
/// \return
/// Returns an MgStringCollection object containing the names of the hidden layers.
///
virtual MgStringCollection* GetHiddenLayerNames();
///////////////////////////////////////////////////////////////////////////
/// \brief
/// Gets the flag that specifies if the map viewport is locked.
///
/// \return
/// Returns the flag indicating if the map viewport is locked.
///
virtual bool GetIsLocked();
///////////////////////////////////////////////////////////////////////////
/// \brief
/// Gets the flag that specifies if the map viewport is on.
///
/// \return
/// Returns true if the map viewport is on; false otherwise.
///
virtual bool GetIsOn();
///////////////////////////////////////////////////////////////////////////
/// \brief
/// Gets the map view of the map viewport.
///
/// \return
/// Returns the map view of the map viewport.
///
virtual MgMapView* GetMapView();
INTERNAL_API:
///////////////////////////////////////////////////////////////////////////
/// \brief
/// Serializes data to TCP/IP stream.
///
/// \param stream
/// Stream
///
virtual void Serialize(MgStream* stream);
///////////////////////////////////////////////////////////////////////////
/// \brief
/// Deserializes data from TCP/IP stream.
///
/// \param stream
/// Stream
///
virtual void Deserialize(MgStream* stream);
///////////////////////////////////////////////////////////////////////////
/// \brief
/// Populates the map viewport from the MDF representation.
///
/// \param element
/// The MDF PrintLayoutElementDefinition that contained the deserialized
/// representation of the Viewport
///
virtual void PopulateFromResource(MdfModel::PrintLayoutElementDefinition *element);
protected:
///////////////////////////////////////////////////////////////////////////
/// \brief
/// Gets the class ID.
///
/// \return
/// The integer value.
///
virtual INT32 GetClassId();
///////////////////////////////////////////////////////////////////////////
/// \brief
/// Disposes this object.
///
/// \return
/// Nothing.
///
virtual void Dispose();
private:
// Data Members
bool m_isOn;
bool m_isLocked;
STRING m_mapName;
Ptr<MgMapView> m_view;
Ptr<MgStringCollection> m_hiddenLayerNames;
CLASS_ID:
static const INT32 m_cls_id = PlatformBase_PrintLayoutService_MapViewportBase;
};
#endif
| 28.496815 | 87 | 0.498882 | [
"object"
] |
d3eef1d1ee4fb1638f24f663a18097b2a9774f21 | 12,118 | c | C | interfaces/dia/objects/UML/small_package.c | krattai/monoflow | d777b8f345c5f2910114af7a186dc3bb6fe14aaf | [
"BSD-2-Clause"
] | 1 | 2021-05-04T16:35:42.000Z | 2021-05-04T16:35:42.000Z | interfaces/dia/objects/UML/small_package.c | krattai/monoflow | d777b8f345c5f2910114af7a186dc3bb6fe14aaf | [
"BSD-2-Clause"
] | null | null | null | interfaces/dia/objects/UML/small_package.c | krattai/monoflow | d777b8f345c5f2910114af7a186dc3bb6fe14aaf | [
"BSD-2-Clause"
] | 1 | 2021-05-04T16:35:35.000Z | 2021-05-04T16:35:35.000Z | /* Dia -- an diagram creation/manipulation program
* Copyright (C) 1998 Alexander Larsson
*
* 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <assert.h>
#include <math.h>
#include <string.h>
#include "intl.h"
#include "object.h"
#include "element.h"
#include "diarenderer.h"
#include "attributes.h"
#include "text.h"
#include "properties.h"
#include "stereotype.h"
#include "pixmaps/smallpackage.xpm"
#define NUM_CONNECTIONS 9
typedef struct _SmallPackage SmallPackage;
struct _SmallPackage {
Element element;
ConnectionPoint connections[NUM_CONNECTIONS];
char *stereotype;
Text *text;
char *st_stereotype;
TextAttributes attrs;
real line_width;
Color line_color;
Color fill_color;
};
/* The old border width, kept for compatibility with dia files created with
* older versions.
*/
#define SMALLPACKAGE_BORDERWIDTH 0.1
#define SMALLPACKAGE_TOPHEIGHT 0.9
#define SMALLPACKAGE_TOPWIDTH 1.5
#define SMALLPACKAGE_MARGIN_X 0.3
#define SMALLPACKAGE_MARGIN_Y 0.3
static real smallpackage_distance_from(SmallPackage *pkg, Point *point);
static void smallpackage_select(SmallPackage *pkg, Point *clicked_point,
DiaRenderer *interactive_renderer);
static ObjectChange* smallpackage_move_handle(SmallPackage *pkg, Handle *handle,
Point *to, ConnectionPoint *cp,
HandleMoveReason reason, ModifierKeys modifiers);
static ObjectChange* smallpackage_move(SmallPackage *pkg, Point *to);
static void smallpackage_draw(SmallPackage *pkg, DiaRenderer *renderer);
static DiaObject *smallpackage_create(Point *startpoint,
void *user_data,
Handle **handle1,
Handle **handle2);
static void smallpackage_destroy(SmallPackage *pkg);
static DiaObject *smallpackage_load(ObjectNode obj_node, int version,
const char *filename);
static PropDescription *smallpackage_describe_props(SmallPackage *smallpackage);
static void smallpackage_get_props(SmallPackage *smallpackage, GPtrArray *props);
static void smallpackage_set_props(SmallPackage *smallpackage, GPtrArray *props);
static void smallpackage_update_data(SmallPackage *pkg);
static ObjectTypeOps smallpackage_type_ops =
{
(CreateFunc) smallpackage_create,
(LoadFunc) smallpackage_load,/*using_properties*/ /* load */
(SaveFunc) object_save_using_properties, /* save */
(GetDefaultsFunc) NULL,
(ApplyDefaultsFunc) NULL
};
DiaObjectType smallpackage_type =
{
"UML - SmallPackage", /* name */
0, /* version */
(char **) smallpackage_xpm, /* pixmap */
&smallpackage_type_ops /* ops */
};
static ObjectOps smallpackage_ops = {
(DestroyFunc) smallpackage_destroy,
(DrawFunc) smallpackage_draw,
(DistanceFunc) smallpackage_distance_from,
(SelectFunc) smallpackage_select,
(CopyFunc) object_copy_using_properties,
(MoveFunc) smallpackage_move,
(MoveHandleFunc) smallpackage_move_handle,
(GetPropertiesFunc) object_create_props_dialog,
(ApplyPropertiesDialogFunc) object_apply_props_from_dialog,
(ObjectMenuFunc) NULL,
(DescribePropsFunc) smallpackage_describe_props,
(GetPropsFunc) smallpackage_get_props,
(SetPropsFunc) smallpackage_set_props,
(TextEditFunc) 0,
(ApplyPropertiesListFunc) object_apply_props,
};
static PropDescription smallpackage_props[] = {
ELEMENT_COMMON_PROPERTIES,
PROP_STD_LINE_WIDTH_OPTIONAL,
PROP_STD_LINE_COLOUR_OPTIONAL,
PROP_STD_FILL_COLOUR_OPTIONAL,
{ "stereotype", PROP_TYPE_STRING, PROP_FLAG_VISIBLE,
N_("Stereotype"), NULL, NULL },
PROP_STD_TEXT_FONT,
PROP_STD_TEXT_HEIGHT,
PROP_STD_TEXT_COLOUR,
{ "text", PROP_TYPE_TEXT, 0, N_("Text"), NULL, NULL },
PROP_DESC_END
};
static PropDescription *
smallpackage_describe_props(SmallPackage *smallpackage)
{
if (smallpackage_props[0].quark == 0) {
prop_desc_list_calculate_quarks(smallpackage_props);
}
return smallpackage_props;
}
static PropOffset smallpackage_offsets[] = {
ELEMENT_COMMON_PROPERTIES_OFFSETS,
{ PROP_STDNAME_LINE_WIDTH, PROP_STDTYPE_LINE_WIDTH, offsetof(SmallPackage, line_width) },
{"line_colour", PROP_TYPE_COLOUR, offsetof(SmallPackage, line_color) },
{"fill_colour", PROP_TYPE_COLOUR, offsetof(SmallPackage, fill_color) },
{"stereotype", PROP_TYPE_STRING, offsetof(SmallPackage , stereotype) },
{"text",PROP_TYPE_TEXT,offsetof(SmallPackage,text)},
{"text_font",PROP_TYPE_FONT,offsetof(SmallPackage,attrs.font)},
{PROP_STDNAME_TEXT_HEIGHT,PROP_STDTYPE_TEXT_HEIGHT,offsetof(SmallPackage,attrs.height)},
{"text_colour",PROP_TYPE_COLOUR,offsetof(SmallPackage,attrs.color)},
{ NULL, 0, 0 },
};
static void
smallpackage_get_props(SmallPackage * smallpackage,
GPtrArray *props)
{
text_get_attributes(smallpackage->text,&smallpackage->attrs);
object_get_props_from_offsets(&smallpackage->element.object,
smallpackage_offsets,props);
}
static void
smallpackage_set_props(SmallPackage *smallpackage,
GPtrArray *props)
{
object_set_props_from_offsets(&smallpackage->element.object,
smallpackage_offsets, props);
apply_textattr_properties(props,smallpackage->text,
"text",&smallpackage->attrs);
g_free(smallpackage->st_stereotype);
smallpackage->st_stereotype = NULL;
smallpackage_update_data(smallpackage);
}
static real
smallpackage_distance_from(SmallPackage *pkg, Point *point)
{
DiaObject *obj = &pkg->element.object;
return distance_rectangle_point(&obj->bounding_box, point);
}
static void
smallpackage_select(SmallPackage *pkg, Point *clicked_point,
DiaRenderer *interactive_renderer)
{
text_set_cursor(pkg->text, clicked_point, interactive_renderer);
text_grab_focus(pkg->text, &pkg->element.object);
element_update_handles(&pkg->element);
}
static ObjectChange*
smallpackage_move_handle(SmallPackage *pkg, Handle *handle,
Point *to, ConnectionPoint *cp,
HandleMoveReason reason, ModifierKeys modifiers)
{
assert(pkg!=NULL);
assert(handle!=NULL);
assert(to!=NULL);
assert(handle->id < 8);
return NULL;
}
static ObjectChange*
smallpackage_move(SmallPackage *pkg, Point *to)
{
Point p;
pkg->element.corner = *to;
p = *to;
p.x += SMALLPACKAGE_MARGIN_X;
p.y += pkg->text->ascent + SMALLPACKAGE_MARGIN_Y;
text_set_position(pkg->text, &p);
smallpackage_update_data(pkg);
return NULL;
}
static void
smallpackage_draw(SmallPackage *pkg, DiaRenderer *renderer)
{
DiaRendererClass *renderer_ops = DIA_RENDERER_GET_CLASS (renderer);
Element *elem;
real x, y, w, h;
Point p1, p2;
assert(pkg != NULL);
assert(renderer != NULL);
elem = &pkg->element;
x = elem->corner.x;
y = elem->corner.y;
w = elem->width;
h = elem->height;
renderer_ops->set_fillstyle(renderer, FILLSTYLE_SOLID);
renderer_ops->set_linewidth(renderer, pkg->line_width);
renderer_ops->set_linestyle(renderer, LINESTYLE_SOLID);
p1.x = x; p1.y = y;
p2.x = x+w; p2.y = y+h;
renderer_ops->fill_rect(renderer,
&p1, &p2,
&pkg->fill_color);
renderer_ops->draw_rect(renderer,
&p1, &p2,
&pkg->line_color);
p1.x= x; p1.y = y-SMALLPACKAGE_TOPHEIGHT;
p2.x = x+SMALLPACKAGE_TOPWIDTH; p2.y = y;
renderer_ops->fill_rect(renderer,
&p1, &p2,
&pkg->fill_color);
renderer_ops->draw_rect(renderer,
&p1, &p2,
&pkg->line_color);
text_draw(pkg->text, renderer);
if ((pkg->st_stereotype != NULL) && (pkg->st_stereotype[0] != '\0')) {
renderer_ops->set_font(renderer, pkg->text->font, pkg->text->height);
p1 = pkg->text->position;
p1.y -= pkg->text->height;
renderer_ops->draw_string(renderer, pkg->st_stereotype, &p1,
ALIGN_LEFT, &pkg->attrs.color);
}
}
static void
smallpackage_update_data(SmallPackage *pkg)
{
Element *elem = &pkg->element;
DiaObject *obj = &elem->object;
Point p;
DiaFont *font;
pkg->stereotype = remove_stereotype_from_string(pkg->stereotype);
if (!pkg->st_stereotype) {
pkg->st_stereotype = string_to_stereotype(pkg->stereotype);
}
text_calc_boundingbox(pkg->text, NULL);
elem->width = pkg->text->max_width + 2*SMALLPACKAGE_MARGIN_X;
elem->width = MAX(elem->width, SMALLPACKAGE_TOPWIDTH+1.0);
elem->height =
pkg->text->height*pkg->text->numlines + 2*SMALLPACKAGE_MARGIN_Y;
p = elem->corner;
p.x += SMALLPACKAGE_MARGIN_X;
p.y += SMALLPACKAGE_MARGIN_Y + pkg->text->ascent;
if ((pkg->stereotype != NULL) && (pkg->stereotype[0] != '\0')) {
font = pkg->text->font;
elem->height += pkg->text->height;
elem->width = MAX(elem->width,
dia_font_string_width(pkg->st_stereotype,
font, pkg->text->height)+
2*SMALLPACKAGE_MARGIN_X);
p.y += pkg->text->height;
}
pkg->text->position = p;
/* Update connections: */
element_update_connections_rectangle(elem, pkg->connections);
element_update_boundingbox(elem);
/* fix boundingbox for top rectangle: */
obj->bounding_box.top -= SMALLPACKAGE_TOPHEIGHT;
obj->position = elem->corner;
element_update_handles(elem);
}
static DiaObject *
smallpackage_create(Point *startpoint,
void *user_data,
Handle **handle1,
Handle **handle2)
{
SmallPackage *pkg;
Element *elem;
DiaObject *obj;
Point p;
DiaFont *font;
int i;
pkg = g_malloc0(sizeof(SmallPackage));
elem = &pkg->element;
obj = &elem->object;
obj->type = &smallpackage_type;
obj->ops = &smallpackage_ops;
elem->corner = *startpoint;
font = dia_font_new_from_style(DIA_FONT_MONOSPACE, 0.8);
p = *startpoint;
p.x += SMALLPACKAGE_MARGIN_X;
p.y += SMALLPACKAGE_MARGIN_Y+ dia_font_ascent("A",font, 0.8);
pkg->text = new_text("", font, 0.8, &p, &color_black, ALIGN_LEFT);
dia_font_unref(font);
text_get_attributes(pkg->text,&pkg->attrs);
element_init(elem, 8, NUM_CONNECTIONS);
for (i=0;i<NUM_CONNECTIONS;i++) {
obj->connections[i] = &pkg->connections[i];
pkg->connections[i].object = obj;
pkg->connections[i].connected = NULL;
}
pkg->connections[8].flags = CP_FLAGS_MAIN;
pkg->line_width = attributes_get_default_linewidth();
elem->extra_spacing.border_trans = pkg->line_width/2.0;
pkg->line_color = attributes_get_foreground();
pkg->fill_color = attributes_get_background();
pkg->stereotype = NULL;
pkg->st_stereotype = NULL;
smallpackage_update_data(pkg);
for (i=0;i<8;i++) {
obj->handles[i]->type = HANDLE_NON_MOVABLE;
}
*handle1 = NULL;
*handle2 = NULL;
return &pkg->element.object;
}
static void
smallpackage_destroy(SmallPackage *pkg)
{
text_destroy(pkg->text);
g_free(pkg->stereotype);
g_free(pkg->st_stereotype);
element_destroy(&pkg->element);
}
static DiaObject *
smallpackage_load(ObjectNode obj_node, int version, const char *filename)
{
DiaObject *obj = object_load_using_properties(&smallpackage_type,
obj_node,version,filename);
AttributeNode attr;
/* For compatibility with previous dia files. If no line_width, use
* SMALLPACKAGE_BORDERWIDTH, that was the previous line width.
*/
attr = object_find_attribute(obj_node, PROP_STDNAME_LINE_WIDTH);
if (attr == NULL)
((SmallPackage*)obj)->line_width = SMALLPACKAGE_BORDERWIDTH;
return obj;
}
| 28.852381 | 91 | 0.709441 | [
"object"
] |
d3ef70e22d3209e6ef6957fc9f5ead1615a07d27 | 6,205 | h | C | aws-cpp-sdk-iot/include/aws/iot/model/DetectMitigationActionsTaskTarget.h | perfectrecall/aws-sdk-cpp | fb8cbebf2fd62720b65aeff841ad2950e73d8ebd | [
"Apache-2.0"
] | 1 | 2022-02-10T08:06:54.000Z | 2022-02-10T08:06:54.000Z | aws-cpp-sdk-iot/include/aws/iot/model/DetectMitigationActionsTaskTarget.h | perfectrecall/aws-sdk-cpp | fb8cbebf2fd62720b65aeff841ad2950e73d8ebd | [
"Apache-2.0"
] | 1 | 2021-10-14T16:57:00.000Z | 2021-10-18T10:47:24.000Z | aws-cpp-sdk-iot/include/aws/iot/model/DetectMitigationActionsTaskTarget.h | ravindra-wagh/aws-sdk-cpp | 7d5ff01b3c3b872f31ca98fb4ce868cd01e97696 | [
"Apache-2.0"
] | 1 | 2021-11-09T11:58:03.000Z | 2021-11-09T11:58:03.000Z | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#pragma once
#include <aws/iot/IoT_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSVector.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <utility>
namespace Aws
{
namespace Utils
{
namespace Json
{
class JsonValue;
class JsonView;
} // namespace Json
} // namespace Utils
namespace IoT
{
namespace Model
{
/**
* <p> The target of a mitigation action task. </p><p><h3>See Also:</h3> <a
* href="http://docs.aws.amazon.com/goto/WebAPI/iot-2015-05-28/DetectMitigationActionsTaskTarget">AWS
* API Reference</a></p>
*/
class AWS_IOT_API DetectMitigationActionsTaskTarget
{
public:
DetectMitigationActionsTaskTarget();
DetectMitigationActionsTaskTarget(Aws::Utils::Json::JsonView jsonValue);
DetectMitigationActionsTaskTarget& operator=(Aws::Utils::Json::JsonView jsonValue);
Aws::Utils::Json::JsonValue Jsonize() const;
/**
* <p> The unique identifiers of the violations. </p>
*/
inline const Aws::Vector<Aws::String>& GetViolationIds() const{ return m_violationIds; }
/**
* <p> The unique identifiers of the violations. </p>
*/
inline bool ViolationIdsHasBeenSet() const { return m_violationIdsHasBeenSet; }
/**
* <p> The unique identifiers of the violations. </p>
*/
inline void SetViolationIds(const Aws::Vector<Aws::String>& value) { m_violationIdsHasBeenSet = true; m_violationIds = value; }
/**
* <p> The unique identifiers of the violations. </p>
*/
inline void SetViolationIds(Aws::Vector<Aws::String>&& value) { m_violationIdsHasBeenSet = true; m_violationIds = std::move(value); }
/**
* <p> The unique identifiers of the violations. </p>
*/
inline DetectMitigationActionsTaskTarget& WithViolationIds(const Aws::Vector<Aws::String>& value) { SetViolationIds(value); return *this;}
/**
* <p> The unique identifiers of the violations. </p>
*/
inline DetectMitigationActionsTaskTarget& WithViolationIds(Aws::Vector<Aws::String>&& value) { SetViolationIds(std::move(value)); return *this;}
/**
* <p> The unique identifiers of the violations. </p>
*/
inline DetectMitigationActionsTaskTarget& AddViolationIds(const Aws::String& value) { m_violationIdsHasBeenSet = true; m_violationIds.push_back(value); return *this; }
/**
* <p> The unique identifiers of the violations. </p>
*/
inline DetectMitigationActionsTaskTarget& AddViolationIds(Aws::String&& value) { m_violationIdsHasBeenSet = true; m_violationIds.push_back(std::move(value)); return *this; }
/**
* <p> The unique identifiers of the violations. </p>
*/
inline DetectMitigationActionsTaskTarget& AddViolationIds(const char* value) { m_violationIdsHasBeenSet = true; m_violationIds.push_back(value); return *this; }
/**
* <p> The name of the security profile. </p>
*/
inline const Aws::String& GetSecurityProfileName() const{ return m_securityProfileName; }
/**
* <p> The name of the security profile. </p>
*/
inline bool SecurityProfileNameHasBeenSet() const { return m_securityProfileNameHasBeenSet; }
/**
* <p> The name of the security profile. </p>
*/
inline void SetSecurityProfileName(const Aws::String& value) { m_securityProfileNameHasBeenSet = true; m_securityProfileName = value; }
/**
* <p> The name of the security profile. </p>
*/
inline void SetSecurityProfileName(Aws::String&& value) { m_securityProfileNameHasBeenSet = true; m_securityProfileName = std::move(value); }
/**
* <p> The name of the security profile. </p>
*/
inline void SetSecurityProfileName(const char* value) { m_securityProfileNameHasBeenSet = true; m_securityProfileName.assign(value); }
/**
* <p> The name of the security profile. </p>
*/
inline DetectMitigationActionsTaskTarget& WithSecurityProfileName(const Aws::String& value) { SetSecurityProfileName(value); return *this;}
/**
* <p> The name of the security profile. </p>
*/
inline DetectMitigationActionsTaskTarget& WithSecurityProfileName(Aws::String&& value) { SetSecurityProfileName(std::move(value)); return *this;}
/**
* <p> The name of the security profile. </p>
*/
inline DetectMitigationActionsTaskTarget& WithSecurityProfileName(const char* value) { SetSecurityProfileName(value); return *this;}
/**
* <p> The name of the behavior. </p>
*/
inline const Aws::String& GetBehaviorName() const{ return m_behaviorName; }
/**
* <p> The name of the behavior. </p>
*/
inline bool BehaviorNameHasBeenSet() const { return m_behaviorNameHasBeenSet; }
/**
* <p> The name of the behavior. </p>
*/
inline void SetBehaviorName(const Aws::String& value) { m_behaviorNameHasBeenSet = true; m_behaviorName = value; }
/**
* <p> The name of the behavior. </p>
*/
inline void SetBehaviorName(Aws::String&& value) { m_behaviorNameHasBeenSet = true; m_behaviorName = std::move(value); }
/**
* <p> The name of the behavior. </p>
*/
inline void SetBehaviorName(const char* value) { m_behaviorNameHasBeenSet = true; m_behaviorName.assign(value); }
/**
* <p> The name of the behavior. </p>
*/
inline DetectMitigationActionsTaskTarget& WithBehaviorName(const Aws::String& value) { SetBehaviorName(value); return *this;}
/**
* <p> The name of the behavior. </p>
*/
inline DetectMitigationActionsTaskTarget& WithBehaviorName(Aws::String&& value) { SetBehaviorName(std::move(value)); return *this;}
/**
* <p> The name of the behavior. </p>
*/
inline DetectMitigationActionsTaskTarget& WithBehaviorName(const char* value) { SetBehaviorName(value); return *this;}
private:
Aws::Vector<Aws::String> m_violationIds;
bool m_violationIdsHasBeenSet;
Aws::String m_securityProfileName;
bool m_securityProfileNameHasBeenSet;
Aws::String m_behaviorName;
bool m_behaviorNameHasBeenSet;
};
} // namespace Model
} // namespace IoT
} // namespace Aws
| 33.907104 | 177 | 0.680097 | [
"vector",
"model"
] |
31071a32e17cda5b6ea626f11e17b7f6fb42391f | 3,427 | h | C | core/include/mmcore/view/special/AnaglyphStereoView.h | voei/megamol | 569b7b58c1f9bc5405b79549b86f84009329f668 | [
"BSD-3-Clause"
] | 2 | 2020-10-16T10:15:37.000Z | 2021-01-21T13:06:00.000Z | core/include/mmcore/view/special/AnaglyphStereoView.h | voei/megamol | 569b7b58c1f9bc5405b79549b86f84009329f668 | [
"BSD-3-Clause"
] | null | null | null | core/include/mmcore/view/special/AnaglyphStereoView.h | voei/megamol | 569b7b58c1f9bc5405b79549b86f84009329f668 | [
"BSD-3-Clause"
] | 1 | 2021-01-28T01:19:54.000Z | 2021-01-28T01:19:54.000Z | /*
* AnaglyphStereoView.h
*
* Copyright (C) 2010 by VISUS (Universitaet Stuttgart)
* Alle Rechte vorbehalten.
*/
#ifndef MEGAMOLCORE_ANAGLYPHSTEREOVIEW_H_INCLUDED
#define MEGAMOLCORE_ANAGLYPHSTEREOVIEW_H_INCLUDED
#if (defined(_MSC_VER) && (_MSC_VER > 1000))
#pragma once
#endif /* (defined(_MSC_VER) && (_MSC_VER > 1000)) */
#include "mmcore/param/ParamSlot.h"
#include "mmcore/view/special/AbstractStereoView.h"
#include "vislib/graphics/gl/FramebufferObject.h"
#include "vislib/graphics/gl/GLSLShader.h"
namespace megamol {
namespace core {
namespace view {
namespace special {
/**
* Abstract base class of override rendering views
*/
class AnaglyphStereoView : public AbstractStereoView {
public:
/**
* Answer the name of this module.
*
* @return The name of this module.
*/
static const char *ClassName(void) {
return "AnaglyphStereoView";
}
/**
* Answer a human readable description of this module.
*
* @return A human readable description of this module.
*/
static const char *Description(void) {
return "Override View Module for anaglyph stereo output";
}
/**
* Answers whether this module is available on the current system.
*
* @return 'true' if the module is available, 'false' otherwise.
*/
static bool IsAvailable(void) {
return vislib::graphics::gl::FramebufferObject::AreExtensionsAvailable()
&& vislib::graphics::gl::GLSLShader::AreExtensionsAvailable()
&& isExtAvailable("GL_ARB_multitexture");
}
/** Ctor. */
AnaglyphStereoView(void);
/** Dtor. */
virtual ~AnaglyphStereoView(void);
/**
* Resizes the AbstractView3D.
*
* @param width The new width.
* @param height The new height.
*/
virtual void Resize(unsigned int width, unsigned int height);
/**
* Renders this AbstractView3D in the currently active OpenGL context.
*/
virtual void Render(const mmcRenderViewContext& context);
protected:
/**
* Initializes the module directly after instanziation
*
* @return 'true' on success
*/
virtual bool create(void);
/**
* Releases all resources of the module
*/
virtual void release(void);
private:
/** The left frame buffer */
vislib::graphics::gl::FramebufferObject leftBuffer;
/** The right frame buffer */
vislib::graphics::gl::FramebufferObject rightBuffer;
/** The compositing shader */
vislib::graphics::gl::GLSLShader shader;
/** parameter specifying the left eye colour */
param::ParamSlot leftColourSlot;
/** parameter specifying the right eye colour */
param::ParamSlot rightColourSlot;
/** parameter to select available eye colour presets */
param::ParamSlot colourPresetsSlot;
/** The left eye colour */
float leftColour[3];
/** The right eye colour */
float rightColour[3];
};
} /* end namespace special */
} /* end namespace view */
} /* end namespace core */
} /* end namespace megamol */
#endif /* MEGAMOLCORE_ANAGLYPHSTEREOVIEW_H_INCLUDED */
| 26.773438 | 84 | 0.605194 | [
"render"
] |
310bcd768cd5a3d68e442035991650e8c68e3ab8 | 10,691 | c | C | openeuler-kernel/arch/powerpc/kernel/syscall_64.c | Ddnirvana/test-CI | dd7a0a71281075e8ab300bddbab4a9fa039958f0 | [
"MulanPSL-1.0"
] | 31 | 2021-04-27T08:50:40.000Z | 2022-03-01T02:26:21.000Z | openeuler-kernel/arch/powerpc/kernel/syscall_64.c | Ddnirvana/test-CI | dd7a0a71281075e8ab300bddbab4a9fa039958f0 | [
"MulanPSL-1.0"
] | 13 | 2021-07-10T04:36:17.000Z | 2022-03-03T10:50:05.000Z | openeuler-kernel/arch/powerpc/kernel/syscall_64.c | Ddnirvana/test-CI | dd7a0a71281075e8ab300bddbab4a9fa039958f0 | [
"MulanPSL-1.0"
] | 12 | 2021-04-06T02:23:10.000Z | 2022-02-28T11:43:19.000Z | // SPDX-License-Identifier: GPL-2.0-or-later
#include <linux/err.h>
#include <asm/asm-prototypes.h>
#include <asm/kup.h>
#include <asm/cputime.h>
#include <asm/hw_irq.h>
#include <asm/kprobes.h>
#include <asm/paca.h>
#include <asm/ptrace.h>
#include <asm/reg.h>
#include <asm/signal.h>
#include <asm/switch_to.h>
#include <asm/syscall.h>
#include <asm/time.h>
#include <asm/unistd.h>
typedef long (*syscall_fn)(long, long, long, long, long, long);
/* Has to run notrace because it is entered not completely "reconciled" */
notrace long system_call_exception(long r3, long r4, long r5,
long r6, long r7, long r8,
unsigned long r0, struct pt_regs *regs)
{
syscall_fn f;
if (IS_ENABLED(CONFIG_PPC_IRQ_SOFT_MASK_DEBUG))
BUG_ON(irq_soft_mask_return() != IRQS_ALL_DISABLED);
trace_hardirqs_off(); /* finish reconciling */
if (IS_ENABLED(CONFIG_PPC_BOOK3S))
BUG_ON(!(regs->msr & MSR_RI));
BUG_ON(!(regs->msr & MSR_PR));
BUG_ON(!FULL_REGS(regs));
BUG_ON(regs->softe != IRQS_ENABLED);
kuap_check_amr();
account_cpu_user_entry();
#ifdef CONFIG_PPC_SPLPAR
if (IS_ENABLED(CONFIG_VIRT_CPU_ACCOUNTING_NATIVE) &&
firmware_has_feature(FW_FEATURE_SPLPAR)) {
struct lppaca *lp = local_paca->lppaca_ptr;
if (unlikely(local_paca->dtl_ridx != be64_to_cpu(lp->dtl_idx)))
accumulate_stolen_time();
}
#endif
/*
* This is not required for the syscall exit path, but makes the
* stack frame look nicer. If this was initialised in the first stack
* frame, or if the unwinder was taught the first stack frame always
* returns to user with IRQS_ENABLED, this store could be avoided!
*/
regs->softe = IRQS_ENABLED;
local_irq_enable();
if (unlikely(current_thread_info()->flags & _TIF_SYSCALL_DOTRACE)) {
if (unlikely(regs->trap == 0x7ff0)) {
/* Unsupported scv vector */
_exception(SIGILL, regs, ILL_ILLOPC, regs->nip);
return regs->gpr[3];
}
/*
* We use the return value of do_syscall_trace_enter() as the
* syscall number. If the syscall was rejected for any reason
* do_syscall_trace_enter() returns an invalid syscall number
* and the test against NR_syscalls will fail and the return
* value to be used is in regs->gpr[3].
*/
r0 = do_syscall_trace_enter(regs);
if (unlikely(r0 >= NR_syscalls))
return regs->gpr[3];
r3 = regs->gpr[3];
r4 = regs->gpr[4];
r5 = regs->gpr[5];
r6 = regs->gpr[6];
r7 = regs->gpr[7];
r8 = regs->gpr[8];
} else if (unlikely(r0 >= NR_syscalls)) {
if (unlikely(regs->trap == 0x7ff0)) {
/* Unsupported scv vector */
_exception(SIGILL, regs, ILL_ILLOPC, regs->nip);
return regs->gpr[3];
}
return -ENOSYS;
}
/* May be faster to do array_index_nospec? */
barrier_nospec();
if (unlikely(is_32bit_task())) {
f = (void *)compat_sys_call_table[r0];
r3 &= 0x00000000ffffffffULL;
r4 &= 0x00000000ffffffffULL;
r5 &= 0x00000000ffffffffULL;
r6 &= 0x00000000ffffffffULL;
r7 &= 0x00000000ffffffffULL;
r8 &= 0x00000000ffffffffULL;
} else {
f = (void *)sys_call_table[r0];
}
return f(r3, r4, r5, r6, r7, r8);
}
/*
* local irqs must be disabled. Returns false if the caller must re-enable
* them, check for new work, and try again.
*/
static notrace inline bool prep_irq_for_enabled_exit(bool clear_ri)
{
/* This must be done with RI=1 because tracing may touch vmaps */
trace_hardirqs_on();
/* This pattern matches prep_irq_for_idle */
if (clear_ri)
__hard_EE_RI_disable();
else
__hard_irq_disable();
if (unlikely(lazy_irq_pending_nocheck())) {
/* Took an interrupt, may have more exit work to do. */
if (clear_ri)
__hard_RI_enable();
trace_hardirqs_off();
local_paca->irq_happened |= PACA_IRQ_HARD_DIS;
return false;
}
local_paca->irq_happened = 0;
irq_soft_mask_set(IRQS_ENABLED);
return true;
}
/*
* This should be called after a syscall returns, with r3 the return value
* from the syscall. If this function returns non-zero, the system call
* exit assembly should additionally load all GPR registers and CTR and XER
* from the interrupt frame.
*
* The function graph tracer can not trace the return side of this function,
* because RI=0 and soft mask state is "unreconciled", so it is marked notrace.
*/
notrace unsigned long syscall_exit_prepare(unsigned long r3,
struct pt_regs *regs,
long scv)
{
unsigned long *ti_flagsp = ¤t_thread_info()->flags;
unsigned long ti_flags;
unsigned long ret = 0;
kuap_check_amr();
regs->result = r3;
/* Check whether the syscall is issued inside a restartable sequence */
rseq_syscall(regs);
ti_flags = *ti_flagsp;
if (unlikely(r3 >= (unsigned long)-MAX_ERRNO) && !scv) {
if (likely(!(ti_flags & (_TIF_NOERROR | _TIF_RESTOREALL)))) {
r3 = -r3;
regs->ccr |= 0x10000000; /* Set SO bit in CR */
}
}
if (unlikely(ti_flags & _TIF_PERSYSCALL_MASK)) {
if (ti_flags & _TIF_RESTOREALL)
ret = _TIF_RESTOREALL;
else
regs->gpr[3] = r3;
clear_bits(_TIF_PERSYSCALL_MASK, ti_flagsp);
} else {
regs->gpr[3] = r3;
}
if (unlikely(ti_flags & _TIF_SYSCALL_DOTRACE)) {
do_syscall_trace_leave(regs);
ret |= _TIF_RESTOREALL;
}
again:
local_irq_disable();
ti_flags = READ_ONCE(*ti_flagsp);
while (unlikely(ti_flags & (_TIF_USER_WORK_MASK & ~_TIF_RESTORE_TM))) {
local_irq_enable();
if (ti_flags & _TIF_NEED_RESCHED) {
schedule();
} else {
/*
* SIGPENDING must restore signal handler function
* argument GPRs, and some non-volatiles (e.g., r1).
* Restore all for now. This could be made lighter.
*/
if (ti_flags & _TIF_SIGPENDING)
ret |= _TIF_RESTOREALL;
do_notify_resume(regs, ti_flags);
}
local_irq_disable();
ti_flags = READ_ONCE(*ti_flagsp);
}
if (IS_ENABLED(CONFIG_PPC_BOOK3S) && IS_ENABLED(CONFIG_PPC_FPU)) {
if (IS_ENABLED(CONFIG_PPC_TRANSACTIONAL_MEM) &&
unlikely((ti_flags & _TIF_RESTORE_TM))) {
restore_tm_state(regs);
} else {
unsigned long mathflags = MSR_FP;
if (cpu_has_feature(CPU_FTR_VSX))
mathflags |= MSR_VEC | MSR_VSX;
else if (cpu_has_feature(CPU_FTR_ALTIVEC))
mathflags |= MSR_VEC;
/*
* If userspace MSR has all available FP bits set,
* then they are live and no need to restore. If not,
* it means the regs were given up and restore_math
* may decide to restore them (to avoid taking an FP
* fault).
*/
if ((regs->msr & mathflags) != mathflags)
restore_math(regs);
}
}
/* scv need not set RI=0 because SRRs are not used */
if (unlikely(!prep_irq_for_enabled_exit(!scv))) {
local_irq_enable();
goto again;
}
#ifdef CONFIG_PPC_TRANSACTIONAL_MEM
local_paca->tm_scratch = regs->msr;
#endif
account_cpu_user_exit();
return ret;
}
#ifdef CONFIG_PPC_BOOK3S /* BOOK3E not yet using this */
notrace unsigned long interrupt_exit_user_prepare(struct pt_regs *regs, unsigned long msr)
{
#ifdef CONFIG_PPC_BOOK3E
struct thread_struct *ts = ¤t->thread;
#endif
unsigned long *ti_flagsp = ¤t_thread_info()->flags;
unsigned long ti_flags;
unsigned long flags;
unsigned long ret = 0;
if (IS_ENABLED(CONFIG_PPC_BOOK3S))
BUG_ON(!(regs->msr & MSR_RI));
BUG_ON(!(regs->msr & MSR_PR));
BUG_ON(!FULL_REGS(regs));
BUG_ON(regs->softe != IRQS_ENABLED);
/*
* We don't need to restore AMR on the way back to userspace for KUAP.
* AMR can only have been unlocked if we interrupted the kernel.
*/
kuap_check_amr();
local_irq_save(flags);
again:
ti_flags = READ_ONCE(*ti_flagsp);
while (unlikely(ti_flags & (_TIF_USER_WORK_MASK & ~_TIF_RESTORE_TM))) {
local_irq_enable(); /* returning to user: may enable */
if (ti_flags & _TIF_NEED_RESCHED) {
schedule();
} else {
if (ti_flags & _TIF_SIGPENDING)
ret |= _TIF_RESTOREALL;
do_notify_resume(regs, ti_flags);
}
local_irq_disable();
ti_flags = READ_ONCE(*ti_flagsp);
}
if (IS_ENABLED(CONFIG_PPC_BOOK3S) && IS_ENABLED(CONFIG_PPC_FPU)) {
if (IS_ENABLED(CONFIG_PPC_TRANSACTIONAL_MEM) &&
unlikely((ti_flags & _TIF_RESTORE_TM))) {
restore_tm_state(regs);
} else {
unsigned long mathflags = MSR_FP;
if (cpu_has_feature(CPU_FTR_VSX))
mathflags |= MSR_VEC | MSR_VSX;
else if (cpu_has_feature(CPU_FTR_ALTIVEC))
mathflags |= MSR_VEC;
/* See above restore_math comment */
if ((regs->msr & mathflags) != mathflags)
restore_math(regs);
}
}
if (unlikely(!prep_irq_for_enabled_exit(true))) {
local_irq_enable();
local_irq_disable();
goto again;
}
#ifdef CONFIG_PPC_BOOK3E
if (unlikely(ts->debug.dbcr0 & DBCR0_IDM)) {
/*
* Check to see if the dbcr0 register is set up to debug.
* Use the internal debug mode bit to do this.
*/
mtmsr(mfmsr() & ~MSR_DE);
mtspr(SPRN_DBCR0, ts->debug.dbcr0);
mtspr(SPRN_DBSR, -1);
}
#endif
#ifdef CONFIG_PPC_TRANSACTIONAL_MEM
local_paca->tm_scratch = regs->msr;
#endif
account_cpu_user_exit();
return ret;
}
void unrecoverable_exception(struct pt_regs *regs);
void preempt_schedule_irq(void);
notrace unsigned long interrupt_exit_kernel_prepare(struct pt_regs *regs, unsigned long msr)
{
unsigned long *ti_flagsp = ¤t_thread_info()->flags;
unsigned long flags;
unsigned long ret = 0;
unsigned long amr;
if (IS_ENABLED(CONFIG_PPC_BOOK3S) && unlikely(!(regs->msr & MSR_RI)))
unrecoverable_exception(regs);
BUG_ON(regs->msr & MSR_PR);
BUG_ON(!FULL_REGS(regs));
amr = kuap_get_and_check_amr();
if (unlikely(*ti_flagsp & _TIF_EMULATE_STACK_STORE)) {
clear_bits(_TIF_EMULATE_STACK_STORE, ti_flagsp);
ret = 1;
}
local_irq_save(flags);
if (regs->softe == IRQS_ENABLED) {
/* Returning to a kernel context with local irqs enabled. */
WARN_ON_ONCE(!(regs->msr & MSR_EE));
again:
if (IS_ENABLED(CONFIG_PREEMPT)) {
/* Return to preemptible kernel context */
if (unlikely(*ti_flagsp & _TIF_NEED_RESCHED)) {
if (preempt_count() == 0)
preempt_schedule_irq();
}
}
if (unlikely(!prep_irq_for_enabled_exit(true))) {
/*
* Can't local_irq_restore to replay if we were in
* interrupt context. Must replay directly.
*/
if (irqs_disabled_flags(flags)) {
replay_soft_interrupts();
} else {
local_irq_restore(flags);
local_irq_save(flags);
}
/* Took an interrupt, may have more exit work to do. */
goto again;
}
} else {
/* Returning to a kernel context with local irqs disabled. */
__hard_EE_RI_disable();
if (regs->msr & MSR_EE)
local_paca->irq_happened &= ~PACA_IRQ_HARD_DIS;
}
#ifdef CONFIG_PPC_TRANSACTIONAL_MEM
local_paca->tm_scratch = regs->msr;
#endif
/*
* Don't want to mfspr(SPRN_AMR) here, because this comes after mtmsr,
* which would cause Read-After-Write stalls. Hence, we take the AMR
* value from the check above.
*/
kuap_restore_amr(regs, amr);
return ret;
}
#endif
| 26.203431 | 92 | 0.700496 | [
"vector"
] |
310cd0a676e21404d0fa818ffdacb3cef85969db | 11,560 | c | C | tests/unit/test_psi_sor.c | qikaifzj/ludwig | e16d2d3472772fb3a36c1ee1bde028029c9ecd2d | [
"BSD-3-Clause"
] | 34 | 2018-10-05T11:54:23.000Z | 2022-03-21T06:40:49.000Z | tests/unit/test_psi_sor.c | qikaifzj/ludwig | e16d2d3472772fb3a36c1ee1bde028029c9ecd2d | [
"BSD-3-Clause"
] | 108 | 2018-07-26T11:01:23.000Z | 2022-03-31T07:51:10.000Z | tests/unit/test_psi_sor.c | qikaifzj/ludwig | e16d2d3472772fb3a36c1ee1bde028029c9ecd2d | [
"BSD-3-Clause"
] | 24 | 2018-12-21T19:05:00.000Z | 2022-03-31T07:51:32.000Z | /*****************************************************************************
*
* test_psi_sor.c
*
* This is specifically SOR.
*
* Edinburgh Soft Matter and Statistical Physics Group and
* Edinburgh Parallel Computing Centre
*
* (c) 2012-2020 The University of Edinburgh
*
* Contributing authors:
* Kevin Stratford (kevin@epcc.ed.ac.uk)
*
*****************************************************************************/
#include <assert.h>
#include <float.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include "pe.h"
#include "coords.h"
#include "physics.h"
#include "control.h"
#include "psi_s.h"
#include "psi_sor.h"
#include "util.h"
#include "psi_stats.h"
#include "tests.h"
#define fe_fake_t void
static int do_test_sor1(pe_t * pe);
static int test_charge1_set(psi_t * psi);
static int test_charge1_exact(psi_t * obj, f_vare_t fepsilon);
#define REF_PERMEATIVITY 1.0
static int fepsilon_constant(fe_fake_t * fe, int index, double * epsilon);
static int fepsilon_sinz(fe_fake_t * fe, int index, double * epsilon);
/*****************************************************************************
*
* test_psi_sor_suite
*
*****************************************************************************/
int test_psi_sor_suite(void) {
pe_t * pe = NULL;
physics_t * phys = NULL;
pe_create(MPI_COMM_WORLD, PE_QUIET, &pe);
physics_ref(&phys);
do_test_sor1(pe);
pe_info(pe, "PASS ./unit/test_psi_sor\n");
pe_free(pe);
return 0;
}
/*****************************************************************************
*
* do_test_sor1
*
* Set rho(z = 1) = + (1/2NxNy)
* rho(z = Lz) = + (1/2NxNy)
* rho = - 1/(NxNy*(Nz-2)) everywhere else.
*
* This is a fully periodic system with zero total charge.
*
*****************************************************************************/
static int do_test_sor1(pe_t * pe) {
int mpi_cartsz[3];
cs_t * cs = NULL;
psi_t * psi = NULL;
assert(pe);
cs_create(pe, &cs);
cs_nhalo_set(cs, 1);
cs_init(cs);
cs_cartsz(cs, mpi_cartsz);
psi_create(pe, cs, 2, &psi);
assert(psi);
psi_valency_set(psi, 0, +1.0);
psi_valency_set(psi, 1, -1.0);
psi_epsilon_set(psi, REF_PERMEATIVITY);
test_charge1_set(psi);
psi_halo_psi(psi);
psi_halo_rho(psi);
psi_sor_poisson(psi);
if (mpi_cartsz[Z] == 1) test_charge1_exact(psi, fepsilon_constant);
/* Varying permeativity */
test_charge1_set(psi);
psi_halo_psi(psi);
psi_halo_rho(psi);
/* Following broken in latest vare solver */
psi_sor_vare_poisson(psi, NULL, fepsilon_sinz);
/*
if (cart_size(Z) == 1) test_charge1_exact(psi, fepsilon_sinz);
*/
psi_free(psi);
cs_free(cs);
return 0;
}
/*****************************************************************************
*
* test_charge1_set
*
* Sets a uniform 'wall' charge at z = 1 and z = L_z and a uniform
* interior value elsewhere such that the system is overall charge
* neutral.
*
* There is no sign, just a density. We expect valency[0] and valency[1]
* to be \pm 1.
*
*****************************************************************************/
static int test_charge1_set(psi_t * psi) {
int nk;
int ic, jc, kc, index;
int nlocal[3];
int mpi_cartsz[3];
int mpi_cartcoords[3];
double ltot[3];
double rho0, rho1;
double rho_min[4]; /* For psi_stats */
double rho_max[4]; /* For psi_stats */
double rho_tot[4]; /* For psi_stats */
MPI_Comm comm;
cs_ltot(psi->cs, ltot);
cs_nlocal(psi->cs, nlocal);
cs_cartsz(psi->cs, mpi_cartsz);
cs_cart_coords(psi->cs, mpi_cartcoords);
cs_cart_comm(psi->cs, &comm);
rho0 = 1.0 / (2.0*ltot[X]*ltot[Y]); /* Edge values */
rho1 = 1.0 / (ltot[X]*ltot[Y]*(ltot[Z] - 2.0)); /* Interior values */
psi_nk(psi, &nk);
test_assert(nk == 2);
/* Throughout set to rho1 */
for (ic = 1; ic <= nlocal[X]; ic++) {
for (jc = 1; jc <= nlocal[Y]; jc++) {
for (kc = 1; kc <= nlocal[Z]; kc++) {
index = cs_index(psi->cs, ic, jc, kc);
psi_psi_set(psi, index, 0.0);
psi_rho_set(psi, index, 0, 0.0);
psi_rho_set(psi, index, 1, rho1);
}
}
}
/* Now overwrite at the edges with rho0 */
if (mpi_cartcoords[Z] == 0) {
kc = 1;
for (ic = 1; ic <= nlocal[X]; ic++) {
for (jc = 1; jc <= nlocal[Y]; jc++) {
index = cs_index(psi->cs, ic, jc, kc);
psi_rho_set(psi, index, 0, rho0);
psi_rho_set(psi, index, 1, 0.0);
}
}
}
if (mpi_cartcoords[Z] == mpi_cartsz[Z] - 1) {
kc = nlocal[Z];
for (ic = 1; ic <= nlocal[X]; ic++) {
for (jc = 1; jc <= nlocal[Y]; jc++) {
index = cs_index(psi->cs, ic, jc, kc);
psi_rho_set(psi, index, 0, rho0);
psi_rho_set(psi, index, 1, 0.0);
}
}
}
psi_stats_reduce(psi, rho_min, rho_max, rho_tot, 0, comm);
if (pe_mpi_rank(psi->pe) == 0) {
/* psi all zero */
test_assert(fabs(rho_min[0] - 0.0) < DBL_EPSILON);
test_assert(fabs(rho_max[0] - 0.0) < DBL_EPSILON);
test_assert(fabs(rho_tot[0] - 0.0) < DBL_EPSILON);
/* First rho0 interior */
test_assert(fabs(rho_min[1] - 0.0) < DBL_EPSILON);
test_assert(fabs(rho_max[1] - rho0) < DBL_EPSILON);
test_assert(fabs(rho_tot[1] - 1.0) < DBL_EPSILON);
/* Next rho1 edge */
test_assert(fabs(rho_min[2] - 0.0) < DBL_EPSILON);
test_assert(fabs(rho_max[2] - rho1) < DBL_EPSILON);
test_assert(fabs(rho_tot[2] - 1.0) < FLT_EPSILON);
/* Total rho_elec */
test_assert(fabs(rho_min[3] + rho1) < DBL_EPSILON); /* + because valency is - */
test_assert(fabs(rho_max[3] - rho0) < DBL_EPSILON);
test_assert(fabs(rho_tot[3] - 0.0) < FLT_EPSILON);
}
return 0;
}
/*****************************************************************************
*
* test_charge1_exact
*
* Solve the tri-diagonal system appropriate for the 3-point stencil
* in one dimension (which is the z-direction). In parallel, all
* processes perform the whole solution.
*
* The precise numerical solution is then obtained by solving the
* linear system.
*
* We compare this with the solution obtained via the SOR function.
* Note that the linear system gives an answer which is different
* by a constant offset \psi_0. (All solutions of the Poisson equation
* in periodic boundary conditions are the same to within an arbitrary
* constant provided the 'unit cell' is charge neutral.)
*
* The two solutions may then be compared to within (roughly) the
* relative tolerance prescribed for the SOR. In turn, the solution
* of the Gauss Jordan routine has been checked agaisnt NAG F04AAF.
*
* We also recompute the RHS by differencing the SOR solution with
* a three point stencil in one dimension to provide a final check.
*
* For variable epsilon, described by the f_vare_t fepsilon,
* we set up a difference scheme using a three-point stencil:
*
* e(i+1/2) psi(i+1) - [ e(i+1/2) + e(i-1/2) ] psi(i) + e(i-1/2) psi(i-1)
*
* which is the same as that used in psi_cor.c and which collapses to the
* uniform case if e(r) is constant.
*
*****************************************************************************/
static int test_charge1_exact(psi_t * obj, f_vare_t fepsilon) {
int k, kp1, km1, index;
int nlocal[3];
int n;
int ifail;
double * epsilon = NULL; /* 1-d e = e(z) from fepsilon */
double eph; /* epsilon(k + 1/2) */
double emh; /* epsilon(k - 1/2) */
double psi, psi0; /* Potential values */
double tolerance; /* Absolute tolerance from psi_t */
double rhotot; /* Charge conservation check */
double rhodiff; /* Difference RHS check */
double * a = NULL; /* A is matrix for linear system */
double * b = NULL; /* B is RHS / solution vector */
double * c = NULL; /* Copy of the original RHS. */
cs_nlocal(obj->cs, nlocal);
/* assert(cart_size(Z) == 1); Rewrite elsewhere? */
n = nlocal[Z];
/* Compute and store the permeativity values for convenience */
epsilon = (double *) calloc(n, sizeof(double));
assert(epsilon);
if (epsilon == NULL) pe_fatal(obj->pe, "calloc(epsilon) failed\n");
for (k = 0; k < n; k++) {
index = cs_index(obj->cs, 1, 1, 1+k);
fepsilon(NULL, index, epsilon + k);
}
/* Allocate space for exact solution */
a = (double *) calloc((size_t) n*n, sizeof(double));
b = (double *) calloc(n, sizeof(double));
c = (double *) calloc(n, sizeof(double));
assert(a && b && c);
if (a == NULL) pe_fatal(obj->pe, "calloc(a) failed\n");
if (b == NULL) pe_fatal(obj->pe, "calloc(b) failed\n");
if (c == NULL) pe_fatal(obj->pe, "calloc(c) failed\n");
/* Set tridiagonal elements for periodic solution for the
* three-point stencil. The logic is to remove the perioidic end
* points which prevent a solution of the linear system. This
* effectively sets a Dirichlet boundary condition with psi = 0
* at both ends. */
for (k = 0; k < n; k++) {
kp1 = k + 1;
km1 = k - 1;
if (k == 0) km1 = kp1;
if (k == n-1) kp1 = km1;
eph = 0.5*(epsilon[k] + epsilon[kp1]);
emh = 0.5*(epsilon[km1] + epsilon[k]);
a[k*n + kp1] = eph;
a[k*n + km1] = emh;
a[k*n + k] = -(eph + emh);
}
/* Set the right hand side and solve the linear system. */
for (k = 0; k < n; k++) {
index = cs_index(obj->cs, 1, 1, k + 1);
psi_rho_elec(obj, index, b + k);
b[k] *= -1.0; /* Minus sign in RHS Poisson equation */
c[k] = b[k];
}
ifail = util_gauss_jordan(n, a, b);
test_assert(ifail == 0);
/* Check the Gauss Jordan answer against the answer from psi_t */
psi_abstol(obj, &tolerance);
rhotot = 0.0;
psi0 = 0.0;
for (k = 0; k < n; k++) {
index = cs_index(obj->cs, 1, 1, 1+k);
psi_psi(obj, index, &psi);
if (k == 0) psi0 = psi;
test_assert(fabs(b[k] + psi0 - psi) < tolerance);
kp1 = k + 1;
km1 = k - 1;
if (k == 0) km1 = kp1;
if (k == n-1) kp1 = km1;
eph = 0.5*(epsilon[k] + epsilon[kp1]);
emh = 0.5*(epsilon[km1] + epsilon[k]);
rhodiff = emh*obj->psi[index-1] - (emh + eph)*obj->psi[index]
+ eph*obj->psi[index+1];
test_assert(fabs(c[k] - rhodiff) < tolerance);
rhotot += c[k];
}
/* Total rho should be unchanged at zero. */
test_assert(fabs(rhotot) < tolerance);
free(c);
free(b);
free(a);
free(epsilon);
return 0;
}
/*****************************************************************************
*
* fepsilon_constant
*
* Returns constant epsilon REF_PERMEATIVITY
*
*****************************************************************************/
static int fepsilon_constant(fe_fake_t * fe, int index, double * epsilon) {
assert(epsilon);
*epsilon = REF_PERMEATIVITY;
return 0;
}
/*****************************************************************************
*
* fepsilon_sinz
*
* Permeativity is a function of z only:
*
* e = e0 sin(pi z / Lz)
*
* The - 0.5 is to make it symmetric about the centre line.
*
*****************************************************************************/
static int fepsilon_sinz(fe_fake_t * fe, int index, double * epsilon) {
test_assert(0);
#ifdef OLD_PENDING_REFACTOR
int coords[3];
double ltot[3];
cs_t * cs = NULL;
PI_DOUBLE(pi);
assert(0);
cs_ref(&cs); /* SHIT */
cs_index_to_ijk(cs, index, coords);
cs_ltot(cs, ltot);
*epsilon = REF_PERMEATIVITY*sin(pi*(1.0*coords[Z] - 0.5)/ltot[Z]);
#endif
return 0;
}
| 27.0726 | 84 | 0.552336 | [
"vector"
] |
310dbe79e83997321a8363486bc1b212278b66f8 | 6,491 | h | C | gtsam/slam/tests/smartFactorScenarios.h | NaokiTakahashi12/gtsam | 0bab7b00c8c822b172e9d4d1cfa88ed471763e26 | [
"BSD-3-Clause"
] | null | null | null | gtsam/slam/tests/smartFactorScenarios.h | NaokiTakahashi12/gtsam | 0bab7b00c8c822b172e9d4d1cfa88ed471763e26 | [
"BSD-3-Clause"
] | 22 | 2022-02-08T18:34:07.000Z | 2022-03-28T16:14:32.000Z | gtsam/slam/tests/smartFactorScenarios.h | NaokiTakahashi12/gtsam | 0bab7b00c8c822b172e9d4d1cfa88ed471763e26 | [
"BSD-3-Clause"
] | 1 | 2022-02-14T10:10:40.000Z | 2022-02-14T10:10:40.000Z | /* ----------------------------------------------------------------------------
* GTSAM Copyright 2010, Georgia Tech Research Corporation,
* Atlanta, Georgia 30332-0415
* All Rights Reserved
* Authors: Frank Dellaert, et al. (see THANKS for the full author list)
* See LICENSE for the license information
* -------------------------------------------------------------------------- */
/**
* @file SmartFactorScenarios.h
* @brief Scenarios for testSmart*.cpp
* @author Frank Dellaert
* @date Feb 2015
*/
#pragma once
#include <gtsam/geometry/Cal3Bundler.h>
#include <gtsam/geometry/Cal3_S2.h>
#include <gtsam/geometry/SphericalCamera.h>
#include <gtsam/slam/GeneralSFMFactor.h>
#include <gtsam/slam/SmartProjectionFactor.h>
#include <gtsam/slam/SmartProjectionPoseFactor.h>
#include "../SmartProjectionRigFactor.h"
using namespace std;
using namespace gtsam;
// three landmarks ~5 meters infront of camera
Point3 landmark1(5, 0.5, 1.2);
Point3 landmark2(5, -0.5, 1.2);
Point3 landmark3(3, 0, 3.0);
Point3 landmark4(10, 0.5, 1.2);
Point3 landmark5(10, -0.5, 1.2);
// First camera pose, looking along X-axis, 1 meter above ground plane (x-y)
Pose3 level_pose = Pose3(Rot3::Ypr(-M_PI / 2, 0., -M_PI / 2), Point3(0, 0, 1));
// Second camera 1 meter to the right of first camera
Pose3 pose_right = level_pose * Pose3(Rot3(), Point3(1, 0, 0));
// Third camera 1 meter above the first camera
Pose3 pose_above = level_pose * Pose3(Rot3(), Point3(0, -1, 0));
// Create a noise unit2 for the pixel error
static SharedNoiseModel unit2(noiseModel::Unit::Create(2));
static double fov = 60; // degrees
static size_t w = 640, h = 480;
/* ************************************************************************* */
// default Cal3_S2 cameras
namespace vanilla {
typedef PinholeCamera<Cal3_S2> Camera;
typedef SmartProjectionFactor<Camera> SmartFactor;
static Cal3_S2 K(fov, w, h);
static Cal3_S2 K2(1500, 1200, 0, w, h);
Camera level_camera(level_pose, K2);
Camera level_camera_right(pose_right, K2);
Point2 level_uv = level_camera.project(landmark1);
Point2 level_uv_right = level_camera_right.project(landmark1);
Camera cam1(level_pose, K2);
Camera cam2(pose_right, K2);
Camera cam3(pose_above, K2);
typedef GeneralSFMFactor<Camera, Point3> SFMFactor;
SmartProjectionParams params;
} // namespace vanilla
/* ************************************************************************* */
// default Cal3_S2 poses
namespace vanillaPose {
typedef PinholePose<Cal3_S2> Camera;
typedef CameraSet<Camera> Cameras;
typedef SmartProjectionPoseFactor<Cal3_S2> SmartFactor;
typedef SmartProjectionRigFactor<Camera> SmartRigFactor;
static Cal3_S2::shared_ptr sharedK(new Cal3_S2(fov, w, h));
Camera level_camera(level_pose, sharedK);
Camera level_camera_right(pose_right, sharedK);
Camera cam1(level_pose, sharedK);
Camera cam2(pose_right, sharedK);
Camera cam3(pose_above, sharedK);
} // namespace vanillaPose
/* ************************************************************************* */
// default Cal3_S2 poses
namespace vanillaPose2 {
typedef PinholePose<Cal3_S2> Camera;
typedef CameraSet<Camera> Cameras;
typedef SmartProjectionPoseFactor<Cal3_S2> SmartFactor;
typedef SmartProjectionRigFactor<Camera> SmartRigFactor;
static Cal3_S2::shared_ptr sharedK2(new Cal3_S2(1500, 1200, 0, 640, 480));
Camera level_camera(level_pose, sharedK2);
Camera level_camera_right(pose_right, sharedK2);
Camera cam1(level_pose, sharedK2);
Camera cam2(pose_right, sharedK2);
Camera cam3(pose_above, sharedK2);
} // namespace vanillaPose2
/* *************************************************************************/
// Cal3Bundler cameras
namespace bundler {
typedef PinholeCamera<Cal3Bundler> Camera;
typedef CameraSet<Camera> Cameras;
typedef SmartProjectionFactor<Camera> SmartFactor;
static Cal3Bundler K(500, 1e-3, 1e-3, 0, 0);
Camera level_camera(level_pose, K);
Camera level_camera_right(pose_right, K);
Point2 level_uv = level_camera.project(landmark1);
Point2 level_uv_right = level_camera_right.project(landmark1);
Pose3 pose1 = level_pose;
Camera cam1(level_pose, K);
Camera cam2(pose_right, K);
Camera cam3(pose_above, K);
typedef GeneralSFMFactor<Camera, Point3> SFMFactor;
} // namespace bundler
/* *************************************************************************/
// Cal3Bundler poses
namespace bundlerPose {
typedef PinholePose<Cal3Bundler> Camera;
typedef CameraSet<Camera> Cameras;
typedef SmartProjectionPoseFactor<Cal3Bundler> SmartFactor;
typedef SmartProjectionRigFactor<Camera> SmartRigFactor;
static boost::shared_ptr<Cal3Bundler> sharedBundlerK(new Cal3Bundler(500, 1e-3,
1e-3, 1000,
2000));
Camera level_camera(level_pose, sharedBundlerK);
Camera level_camera_right(pose_right, sharedBundlerK);
Camera cam1(level_pose, sharedBundlerK);
Camera cam2(pose_right, sharedBundlerK);
Camera cam3(pose_above, sharedBundlerK);
} // namespace bundlerPose
/* ************************************************************************* */
// sphericalCamera
namespace sphericalCamera {
typedef SphericalCamera Camera;
typedef CameraSet<Camera> Cameras;
typedef SmartProjectionRigFactor<Camera> SmartFactorP;
static EmptyCal::shared_ptr emptyK;
Camera level_camera(level_pose);
Camera level_camera_right(pose_right);
Camera cam1(level_pose);
Camera cam2(pose_right);
Camera cam3(pose_above);
} // namespace sphericalCamera
/* *************************************************************************/
template <class CAMERA>
CAMERA perturbCameraPose(const CAMERA& camera) {
Pose3 noise_pose =
Pose3(Rot3::Ypr(-M_PI / 10, 0., -M_PI / 10), Point3(0.5, 0.1, 0.3));
Pose3 cameraPose = camera.pose();
Pose3 perturbedCameraPose = cameraPose.compose(noise_pose);
return CAMERA(perturbedCameraPose, camera.calibration());
}
template <class CAMERA>
void projectToMultipleCameras(
const CAMERA& cam1, const CAMERA& cam2, const CAMERA& cam3, Point3 landmark,
typename CAMERA::MeasurementVector& measurements_cam) {
typename CAMERA::Measurement cam1_uv1 = cam1.project(landmark);
typename CAMERA::Measurement cam2_uv1 = cam2.project(landmark);
typename CAMERA::Measurement cam3_uv1 = cam3.project(landmark);
measurements_cam.push_back(cam1_uv1);
measurements_cam.push_back(cam2_uv1);
measurements_cam.push_back(cam3_uv1);
}
/* ************************************************************************* */
| 37.738372 | 80 | 0.669542 | [
"geometry"
] |
3118d9e9f9a69629a54b62f42a2782e1f2496042 | 21,967 | h | C | minidump/minidump_context.h | leo-lb/crashpad | 72feb80be08f5ca4b0c3b67e5493b2717f35e20f | [
"Apache-2.0"
] | null | null | null | minidump/minidump_context.h | leo-lb/crashpad | 72feb80be08f5ca4b0c3b67e5493b2717f35e20f | [
"Apache-2.0"
] | null | null | null | minidump/minidump_context.h | leo-lb/crashpad | 72feb80be08f5ca4b0c3b67e5493b2717f35e20f | [
"Apache-2.0"
] | null | null | null | // Copyright 2014 The Crashpad Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef CRASHPAD_MINIDUMP_MINIDUMP_CONTEXT_H_
#define CRASHPAD_MINIDUMP_MINIDUMP_CONTEXT_H_
#include <stdint.h>
#include "base/compiler_specific.h"
#include "snapshot/cpu_context.h"
#include "util/numeric/int128.h"
namespace crashpad {
//! \brief Architecture-independent flags for `context_flags` fields in Minidump
//! context structures.
//
// https://zachsaw.blogspot.com/2010/11/wow64-bug-getthreadcontext-may-return.html#c5639760895973344002
enum MinidumpContextFlags : uint32_t {
//! \brief The thread was executing a trap handler in kernel mode
//! (`CONTEXT_EXCEPTION_ACTIVE`).
//!
//! If this bit is set, it indicates that the context is from a thread that
//! was executing a trap handler in the kernel. This bit is only valid when
//! ::kMinidumpContextExceptionReporting is also set. This bit is only used on
//! Windows.
kMinidumpContextExceptionActive = 0x08000000,
//! \brief The thread was executing a system call in kernel mode
//! (`CONTEXT_SERVICE_ACTIVE`).
//!
//! If this bit is set, it indicates that the context is from a thread that
//! was executing a system call in the kernel. This bit is only valid when
//! ::kMinidumpContextExceptionReporting is also set. This bit is only used on
//! Windows.
kMinidumpContextServiceActive = 0x10000000,
//! \brief Kernel-mode state reporting is desired
//! (`CONTEXT_EXCEPTION_REQUEST`).
//!
//! This bit is not used in context structures containing snapshots of thread
//! CPU context. It used when calling `GetThreadContext()` on Windows to
//! specify that kernel-mode state reporting
//! (::kMinidumpContextExceptionReporting) is desired in the returned context
//! structure.
kMinidumpContextExceptionRequest = 0x40000000,
//! \brief Kernel-mode state reporting is provided
//! (`CONTEXT_EXCEPTION_REPORTING`).
//!
//! If this bit is set, it indicates that the bits indicating how the thread
//! had entered kernel mode (::kMinidumpContextExceptionActive and
//! ::kMinidumpContextServiceActive) are valid. This bit is only used on
//! Windows.
kMinidumpContextExceptionReporting = 0x80000000,
};
//! \brief 32-bit x86-specifc flags for MinidumpContextX86::context_flags.
enum MinidumpContextX86Flags : uint32_t {
//! \brief Identifies the context structure as 32-bit x86. This is the same as
//! `CONTEXT_i386` and `CONTEXT_i486` on Windows for this architecture.
kMinidumpContextX86 = 0x00010000,
//! \brief Indicates the validity of control registers (`CONTEXT_CONTROL`).
//!
//! The `ebp`, `eip`, `cs`, `eflags`, `esp`, and `ss` fields are valid.
kMinidumpContextX86Control = kMinidumpContextX86 | 0x00000001,
//! \brief Indicates the validity of non-control integer registers
//! (`CONTEXT_INTEGER`).
//!
//! The `edi`, `esi`, `ebx`, `edx`, `ecx, and `eax` fields are valid.
kMinidumpContextX86Integer = kMinidumpContextX86 | 0x00000002,
//! \brief Indicates the validity of non-control segment registers
//! (`CONTEXT_SEGMENTS`).
//!
//! The `gs`, `fs`, `es`, and `ds` fields are valid.
kMinidumpContextX86Segment = kMinidumpContextX86 | 0x00000004,
//! \brief Indicates the validity of floating-point state
//! (`CONTEXT_FLOATING_POINT`).
//!
//! The `fsave` field is valid. The `float_save` field is included in this
//! definition, but its members have no practical use asdie from `fsave`.
kMinidumpContextX86FloatingPoint = kMinidumpContextX86 | 0x00000008,
//! \brief Indicates the validity of debug registers
//! (`CONTEXT_DEBUG_REGISTERS`).
//!
//! The `dr0` through `dr3`, `dr6`, and `dr7` fields are valid.
kMinidumpContextX86Debug = kMinidumpContextX86 | 0x00000010,
//! \brief Indicates the validity of extended registers in `fxsave` format
//! (`CONTEXT_EXTENDED_REGISTERS`).
//!
//! The `extended_registers` field is valid and contains `fxsave` data.
kMinidumpContextX86Extended = kMinidumpContextX86 | 0x00000020,
//! \brief Indicates the validity of `xsave` data (`CONTEXT_XSTATE`).
//!
//! The context contains `xsave` data. This is used with an extended context
//! structure not currently defined here.
kMinidumpContextX86Xstate = kMinidumpContextX86 | 0x00000040,
//! \brief Indicates the validity of control, integer, and segment registers.
//! (`CONTEXT_FULL`).
kMinidumpContextX86Full = kMinidumpContextX86Control |
kMinidumpContextX86Integer |
kMinidumpContextX86Segment,
//! \brief Indicates the validity of all registers except `xsave` data.
//! (`CONTEXT_ALL`).
kMinidumpContextX86All = kMinidumpContextX86Full |
kMinidumpContextX86FloatingPoint |
kMinidumpContextX86Debug |
kMinidumpContextX86Extended,
};
//! \brief A 32-bit x86 CPU context (register state) carried in a minidump file.
//!
//! This is analogous to the `CONTEXT` structure on Windows when targeting
//! 32-bit x86, and the `WOW64_CONTEXT` structure when targeting an x86-family
//! CPU, either 32- or 64-bit. This structure is used instead of `CONTEXT` or
//! `WOW64_CONTEXT` to make it available when targeting other architectures.
//!
//! \note This structure doesn’t carry `dr4` or `dr5`, which are obsolete and
//! normally alias `dr6` and `dr7`, respectively. See Intel Software
//! Developer’s Manual, Volume 3B: System Programming, Part 2 (253669-052),
//! 17.2.2 “Debug Registers DR4 and DR5”.
struct MinidumpContextX86 {
//! \brief A bitfield composed of values of #MinidumpContextFlags and
//! #MinidumpContextX86Flags.
//!
//! This field identifies the context structure as a 32-bit x86 CPU context,
//! and indicates which other fields in the structure are valid.
uint32_t context_flags;
uint32_t dr0;
uint32_t dr1;
uint32_t dr2;
uint32_t dr3;
uint32_t dr6;
uint32_t dr7;
// CPUContextX86::Fsave has identical layout to what the x86 CONTEXT structure
// places here.
CPUContextX86::Fsave fsave;
union {
uint32_t spare_0; // As in the native x86 CONTEXT structure since Windows 8
uint32_t cr0_npx_state; // As in WOW64_CONTEXT and older SDKs’ x86 CONTEXT
} float_save;
uint32_t gs;
uint32_t fs;
uint32_t es;
uint32_t ds;
uint32_t edi;
uint32_t esi;
uint32_t ebx;
uint32_t edx;
uint32_t ecx;
uint32_t eax;
uint32_t ebp;
uint32_t eip;
uint32_t cs;
uint32_t eflags;
uint32_t esp;
uint32_t ss;
// CPUContextX86::Fxsave has identical layout to what the x86 CONTEXT
// structure places here.
CPUContextX86::Fxsave fxsave;
};
//! \brief x86_64-specific flags for MinidumpContextAMD64::context_flags.
enum MinidumpContextAMD64Flags : uint32_t {
//! \brief Identifies the context structure as x86_64. This is the same as
//! `CONTEXT_AMD64` on Windows for this architecture.
kMinidumpContextAMD64 = 0x00100000,
//! \brief Indicates the validity of control registers (`CONTEXT_CONTROL`).
//!
//! The `cs`, `ss`, `eflags`, `rsp`, and `rip` fields are valid.
kMinidumpContextAMD64Control = kMinidumpContextAMD64 | 0x00000001,
//! \brief Indicates the validity of non-control integer registers
//! (`CONTEXT_INTEGER`).
//!
//! The `rax`, `rcx`, `rdx`, `rbx`, `rbp`, `rsi`, `rdi`, and `r8` through
//! `r15` fields are valid.
kMinidumpContextAMD64Integer = kMinidumpContextAMD64 | 0x00000002,
//! \brief Indicates the validity of non-control segment registers
//! (`CONTEXT_SEGMENTS`).
//!
//! The `ds`, `es`, `fs`, and `gs` fields are valid.
kMinidumpContextAMD64Segment = kMinidumpContextAMD64 | 0x00000004,
//! \brief Indicates the validity of floating-point state
//! (`CONTEXT_FLOATING_POINT`).
//!
//! The `xmm0` through `xmm15` fields are valid.
kMinidumpContextAMD64FloatingPoint = kMinidumpContextAMD64 | 0x00000008,
//! \brief Indicates the validity of debug registers
//! (`CONTEXT_DEBUG_REGISTERS`).
//!
//! The `dr0` through `dr3`, `dr6`, and `dr7` fields are valid.
kMinidumpContextAMD64Debug = kMinidumpContextAMD64 | 0x00000010,
//! \brief Indicates the validity of `xsave` data (`CONTEXT_XSTATE`).
//!
//! The context contains `xsave` data. This is used with an extended context
//! structure not currently defined here.
kMinidumpContextAMD64Xstate = kMinidumpContextAMD64 | 0x00000040,
//! \brief Indicates the validity of control, integer, and floating-point
//! registers (`CONTEXT_FULL`).
kMinidumpContextAMD64Full = kMinidumpContextAMD64Control |
kMinidumpContextAMD64Integer |
kMinidumpContextAMD64FloatingPoint,
//! \brief Indicates the validity of all registers except `xsave` data
//! (`CONTEXT_ALL`).
kMinidumpContextAMD64All = kMinidumpContextAMD64Full |
kMinidumpContextAMD64Segment |
kMinidumpContextAMD64Debug,
};
//! \brief An x86_64 (AMD64) CPU context (register state) carried in a minidump
//! file.
//!
//! This is analogous to the `CONTEXT` structure on Windows when targeting
//! x86_64. This structure is used instead of `CONTEXT` to make it available
//! when targeting other architectures.
//!
//! \note This structure doesn’t carry `dr4` or `dr5`, which are obsolete and
//! normally alias `dr6` and `dr7`, respectively. See Intel Software
//! Developer’s Manual, Volume 3B: System Programming, Part 2 (253669-052),
//! 17.2.2 “Debug Registers DR4 and DR5”.
struct alignas(16) MinidumpContextAMD64 {
//! \brief Register parameter home address.
//!
//! On Windows, this field may contain the “home” address (on-stack, in the
//! shadow area) of a parameter passed by register. This field is present for
//! convenience but is not necessarily populated, even if a corresponding
//! parameter was passed by register.
//!
//! \{
uint64_t p1_home;
uint64_t p2_home;
uint64_t p3_home;
uint64_t p4_home;
uint64_t p5_home;
uint64_t p6_home;
//! \}
//! \brief A bitfield composed of values of #MinidumpContextFlags and
//! #MinidumpContextAMD64Flags.
//!
//! This field identifies the context structure as an x86_64 CPU context, and
//! indicates which other fields in the structure are valid.
uint32_t context_flags;
uint32_t mx_csr;
uint16_t cs;
uint16_t ds;
uint16_t es;
uint16_t fs;
uint16_t gs;
uint16_t ss;
uint32_t eflags;
uint64_t dr0;
uint64_t dr1;
uint64_t dr2;
uint64_t dr3;
uint64_t dr6;
uint64_t dr7;
uint64_t rax;
uint64_t rcx;
uint64_t rdx;
uint64_t rbx;
uint64_t rsp;
uint64_t rbp;
uint64_t rsi;
uint64_t rdi;
uint64_t r8;
uint64_t r9;
uint64_t r10;
uint64_t r11;
uint64_t r12;
uint64_t r13;
uint64_t r14;
uint64_t r15;
uint64_t rip;
// CPUContextX86_64::Fxsave has identical layout to what the x86_64 CONTEXT
// structure places here.
CPUContextX86_64::Fxsave fxsave;
uint128_struct vector_register[26];
uint64_t vector_control;
//! \brief Model-specific debug extension register.
//!
//! See Intel Software Developer’s Manual, Volume 3B: System Programming, Part
//! 2 (253669-051), 17.4 “Last Branch, Interrupt, and Exception Recording
//! Overview”, and AMD Architecture Programmer’s Manual, Volume 2: System
//! Programming (24593-3.24), 13.1.6 “Control-Transfer Breakpoint Features”.
//!
//! \{
uint64_t debug_control;
uint64_t last_branch_to_rip;
uint64_t last_branch_from_rip;
uint64_t last_exception_to_rip;
uint64_t last_exception_from_rip;
//! \}
};
//! \brief 32-bit ARM-specifc flags for MinidumpContextARM::context_flags.
enum MinidumpContextARMFlags : uint32_t {
//! \brief Identifies the context structure as 32-bit ARM.
kMinidumpContextARM = 0x40000000,
//! \brief Indicates the validity of integer regsiters.
//!
//! Regsiters `r0`-`r15` and `cpsr` are valid.
kMinidumpContextARMInteger = kMinidumpContextARM | 0x00000002,
//! \brief Inidicates the validity of VFP regsiters.
//!
//! Registers `d0`-`d31` and `fpscr` are valid.
kMinidumpContextARMVFP = kMinidumpContextARM | 0x00000004,
//! \brief Indicates the validity of all registers.
kMinidumpContextARMAll = kMinidumpContextARMInteger | kMinidumpContextARMVFP,
};
//! \brief A 32-bit ARM CPU context (register state) carried in a minidump file.
struct MinidumpContextARM {
//! \brief A bitfield composed of values of #MinidumpContextFlags and
//! #MinidumpContextARMFlags.
//!
//! This field identifies the context structure as a 32-bit ARM CPU context,
//! and indicates which other fields in the structure are valid.
uint32_t context_flags;
//! \brief General-purpose registers `r0`-`r15`.
uint32_t regs[11];
uint32_t fp; // r11
uint32_t ip; // r12
uint32_t sp; // r13
uint32_t lr; // r14
uint32_t pc; // r15
//! \brief Current program status register.
uint32_t cpsr;
//! \brief Floating-point status and control register.
uint32_t fpscr;
//! \brief VFP registers `d0`-`d31`.
uint64_t vfp[32];
//! \brief This space is unused. It is included for compatibility with
//! breakpad (which also doesn't use it).
uint32_t extra[8];
};
//! \brief 64-bit ARM-specifc flags for MinidumpContextARM64::context_flags.
enum MinidumpContextARM64Flags : uint32_t {
//! \brief Identifies the context structure as 64-bit ARM.
kMinidumpContextARM64 = 0x00400000,
//! \brief Indicates the validity of control registers.
//!
//! Registers `fp`, `lr`, `sp`, `pc`, and `cpsr`.
kMinidumpContextARM64Control = kMinidumpContextARM64 | 0x00000001,
//! \brief Indicates the validty of integer registers.
//!
//! Registers `x0`-`x28`.
kMinidumpContextARM64Integer = kMinidumpContextARM64 | 0x00000002,
//! \brief Indicates the validity of fpsimd registers.
//!
//! Registers `v0`-`v31`, `fpsr`, and `fpcr` are valid.
kMinidumpContextARM64Fpsimd = kMinidumpContextARM64 | 0x00000004,
//! \brief Indicates the validity of debug registers.
//!
//! `bcr`, `bvr`, `wcr`, and `wvr` are valid.
kMinidumpContextARM64Debug = kMinidumpContextARM64 | 0x00000008,
//! \brief Indicates the validity of control, integer and floating point
//! registers.
kMinidumpContextARM64Full = kMinidumpContextARM64Control |
kMinidumpContextARM64Integer |
kMinidumpContextARM64Fpsimd,
//! \brief Indicates the validity of all registers.
kMinidumpContextARM64All =
kMinidumpContextARM64Full | kMinidumpContextARM64Debug,
};
//! \brief A 64-bit ARM CPU context (register state) carried in a minidump file.
struct MinidumpContextARM64 {
uint32_t context_flags;
//! \brief Current program status register.
uint32_t cpsr;
//! \brief General-purpose registers `x0`-`x28`.
uint64_t regs[29];
//! \brief Frame pointer or `x29`.
uint64_t fp;
//! \brief Link register or `x30`.
uint64_t lr;
//! \brief Stack pointer or `x31`.
uint64_t sp;
//! \brief Program counter.
uint64_t pc;
//! \brief NEON registers `v0`-`v31`.
uint128_struct fpsimd[32];
//! \brief Floating-point control register.
uint32_t fpcr;
//! \brief Floating-point status register.
uint32_t fpsr;
//! \brief Debug registers.
uint32_t bcr[8];
uint64_t bvr[8];
uint32_t wcr[2];
uint64_t wvr[2];
};
//! \brief 32bit MIPS-specifc flags for MinidumpContextMIPS::context_flags.
//! Based on minidump_cpu_mips.h from breakpad
enum MinidumpContextMIPSFlags : uint32_t {
//! \brief Identifies the context structure as MIPSEL.
kMinidumpContextMIPS = 0x00040000,
//! \brief Indicates the validity of integer registers.
//!
//! Registers `0`-`31`, `mdhi`, `mdlo`, `epc`, `badvaddr`, `status` and
//! `cause` are valid.
kMinidumpContextMIPSInteger = kMinidumpContextMIPS | 0x00000002,
//! \brief Indicates the validity of floating point registers.
//!
//! Floating point registers `0`-`31`, `fpcsr` and `fir` are valid
kMinidumpContextMIPSFloatingPoint = kMinidumpContextMIPS | 0x00000004,
//! \brief Indicates the validity of DSP registers.
//!
//! Registers `hi0`-`hi2`, `lo0`-`lo2` and `dsp_control` are valid
kMinidumpContextMIPSDSP = kMinidumpContextMIPS | 0x00000008,
//! \brief Indicates the validity of all registers.
kMinidumpContextMIPSAll = kMinidumpContextMIPSInteger |
kMinidumpContextMIPSFloatingPoint |
kMinidumpContextMIPSDSP,
};
//! \brief A 32bit MIPS CPU context (register state) carried in a minidump file.
struct MinidumpContextMIPS {
uint32_t context_flags;
//! \brief This padding field is included for breakpad compatibility.
uint32_t _pad0;
//! \brief General purpose registers `0`-`31`.
uint64_t regs[32];
//! \brief Multiply/divide result.
uint64_t mdhi, mdlo;
//! \brief DSP registers.
uint32_t hi[3];
uint32_t lo[3];
uint32_t dsp_control;
//! \brief This padding field is included for breakpad compatibility.
uint32_t _pad1;
// \brief cp0 registers.
uint64_t epc;
uint64_t badvaddr;
uint32_t status;
uint32_t cause;
//! \brief FPU registers.
union {
struct {
float _fp_fregs;
uint32_t _fp_pad;
} fregs[32];
double dregs[32];
} fpregs;
//! \brief FPU status register.
uint32_t fpcsr;
//! \brief FPU implementation register.
uint32_t fir;
};
//! \brief 64bit MIPS-specifc flags for MinidumpContextMIPS64::context_flags.
//! Based on minidump_cpu_mips.h from breakpad
enum MinidumpContextMIPS64Flags : uint32_t {
//! \brief Identifies the context structure as MIPS64EL.
kMinidumpContextMIPS64 = 0x00080000,
//! \brief Indicates the validity of integer registers.
//!
//! Registers `0`-`31`, `mdhi`, `mdlo`, `epc`, `badvaddr`, `status` and
//! `cause` are valid.
kMinidumpContextMIPS64Integer = kMinidumpContextMIPS64 | 0x00000002,
//! \brief Indicates the validity of floating point registers.
//!
//! Floating point registers `0`-`31`, `fpcsr` and `fir` are valid
kMinidumpContextMIPS64FloatingPoint = kMinidumpContextMIPS64 | 0x00000004,
//! \brief Indicates the validity of DSP registers.
//!
//! Registers `hi0`-`hi2`, `lo0`-`lo2` and `dsp_control` are valid.
kMinidumpContextMIPS64DSP = kMinidumpContextMIPS64 | 0x00000008,
//! \brief Indicates the validity of all registers.
kMinidumpContextMIPS64All = kMinidumpContextMIPS64Integer |
kMinidumpContextMIPS64FloatingPoint |
kMinidumpContextMIPS64DSP,
};
//! \brief A 32bit MIPS CPU context (register state) carried in a minidump file.
struct MinidumpContextMIPS64 {
uint64_t context_flags;
//! \brief General purpose registers.
uint64_t regs[32];
//! \brief Multiply/divide result.
uint64_t mdhi, mdlo;
//! \brief DSP registers.
uint64_t hi[3];
uint64_t lo[3];
uint64_t dsp_control;
//! \brief cp0 registers.
uint64_t epc;
uint64_t badvaddr;
uint64_t status;
uint64_t cause;
//! \brief FPU registers.
union {
struct {
float _fp_fregs;
uint32_t _fp_pad;
} fregs[32];
double dregs[32];
} fpregs;
//! \brief FPU status register.
uint64_t fpcsr;
//! \brief FPU implementation register.
uint64_t fir;
};
//! \brief ppc64-specific flags for MinidumpPPC64::context_flags
//! Based on minidump_cpu_ppc64.h from breakpad
enum MinidumpContextPPC64Flags : uint32_t {
//! \brief Identifies the context as PPC64.
kMinidumpContextPPC64 = 0x01000000,
//! \brief Indicates the validity of general purpose registers.
//!
//! Registers `r0`-`r31`, `nip`, `msr`, `lr`, etc. are valid.
kMinidumpContextPPC64Base = kMinidumpContextPPC64 | 0x00000001,
//! \brief Indicates the validity of floating point registers.
//!
//! Registers `fp0`-`fp31`, `fpscr` are valid.
kMinidumpContextPPC64Floating = kMinidumpContextPPC64 | 0x00000008,
//! \brief Indicates the validity of Altivec/VMX registers.
//!
//! Registers `v0`-`v31`, `vscr`, `vrsave`.
kMinidumpContextPPC64Vector = kMinidumpContextPPC64 | 0x00000020,
//! \brief Indicates the validity of all registers
kMinidumpContextPPC64All = kMinidumpContextPPC64Base |
kMinidumpContextPPC64Floating |
kMinidumpContextPPC64Vector
};
//! \brief A PPC64 CPU context carried in a minidump file.
//! Based on minidump_cpu_ppc64.h from breakpad.
struct MinidumpContextPPC64 {
uint64_t context_flags;
//! \brief General purpose registers.
uint64_t nip;
uint64_t msr;
uint64_t regs[32];
uint64_t ccr;
uint64_t xer;
uint64_t lnk;
uint64_t ctr;
//! \brief Floating point registers.
double fpregs[32];
//! \brief FPU status register.
double fpscr;
//! \brief Altivec/VMX vector registers.
struct {
//! \brief Vector registers are 128bits.
uint128_struct save_vr[32];
uint128_struct save_vscr;
//! \brief Padding included for breakpad compatibiltiy.
uint32_t save_pad5[4];
//! \brief VRSAVE register.
uint32_t save_vrsave;
//! \brief Padding included for breakpad compatibiltiy.
uint32_t save_pad6[7];
} vregs;
};
} // namespace crashpad
#endif // CRASHPAD_MINIDUMP_MINIDUMP_CONTEXT_H_
| 33.182779 | 103 | 0.700961 | [
"vector",
"model"
] |
311d911899a1fe7ce355a7ee22a804f03619cbbb | 15,391 | c | C | src/conf.c | stargieg/KadNode | 4dfe5be17d18911becddb8598e8ca44b08624367 | [
"MIT"
] | null | null | null | src/conf.c | stargieg/KadNode | 4dfe5be17d18911becddb8598e8ca44b08624367 | [
"MIT"
] | null | null | null | src/conf.c | stargieg/KadNode | 4dfe5be17d18911becddb8598e8ca44b08624367 | [
"MIT"
] | null | null | null |
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <signal.h>
#include <limits.h>
#include <errno.h>
#include <getopt.h>
#include "main.h"
#include "log.h"
#include "utils.h"
#include "conf.h"
#include "peerfile.h"
#include "kad.h"
#ifdef TLS
#include "ext-tls-client.h"
#include "ext-tls-server.h"
#endif
#ifdef BOB
#include "ext-bob.h"
#endif
#ifdef FWD
#include "ext-fwd.h"
#endif
#ifdef __CYGWIN__
#include "windows.h"
#endif
// Global object variables
struct gconf_t *gconf = NULL;
static const char *g_announce_args[64] = { 0 };
#ifdef TLS
static const char *g_tls_client_args[16] = { 0 };
static const char *g_tls_server_args[16] = { 0 };
#endif
const char *kadnode_version_str = "KadNode v"MAIN_VERSION" ("
#ifdef BOB
" bob"
#endif
#ifdef CMD
" cmd"
#endif
#ifdef DEBUG
" debug"
#endif
#ifdef DNS
" dns"
#endif
#ifdef LPD
" lpd"
#endif
#ifdef FWD_NATPMP
" natpmp"
#endif
#ifdef NSS
" nss"
#endif
#ifdef TLS
" tls"
#endif
#ifdef FWD_UPNP
" upnp"
#endif
" )";
static const char *kadnode_usage_str =
"KadNode is a small decentralized DNS resolver.\n"
"\n"
"Usage: kadnode [OPTIONS]*\n"
"\n"
" --announce <name>:<port> Announce a name and port.\n\n"
" --peerfile <file> Import/Export peers from and to a file.\n\n"
" --peer <addr> Add a static peer address.\n"
" This option may occur multiple times.\n\n"
" --user <user> Change the UUID after start.\n\n"
" --port <port> Bind DHT to this port.\n"
" Default: "STR(DHT_PORT)"\n\n"
" --config <file> Provide a configuration file with one command line\n"
" option on each line. Comments start after '#'.\n\n"
" --ifname <interface> Bind to this interface.\n"
" Default: <any>\n\n"
" --daemon Run the node in background.\n\n"
" --verbosity <level> Verbosity level: quiet, verbose or debug.\n"
" Default: verbose\n\n"
" --pidfile <file> Write process pid to a file.\n\n"
" --ipv4, -4, --ipv6, -6 Enable IPv4 or IPv6 only mode.\n"
" Default: IPv4+IPv6\n\n"
" --query-tld <domain> Top level domain to be handled by KadNode.\n"
" Default: "QUERY_TLD_DEFAULT"\n\n"
#ifdef LPD
" --lpd-disable Disable multicast to discover local peers.\n\n"
#endif
#ifdef BOB
" --bob-create-key <file> Write a new secp256r1 secret key in PEM format to the file.\n"
" The public key will be printed to the terminal before exit.\n\n"
" --bob-load-key <file> Read a secret key in PEM format and announce the public key.\n"
" This option may occur multiple times.\n\n"
#endif
#ifdef CMD
" --cmd-disable-stdin Disable the local control interface.\n\n"
" --cmd-path <path> Bind the remote control interface to this unix socket path.\n"
" Default: "CMD_PATH"\n\n"
#endif
#ifdef DNS
" --dns-port <port> Bind the DNS server interface to this local port.\n"
" Default: "STR(DNS_PORT)"\n\n"
" --dns-proxy-enable Enable DNS proxy mode. The proxy reads /etc/resolv.conf by default.\n\n"
" --dns-proxy-server <ip-addr> Use IP address of an external DNS server instead of resolv.conf.\n\n"
#endif
#ifdef NSS
" --nss-path <path> Bind the Network Service Switch to this unix socket path.\n"
" Default: "NSS_PATH"\n\n"
#endif
#ifdef FWD
" --fwd-disable Disable UPnP/NAT-PMP to forward router ports.\n\n"
#endif
#ifdef TLS
" --tls-client-cert <path> Path to file or folder of CA root certificates.\n"
" This option may occur multiple times.\n\n"
" --tls-server-cert <path>,<path> Add a comma separated tuple of server certificate file and key.\n"
" This option may occur multiple times.\n"
" Example: kadnode.crt,kadnode.key\n\n"
#endif
#ifdef __CYGWIN__
" --service-start Start, install and remove KadNode as Windows service.\n"
" --service-install KadNode will be started/shut down along with Windows\n"
" --service-remove or on request by using the Service Control Manager.\n\n"
#endif
" -h, --help Print this help.\n\n"
" -v, --version Print program version.\n";
// Set default if setting was not set and validate settings
void conf_defaults(void)
{
if (gconf->af == 0) {
gconf->af = AF_UNSPEC;
}
if (gconf->query_tld == NULL) {
gconf->query_tld = strdup(QUERY_TLD_DEFAULT);
}
if (gconf->dht_port < 0) {
gconf->dht_port = DHT_PORT;
}
#ifdef CMD
if (gconf->cmd_path == NULL) {
gconf->cmd_path = strdup(CMD_PATH);
}
#endif
#ifdef DNS
if (gconf->dns_port < 0) {
gconf->dns_port = DNS_PORT;
}
#endif
#ifdef NSS
if (gconf->nss_path == NULL) {
gconf->nss_path = strdup(NSS_PATH);
}
#endif
time_t now = time(NULL);
gconf->time_now = now;
gconf->startup_time = now;
gconf->is_running = 1;
}
const char *verbosity_str(int verbosity)
{
switch (verbosity) {
case VERBOSITY_QUIET: return "quiet";
case VERBOSITY_VERBOSE: return "verbose";
case VERBOSITY_DEBUG: return "debug";
default:
log_error("Invalid verbosity: %d", verbosity);
exit(1);
}
}
void conf_info(void)
{
log_info("Starting %s", kadnode_version_str);
log_info("Net Mode: %s", str_af(gconf->af));
log_info("Run Mode: %s", gconf->is_daemon ? "daemon" : "foreground");
if (gconf->configfile) {
log_info("Configuration File: %s", gconf->configfile);
}
log_info("Verbosity: %s", verbosity_str(gconf->verbosity));
log_info("Query TLD: %s", gconf->query_tld);
log_info("Peer File: %s", gconf->peerfile ? gconf->peerfile : "none");
#ifdef LPD
log_info("Local Peer Discovery: %s", gconf->lpd_disable ? "disabled" : "enabled");
#endif
#ifdef DNS
if (gconf->dns_proxy_enable) {
if (gconf->dns_proxy_server) {
log_info("DNS proxy enabled: %s", gconf->dns_proxy_server);
} else {
log_info("DNS proxy enabled: /etc/resolv.conf");
}
}
#endif
}
void conf_free(void)
{
free(gconf->query_tld);
free(gconf->user);
free(gconf->pidfile);
free(gconf->peerfile);
free(gconf->dht_ifname);
free(gconf->configfile);
#ifdef CMD
free(gconf->cmd_path);
#endif
#ifdef DNS
free(gconf->dns_proxy_server);
#endif
#ifdef NSS
free(gconf->nss_path);
#endif
free(gconf);
}
// Enumerate all options to keep binary size smaller
enum OPCODE {
oAnnounce,
oQueryTld,
oPidFile,
oPeerFile,
oPeer,
oVerbosity,
oCmdDisableStdin,
oCmdPath,
oDnsPort,
oDnsProxyEnable,
oDnsProxyServer,
oNssPath,
oTlsClientCert,
oTlsServerCert,
oConfig,
oIpv4,
oIpv6,
oPort,
oLpdAddr,
oLpdDisable,
oFwdDisable,
oServiceInstall,
oServiceRemove,
oServiceStart,
oBobCreateKey,
oBobLoadKey,
oIfname,
oUser,
oDaemon,
oHelp,
oVersion
};
struct option_t {
const char *name;
uint16_t num_args;
uint16_t code;
};
static struct option_t g_options[] = {
{"--announce", 1, oAnnounce},
{"--query-tld", 1, oQueryTld},
{"--pidfile", 1, oPidFile},
{"--peerfile", 1, oPeerFile},
{"--peer", 1, oPeer},
{"--verbosity", 1, oVerbosity},
#ifdef CMD
{"--cmd-disable-stdin", 0, oCmdDisableStdin},
{"--cmd-port", 1, oCmdPath},
#endif
#ifdef DNS
{"--dns-port", 1, oDnsPort},
{"--dns-proxy-enable", 0, oDnsProxyEnable},
{"--dns-proxy-server", 1, oDnsProxyServer},
#endif
#ifdef NSS
{"--nss-path", 1, oNssPath},
#endif
#ifdef TLS
{"--tls-client-cert", 1, oTlsClientCert},
{"--tls-server-cert", 1, oTlsServerCert},
#endif
{"--config", 1, oConfig},
{"--port", 1, oPort},
{"-4", 0, oIpv4},
{"--ipv4", 0, oIpv4},
{"-6", 0, oIpv6},
{"--ipv6", 0, oIpv6},
#ifdef LPD
{"--lpd-addr", 1, oLpdAddr},
{"--lpd-disable", 0, oLpdDisable},
#endif
#ifdef FWD
{"--fwd-disable", 0, oFwdDisable},
#endif
#ifdef __CYGWIN__
{"--service-install", 0, oServiceInstall},
{"--service-remove", 0, oServiceRemove},
{"--service-start", 0, oServiceStart},
#endif
#ifdef BOB
{"--bob-create-key", 1, oBobCreateKey},
{"--bob-load-key", 1, oBobLoadKey},
#endif
{"--ifname", 1, oIfname},
{"--user", 1, oUser},
{"--daemon", 0, oDaemon},
{"-h", 0, oHelp},
{"--help", 0, oHelp},
{"-v", 0, oVersion},
{"--version", 0, oVersion},
{NULL, 0, 0}
};
static const struct option_t *find_option(const char name[])
{
struct option_t *option;
option = g_options;
while (option->name) {
if (0 == strcmp(name, option->name)) {
return option;
}
option++;
}
return NULL;
}
// Set a string once - error when already set
static int conf_str(const char opt[], char *dst[], const char src[])
{
if (*dst != NULL) {
log_error("Value was already set for %s: %s", opt, src);
return EXIT_FAILURE;
}
*dst = strdup(src);
return EXIT_SUCCESS;
}
static int conf_port(const char opt[], int *dst, const char src[])
{
int n = port_parse(src, -1);
if (n < 0) {
log_error("Invalid port for %s: %s", opt, src);
return EXIT_FAILURE;
}
if (*dst >= 0) {
log_error("Value was already set for %s: %s", opt, src);
return EXIT_FAILURE;
}
*dst = n;
return EXIT_SUCCESS;
}
// forward declaration
static int conf_set(const char opt[], const char val[]);
static int conf_load_file(const char path[])
{
char option[32];
char value[256];
char line[32 + 256];
char dummy[4];
char *last;
struct stat s;
int ret;
FILE *file;
size_t nline;
if (stat(path, &s) == 0 && !(s.st_mode & S_IFREG)) {
log_error("File expected: %s", path);
return EXIT_FAILURE;
}
nline = 0;
file = fopen(path, "r");
if (file == NULL) {
log_error("Cannot open file: %s (%s)", path, strerror(errno));
return EXIT_FAILURE;
}
while (fgets(line, sizeof(line), file) != NULL) {
nline += 1;
// Cut off comments
last = strchr(line, '#');
if (last) {
*last = '\0';
}
if (line[0] == '\n' || line[0] == '\0') {
continue;
}
ret = sscanf(line, " %31s%*[ ]%255s %3s", option, value, dummy);
if (ret == 1 || ret == 2) {
// Prevent recursive inclusion
if (strcmp(option, "--config ") == 0) {
fclose(file);
log_error("Option '--config' not allowed inside a configuration file, line %ld.", nline);
return EXIT_FAILURE;
}
// parse --option value / --option
ret = conf_set(option, (ret == 2) ? value : NULL);
if (ret == EXIT_FAILURE) {
fclose(file);
return EXIT_FAILURE;
}
} else {
fclose(file);
log_error("Invalid line in config file: %s (%d)", path, nline);
return EXIT_FAILURE;
}
}
fclose(file);
return EXIT_SUCCESS;
}
// Append to an array (assumes there is alway enough space ...)
static void array_append(const char **array, const char element[])
{
while (*array) {
array++;
}
*array = strdup(element);
}
// Free array elements
static void array_free(const char **array)
{
while (*array) {
free((void*) *array);
array += 1;
}
}
static int conf_set(const char opt[], const char val[])
{
const struct option_t *option;
option = find_option(opt);
if (option == NULL) {
log_error("Unknown parameter: %s", opt);
return EXIT_FAILURE;
}
if (option->num_args == 1 && val == NULL) {
log_error("Argument expected for option: %s", opt);
return EXIT_FAILURE;
}
if (option->num_args == 0 && val != NULL) {
log_error("No argument expected for option: %s", opt);
return EXIT_FAILURE;
}
switch (option->code)
{
case oAnnounce:
array_append(&g_announce_args[0], val);
break;
case oQueryTld:
return conf_str(opt, &gconf->query_tld, val);
case oPidFile:
return conf_str(opt, &gconf->pidfile, val);
case oPeerFile:
return conf_str(opt, &gconf->peerfile, val);
case oPeer:
return peerfile_add_peer(val);
case oVerbosity:
if (strcmp(val, "quiet") == 0) {
gconf->verbosity = VERBOSITY_QUIET;
} else if (strcmp(val, "verbose") == 0) {
gconf->verbosity = VERBOSITY_VERBOSE;
} else if (strcmp(val, "debug") == 0) {
gconf->verbosity = VERBOSITY_DEBUG;
} else {
log_error("Invalid argument for %s", opt);
return EXIT_FAILURE;
}
break;
#ifdef CMD
case oCmdDisableStdin:
gconf->cmd_disable_stdin = 1;
break;
case oCmdPath:
return conf_str(opt, &gconf->cmd_path, val);
#endif
#ifdef DNS
case oDnsPort:
return conf_port(opt, &gconf->dns_port, val);
case oDnsProxyEnable:
gconf->dns_proxy_enable = 1;
break;
case oDnsProxyServer:
return conf_str(opt, &gconf->dns_proxy_server, val);
#endif
#ifdef NSS
case oNssPath:
return conf_str(opt, &gconf->nss_path, val);
#endif
#ifdef TLS
case oTlsClientCert:
array_append(&g_tls_client_args[0], val);
break;
case oTlsServerCert:
array_append(&g_tls_server_args[0], val);
break;
#endif
case oConfig:
return conf_str(opt, &gconf->configfile, val);
case oIpv4:
case oIpv6:
if (gconf->af != AF_UNSPEC) {
log_error("IPv4 or IPv6 mode already set: %s", opt);
return EXIT_FAILURE;
}
gconf->af = (option->code == oIpv6) ? AF_INET6 : AF_INET;
break;
case oPort:
return conf_port(opt, &gconf->dht_port, val);
#ifdef LPD
case oLpdDisable:
gconf->lpd_disable = 1;
break;
#endif
#ifdef FWD
case oFwdDisable:
gconf->fwd_disable = 1;
break;
#endif
#ifdef __CYGWIN__
case oServiceInstall:
windows_service_install();
exit(0);
case oServiceRemove:
windows_service_remove();
exit(0);
case oServiceStart:
gconf->service_start = 1;
break;
#endif
case oIfname:
return conf_str(opt, &gconf->dht_ifname, val);
case oUser:
return conf_str(opt, &gconf->user, val);
case oDaemon:
gconf->is_daemon = 1;
break;
case oHelp:
printf("%s\n", kadnode_usage_str);
exit(0);
case oVersion:
printf("%s\n", kadnode_version_str);
exit(0);
#ifdef BOB
case oBobCreateKey:
exit(bob_create_key(val));
case oBobLoadKey:
return bob_load_key(val);
#endif
default:
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
// Load some values that depend on proper settings
int conf_load(void)
{
const char **args;
int rc = 0;
args = g_announce_args;
while (rc == 0 && *args) {
uint16_t port = gconf->dht_port;
char name[QUERY_MAX_SIZE] = { 0 };
int n = sscanf(*args, "%254[^:]:%hu", name, &port);
if (n == 1 || n == 2) {
rc = (EXIT_FAILURE == kad_announce(name, port, LONG_MAX));
} else {
log_error("Invalid announcement: %s", *args);
rc = 1;
}
args += 1;
}
#ifdef TLS
args = g_tls_client_args;
while (rc == 0 && *args) {
// Add Certificate Authority (CA) entries for the TLS client
rc = (EXIT_FAILURE == tls_client_add_ca(*args));
args += 1;
}
args = g_tls_server_args;
while (rc == 0 && *args) {
// Add SNI entries for the TLS server (e.g. my.cert,my.key)
char crt_file[128];
char key_file[128];
if (sscanf(*args, "%127[^,],%127[^,]", crt_file, key_file) == 2) {
rc = (EXIT_FAILURE == tls_server_add_sni(crt_file, key_file));
} else {
log_error("Invalid cert/key tuple: %s", *args);
rc = 1;
}
args += 1;
}
#endif
array_free(&g_announce_args[0]);
#ifdef TLS
array_free(&g_tls_client_args[0]);
array_free(&g_tls_server_args[0]);
#endif
return (rc != 0) ? EXIT_FAILURE : EXIT_SUCCESS;
}
int conf_setup(int argc, char **argv)
{
const char *opt;
const char *val;
int rc;
int i;
gconf = (struct gconf_t*) calloc(1, sizeof(struct gconf_t));
*gconf = ((struct gconf_t) {
.dht_port = -1,
.af = AF_UNSPEC,
#ifdef DNS
.dns_port = -1,
#endif
#ifdef DEBUG
.verbosity = VERBOSITY_DEBUG
#else
.verbosity = VERBOSITY_VERBOSE
#endif
});
for (i = 1; i < argc; ++i) {
opt = argv[i];
val = argv[i + 1];
if (val && val[0] != '-') {
// -x abc
rc = conf_set(opt, val);
i += 1;
} else {
// -x
rc = conf_set(opt, NULL);
}
if (rc == EXIT_FAILURE) {
return EXIT_FAILURE;
}
}
if (gconf->configfile) {
rc = conf_load_file(gconf->configfile);
if (rc == EXIT_FAILURE) {
return EXIT_FAILURE;
}
}
// Set defaults for unset settings
conf_defaults();
return EXIT_SUCCESS;
}
| 21.831206 | 101 | 0.656423 | [
"object"
] |
311e114dc66afa76b821c4634a6fb7404fbb8358 | 444 | c | C | vos/p2/sub/voos/test/tzvoos.c | NASA-AMMOS/VICAR | 4504c1f558855d9c6eaef89f4460217aa4909f8e | [
"BSD-3-Clause"
] | 16 | 2020-10-21T05:56:26.000Z | 2022-03-31T10:02:01.000Z | vos/p2/sub/voos/test/tzvoos.c | NASA-AMMOS/VICAR | 4504c1f558855d9c6eaef89f4460217aa4909f8e | [
"BSD-3-Clause"
] | null | null | null | vos/p2/sub/voos/test/tzvoos.c | NASA-AMMOS/VICAR | 4504c1f558855d9c6eaef89f4460217aa4909f8e | [
"BSD-3-Clause"
] | 2 | 2021-03-09T01:51:08.000Z | 2021-03-23T00:23:24.000Z | #include "xvmaininc.h"
#include "ftnbridge.h"
/************************************************************************/
/* Unit test C-bridge for TVOOS.F */
/************************************************************************/
void FTN_NAME(tzvoos)(icam,oloc)
int *icam; /* Input VO camera serial number. */
void *oloc; /* Output object space reseau locations stored
as (line,sample) pairs. */
{
zvoos(*icam,oloc);
}
| 29.6 | 74 | 0.432432 | [
"object"
] |
311ec7fe85959c1e2173cafccc3ac77b7937461d | 5,143 | h | C | Binding.Marketo.iOS/Native References/Marketo.framework/Versions/Current/Headers/Marketo.h | nventive/Binding.Marketo | 34f30092a3605953df70f998a892126c4e498eb3 | [
"Apache-2.0"
] | 5 | 2015-05-19T17:02:15.000Z | 2019-01-04T02:42:22.000Z | Binding.Marketo.iOS/Native References/Marketo.framework/Versions/Current/Headers/Marketo.h | nventive/Binding.Marketo | 34f30092a3605953df70f998a892126c4e498eb3 | [
"Apache-2.0"
] | 19 | 2015-04-20T16:17:16.000Z | 2022-01-25T12:35:43.000Z | Binding.Marketo.iOS/Native References/Marketo.framework/Versions/Current/Headers/Marketo.h | nventive/Binding.Marketo | 34f30092a3605953df70f998a892126c4e498eb3 | [
"Apache-2.0"
] | 6 | 2015-04-28T01:15:15.000Z | 2021-12-13T13:51:25.000Z | //
// Marketo.h
//
// Marketo Mobile Engagement framework
//
// Copyright (c) 2007-2016, Marketo, Inc. All rights reserved.
/*!
* @header Marketo.h
* @discussion The Marketo class is used to initialize the Marketo SDK.
*/
#import <Marketo/MKTSecuritySignature.h>
#import <Marketo/MarketoActionMetaData.h>
#import <Marketo/MarketoLead.h>
#import <UIKit/UIKit.h>
#import <UserNotifications/UserNotifications.h>
@interface Marketo : NSObject
/*!
* Returns the App Secret used to initialize Marketo SDK.
*/
@property (nonatomic, readonly) NSString *appSecret;
/*!
* Returns a singleton that is an instance of Marketo SDK.
* @return Singleton instance of class Marketo.
*/
+ (Marketo *)sharedInstance;
/*!
* Initializes Marketo SDK. This method should be called before calling any other Marketo SDK method.
* @param appSecret An app secret used to initialize the app
* @param munchkinID Used to connect to marketo end-point
*/
- (void)initializeWithMunchkinID:(NSString *)munchkinID appSecret:(NSString *)appSecret launchOptions:(NSDictionary *)launchOptions;
/*!
* The timeout interval, in seconds. If during a connection attempt the request remains idle for longer
* than the timeout interval, the request is considered to have timed out.
* The default timeout interval is 10 seconds.
*/
- (void)setTimeoutInterval:(NSInteger)seconds;
/*!
* Reports an action to the Marketo server
* @param actionName The action to be reported
* @param metaData Optional - Use the setter methods to send metadata
* ex:- {
* "Action Type":"Shopping",
* "Action Details":"RedShirt",
* "Action Metric":10,
* "Action Length":30
* }
*/
- (void)reportAction:(NSString *)actionName withMetaData:(MarketoActionMetaData *)metaData;
/*!
* This function updates a single lead record from Marketo.
* If a lead without a matching email isn't found in the database, a new one is created
* @param lead Marketo Lead Object
*/
- (void)associateLead:(MarketoLead *)lead;
/*!
* This function registers a Push Token.
* If a Push Token is already registered, just use registered token.
* @param deviceToken Token in form of NSData
*/
- (void)registerPushDeviceToken:(NSData *)deviceToken;
/*!
* This function unregisters a Push Token.
* If a Push Token is already registered, call unregisterPushDeviceToken to unregister token.
*/
- (void)unregisterPushDeviceToken;
/*!
* This tracks the push notification by sending an activity.
* @param userInfo Dictionary containing push payload
*/
- (void)trackPushNotification:(NSDictionary *)userInfo;
/*!
* This function allows you to handle a push notificaiton appropriatly.
* @param userInfo Dictionary containing push payload
*/
- (void)handlePushNotification:(NSDictionary *)userInfo;
/*!
* This function checks to see if a push token is already registered.
* @return true if push token has already been registered
*/
- (BOOL)isPushRegistered;
/*!
* Deep link handler for Marketo Url and scheema
* @param application The singleton app object
* @param url The URL resource to open. This resource can be a network resource or a file. For information about the Apple-registered URL schemes, see
* @param sourceApplication The bundle ID of the app that is requesting your app to open the URL (url)
* @param annotation A property list object supplied by the source app to communicate information to the receiving app.
*/
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation;
/*!
* Override System's didReceiveLocalNotification method to Operate PushNotification
* @param application The singleton app object
* @param notification UILocalNotification object supplied by the source app.
*/
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification;
/*!
* Override System's userNotificationCenter method to Operate PushNotification
* @param center The UNUserNotificationCenter object supplied by the source app.
* @param response UNNotificationResponse object supplied by the source app.
* @param completionHandler object supplied by the source app.
*/
- (void)userNotificationCenter:(UNUserNotificationCenter *)center
didReceiveNotificationResponse:(UNNotificationResponse *)response
withCompletionHandler:(void(^)())completionHandler;
/*!
* Set security Signature for Authentication
* @param token - The Security Token recived from client server
*/
- (void)setSecureSignature:(MKTSecuritySignature *)conf;
/*!
* Remove security Signature from SDK .
*
*/
- (void)removeSecureSignature;
/*!
* Returns a BOOL for the SDK enabled the Secure mode or not .
*
*/
- (BOOL)isSecureModeEnabled;
/*!
* Returns a Device ID used by SDK.
*
*/
- (NSString *)getDeviceId;
/*!
* Force report all data to Server.
*
*/
- (void)reportAll;
/*!
* This object should be initialized via shared instance
*/
- (id)init __attribute__ ((unavailable ("cannot use init for this class, use +(Marketo*)sharedInstance instead")));
@end
| 32.757962 | 150 | 0.739063 | [
"object"
] |
312a7856cf3a8a71d48596f88832093ade4533cb | 1,774 | h | C | include/lexer.h | jezzi23/code-indexer | 1133dac5c2dc05eb10063b9bc0c2735e5dd03142 | [
"MIT"
] | null | null | null | include/lexer.h | jezzi23/code-indexer | 1133dac5c2dc05eb10063b9bc0c2735e5dd03142 | [
"MIT"
] | null | null | null | include/lexer.h | jezzi23/code-indexer | 1133dac5c2dc05eb10063b9bc0c2735e5dd03142 | [
"MIT"
] | null | null | null |
#ifndef LEXER_H_
#define LEXER_H_
#include <vector>
#include "types.h"
#include "nfa.h"
// The regular expression documentation used by the lexer can be found
// in regex.h
//
// When adding multiple tokenize rules to the lexer, there will likely be
// conflicts which have to be solved by two rules in the particular order:
//
// 1) The longest possible matching token will be chosen.
// Example: [0-9]+ expression on content "51262" will match the whole
// sequence instead of "5", "1", ..., "2".
//
// 2) In case of a tie, the token for a rule added earlier
// to the lexing ruleset will be chosen.
struct LexingIterator {
const char* begin;
const char* itr;
const char* end;
const char* last_line_begin;
unsigned int line_count;
const char* token_begin;
unsigned int token_line;
unsigned int token_column;
};
class Token {
public:
Token();
Token(LexingIterator lex_itr, int token_id);
u64 index;
unsigned int length;
int id;
unsigned int line_count;
unsigned int column_count;
};
class Lexer {
public:
Lexer();
~Lexer();
void addRule(const Regexpr regexpr, int token_id);
void build();
void setStream(const char* input_data_begin, const char* input_data_end);
const char* begin();
Token nextToken();
void rewind();
private:
void rewindBackTo(LexingIterator& rewind_data, std::vector<unsigned int>& state_set);
LexingIterator lexing_data;
enum class LexingState : u8 {
INITIALIZATION_PHASE,
BUILD_PHASE,
QUERY_PHASE
} status;
// Lexer internally constructs NFA during build phase
// which gets replaced with a DFA for lexing phase.
union {
// DFA<unsigned int, int, 1 << 7>* dfa;
NFA<unsigned int, int, 1 << 7>* nfa;
};
};
#endif // LEXER_H_
| 21.634146 | 87 | 0.688839 | [
"vector"
] |
312b9efb05d936e1a4ac2e373743629e41193f90 | 8,187 | h | C | aws-cpp-sdk-medialive/include/aws/medialive/model/VideoSelector.h | ploki/aws-sdk-cpp | 17074e3e48c7411f81294e2ee9b1550c4dde842c | [
"Apache-2.0"
] | 2 | 2019-03-11T15:50:55.000Z | 2020-02-27T11:40:27.000Z | aws-cpp-sdk-medialive/include/aws/medialive/model/VideoSelector.h | ploki/aws-sdk-cpp | 17074e3e48c7411f81294e2ee9b1550c4dde842c | [
"Apache-2.0"
] | null | null | null | aws-cpp-sdk-medialive/include/aws/medialive/model/VideoSelector.h | ploki/aws-sdk-cpp | 17074e3e48c7411f81294e2ee9b1550c4dde842c | [
"Apache-2.0"
] | 1 | 2019-01-18T13:03:55.000Z | 2019-01-18T13:03:55.000Z | /*
* Copyright 2010-2017 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.
*/
#pragma once
#include <aws/medialive/MediaLive_EXPORTS.h>
#include <aws/medialive/model/VideoSelectorColorSpace.h>
#include <aws/medialive/model/VideoSelectorColorSpaceUsage.h>
#include <aws/medialive/model/VideoSelectorSettings.h>
#include <utility>
namespace Aws
{
namespace Utils
{
namespace Json
{
class JsonValue;
class JsonView;
} // namespace Json
} // namespace Utils
namespace MediaLive
{
namespace Model
{
/**
* Specifies a particular video stream within an input source. An input may have
* only a single video selector.<p><h3>See Also:</h3> <a
* href="http://docs.aws.amazon.com/goto/WebAPI/medialive-2017-10-14/VideoSelector">AWS
* API Reference</a></p>
*/
class AWS_MEDIALIVE_API VideoSelector
{
public:
VideoSelector();
VideoSelector(Aws::Utils::Json::JsonView jsonValue);
VideoSelector& operator=(Aws::Utils::Json::JsonView jsonValue);
Aws::Utils::Json::JsonValue Jsonize() const;
/**
* Specifies the colorspace of an input. This setting works in tandem with
* colorSpaceConversion to determine if any conversion will be performed.
*/
inline const VideoSelectorColorSpace& GetColorSpace() const{ return m_colorSpace; }
/**
* Specifies the colorspace of an input. This setting works in tandem with
* colorSpaceConversion to determine if any conversion will be performed.
*/
inline void SetColorSpace(const VideoSelectorColorSpace& value) { m_colorSpaceHasBeenSet = true; m_colorSpace = value; }
/**
* Specifies the colorspace of an input. This setting works in tandem with
* colorSpaceConversion to determine if any conversion will be performed.
*/
inline void SetColorSpace(VideoSelectorColorSpace&& value) { m_colorSpaceHasBeenSet = true; m_colorSpace = std::move(value); }
/**
* Specifies the colorspace of an input. This setting works in tandem with
* colorSpaceConversion to determine if any conversion will be performed.
*/
inline VideoSelector& WithColorSpace(const VideoSelectorColorSpace& value) { SetColorSpace(value); return *this;}
/**
* Specifies the colorspace of an input. This setting works in tandem with
* colorSpaceConversion to determine if any conversion will be performed.
*/
inline VideoSelector& WithColorSpace(VideoSelectorColorSpace&& value) { SetColorSpace(std::move(value)); return *this;}
/**
* Applies only if colorSpace is a value other than follow. This field controls how
* the value in the colorSpace field will be used. fallback means that when the
* input does include color space data, that data will be used, but when the input
* has no color space data, the value in colorSpace will be used. Choose fallback
* if your input is sometimes missing color space data, but when it does have color
* space data, that data is correct. force means to always use the value in
* colorSpace. Choose force if your input usually has no color space data or might
* have unreliable color space data.
*/
inline const VideoSelectorColorSpaceUsage& GetColorSpaceUsage() const{ return m_colorSpaceUsage; }
/**
* Applies only if colorSpace is a value other than follow. This field controls how
* the value in the colorSpace field will be used. fallback means that when the
* input does include color space data, that data will be used, but when the input
* has no color space data, the value in colorSpace will be used. Choose fallback
* if your input is sometimes missing color space data, but when it does have color
* space data, that data is correct. force means to always use the value in
* colorSpace. Choose force if your input usually has no color space data or might
* have unreliable color space data.
*/
inline void SetColorSpaceUsage(const VideoSelectorColorSpaceUsage& value) { m_colorSpaceUsageHasBeenSet = true; m_colorSpaceUsage = value; }
/**
* Applies only if colorSpace is a value other than follow. This field controls how
* the value in the colorSpace field will be used. fallback means that when the
* input does include color space data, that data will be used, but when the input
* has no color space data, the value in colorSpace will be used. Choose fallback
* if your input is sometimes missing color space data, but when it does have color
* space data, that data is correct. force means to always use the value in
* colorSpace. Choose force if your input usually has no color space data or might
* have unreliable color space data.
*/
inline void SetColorSpaceUsage(VideoSelectorColorSpaceUsage&& value) { m_colorSpaceUsageHasBeenSet = true; m_colorSpaceUsage = std::move(value); }
/**
* Applies only if colorSpace is a value other than follow. This field controls how
* the value in the colorSpace field will be used. fallback means that when the
* input does include color space data, that data will be used, but when the input
* has no color space data, the value in colorSpace will be used. Choose fallback
* if your input is sometimes missing color space data, but when it does have color
* space data, that data is correct. force means to always use the value in
* colorSpace. Choose force if your input usually has no color space data or might
* have unreliable color space data.
*/
inline VideoSelector& WithColorSpaceUsage(const VideoSelectorColorSpaceUsage& value) { SetColorSpaceUsage(value); return *this;}
/**
* Applies only if colorSpace is a value other than follow. This field controls how
* the value in the colorSpace field will be used. fallback means that when the
* input does include color space data, that data will be used, but when the input
* has no color space data, the value in colorSpace will be used. Choose fallback
* if your input is sometimes missing color space data, but when it does have color
* space data, that data is correct. force means to always use the value in
* colorSpace. Choose force if your input usually has no color space data or might
* have unreliable color space data.
*/
inline VideoSelector& WithColorSpaceUsage(VideoSelectorColorSpaceUsage&& value) { SetColorSpaceUsage(std::move(value)); return *this;}
/**
* The video selector settings.
*/
inline const VideoSelectorSettings& GetSelectorSettings() const{ return m_selectorSettings; }
/**
* The video selector settings.
*/
inline void SetSelectorSettings(const VideoSelectorSettings& value) { m_selectorSettingsHasBeenSet = true; m_selectorSettings = value; }
/**
* The video selector settings.
*/
inline void SetSelectorSettings(VideoSelectorSettings&& value) { m_selectorSettingsHasBeenSet = true; m_selectorSettings = std::move(value); }
/**
* The video selector settings.
*/
inline VideoSelector& WithSelectorSettings(const VideoSelectorSettings& value) { SetSelectorSettings(value); return *this;}
/**
* The video selector settings.
*/
inline VideoSelector& WithSelectorSettings(VideoSelectorSettings&& value) { SetSelectorSettings(std::move(value)); return *this;}
private:
VideoSelectorColorSpace m_colorSpace;
bool m_colorSpaceHasBeenSet;
VideoSelectorColorSpaceUsage m_colorSpaceUsage;
bool m_colorSpaceUsageHasBeenSet;
VideoSelectorSettings m_selectorSettings;
bool m_selectorSettingsHasBeenSet;
};
} // namespace Model
} // namespace MediaLive
} // namespace Aws
| 44.254054 | 150 | 0.729693 | [
"model"
] |
3134f045cecdedaa1b78dee9a98aac77a09d04d6 | 560 | h | C | MAze/Laberinto.h | IzaguirreYamile/MAze | d6e0f0a0ef1231dd53c32514c5b7f940ff801890 | [
"MIT"
] | 1 | 2021-09-02T21:19:19.000Z | 2021-09-02T21:19:19.000Z | MAze/Laberinto.h | IzaguirreYamile/MAze | d6e0f0a0ef1231dd53c32514c5b7f940ff801890 | [
"MIT"
] | null | null | null | MAze/Laberinto.h | IzaguirreYamile/MAze | d6e0f0a0ef1231dd53c32514c5b7f940ff801890 | [
"MIT"
] | null | null | null | #pragma once
#include "Celda.h"
#include <time.h>
#include <vector>
#include "Personaje.h"
#include <iostream>
using namespace std;
class Laberinto
{
public:
int cols, rows;
vector<Celda*>grid;
Celda* current;
vector<Celda*>stack;
public:
Laberinto() ;
void Iniciar(Graphics^ g) ;
void Dibujar(Graphics^ g) ;
Celda* Rectornar_celda(int i) ;
Celda* Verificar_Vecino(Celda* celda) ;
int index(int i, int j) ;
void Remover_Pared(Celda* a, Celda* b);
int retornar_cant();
void Dibujar_Current(Graphics^g) ;
Celda* colision(Rectangle per);
};
| 17.5 | 40 | 0.705357 | [
"vector"
] |
3138199559e47adf2e7315efd770c08bbaa5ecd9 | 7,862 | h | C | src/core/qgstracer.h | dyna-mis/Hilabeling | cb7d5d4be29624a20c8a367162dbc6fd779b2b52 | [
"MIT"
] | null | null | null | src/core/qgstracer.h | dyna-mis/Hilabeling | cb7d5d4be29624a20c8a367162dbc6fd779b2b52 | [
"MIT"
] | null | null | null | src/core/qgstracer.h | dyna-mis/Hilabeling | cb7d5d4be29624a20c8a367162dbc6fd779b2b52 | [
"MIT"
] | 1 | 2021-12-25T08:40:30.000Z | 2021-12-25T08:40:30.000Z | /***************************************************************************
qgstracer.h
--------------------------------------
Date : January 2016
Copyright : (C) 2016 by Martin Dobias
Email : wonder dot sk at gmail dot com
***************************************************************************
* *
* 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. *
* *
***************************************************************************/
#ifndef QGSTRACER_H
#define QGSTRACER_H
class QgsVectorLayer;
#include "qgis_core.h"
#include <QSet>
#include <QVector>
#include <memory>
#include "qgsfeatureid.h"
#include "qgscoordinatereferencesystem.h"
#include "qgsrectangle.h"
#include "qgsgeometry.h"
struct QgsTracerGraph;
class QgsFeatureRenderer;
class QgsRenderContext;
/**
* \ingroup core
* Utility class that construct a planar graph from the input vector
* layers and provides shortest path search for tracing of existing
* features.
*
* \since QGIS 2.14
*/
class CORE_EXPORT QgsTracer : public QObject
{
Q_OBJECT
public:
/**
* Constructor for QgsTracer.
*/
QgsTracer();
~QgsTracer() override;
//! Gets layers used for tracing
QList<QgsVectorLayer *> layers() const { return mLayers; }
//! Sets layers used for tracing
void setLayers( const QList<QgsVectorLayer *> &layers );
/**
* Returns the CRS used for tracing.
* \see setDestinationCrs()
*/
QgsCoordinateReferenceSystem destinationCrs() const { return mCRS; }
/**
* Sets the \a crs and transform \a context used for tracing.
* \see destinationCrs()
*/
void setDestinationCrs( const QgsCoordinateReferenceSystem &crs, const QgsCoordinateTransformContext &context );
/**
* Sets the \a renderContext used for tracing only on visible features.
* \since QGIS 3.4
*/
void setRenderContext( const QgsRenderContext *renderContext );
//! Gets extent to which graph's features will be limited (empty extent means no limit)
QgsRectangle extent() const { return mExtent; }
//! Sets extent to which graph's features will be limited (empty extent means no limit)
void setExtent( const QgsRectangle &extent );
/**
* Gets offset in map units that should be applied to the traced paths returned from findShortestPath().
* Positive offset for right side, negative offset for left side.
* \since QGIS 3.0
*/
double offset() const { return mOffset; }
/**
* Set offset in map units that should be applied to the traced paths returned from findShortestPath().
* Positive offset for right side, negative offset for left side.
* \since QGIS 3.0
*/
void setOffset( double offset );
/**
* Gets extra parameters for offset curve algorithm (used when offset is non-zero)
* \since QGIS 3.0
*/
void offsetParameters( int &quadSegments SIP_OUT, int &joinStyle SIP_OUT, double &miterLimit SIP_OUT );
/**
* Set extra parameters for offset curve algorithm (used when offset is non-zero)
* \since QGIS 3.0
*/
void setOffsetParameters( int quadSegments, int joinStyle, double miterLimit );
//! Gets maximum possible number of features in graph. If the number is exceeded, graph is not created.
int maxFeatureCount() const { return mMaxFeatureCount; }
//! Gets maximum possible number of features in graph. If the number is exceeded, graph is not created.
void setMaxFeatureCount( int count ) { mMaxFeatureCount = count; }
/**
* Build the internal data structures. This may take some time
* depending on how big the input layers are. It is not necessary
* to call this method explicitly - it will be called by findShortestPath()
* if necessary.
*/
bool init();
//! Whether the internal data structures have been initialized
bool isInitialized() const { return static_cast< bool >( mGraph ); }
/**
* Whether there was an error during graph creation due to noding exception,
* indicating some input data topology problems
* \since QGIS 2.16
*/
bool hasTopologyProblem() const { return mHasTopologyProblem; }
//! Possible errors that may happen when calling findShortestPath()
enum PathError
{
ErrNone, //!< No error
ErrTooManyFeatures, //!< Max feature count threshold was reached while reading features
ErrPoint1, //!< Start point cannot be joined to the graph
ErrPoint2, //!< End point cannot be joined to the graph
ErrNoPath, //!< Points are not connected in the graph
};
/**
* Given two points, find the shortest path and return points on the way.
* The optional "error" argument may receive error code (PathError enum) if it is not NULLPTR
* \returns array of points - trace of linestrings of other features (empty array one error)
*/
QVector<QgsPointXY> findShortestPath( const QgsPointXY &p1, const QgsPointXY &p2, PathError *error SIP_OUT = nullptr );
//! Find out whether the point is snapped to a vertex or edge (i.e. it can be used for tracing start/stop)
bool isPointSnapped( const QgsPointXY &pt );
protected:
/**
* Allows derived classes to setup the settings just before the tracer is initialized.
* This allows the configuration to be set in a lazy way only when it is really necessary.
* Default implementation does nothing.
*/
virtual void configure() {}
protected slots:
//! Destroy the existing graph structure if any (de-initialize)
void invalidateGraph();
private:
bool initGraph();
private slots:
void onFeatureAdded( QgsFeatureId fid );
void onFeatureDeleted( QgsFeatureId fid );
void onGeometryChanged( QgsFeatureId fid, const QgsGeometry &geom );
void onAttributeValueChanged( QgsFeatureId fid, int idx, const QVariant &value );
void onDataChanged( );
void onStyleChanged( );
void onLayerDestroyed( QObject *obj );
private:
//! Graph data structure for path searching
std::unique_ptr< QgsTracerGraph > mGraph;
//! Input layers for the graph building
QList<QgsVectorLayer *> mLayers;
//! Destination CRS in which graph is built and tracing done
QgsCoordinateReferenceSystem mCRS;
//! Coordinate transform context
QgsCoordinateTransformContext mTransformContext;
//! Render context
std::unique_ptr<QgsRenderContext> mRenderContext;
//! Extent for graph building (empty extent means no limit)
QgsRectangle mExtent;
//! Offset in map units that should be applied to the traced paths
double mOffset = 0;
//! Offset parameter: Number of segments (approximation of circle quarter) when using round join style
int mOffsetSegments = 8;
//! Offset parameter: Join style (1 = round, 2 = miter, 3 = bevel)
int mOffsetJoinStyle = 2;
//! Offset parameter: Limit for miter join style
double mOffsetMiterLimit = 5.;
/**
* Limit of how many features can be in the graph (0 means no limit).
* This is to avoid possibly long graph preparation for complicated layers
*/
int mMaxFeatureCount = 0;
/**
* A flag indicating that there was an error during graph creation
* due to noding exception, indicating some input data topology problems
*/
bool mHasTopologyProblem = false;
};
#endif // QGSTRACER_H
| 36.738318 | 123 | 0.646146 | [
"render",
"vector",
"transform"
] |
ebdb60ba69aa38b4124355df00fc72de0ac96a5d | 8,220 | h | C | motioncorr_v2.1/src/SP++3/include/dgt_usefftw-impl.h | cianfrocco-lab/Motion-correction | c77ee034bba2ef184837e070dde43f75d8a4e1e7 | [
"MIT"
] | 11 | 2015-12-21T19:47:53.000Z | 2021-01-21T02:58:43.000Z | src/SP++3/include/dgt_usefftw-impl.h | wjiang/motioncorr | 14ed37d1cc72e55d1592e78e3dda758cd46a3698 | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | 5 | 2017-04-24T12:26:42.000Z | 2020-06-29T11:43:34.000Z | src/SP++3/include/dgt_usefftw-impl.h | wjiang/motioncorr | 14ed37d1cc72e55d1592e78e3dda758cd46a3698 | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | 9 | 2016-04-26T10:14:20.000Z | 2020-10-14T07:34:59.000Z | /*
* Copyright (c) 2008-2011 Zhang Ming (M. Zhang), zmjerry@163.com
*
* 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 or any later version.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* 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. A copy of the GNU General Public License is available at:
* http://www.fsf.org/licensing/licenses
*/
/*****************************************************************************
* dgt_usefftw-impl.h
*
* Implementation for Discrete Gabor Transform by using FFTW.
*
* Zhang Ming, 2010-03, Xi'an Jiaotong University.
*****************************************************************************/
/**
* Return the daul function of input window "g".
*/
template <typename Type>
Vector<Type> daulFFTW( const Vector<Type> &gn, int N, int dM )
{
int L = gn.size(),
NL = 2*L-N;
Vector<Type> hn(L);
Vector<Type> gg = wextend( gn, NL, "right", "zpd" );
// coefficient matrix and constant vector
Matrix<Type> H(NL/N,L/dM);
Vector<Type> u(NL/N);
u[0] = Type(1.0/N);
// evaluate matrix H
for( int k=0; k<dM; ++k )
{
for( int q=0; q<NL/N; ++q )
for( int p=0; p<L/dM; ++p )
{
int index = mod( k+p*dM+q*N, NL );
H[q][p] = gg[index];
}
// calculate the kth part value of h
Vector<Type> tmp = trMult( H, luSolver( multTr(H,H), u ) );
// Vector<Type> tmp = tsvd( H, u );
for( int i=0; i<tmp.dim(); ++i )
hn[k+i*dM] = tmp[i];
}
return hn;
}
/**
* Compute the discrete Gabor transform of "signal". The coeffitions are
* stored in "coefs", a Ls+Lw by Lw (Ls: lengthof "signsl", Lw:
* length of "window") matrix. The row represents frequency ordinate
* and column represents the time ordinate.
*/
template <typename Type>
Matrix< complex<Type> > dgtFFTW( const Vector<Type> &signal,
const Vector<Type> &anaWin,
int N, int dM, const string &mode )
{
int Ls = signal.dim();
int Lw = anaWin.dim();
int M = (Ls+Lw)/dM;
Vector<Type> sn = wextend( signal, Lw, "both", mode );
Matrix< complex<Type> > coefs(N/2+1,M);
Vector<Type> segment(Lw);
Vector< complex<Type> > segDFT(Lw/2+1);
Vector< complex<Type> > tmp(N/2+1);
complex<Type> W = polar( Type(1), Type(-2*PI/N) );
for( int m=0; m<M; ++m )
{
// intercept signal by window function
for( int i=0; i<Lw; ++i )
segment[i] = sn[i+m*dM]*anaWin[i];
// Fourier transform
fftw( segment, segDFT );
// calculate the mth culumn coefficients
for( int n=0; n<N/2+1; ++n )
tmp[n] = pow(W,n*m*dM) * segDFT[n*Lw/N];
coefs.setColumn( tmp, m );
}
return coefs;
}
/**
* Compute the inverse discrete Gabor transform from "coefs".
*/
template <typename Type>
Vector<Type> idgtFFTW( const Matrix< complex<Type> > &coefs,
const Vector<Type> &synWin,
int N, int dM )
{
int M = coefs.cols();
int Lw = synWin.size();
int Ls = dM*M-Lw;
// reallocate for signal and initialize it by "0"
Vector<Type> signal(Ls);
Matrix<Type> idftCoefs(N,M);
Vector<Type> sn(N);
Vector< complex<Type> > Sk(N/2+1);
for( int i=0; i<M; ++i )
{
Sk = coefs.getColumn(i);
ifftw( Sk, sn );
sn *= Type(N);
idftCoefs.setColumn( sn, i );
}
// compulate the ith element of signal
for( int i=0; i<Ls; ++i )
{
int p = ceil(i+1, dM);
for( int m=p; m<p+Lw/dM; ++m )
{
int n = mod(i,N);
signal[i] += idftCoefs[n][m]*synWin[Lw-m*dM+i];
}
}
/*======================replace line 107 to 125================================
complex<Type> W = polar( Type(1), Type(2*PI/N) );
// compulate the ith element of sig
for( int i=0; i<Ls; ++i )
{
int p = ceil( i+1, dM );
for( int m=p; m<p+Lw/dM; ++m )
{
for( int n=0; n<N/2+1; ++n )
signal[i] += real( coefs[n][m]*
synWin[Lw-m*dM+i]*pow(W,i*n) );
for( int n=N/2+1; n<N; ++n )
signal[i] += real( conj(coefs[N-n][m])*
synWin[Lw-m*dM+i]*pow(W,i*n) );
}
}
=============================================================================*/
return signal;
}
// template <typename Type>
// Matrix< complex<Type> > dgt( const Vector<Type> &signal, const Vector<Type> &anaWin,
// int N, int dM, const string &mode = "zpd" )
// {
// int Ls = signal.dim();
// int Lw = anaWin.dim();
// int M = (Ls+Lw)/dM;
//
// Vector<Type> sn = wextend( signal, Lw, "both", mode );
//
// Matrix< complex<Type> > coefs(N/2+1,M);
// Vector<Type> segment(Lw);
// Vector< complex<Type> > segDFT(Lw/2+1);
// Vector< complex<Type> > tmp(N/2+1);
// complex<Type> W = polar( Type(1), Type(-2*PI/N) );
//
// fftw_plan r2cP;
// for( int m=0; m<M; ++m )
// {
// // intercept signal by window function
// for( int i=0; i<Lw; ++i )
// segment[i] = sn[i+m*dM]*anaWin[i];
//
// // Fourier transform
// r2cP = fftw_plan_dft_r2c_1d( segment.size(), segment.begin(),
// reinterpret_cast<fftw_complex*>(segDFT.begin()),
// FFTW_ESTIMATE );
// fftw_execute( r2cP );
//
// // calculate the mth culumn coefficients
// for( int n=0; n<N/2+1; ++n )
// tmp[n] = pow(W,n*m*dM) * segDFT[n*Lw/N];
//
// coefs.setColumn(tmp, m+1);
// }
// fftw_destroy_plan( r2cP );
//
// return coefs;
// }
//
//
// template <typename Type>
// Vector<Type> idgt( const Matrix< complex<Type> > &coefs, const Vector<Type> &synWin,
// int N, int dM )
// {
// int M = coefs.cols();
// int Lw = synWin.size();
// int Ls = dM*M-Lw;
//
// // reallocate for signal and initialize it by "0"
// Vector<Type> signal(Ls);
// Matrix<Type> idftCoefs(N,M);
// Vector<Type> sn(N);
// Vector< complex<double> > Sk(N/2+1);
//
// fftw_plan c2rP;
// for( int i=0; i<M; ++i )
// {
// Sk = coefs.getColumn(i+1);
// c2rP = fftw_plan_dft_c2r_1d( N,
// reinterpret_cast<fftw_complex*>(Sk.begin()),
// sn.begin(), FFTW_ESTIMATE );
// fftw_execute( c2rP );
//
// idftCoefs.setColumn( sn, i+1 );
// }
// fftw_destroy_plan( c2rP );
//
// // compulate the ith element of signal
// for( int i=0; i<Ls; ++i )
// {
// int p = ceil(i+1, dM);
// for( int m=p; m<p+Lw/dM; ++m )
// {
// int n = mod(i,N);
// signal[i] += idftCoefs[n][m]*synWin[Lw-m*dM+i];
// }
// }
// return signal;
// }
| 31.737452 | 91 | 0.485766 | [
"vector",
"transform"
] |
ebe04031f8ad6196778b87af865f01cbb782207a | 5,279 | c | C | DmfSamples/VHidMini2Dmf/User/DmfInterface.c | williambernardet/DMF | 225c72d5434400409487db3803328a0e51c3a7cf | [
"MIT"
] | 130 | 2018-08-07T11:36:38.000Z | 2019-04-12T00:17:37.000Z | DmfSamples/VHidMini2Dmf/User/DmfInterface.c | QPC-database/DMF | 3a532fd30abf1f37d8d02c2f9ee84e065200c8fa | [
"MIT"
] | 32 | 2019-05-20T17:04:44.000Z | 2022-03-30T20:40:18.000Z | DmfSamples/VHidMini2Dmf/User/DmfInterface.c | QPC-database/DMF | 3a532fd30abf1f37d8d02c2f9ee84e065200c8fa | [
"MIT"
] | 50 | 2019-06-06T09:20:13.000Z | 2022-03-23T04:23:23.000Z | /*++
Copyright (c) Microsoft Corporation. All rights reserved.
THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY
KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR
PURPOSE.
Module Name:
DmfInterface.c
Abstract:
VHidMini2DmfU Sample: DMF version of VHIDMINI2 Sample (User-mode).
Environment:
User-mode
--*/
#include "DmfModules.Template.h"
#include "Trace.h"
#include "DmfInterface.tmh"
// DMF: These lines provide default DriverEntry/AddDevice/DriverCleanup functions.
//
DRIVER_INITIALIZE DriverEntry;
EVT_WDF_DRIVER_DEVICE_ADD VHidMini2DmfEvtDeviceAdd;
EVT_WDF_OBJECT_CONTEXT_CLEANUP VHidMini2DmfEvtDriverContextCleanup;
EVT_DMF_DEVICE_MODULES_ADD DmfDeviceModulesAdd;
/*WPP_INIT_TRACING(); (This comment is necessary for WPP Scanner.)*/
#pragma code_seg("INIT")
DMF_DEFAULT_DRIVERENTRY(DriverEntry,
VHidMini2DmfEvtDriverContextCleanup,
VHidMini2DmfEvtDeviceAdd,
L"VHidMini2DmfU")
#pragma code_seg()
typedef struct
{
// Allows this driver to send requests to the next driver down the stack.
//
DMFMODULE DmfModuleVirtualHidDeviceMiniSample;
} DEVICE_CONTEXT, *PDEVICE_CONTEXT;
WDF_DECLARE_CONTEXT_TYPE_WITH_NAME(DEVICE_CONTEXT, DeviceContextGet)
#pragma code_seg("PAGED")
DMF_DEFAULT_DRIVERCLEANUP(VHidMini2DmfEvtDriverContextCleanup)
_Use_decl_annotations_
NTSTATUS
VHidMini2DmfEvtDeviceAdd(
_In_ WDFDRIVER Driver,
_Inout_ PWDFDEVICE_INIT DeviceInit
)
{
NTSTATUS ntStatus;
WDFDEVICE device;
PDMFDEVICE_INIT dmfDeviceInit;
DMF_EVENT_CALLBACKS dmfCallbacks;
WDF_OBJECT_ATTRIBUTES objectAttributes;
UNREFERENCED_PARAMETER(Driver);
PAGED_CODE();
TraceEvents(TRACE_LEVEL_INFORMATION, TRACE_DEVICE, "-->%!FUNC!");
dmfDeviceInit = DMF_DmfDeviceInitAllocate(DeviceInit);
// All DMF drivers must call this function even if they do not support PnP Power callbacks.
// (In this case, this driver does support a PnP Power callback.)
//
DMF_DmfDeviceInitHookPnpPowerEventCallbacks(dmfDeviceInit,
NULL);
// All DMF drivers must call this function even if they do not support File Object callbacks.
//
DMF_DmfDeviceInitHookFileObjectConfig(dmfDeviceInit,
NULL);
// All DMF drivers must call this function even if they do not support Power Policy callbacks.
//
DMF_DmfDeviceInitHookPowerPolicyEventCallbacks(dmfDeviceInit,
NULL);
// This is a filter driver that loads on MSHIDUMDF driver.
//
WdfFdoInitSetFilter(DeviceInit);
// DMF Client drivers that are filter drivers must also make this call.
//
DMF_DmfFdoSetFilter(dmfDeviceInit);
// Define a device context type.
//
WDF_OBJECT_ATTRIBUTES_INIT_CONTEXT_TYPE(&objectAttributes,
DEVICE_CONTEXT);
// Create the Client driver's WDFDEVICE.
//
ntStatus = WdfDeviceCreate(&DeviceInit,
&objectAttributes,
&device);
if (! NT_SUCCESS(ntStatus))
{
goto Exit;
}
// Create the DMF Modules this Client driver will use.
//
dmfCallbacks.EvtDmfDeviceModulesAdd = DmfDeviceModulesAdd;
DMF_DmfDeviceInitSetEventCallbacks(dmfDeviceInit,
&dmfCallbacks);
ntStatus = DMF_ModulesCreate(device,
&dmfDeviceInit);
if (! NT_SUCCESS(ntStatus))
{
goto Exit;
}
Exit:
if (dmfDeviceInit != NULL)
{
DMF_DmfDeviceInitFree(&dmfDeviceInit);
}
TraceEvents(TRACE_LEVEL_INFORMATION, TRACE_CALLBACK, "<--%!FUNC! ntStatus=%!STATUS!", ntStatus);
return ntStatus;
}
#pragma code_seg()
#pragma code_seg("PAGED")
_IRQL_requires_max_(PASSIVE_LEVEL)
VOID
DmfDeviceModulesAdd(
_In_ WDFDEVICE Device,
_In_ PDMFMODULE_INIT DmfModuleInit
)
/*++
Routine Description:
Add all the DMF Modules used by this driver.
Arguments:
Device - WDFDEVICE handle.
DmfModuleInit - Opaque structure to be passed to DMF_DmfModuleAdd.
Return Value:
NTSTATUS
--*/
{
PDEVICE_CONTEXT deviceContext;
DMF_MODULE_ATTRIBUTES moduleAttributes;
DMF_CONFIG_VirtualHidMiniSample moduleConfigVirtualHidDeviceMiniSample;
UNREFERENCED_PARAMETER(Device);
PAGED_CODE();
deviceContext = DeviceContextGet(Device);
// VirtualHidDeviceMiniSample
// --------------------------
//
DMF_CONFIG_VirtualHidMiniSample_AND_ATTRIBUTES_INIT(&moduleConfigVirtualHidDeviceMiniSample,
&moduleAttributes);
DMF_DmfModuleAdd(DmfModuleInit,
&moduleAttributes,
WDF_NO_OBJECT_ATTRIBUTES,
&deviceContext->DmfModuleVirtualHidDeviceMiniSample);
}
#pragma code_seg()
| 28.38172 | 101 | 0.652017 | [
"object"
] |
ebe08adaf22224417d650d9c77ab4fdb0e8c7c16 | 12,597 | h | C | lib/ErrorContext.h | sten13/libfc | dccfab49a2cc2112bc6a20315a842ee92b31bcd4 | [
"Unlicense"
] | 4 | 2017-01-04T12:08:45.000Z | 2021-11-22T13:38:07.000Z | lib/ErrorContext.h | sten13/libfc | dccfab49a2cc2112bc6a20315a842ee92b31bcd4 | [
"Unlicense"
] | 1 | 2017-05-31T13:51:06.000Z | 2017-05-31T13:51:06.000Z | lib/ErrorContext.h | sten13/libfc | dccfab49a2cc2112bc6a20315a842ee92b31bcd4 | [
"Unlicense"
] | 4 | 2016-04-07T09:15:59.000Z | 2021-06-24T13:32:15.000Z | /* Hi Emacs, please use -*- mode: C++; -*- */
/* Copyright (c) 2011-2014 ETH Zürich. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the names of ETH Zürich nor the names of other contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL ETH
* ZURICH BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* @file
* @author Stephan Neuhaus <neuhaust@tik.ee.ethz.ch>
*/
#ifndef _libfc_ERRORCONTEXT_H_
# define _libfc_ERRORCONTEXT_H_
# include <sstream>
# if defined(_libfc_HAVE_LOG4CPLUS_)
# include <log4cplus/logger.h>
# endif /* defined(_libfc_HAVE_LOG4CPLUS_) */
# include "Error.h"
# include "InputSource.h"
# include <sstream>
namespace libfc {
/** Returns a shared pointer to an ErrorContext object.
*
* Initialising and returning such objects is (a) tedious, and (b)
* always the same. This macro takes away some of the pain.
*
* @param severity the severity as per ErrorContext::error_severity_t
* @param error the error as per Error::error_t
* @param message_stream an error message, assemblee as a stream
* @param system_errno the value of errno, or 0
* @param is the input stream in which the error was detected
*/
# define libfc_RETURN_ERROR(severity, error, message_stream, \
system_errno, is, message, size, off) \
do { \
std::stringstream ss; \
\
ss << message_stream; \
/* If you edit this macro, please preserve the space \
* between '<' and ':'. Some people thought it would \
* be funny to invent an abomination called a trigraph. \
* Using trigraphs, '<:' is actually synonymous with \
* '['. Yeah, I know. \
*/ \
return std::shared_ptr< ::libfc::ErrorContext>( \
new ErrorContext(ErrorContext::severity, Error(Error::error), \
system_errno, ss.str().c_str(), is, message, \
size, off)); \
} while (0)
/** Returns an ErrorContext signaling success. */
# define libfc_RETURN_OK() \
do { \
/* If you edit this macro, please preserve the space \
* between '<' and ':'. Some people thought it would \
* be funny to invent an abomination called a trigraph. \
* Using trigraphs, '<:' is actually synonymous with \
* '['. Yeah, I know. \
*/ \
return std::shared_ptr< ::libfc::ErrorContext>(0); \
} while (0)
/** An error context.
*
* This class is used to show upper layers where in the processing
* of a particular InputSource an error happened and what kind of
* error it is. For this purpose, an ErrorContext object contains
* the error that happened, the value of errno, and the InputSource
* in which the error occurred.
*
* The InputSource object also holds information about the location
* of the error, in the form of offset counters. (Depending on the
* type of input source, the offset may or may not be meaningful.
* For example, for message-based input sources, such as
* UDPInputSource, the offset of the current message makes no sense,
* since there is no message stream.)
*
* Many of the functions that parse messages return a pointer to an
* ErrorContext. That pointer is non-0 if an error occurred, and 0
* otherwise. The ContentHandler methods are called from a
* MessageStreamParser object's parse() function that in turn
* returns such a pointer. The idea is that all functions where
* potential errors may occur return an ErrorContext pointer. This
* then causes the caller to stop what it's doing, potentially
* augmenting the ErrorContext object with additional information
* and passing it to the caller's caller and so on, right up to the
* initial caller of parse().
*
* If a method detects an error itself (as opposed to calling a
* method that returns a non-0 ErrorContext pointer), you should use
* the libfc_RETURN_ERROR macro somewhat like this (see the
* documentation for error_severity_t below and Error::error_t in
* the Error class):
*
* @code
* uint8_t* message = ...;
* uint16_t size = ...;
* uint16_t off = ...;
*
* if (some_error_condition) {
* libfc_RETURN_ERROR(recoverable, short_header,
* "Expected " << kMessageHeaderSize
* << " bytes in header, got "
* << nbytes,
* system_errno, is, message, size, off);
* }
* @endcode
*
* If you call a function that returns a non-zero ErrorContext
* pointer, you should do something like this:
*
* @code
* std::shared_ptr<ErrorContext> p = func(message + offset);
* if (p != 0) {
* p->set_message(message, size);
* p->set_offset(p->get_offset() + offset);
* return p;
* }
* @endcode
*
* In this example, we assumed that func() didn't have access to the
* entire message, so we augmented the error context object and
* adjusted the offset.
*
* It is expected that occurrences like these willl be rare, so it's
* perfectly OK if the code in the error handler is somewhat slow.
* Don't try to write clever code, @em{especially} not in error
* handling.
*/
class ErrorContext {
public:
/** The severity of the error. */
enum error_severity_t {
/** Everything is hunky dory. */
fine,
/** Something is weird with the message, even though it's not an
* error. This could be a message that purports to be from 2301
* (because, let's face it, if we haven't replaced IPFIX by the
* 24th century, something is VERY wrong) or a message that's
* supposedly from January 1, 1970. */
warning,
/** The message has an error and must be discarded, but the next
* message in the stream may be recoverable. This could happen
* if the message contained a syntax error but the stream itself
* seems to be OK. (For example, it's entirely possible that a
* bit or two in a large number of large files could flip simply
* through bit rot.) */
recoverable,
/** The entire message stream must be discarded. This can
* happen when a read operation returns an operating system
* error. */
fatal
};
/** Creates an ErrorContext object.
*
* @param severity the error's severity
* @param e the error that occurred
* @param system_errno the value of errno after the error was
* detected (this may be zero)
* @param explanation a message further identifying and/or explaining
* the error
* @param is the input source in which the error was
* detected. It's OK if this parameter is 0; the InputSource can
* be set later.
* @param message the message that caused the error. The
* constructor will make a copy of the message. It's OK if this
* parameter is 0. The message can be set later.
* @param size the size of the message. If the message parameter
* is 0, this value will be ignored.
* @param off the offset at which the error was detected. This
* value will not be ignored, even is message is 0. The reason
* is that offsets will be built gradually, until the
* ErrorContext has percolated upward through the stack to the
* point where the message is wholly visible.
*/
ErrorContext(error_severity_t severity, Error e,
int system_errno, const char* explanation,
InputSource* is, const uint8_t* message,
uint16_t size, uint16_t off);
/** Don't copy ErrorContext-s. */
ErrorContext(const ErrorContext& rhs) = delete;
/** Don't assign ErrorContext-s. */
ErrorContext& operator=(const ErrorContext& rhs) = delete;
/** Destructor. */
~ErrorContext();
/** Returns the error.
*
* @return the error that occurred
*/
const Error::error_t get_error() const;
/** Returns the value of errno when the error occurred.
*
* @return the saved value of errno (might be zero)
*/
const int get_system_errno() const;
/** Returns the explanation.
*
* @return the explanation given in the constructor
*/
const char* get_explanation() const;
/** Returns the input stream.
*
* @return the input stream in which the error occurred. May
* return 0.
*/
InputSource* get_input_source() const;
/** Sets the input source.
*
* This method has an effect only if the input source is not
* already set.
*
* @param is the new input source
*/
void set_input_source(InputSource* is);
/** Returns the message that caused the error.
*
* This returns a pointer to the beginning of a copy of the
* message that caused the error. If the message has not yet been
* set, this method may well return 0. The size of the message
* thus returned can be inquired with get_size().
*
* @return a pointer to the beginning of the erroneous message
*/
const uint8_t* get_message() const;
/** Sets the message that caused the error.
*
* This method causes a copy of the argument to be made, so it's
* safe to delete the message argument after constructing an
* ErrorContext object or to let the buffer go out of scope.
*
* This method has no effect if the message has already been set,
* either through the constructor or through a previous call to
* set_message().
*
* @param message the message that caused the error
* @param size the size of the message
*/
void set_message(const uint8_t* message, uint16_t size);
/** Gets the offset into the message at which the error occurred.
*
* @return offset into the message at which the error occurred
*/
const uint16_t get_offset() const;
/** Sets the offset into the message at which the error occurred.
*
* @param off offset into the message at which the error occurred
*/
void set_offset(uint16_t off);
/** Returns a string representation of this error.
*
* @return a string representation of this error
*/
const std::string to_string() const;
private:
error_severity_t severity;
Error e;
int system_errno;
const char* explanation;
InputSource* is;
const uint8_t* message;
uint16_t size;
uint16_t off;
#if defined(_libfc_HAVE_LOG4CPLUS_)
log4cplus::Logger logger;
#endif /* defined(_libfc_HAVE_LOG4CPLUS_) */
};
} // namespace libfc
#endif /* _libfc_ERRORCONTEXT_H_ */
| 39.365625 | 78 | 0.625228 | [
"object"
] |
ebe1c03b83684fdf7005862c7e07639e58ca0d78 | 1,419 | h | C | include/painting2/Mesh.h | xzrunner/painting2 | c16e0133adf27a877b40b8fce642b5a42e043d09 | [
"MIT"
] | null | null | null | include/painting2/Mesh.h | xzrunner/painting2 | c16e0133adf27a877b40b8fce642b5a42e043d09 | [
"MIT"
] | null | null | null | include/painting2/Mesh.h | xzrunner/painting2 | c16e0133adf27a877b40b8fce642b5a42e043d09 | [
"MIT"
] | null | null | null | #pragma once
#include <cu/cu_stl.h>
#include <SM_Rect.h>
#include <boost/noncopyable.hpp>
#include <memory>
namespace pm2 { class Mesh; class MeshTransform; }
struct rg_skeleton_pose;
struct rg_tl_deform_state;
namespace pt2
{
template<typename T>
class Mesh : boost::noncopyable
{
public:
Mesh();
Mesh(const T& base, float width, float height);
#ifdef S2_MESH_VIRTUAL
virtual ~Mesh();
#else
~Mesh();
#endif // S2_MESH_VIRTUAL
const T& GetBaseSymbol() const { return m_base; }
float GetWidth() const { return m_width; }
float GetHeight() const { return m_height; }
float GetNodeRadius() const { return m_node_radius; }
void DumpToTriangles(CU_VEC<sm::vec2>& vertices, CU_VEC<sm::vec2>& texcoords,
CU_VEC<int>& triangles) const;
void LoadFromTransform(const pm2::MeshTransform& transform);
void StoreToTransforom(pm2::MeshTransform& transform) const;
sm::rect GetRegion() const;
void Update(const rg_skeleton_pose* sk_pose);
void Update(const rg_tl_deform_state* deform_state, const float* vertices);
void SetMesh(std::unique_ptr<pm2::Mesh> mesh) { m_mesh = std::move(mesh); }
std::unique_ptr<pm2::Mesh>& GetMesh() { return m_mesh; }
const std::unique_ptr<pm2::Mesh>& GetMesh() const { return m_mesh; }
protected:
std::unique_ptr<pm2::Mesh> m_mesh = nullptr;
private:
T m_base = nullptr;
float m_width, m_height;
float m_node_radius;
}; // Mesh
}
#include "painting2/Mesh.inl" | 21.830769 | 78 | 0.732206 | [
"mesh",
"transform"
] |
ebe2c5313e44adc9a095e2a425850799e71cb941 | 3,709 | h | C | runtime/onert/backend/gpu_cl/open_cl/InferenceContext.h | juitem/ONE | 8c6a4b7738074573b6ac5c82dcf1f6697520d1ed | [
"Apache-2.0"
] | 1 | 2021-01-23T06:05:14.000Z | 2021-01-23T06:05:14.000Z | runtime/onert/backend/gpu_cl/open_cl/InferenceContext.h | juitem/ONE | 8c6a4b7738074573b6ac5c82dcf1f6697520d1ed | [
"Apache-2.0"
] | 5 | 2021-09-06T01:30:08.000Z | 2021-09-26T09:48:08.000Z | runtime/onert/backend/gpu_cl/open_cl/InferenceContext.h | juitem/ONE | 8c6a4b7738074573b6ac5c82dcf1f6697520d1ed | [
"Apache-2.0"
] | 2 | 2021-09-02T01:35:31.000Z | 2021-09-09T06:47:22.000Z | /*
* Copyright (c) 2021 Samsung Electronics Co., Ltd. All Rights Reserved
* Copyright 2019 The TensorFlow Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef __ONERT_BACKEND_GPU_CL_OPENCL_INFERENCE_CONTEXT_H__
#define __ONERT_BACKEND_GPU_CL_OPENCL_INFERENCE_CONTEXT_H__
#include <cstdint>
#include <functional>
#include <map>
#include <memory>
#include <vector>
#include <unordered_map>
#include "Buffer.h"
#include "ClCommandQueue.h"
#include "Environment.h"
#include "GpuObject.h"
#include "kernels/GpuOperation.h"
#include "ModelHints.h"
#include "OpenclWrapper.h"
#include "Precision.h"
#include "TensorType.h"
#include "Model.h"
#include "InternalTensor.h"
namespace onert
{
namespace backend
{
namespace gpu_cl
{
struct CLNode
{
std::unique_ptr<GPUOperation> operation;
std::vector<ValueId> inputs;
std::vector<ValueId> outputs;
// Mostly for debug purposes.
std::string name;
CLNode() = default;
CLNode(CLNode &&node);
CLNode &operator=(CLNode &&node);
CLNode(const CLNode &) = delete;
CLNode &operator=(const CLNode &) = delete;
};
class InferenceContext
{
public:
struct CreateInferenceInfo
{
CalculationsPrecision precision;
TensorStorageType storage_type;
ModelHints hints;
};
struct DummyTensor
{
BHWC shape;
TensorDescriptor descriptor;
bool operator==(const DummyTensor &b) const
{
return shape == b.shape && descriptor == b.descriptor;
}
};
class TensorReserver
{
public:
ValueId Add(const std::shared_ptr<DummyTensor> dummy)
{
reservations_[next_] = std::move(dummy);
return next_++;
}
void Add(ValueId id, const std::shared_ptr<DummyTensor> dummy)
{
reservations_[id] = std::move(dummy);
}
void SetNext(ValueId id) { next_ = id; }
bool HaveTensor(ValueId id) { return reservations_.find(id) != reservations_.end(); }
std::shared_ptr<DummyTensor> Get(ValueId id) { return reservations_[id]; }
std::vector<std::pair<ValueId, TensorDescriptor>> GetTensorDescs() const
{
std::vector<std::pair<ValueId, TensorDescriptor>> result;
for (auto &v : reservations_)
{
TensorDescriptor desc = v.second->descriptor;
desc.shape.b = v.second->shape.b;
desc.shape.h = v.second->shape.h;
desc.shape.w = v.second->shape.w;
desc.shape.d = 1;
desc.shape.c = v.second->shape.c;
result.push_back({v.first, desc});
}
return result;
}
void Add(const std::vector<std::pair<ValueId, TensorDescriptor>> &tensors)
{
for (auto &v : tensors)
{
auto dummy = std::make_shared<DummyTensor>();
dummy->descriptor = v.second;
dummy->shape.b = v.second.shape.b;
dummy->shape.h = v.second.shape.h;
dummy->shape.w = v.second.shape.w;
dummy->shape.c = v.second.shape.c;
Add(v.first, dummy);
}
}
private:
std::unordered_map<ValueId, std::shared_ptr<DummyTensor>> reservations_;
ValueId next_ = 0;
};
private:
};
} // namespace gpu_cl
} // namespace backend
} // namespace onert
#endif // __ONERT_BACKEND_GPU_CL_OPENCL_INFERENCE_CONTEXT_H__
| 25.756944 | 89 | 0.679428 | [
"shape",
"vector",
"model"
] |
ebe36fb3ec2dcb1c42eec21da65c8ff481dad9c6 | 21,645 | h | C | ruy/create_trmul_params.h | GeorgeARM/ruy | 4790797d11a81f96baf24f3731fd3ca44c2c5f8b | [
"Apache-2.0"
] | null | null | null | ruy/create_trmul_params.h | GeorgeARM/ruy | 4790797d11a81f96baf24f3731fd3ca44c2c5f8b | [
"Apache-2.0"
] | null | null | null | ruy/create_trmul_params.h | GeorgeARM/ruy | 4790797d11a81f96baf24f3731fd3ca44c2c5f8b | [
"Apache-2.0"
] | null | null | null | /* Copyright 2020 Google LLC. 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_capacity 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.
==============================================================================*/
// Implementation of CreateTrMulParams, see function comment.
#ifndef RUY_RUY_CREATE_TRMUL_PARAMS_H_
#define RUY_RUY_CREATE_TRMUL_PARAMS_H_
#include <cstdint>
#include <cstring>
#include <type_traits>
#include "ruy/allocator.h"
#include "ruy/ctx.h"
#include "ruy/kernel.h"
#include "ruy/mat.h"
#include "ruy/mul_params.h"
#include "ruy/pack.h"
#include "ruy/path.h"
#include "ruy/performance_advisory.h"
#include "ruy/trmul_params.h"
namespace ruy {
// While the only entry point to this file is CreateTrMulParams, its templatized
// nature requires putting more code in this header than we would like. This
// internal implementation code is enclosed in namespace 'detail'.
namespace detail {
inline void CreatePackedLayout(const MatLayout& src,
const KernelLayout& kernel_layout,
PMatLayout* packed_layout) {
// Packed matrices are always column-major, because in TrMul that is always
// the dimension of traversal of the kernel's inner loop.
packed_layout->order = Order::kColMajor;
packed_layout->rows = round_up_pot(src.rows, kernel_layout.rows);
packed_layout->cols = round_up_pot(src.cols, kernel_layout.cols);
packed_layout->stride = packed_layout->rows;
packed_layout->kernel = kernel_layout;
}
template <typename Scalar, typename PackedScalar>
void CreatePackedMatrix(Side side, const KernelLayout& kernel_layout,
TrMulParams* params) {
// Ruy always uses 32-bit signed accumulators for quantized
// matrix multiplication, so we would like to always use std::int32_t
// unconditionally for SumsType.
// However, for floating point types, we still need a reasonable type here to
// avoid tripping assertions elsewhere in the code.
using SumsType =
typename std::conditional<std::is_floating_point<Scalar>::value, Scalar,
std::int32_t>::type;
const EMat& src = params->src[side];
PEMat* packed_matrix = ¶ms->packed_matrix[side];
packed_matrix->data_type = Type::Create<PackedScalar>();
packed_matrix->sums_type = Type::Create<SumsType>();
CreatePackedLayout(src.layout, kernel_layout, &packed_matrix->layout);
packed_matrix->zero_point = Pack<PackedScalar, Scalar>(src.zero_point);
}
template <typename KernelType>
struct CheckKernelPathImpl {
static void Run(Path) {
// Do nothing.
// Path fallbacks are normal in general (see RUY_INHERIT_KERNEL).
// That is to say that one may instantiate ruy::Mul with a weird combination
// of types, such as LhsScalar==float and RhsScalar==double, and have it
// work by silently falling back to Path::kStandardCpp. Only in specific
// cases do we have dedicated kernels overriding that fallback, and that is
// what partial specializations of this template will check.
}
};
#if RUY_DCHECK_IS_ENABLED
template <Path ThePath, typename SrcScalar, typename AccumScalar,
typename DstScalar>
struct CheckKernelPathImpl<Kernel<ThePath, SrcScalar, SrcScalar, DstScalar,
MulParams<AccumScalar, DstScalar>>>
final {
using KernelType = Kernel<ThePath, SrcScalar, SrcScalar, DstScalar,
MulParams<AccumScalar, DstScalar>>;
static void Run(Path expected_path) {
// We want to assert that we are using a dedicated Kernel specialization and
// not a fallback when we know we are in a case where such a kernel
// specialization exists. At the moment in the current state of ruy's
// architecture support for ARM and x86, that is when LhsScalar==RhsScalar
// (already implied in this partial specialization) and when that type is
// either float, int8, or uint8. Indeed, we have kernels supporting float
// and int8, and we have the packing code converting uint8 to int8 (see
// PackedTypeImpl).
static constexpr bool kSrcScalarTypeSupportsFastKernels =
std::is_same<SrcScalar, float>::value ||
std::is_same<SrcScalar, std::int8_t>::value ||
std::is_same<SrcScalar, std::uint8_t>::value;
if (kSrcScalarTypeSupportsFastKernels) {
RUY_DCHECK_EQ(expected_path, KernelType::kPath);
}
}
};
#endif
template <typename KernelType>
void CheckKernelPath(Path expected_path) {
CheckKernelPathImpl<KernelType>::Run(expected_path);
}
template <Path ThePath, typename LhsScalar, typename RhsScalar,
typename AccumScalar, typename DstScalar>
void PopulateTrMulParams(TrMulParams* params) {
using PackedLhsScalar = PackedType<ThePath, LhsScalar>;
using PackedRhsScalar = PackedType<ThePath, RhsScalar>;
using Kernel =
Kernel<ThePath, PackedLhsScalar, PackedRhsScalar, AccumScalar, DstScalar>;
using LhsKernelLayout = typename Kernel::LhsLayout;
using RhsKernelLayout = typename Kernel::RhsLayout;
params->path = ThePath;
CreatePackedMatrix<LhsScalar, PackedLhsScalar>(
Side::kLhs, ToKernelLayout<LhsKernelLayout>(), params);
CreatePackedMatrix<RhsScalar, PackedRhsScalar>(
Side::kRhs, ToKernelLayout<RhsKernelLayout>(), params);
params->run_pack[Side::kLhs] =
&RunPack<ThePath, LhsKernelLayout, LhsScalar, PackedLhsScalar>;
params->run_pack[Side::kRhs] =
&RunPack<ThePath, RhsKernelLayout, RhsScalar, PackedRhsScalar>;
params->run_kernel = &RunKernel<Kernel>::Run;
CheckKernelPath<Kernel>(ThePath);
}
// PopulateTrMulParamsAllCompiledPaths calls into one of multiple
// instantiations of PopulateTrMulParams. For each bit that is set in
// CompiledPaths, it statically instantiates PopulateTrMulParams with a Path
// corresponding to that single bit. The call to PopulateTrMulParams is
// guarded by a runtime check that it is in fact the dynamically selected path.
//
// PopulateTrMulParamsAllCompiledPaths is implemented with template
// metaprogramming by mutual recursion between PathSearchCountdown and
// PathSearchCompiledPaths.
//
// PopulateTrMulParamsAllCompiledPaths is logically implementing the following
// computation:
//
// template <Path CompiledPaths>
// void PopulateTrMulParamsAllCompiledPaths(Path the_path,
// TrMulParams* params) {
// for (int bit = 8 * sizeof(Path) - 1; bit != -1; bit--) { // [1]
// Path current_path = static_cast<Path>(1 << bit);
// if ((CompiledPaths & current_path) != Path::kNone) { // [2]
// if (current_path == the_path) { // [3]
// PopulateTrMulParams<current_path, ...>(the_path, params);
// return;
// }
// }
// }
// }
//
//
//
// [1] - Done by the main definition of PathSearchCountdown. The `bit--` is
// done in the recursion of PathSearchOnlyCompiledPaths.
// [2] - Done by PathSearchOnlyCompiledPaths's partial template
// specialization on InCompiledPaths. This is the check which necessitates
// doing the whole computation at C++ compile time.
// [3] - Done by the `if` in the main definition of
// PathSearchOnlyCompiledPaths.
//
// The template metaprogramming is necessary because:
// - In `PopulateTrMulParams<current_path, ...>`, current_path must be a C++
// compile-time constant.
// - PopulateTrMulParamsAllCompiledPaths must not instantiate
// inner loops for paths that are not in CompiledPaths, since that can result in
// bogus instantiations which cause a compile time failure.
template <Path CompiledPaths, int BitNumber, typename LhsScalar,
typename RhsScalar, typename AccumScalar, typename DstScalar>
struct PathSearchCountdown;
template <Path CompiledPaths, bool InCompiledPaths, int BitNumber,
typename LhsScalar, typename RhsScalar, typename AccumScalar,
typename DstScalar>
struct PathSearchOnlyCompiledPaths {
static constexpr Path kCurrentPath = static_cast<Path>(1 << BitNumber);
static void Search(Path the_path, TrMulParams* params) {
if (kCurrentPath == the_path) {
PopulateTrMulParams<kCurrentPath, LhsScalar, RhsScalar, AccumScalar,
DstScalar>(params);
return;
}
PathSearchCountdown<CompiledPaths, BitNumber - 1, LhsScalar, RhsScalar,
AccumScalar, DstScalar>::Search(the_path, params);
}
};
// Skip this iteration if CompiledPaths doesn't contain the specified path.
template <Path CompiledPaths, int BitNumber, typename LhsScalar,
typename RhsScalar, typename AccumScalar, typename DstScalar>
struct PathSearchOnlyCompiledPaths<CompiledPaths, false, BitNumber, LhsScalar,
RhsScalar, AccumScalar, DstScalar> {
static void Search(Path the_path, TrMulParams* params) {
PathSearchCountdown<CompiledPaths, BitNumber - 1, LhsScalar, RhsScalar,
AccumScalar, DstScalar>::Search(the_path, params);
}
};
template <Path CompiledPaths, int BitNumber, typename LhsScalar,
typename RhsScalar, typename AccumScalar, typename DstScalar>
struct PathSearchCountdown {
static constexpr Path kCurrentPath = static_cast<Path>(1 << BitNumber);
static void Search(Path the_path, TrMulParams* params) {
PathSearchOnlyCompiledPaths<
CompiledPaths, (CompiledPaths & kCurrentPath) != Path::kNone, BitNumber,
LhsScalar, RhsScalar, AccumScalar, DstScalar>::Search(the_path, params);
}
};
// Termination of the countdown. If the counter reaches -1, then we haven't
// found the specified path.
template <Path CompiledPaths, typename LhsScalar, typename RhsScalar,
typename AccumScalar, typename DstScalar>
struct PathSearchCountdown<CompiledPaths, -1, LhsScalar, RhsScalar, AccumScalar,
DstScalar> {
static void Search(Path, TrMulParams*) { RUY_DCHECK(false); }
};
template <Path CompiledPaths, typename LhsScalar, typename RhsScalar,
typename AccumScalar, typename DstScalar>
void PopulateTrMulParamsAllCompiledPaths(Path the_path, TrMulParams* params) {
return PathSearchCountdown<CompiledPaths, 8 * sizeof(Path) - 1, LhsScalar,
RhsScalar, AccumScalar,
DstScalar>::Search(the_path, params);
}
template <typename AccumScalar, typename DstScalar>
void AssertThatExtraCapacityInPerChannelBuffersIsZeroInitialized(
const MulParams<AccumScalar, DstScalar>& mul_params, int user_size,
int user_capacity) {
#if RUY_DCHECK_IS_ENABLED
if (mul_params.bias()) {
for (int i = user_size; i < user_capacity; i++) {
RUY_DCHECK_EQ(mul_params.bias()[i], 0);
}
}
if (mul_params.multiplier_fixedpoint_perchannel()) {
for (int i = user_size; i < user_capacity; i++) {
RUY_DCHECK_EQ(mul_params.multiplier_fixedpoint_perchannel()[i], 0);
}
}
if (mul_params.multiplier_exponent_perchannel()) {
for (int i = user_size; i < user_capacity; i++) {
RUY_DCHECK_EQ(mul_params.multiplier_exponent_perchannel()[i], 0);
}
}
#else
(void)mul_params;
(void)user_size;
(void)user_capacity;
#endif
}
template <typename AccumScalar, typename DstScalar,
bool HaveQuantizedMultipliers =
std::is_same<AccumScalar, std::int32_t>::value &&
!std::is_same<DstScalar, std::int32_t>::value>
struct EnsurePerChannelBuffersLargeEnoughImpl {
static void Run(const TrMulParams& params, Allocator* allocator,
MulParams<AccumScalar, DstScalar>* mul_params) {
const Side channel_side =
mul_params->channel_dimension() == ChannelDimension::kRow ? Side::kLhs
: Side::kRhs;
const int required_capacity =
params.packed_matrix[channel_side].layout.cols;
const int user_size = params.src[channel_side].layout.cols;
const int user_capacity = round_up_pot(
user_size, mul_params->perchannel_buffers_capacity_rounding());
// We should have already checked earlier for the case where
// user_capacity >= required_capacity.
RUY_DCHECK_GT(required_capacity, user_capacity);
if (mul_params->bias()) {
AccumScalar* new_data =
allocator->Allocate<AccumScalar>(required_capacity);
std::memcpy(new_data, mul_params->bias(),
user_size * sizeof(AccumScalar));
std::memset(new_data + user_size, 0,
(required_capacity - user_size) * sizeof(AccumScalar));
mul_params->set_bias(new_data);
}
if (mul_params->multiplier_fixedpoint_perchannel()) {
AccumScalar* new_data =
allocator->Allocate<AccumScalar>(required_capacity);
std::memcpy(new_data, mul_params->multiplier_fixedpoint_perchannel(),
user_size * sizeof(AccumScalar));
std::memset(new_data + user_size, 0,
(required_capacity - user_size) * sizeof(AccumScalar));
mul_params->set_multiplier_fixedpoint_perchannel(new_data);
}
if (mul_params->multiplier_exponent_perchannel()) {
int* new_data = allocator->Allocate<int>(required_capacity);
std::memcpy(new_data, mul_params->multiplier_exponent_perchannel(),
user_size * sizeof(int));
std::memset(new_data + user_size, 0,
(required_capacity - user_size) * sizeof(int));
mul_params->set_multiplier_exponent_perchannel(new_data);
}
}
};
template <typename AccumScalar, typename DstScalar>
struct EnsurePerChannelBuffersLargeEnoughImpl<AccumScalar, DstScalar, false> {
static void Run(const TrMulParams& params, Allocator* allocator,
MulParams<AccumScalar, DstScalar>* mul_params) {
const Side channel_side =
mul_params->channel_dimension() == ChannelDimension::kRow ? Side::kLhs
: Side::kRhs;
const int required_capacity =
params.packed_matrix[channel_side].layout.cols;
const int user_size = params.src[channel_side].layout.cols;
const int user_capacity = round_up_pot(
user_size, mul_params->perchannel_buffers_capacity_rounding());
// We should have already checked earlier for the case where
// user_capacity >= required_capacity.
RUY_DCHECK_GT(required_capacity, user_capacity);
if (mul_params->bias()) {
AccumScalar* new_data =
allocator->Allocate<AccumScalar>(required_capacity);
std::memcpy(new_data, mul_params->bias(),
user_size * sizeof(AccumScalar));
std::memset(new_data + user_size, 0,
(required_capacity - user_size) * sizeof(AccumScalar));
mul_params->set_bias(new_data);
}
}
};
template <typename AccumScalar, typename DstScalar>
void EnsurePerChannelBuffersLargeEnough(
const TrMulParams& params, Ctx* ctx,
MulParams<AccumScalar, DstScalar>* mul_params) {
// Early exit in the common case where the packed matrix size matches the
// number of channels (as opposed to having been rounded up to a slightly
// larger value).
const Side channel_side =
mul_params->channel_dimension() == ChannelDimension::kRow ? Side::kLhs
: Side::kRhs;
const int required_capacity = params.packed_matrix[channel_side].layout.cols;
const int user_size = params.src[channel_side].layout.cols;
const int user_capacity = round_up_pot(
user_size, mul_params->perchannel_buffers_capacity_rounding());
AssertThatExtraCapacityInPerChannelBuffersIsZeroInitialized(
*mul_params, user_size, user_capacity);
if (required_capacity <= user_capacity) {
return;
}
ctx->set_performance_advisory(
PerformanceAdvisory::kReallocatedPerChannelBuffer);
EnsurePerChannelBuffersLargeEnoughImpl<AccumScalar, DstScalar>::Run(
params, ctx->GetMainAllocator(), mul_params);
}
// Ensures that `params->mul_params_bytes` contains MulParams data that's ready
// to be consumed by the kernel. As a first-order approximation, that is simply
// copying the user-provided `mul_params`, however there are a few changes.
//
// 1. The specified `channel_dimension` value overrides the channel_dimension
// member in `mul_params`. The reason why `channel_dimension` is being
// special-cased among MulParams members is that we will need to transpose
// MulParams, and that consists just in toggling channel_dimension.
// 2. Per-channel buffers may be reallocated, see
// EnsurePerChannelBuffersLargeEnough.
template <typename AccumScalar, typename DstScalar>
void FinalizeMulParams(const MulParams<AccumScalar, DstScalar>& mul_params,
ChannelDimension channel_dimension, Ctx* ctx,
TrMulParams* params) {
using MulParamsType = MulParams<AccumScalar, DstScalar>;
static_assert(alignof(MulParamsType) <= kMaxMulParamsAlignment, "");
static_assert(sizeof(MulParamsType) <= kMaxMulParamsSize, "");
static_assert(std::is_trivially_copyable<MulParamsType>::value, "");
auto* dst_mul_params =
reinterpret_cast<MulParamsType*>(params->mul_params_bytes);
std::memcpy(dst_mul_params, &mul_params, sizeof(MulParamsType));
dst_mul_params->set_channel_dimension(channel_dimension);
EnsurePerChannelBuffersLargeEnough(*params, ctx, dst_mul_params);
}
// In this function, the `channel_dimension` parameter overrides the value
// of the channel_dimension member in the `mul_params` parameter. See the
// FinalizeMulParams comment.
template <Path CompiledPaths, typename LhsScalar, typename RhsScalar,
typename AccumScalar, typename DstScalar>
void CreateTrMulParamsAssumingColMajorDst(
const Mat<LhsScalar>& lhs, const Mat<RhsScalar>& rhs,
const Mat<DstScalar>& dst,
const MulParams<AccumScalar, DstScalar>& mul_params,
ChannelDimension channel_dimension, Ctx* ctx, TrMulParams* params) {
RUY_DCHECK(IsColMajor(dst.layout));
// Fill in the fields we already know.
params->src[Side::kLhs] = EraseType(lhs);
params->src[Side::kRhs] = EraseType(rhs);
params->dst = EraseType(dst);
// Determine which exact Path we're going to take in this Mul call.
// This is cheap because it's cached in `ctx`. In user scenarios this always
// evaluates to the same value on a given machine with given `CompiledPaths`,
// but could be invalidated by a call to Ctx::SetRuntimeEnabledPaths(), which
// might be exposed publicly in Context in the future.
const Path the_path = ctx->SelectPath(CompiledPaths);
// If we ever need again to fall back to Path::kStandardCpp, this is a good
// place to do it -- just pass Path::kStandardCpp as both the template and
// runtime parameters in this function call.
// In the past we did that here (as version control history remembers).
// A typical reason why we might need to resurrect that is if we implement
// a new Path (i.e. port to a new ISA) and need to subdivide that work into
// a series of incremental changes.
PopulateTrMulParamsAllCompiledPaths<CompiledPaths, LhsScalar, RhsScalar,
AccumScalar, DstScalar>(the_path, params);
// This must be done last, as it depends on the specific choice of kernel.
// Specifically, the EnsurePerChannelBuffersLargeEnough part of this will read
// the packed matrix layouts that are written to `params` by the above
// PopulateTrMulParams* call.
FinalizeMulParams(mul_params, channel_dimension, ctx, params);
}
} // namespace detail
inline ChannelDimension Transpose(ChannelDimension channel_dimension) {
return channel_dimension == ChannelDimension::kCol ? ChannelDimension::kRow
: ChannelDimension::kCol;
}
// CreateTrMulParams's output is a TrMulParams object that encodes
// all of the input information required_capacity by the middle-end, that is,
// the TrMul function.
//
// CreateTrMulParams performs the following tasks:
// 1. Reduce to the case of column-major destination, by transposing the
// whole problem as needed.
// 2. Select the single code path to be taken, out of the set of paths
// described by the `CompiledPaths` template parameter, based on the
// runtime input parameter `the_path`.
// 3. Perform type-erasure, converting templatized typed input parameters
// to the un-typed data stored in TrMulParams.
template <Path CompiledPaths, typename LhsScalar, typename RhsScalar,
typename AccumScalar, typename DstScalar>
void CreateTrMulParams(const Mat<LhsScalar>& lhs, const Mat<RhsScalar>& rhs,
const Mat<DstScalar>& dst,
const MulParams<AccumScalar, DstScalar>& mul_params,
Ctx* ctx, TrMulParams* params) {
ChannelDimension channel_dimension = mul_params.channel_dimension();
if (IsColMajor(dst.layout)) {
detail::CreateTrMulParamsAssumingColMajorDst<CompiledPaths>(
lhs, rhs, dst, mul_params, channel_dimension, ctx, params);
} else {
detail::CreateTrMulParamsAssumingColMajorDst<CompiledPaths>(
rhs, lhs, Transpose(dst), mul_params, Transpose(channel_dimension), ctx,
params);
}
}
} // namespace ruy
#endif // RUY_RUY_CREATE_TRMUL_PARAMS_H_
| 45.472689 | 80 | 0.711111 | [
"object"
] |
ebe3f607ee7049111caa5f7a5935c016e46d83bb | 33,547 | h | C | include/gsl/gsl_linalg.h | zhanghe9704/jspec2 | 0073e0515b87610b7f88ad2b07fc7d23618c159a | [
"Unlicense"
] | 1 | 2020-09-28T08:20:20.000Z | 2020-09-28T08:20:20.000Z | include/gsl/gsl_linalg.h | zhanghe9704/jspec2 | 0073e0515b87610b7f88ad2b07fc7d23618c159a | [
"Unlicense"
] | null | null | null | include/gsl/gsl_linalg.h | zhanghe9704/jspec2 | 0073e0515b87610b7f88ad2b07fc7d23618c159a | [
"Unlicense"
] | 1 | 2020-10-14T12:45:35.000Z | 2020-10-14T12:45:35.000Z | /* linalg/gsl_linalg.h
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000, 2006, 2007, 2019 Gerard Jungman, Brian Gough, Patrick Alken
*
* 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 3 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 Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#ifndef __GSL_LINALG_H__
#define __GSL_LINALG_H__
#if !defined( GSL_FUN )
# if !defined( GSL_DLL )
# define GSL_FUN extern
# elif defined( BUILD_GSL_DLL )
# define GSL_FUN extern __declspec(dllexport)
# else
# define GSL_FUN extern __declspec(dllimport)
# endif
#endif
#include <stdlib.h>
#include <gsl/gsl_mode.h>
#include <gsl/gsl_permutation.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_inline.h>
#include <gsl/gsl_blas.h>
#undef __BEGIN_DECLS
#undef __END_DECLS
#ifdef __cplusplus
#define __BEGIN_DECLS extern "C" {
#define __END_DECLS }
#else
#define __BEGIN_DECLS /* empty */
#define __END_DECLS /* empty */
#endif
__BEGIN_DECLS
typedef enum
{
GSL_LINALG_MOD_NONE = 0,
GSL_LINALG_MOD_TRANSPOSE = 1,
GSL_LINALG_MOD_CONJUGATE = 2
}
gsl_linalg_matrix_mod_t;
/* Note: You can now use the gsl_blas_dgemm function instead of matmult */
/* Simple implementation of matrix multiply.
* Calculates C = A.B
*
* exceptions: GSL_EBADLEN
*/
GSL_FUN int gsl_linalg_matmult (const gsl_matrix * A,
const gsl_matrix * B,
gsl_matrix * C);
/* Simple implementation of matrix multiply.
* Allows transposition of either matrix, so it
* can compute A.B or Trans(A).B or A.Trans(B) or Trans(A).Trans(B)
*
* exceptions: GSL_EBADLEN
*/
GSL_FUN int gsl_linalg_matmult_mod (const gsl_matrix * A,
gsl_linalg_matrix_mod_t modA,
const gsl_matrix * B,
gsl_linalg_matrix_mod_t modB,
gsl_matrix * C);
/* Calculate the matrix exponential by the scaling and
* squaring method described in Moler + Van Loan,
* SIAM Rev 20, 801 (1978). The mode argument allows
* choosing an optimal strategy, from the table
* given in the paper, for a given precision.
*
* exceptions: GSL_ENOTSQR, GSL_EBADLEN
*/
GSL_FUN int gsl_linalg_exponential_ss(
const gsl_matrix * A,
gsl_matrix * eA,
gsl_mode_t mode
);
/* Householder Transformations */
GSL_FUN double gsl_linalg_householder_transform (gsl_vector * v);
GSL_FUN double gsl_linalg_householder_transform2 (double * alpha, gsl_vector * v);
GSL_FUN gsl_complex gsl_linalg_complex_householder_transform (gsl_vector_complex * v);
GSL_FUN int gsl_linalg_householder_hm (double tau,
const gsl_vector * v,
gsl_matrix * A);
GSL_FUN int gsl_linalg_householder_mh (double tau,
const gsl_vector * v,
gsl_matrix * A);
GSL_FUN int gsl_linalg_householder_hv (double tau,
const gsl_vector * v,
gsl_vector * w);
GSL_FUN int gsl_linalg_householder_left(const double tau,
const gsl_vector * v,
gsl_matrix * A,
gsl_vector * work);
GSL_FUN int gsl_linalg_householder_right(const double tau,
const gsl_vector * v,
gsl_matrix * A,
gsl_vector * work);
GSL_FUN int gsl_linalg_householder_hm1 (double tau,
gsl_matrix * A);
GSL_FUN int gsl_linalg_complex_householder_hm (gsl_complex tau,
const gsl_vector_complex * v,
gsl_matrix_complex * A);
GSL_FUN int gsl_linalg_complex_householder_mh (gsl_complex tau,
const gsl_vector_complex * v,
gsl_matrix_complex * A);
GSL_FUN int gsl_linalg_complex_householder_hv (gsl_complex tau,
const gsl_vector_complex * v,
gsl_vector_complex * w);
GSL_FUN int gsl_linalg_complex_householder_left (const gsl_complex tau,
const gsl_vector_complex * v,
gsl_matrix_complex * A,
gsl_vector_complex * work);
/* Hessenberg reduction */
GSL_FUN int gsl_linalg_hessenberg_decomp(gsl_matrix *A, gsl_vector *tau);
GSL_FUN int gsl_linalg_hessenberg_unpack(gsl_matrix * H, gsl_vector * tau,
gsl_matrix * U);
GSL_FUN int gsl_linalg_hessenberg_unpack_accum(gsl_matrix * H, gsl_vector * tau,
gsl_matrix * U);
GSL_FUN int gsl_linalg_hessenberg_set_zero(gsl_matrix * H);
GSL_FUN int gsl_linalg_hessenberg_submatrix(gsl_matrix *M, gsl_matrix *A,
size_t top, gsl_vector *tau);
/* Hessenberg-Triangular reduction */
GSL_FUN int gsl_linalg_hesstri_decomp(gsl_matrix * A, gsl_matrix * B,
gsl_matrix * U, gsl_matrix * V,
gsl_vector * work);
/* Singular Value Decomposition
* exceptions:
*/
GSL_FUN int
gsl_linalg_SV_decomp (gsl_matrix * A,
gsl_matrix * V,
gsl_vector * S,
gsl_vector * work);
GSL_FUN int
gsl_linalg_SV_decomp_mod (gsl_matrix * A,
gsl_matrix * X,
gsl_matrix * V,
gsl_vector * S,
gsl_vector * work);
GSL_FUN int gsl_linalg_SV_decomp_jacobi (gsl_matrix * A,
gsl_matrix * Q,
gsl_vector * S);
GSL_FUN int
gsl_linalg_SV_solve (const gsl_matrix * U,
const gsl_matrix * Q,
const gsl_vector * S,
const gsl_vector * b,
gsl_vector * x);
GSL_FUN int gsl_linalg_SV_leverage(const gsl_matrix *U, gsl_vector *h);
/* LU Decomposition, Gaussian elimination with partial pivoting
*/
GSL_FUN int gsl_linalg_LU_decomp (gsl_matrix * A, gsl_permutation * p, int *signum);
GSL_FUN int gsl_linalg_LU_solve (const gsl_matrix * LU,
const gsl_permutation * p,
const gsl_vector * b,
gsl_vector * x);
GSL_FUN int gsl_linalg_LU_svx (const gsl_matrix * LU,
const gsl_permutation * p,
gsl_vector * x);
GSL_FUN int gsl_linalg_LU_refine (const gsl_matrix * A,
const gsl_matrix * LU,
const gsl_permutation * p,
const gsl_vector * b,
gsl_vector * x,
gsl_vector * work);
GSL_FUN int gsl_linalg_LU_invert (const gsl_matrix * LU,
const gsl_permutation * p,
gsl_matrix * inverse);
GSL_FUN int gsl_linalg_LU_invx (gsl_matrix * LU, const gsl_permutation * p);
GSL_FUN double gsl_linalg_LU_det (gsl_matrix * LU, int signum);
GSL_FUN double gsl_linalg_LU_lndet (gsl_matrix * LU);
GSL_FUN int gsl_linalg_LU_sgndet (gsl_matrix * lu, int signum);
/* Complex LU Decomposition */
GSL_FUN int gsl_linalg_complex_LU_decomp (gsl_matrix_complex * A,
gsl_permutation * p,
int *signum);
GSL_FUN int gsl_linalg_complex_LU_solve (const gsl_matrix_complex * LU,
const gsl_permutation * p,
const gsl_vector_complex * b,
gsl_vector_complex * x);
GSL_FUN int gsl_linalg_complex_LU_svx (const gsl_matrix_complex * LU,
const gsl_permutation * p,
gsl_vector_complex * x);
GSL_FUN int gsl_linalg_complex_LU_refine (const gsl_matrix_complex * A,
const gsl_matrix_complex * LU,
const gsl_permutation * p,
const gsl_vector_complex * b,
gsl_vector_complex * x,
gsl_vector_complex * work);
GSL_FUN int gsl_linalg_complex_LU_invert (const gsl_matrix_complex * LU,
const gsl_permutation * p,
gsl_matrix_complex * inverse);
GSL_FUN int gsl_linalg_complex_LU_invx (gsl_matrix_complex * LU, const gsl_permutation * p);
GSL_FUN gsl_complex gsl_linalg_complex_LU_det (gsl_matrix_complex * LU,
int signum);
GSL_FUN double gsl_linalg_complex_LU_lndet (gsl_matrix_complex * LU);
GSL_FUN gsl_complex gsl_linalg_complex_LU_sgndet (gsl_matrix_complex * LU,
int signum);
/* QR decomposition */
GSL_FUN int gsl_linalg_QR_decomp (gsl_matrix * A, gsl_vector * tau);
GSL_FUN int gsl_linalg_QR_decomp_r (gsl_matrix * A, gsl_matrix * T);
GSL_FUN int gsl_linalg_QR_solve (const gsl_matrix * QR, const gsl_vector * tau, const gsl_vector * b, gsl_vector * x);
GSL_FUN int gsl_linalg_QR_solve_r (const gsl_matrix * QR, const gsl_matrix * T, const gsl_vector * b, gsl_vector * x);
GSL_FUN int gsl_linalg_QR_svx (const gsl_matrix * QR, const gsl_vector * tau, gsl_vector * x);
GSL_FUN int gsl_linalg_QR_lssolve (const gsl_matrix * QR, const gsl_vector * tau, const gsl_vector * b,
gsl_vector * x, gsl_vector * residual);
GSL_FUN int gsl_linalg_QR_lssolve_r (const gsl_matrix * QR, const gsl_matrix * T, const gsl_vector * b,
gsl_vector * x, gsl_vector * work);
GSL_FUN int gsl_linalg_QR_QRsolve (gsl_matrix * Q, gsl_matrix * R, const gsl_vector * b, gsl_vector * x);
GSL_FUN int gsl_linalg_QR_Rsolve (const gsl_matrix * QR, const gsl_vector * b, gsl_vector * x);
GSL_FUN int gsl_linalg_QR_Rsvx (const gsl_matrix * QR, gsl_vector * x);
GSL_FUN int gsl_linalg_QR_update (gsl_matrix * Q, gsl_matrix * R, gsl_vector * w, const gsl_vector * v);
GSL_FUN int gsl_linalg_QR_QTvec (const gsl_matrix * QR, const gsl_vector * tau, gsl_vector * v);
GSL_FUN int gsl_linalg_QR_QTvec_r(const gsl_matrix * QR, const gsl_matrix * T, gsl_vector * b, gsl_vector * work);
GSL_FUN int gsl_linalg_QR_Qvec (const gsl_matrix * QR, const gsl_vector * tau, gsl_vector * v);
GSL_FUN int gsl_linalg_QR_QTmat (const gsl_matrix * QR, const gsl_vector * tau, gsl_matrix * A);
GSL_FUN int gsl_linalg_QR_QTmat_r(const gsl_matrix * QR, const gsl_matrix * T, gsl_matrix * B, gsl_matrix * work);
GSL_FUN int gsl_linalg_QR_matQ (const gsl_matrix * QR, const gsl_vector * tau, gsl_matrix * A);
GSL_FUN int gsl_linalg_QR_unpack (const gsl_matrix * QR, const gsl_vector * tau, gsl_matrix * Q, gsl_matrix * R);
GSL_FUN int gsl_linalg_QR_unpack_r(const gsl_matrix * QR, const gsl_matrix * T, gsl_matrix * Q, gsl_matrix * R);
GSL_FUN int gsl_linalg_R_solve (const gsl_matrix * R, const gsl_vector * b, gsl_vector * x);
GSL_FUN int gsl_linalg_R_svx (const gsl_matrix * R, gsl_vector * x);
GSL_FUN int gsl_linalg_QR_rcond(const gsl_matrix * QR, double * rcond, gsl_vector * work);
/* Q R P^T decomposition */
GSL_FUN int gsl_linalg_QRPT_decomp (gsl_matrix * A,
gsl_vector * tau,
gsl_permutation * p,
int *signum,
gsl_vector * norm);
GSL_FUN int gsl_linalg_QRPT_decomp2 (const gsl_matrix * A,
gsl_matrix * q, gsl_matrix * r,
gsl_vector * tau,
gsl_permutation * p,
int *signum,
gsl_vector * norm);
GSL_FUN int gsl_linalg_QRPT_solve (const gsl_matrix * QR,
const gsl_vector * tau,
const gsl_permutation * p,
const gsl_vector * b,
gsl_vector * x);
GSL_FUN int gsl_linalg_QRPT_lssolve (const gsl_matrix * QR,
const gsl_vector * tau,
const gsl_permutation * p,
const gsl_vector * b,
gsl_vector * x,
gsl_vector * residual);
GSL_FUN int gsl_linalg_QRPT_lssolve2 (const gsl_matrix * QR,
const gsl_vector * tau,
const gsl_permutation * p,
const gsl_vector * b,
const size_t rank,
gsl_vector * x,
gsl_vector * residual);
GSL_FUN int gsl_linalg_QRPT_svx (const gsl_matrix * QR,
const gsl_vector * tau,
const gsl_permutation * p,
gsl_vector * x);
GSL_FUN int gsl_linalg_QRPT_QRsolve (const gsl_matrix * Q,
const gsl_matrix * R,
const gsl_permutation * p,
const gsl_vector * b,
gsl_vector * x);
GSL_FUN int gsl_linalg_QRPT_Rsolve (const gsl_matrix * QR,
const gsl_permutation * p,
const gsl_vector * b,
gsl_vector * x);
GSL_FUN int gsl_linalg_QRPT_Rsvx (const gsl_matrix * QR,
const gsl_permutation * p,
gsl_vector * x);
GSL_FUN int gsl_linalg_QRPT_update (gsl_matrix * Q,
gsl_matrix * R,
const gsl_permutation * p,
gsl_vector * u,
const gsl_vector * v);
GSL_FUN size_t gsl_linalg_QRPT_rank (const gsl_matrix * QR, const double tol);
GSL_FUN int gsl_linalg_QRPT_rcond(const gsl_matrix * QR, double * rcond, gsl_vector * work);
/* triangle on top of rectangle QR decomposition */
GSL_FUN int gsl_linalg_QR_TR_decomp (gsl_matrix * S, gsl_matrix * A, gsl_matrix * T);
/* QL decomposition */
GSL_FUN int gsl_linalg_QL_decomp (gsl_matrix * A, gsl_vector * tau);
GSL_FUN int gsl_linalg_QL_unpack (const gsl_matrix * QL, const gsl_vector * tau, gsl_matrix * Q, gsl_matrix * L);
/* COD decomposition */
GSL_FUN int gsl_linalg_COD_decomp(gsl_matrix * A, gsl_vector * tau_Q, gsl_vector * tau_Z,
gsl_permutation * p, size_t * rank, gsl_vector * work);
GSL_FUN int gsl_linalg_COD_decomp_e(gsl_matrix * A, gsl_vector * tau_Q, gsl_vector * tau_Z,
gsl_permutation * p, double tol, size_t * rank, gsl_vector * work);
GSL_FUN int gsl_linalg_COD_lssolve (const gsl_matrix * QRZT, const gsl_vector * tau_Q, const gsl_vector * tau_Z,
const gsl_permutation * perm, const size_t rank, const gsl_vector * b,
gsl_vector * x, gsl_vector * residual);
GSL_FUN int
gsl_linalg_COD_lssolve2 (const double lambda, const gsl_matrix * QRZT, const gsl_vector * tau_Q, const gsl_vector * tau_Z,
const gsl_permutation * perm, const size_t rank, const gsl_vector * b,
gsl_vector * x, gsl_vector * residual, gsl_matrix * S, gsl_vector * work);
GSL_FUN int gsl_linalg_COD_unpack(const gsl_matrix * QRZT, const gsl_vector * tau_Q,
const gsl_vector * tau_Z, const size_t rank, gsl_matrix * Q,
gsl_matrix * R, gsl_matrix * Z);
GSL_FUN int gsl_linalg_COD_matZ(const gsl_matrix * QRZT, const gsl_vector * tau_Z, const size_t rank,
gsl_matrix * A, gsl_vector * work);
/* LQ decomposition */
GSL_FUN int gsl_linalg_LQ_decomp (gsl_matrix * A, gsl_vector * tau);
GSL_FUN int gsl_linalg_LQ_lssolve(const gsl_matrix * LQ, const gsl_vector * tau,
const gsl_vector * b, gsl_vector * x, gsl_vector * residual);
GSL_FUN int gsl_linalg_LQ_QTvec(const gsl_matrix * LQ, const gsl_vector * tau, gsl_vector * v);
GSL_FUN int gsl_linalg_LQ_solve_T (const gsl_matrix * LQ, const gsl_vector * tau,
const gsl_vector * b, gsl_vector * x);
GSL_FUN int gsl_linalg_LQ_svx_T (const gsl_matrix * LQ, const gsl_vector * tau,
gsl_vector * x);
GSL_FUN int gsl_linalg_LQ_lssolve_T (const gsl_matrix * LQ, const gsl_vector * tau,
const gsl_vector * b, gsl_vector * x,
gsl_vector * residual);
GSL_FUN int gsl_linalg_LQ_Lsolve_T (const gsl_matrix * LQ, const gsl_vector * b,
gsl_vector * x);
GSL_FUN int gsl_linalg_LQ_Lsvx_T (const gsl_matrix * LQ, gsl_vector * x);
GSL_FUN int gsl_linalg_L_solve_T (const gsl_matrix * L, const gsl_vector * b,
gsl_vector * x);
GSL_FUN int gsl_linalg_LQ_vecQ (const gsl_matrix * LQ, const gsl_vector * tau,
gsl_vector * v);
GSL_FUN int gsl_linalg_LQ_vecQT (const gsl_matrix * LQ, const gsl_vector * tau,
gsl_vector * v);
GSL_FUN int gsl_linalg_LQ_unpack (const gsl_matrix * LQ, const gsl_vector * tau,
gsl_matrix * Q, gsl_matrix * L);
GSL_FUN int gsl_linalg_LQ_update (gsl_matrix * Q, gsl_matrix * R,
const gsl_vector * v, gsl_vector * w);
GSL_FUN int gsl_linalg_LQ_LQsolve (gsl_matrix * Q, gsl_matrix * L,
const gsl_vector * b, gsl_vector * x);
/* P^T L Q decomposition */
GSL_FUN int gsl_linalg_PTLQ_decomp (gsl_matrix * A, gsl_vector * tau,
gsl_permutation * p, int *signum,
gsl_vector * norm);
GSL_FUN int gsl_linalg_PTLQ_decomp2 (const gsl_matrix * A, gsl_matrix * q,
gsl_matrix * r, gsl_vector * tau,
gsl_permutation * p, int *signum,
gsl_vector * norm);
GSL_FUN int gsl_linalg_PTLQ_solve_T (const gsl_matrix * QR,
const gsl_vector * tau,
const gsl_permutation * p,
const gsl_vector * b,
gsl_vector * x);
GSL_FUN int gsl_linalg_PTLQ_svx_T (const gsl_matrix * LQ,
const gsl_vector * tau,
const gsl_permutation * p,
gsl_vector * x);
GSL_FUN int gsl_linalg_PTLQ_LQsolve_T (const gsl_matrix * Q, const gsl_matrix * L,
const gsl_permutation * p,
const gsl_vector * b,
gsl_vector * x);
GSL_FUN int gsl_linalg_PTLQ_Lsolve_T (const gsl_matrix * LQ,
const gsl_permutation * p,
const gsl_vector * b,
gsl_vector * x);
GSL_FUN int gsl_linalg_PTLQ_Lsvx_T (const gsl_matrix * LQ,
const gsl_permutation * p,
gsl_vector * x);
GSL_FUN int gsl_linalg_PTLQ_update (gsl_matrix * Q, gsl_matrix * L,
const gsl_permutation * p,
const gsl_vector * v, gsl_vector * w);
/* Cholesky Decomposition */
GSL_FUN int gsl_linalg_cholesky_decomp (gsl_matrix * A);
GSL_FUN int gsl_linalg_cholesky_decomp1 (gsl_matrix * A);
GSL_FUN int gsl_linalg_cholesky_solve (const gsl_matrix * cholesky,
const gsl_vector * b,
gsl_vector * x);
GSL_FUN int gsl_linalg_cholesky_solve_mat (const gsl_matrix * cholesky,
const gsl_matrix * B,
gsl_matrix * X);
GSL_FUN int gsl_linalg_cholesky_svx (const gsl_matrix * cholesky,
gsl_vector * x);
GSL_FUN int gsl_linalg_cholesky_svx_mat (const gsl_matrix * cholesky,
gsl_matrix * X);
GSL_FUN int gsl_linalg_cholesky_invert(gsl_matrix * cholesky);
/* Cholesky decomposition with unit-diagonal triangular parts.
* A = L D L^T, where diag(L) = (1,1,...,1).
* Upon exit, A contains L and L^T as for Cholesky, and
* the diagonal of A is (1,1,...,1). The vector Dis set
* to the diagonal elements of the diagonal matrix D.
*/
GSL_FUN int gsl_linalg_cholesky_decomp_unit(gsl_matrix * A, gsl_vector * D);
GSL_FUN int gsl_linalg_cholesky_scale(const gsl_matrix * A, gsl_vector * S);
GSL_FUN int gsl_linalg_cholesky_scale_apply(gsl_matrix * A, const gsl_vector * S);
GSL_FUN int gsl_linalg_cholesky_decomp2(gsl_matrix * A, gsl_vector * S);
GSL_FUN int gsl_linalg_cholesky_svx2 (const gsl_matrix * LLT,
const gsl_vector * S,
gsl_vector * x);
GSL_FUN int gsl_linalg_cholesky_solve2 (const gsl_matrix * LLT,
const gsl_vector * S,
const gsl_vector * b,
gsl_vector * x);
GSL_FUN int gsl_linalg_cholesky_rcond (const gsl_matrix * LLT, double * rcond,
gsl_vector * work);
/* Complex Cholesky Decomposition */
GSL_FUN int gsl_linalg_complex_cholesky_decomp (gsl_matrix_complex * A);
GSL_FUN int gsl_linalg_complex_cholesky_solve (const gsl_matrix_complex * cholesky,
const gsl_vector_complex * b,
gsl_vector_complex * x);
GSL_FUN int gsl_linalg_complex_cholesky_svx (const gsl_matrix_complex * cholesky,
gsl_vector_complex * x);
GSL_FUN int gsl_linalg_complex_cholesky_invert(gsl_matrix_complex * cholesky);
/* Pivoted Cholesky LDLT decomposition */
GSL_FUN int gsl_linalg_pcholesky_decomp (gsl_matrix * A, gsl_permutation * p);
GSL_FUN int gsl_linalg_pcholesky_solve(const gsl_matrix * LDLT,
const gsl_permutation * p,
const gsl_vector * b,
gsl_vector * x);
GSL_FUN int gsl_linalg_pcholesky_svx(const gsl_matrix * LDLT,
const gsl_permutation * p,
gsl_vector * x);
GSL_FUN int gsl_linalg_pcholesky_decomp2(gsl_matrix * A, gsl_permutation * p,
gsl_vector * S);
GSL_FUN int gsl_linalg_pcholesky_solve2(const gsl_matrix * LDLT,
const gsl_permutation * p,
const gsl_vector * S,
const gsl_vector * b,
gsl_vector * x);
GSL_FUN int gsl_linalg_pcholesky_svx2(const gsl_matrix * LDLT,
const gsl_permutation * p,
const gsl_vector * S,
gsl_vector * x);
GSL_FUN int gsl_linalg_pcholesky_invert(const gsl_matrix * LDLT, const gsl_permutation * p,
gsl_matrix * Ainv);
GSL_FUN int gsl_linalg_pcholesky_rcond (const gsl_matrix * LDLT, const gsl_permutation * p,
double * rcond, gsl_vector * work);
/* Modified Cholesky decomposition */
GSL_FUN int gsl_linalg_mcholesky_decomp (gsl_matrix * A, gsl_permutation * p,
gsl_vector * E);
GSL_FUN int gsl_linalg_mcholesky_solve(const gsl_matrix * LDLT,
const gsl_permutation * p,
const gsl_vector * b,
gsl_vector * x);
GSL_FUN int gsl_linalg_mcholesky_svx(const gsl_matrix * LDLT,
const gsl_permutation * p,
gsl_vector * x);
GSL_FUN int gsl_linalg_mcholesky_rcond (const gsl_matrix * LDLT, const gsl_permutation * p,
double * rcond, gsl_vector * work);
GSL_FUN int gsl_linalg_mcholesky_invert(const gsl_matrix * LDLT, const gsl_permutation * p,
gsl_matrix * Ainv);
/* Banded Cholesky decomposition */
GSL_FUN int gsl_linalg_cholesky_band_decomp(gsl_matrix * A);
GSL_FUN int gsl_linalg_cholesky_band_solve (const gsl_matrix * LLT, const gsl_vector * b,
gsl_vector * x);
GSL_FUN int gsl_linalg_cholesky_band_svx (const gsl_matrix * LLT, gsl_vector * x);
GSL_FUN int gsl_linalg_cholesky_band_invert (const gsl_matrix * LLT, gsl_matrix * Ainv);
GSL_FUN int gsl_linalg_cholesky_band_unpack (const gsl_matrix * LLT, gsl_matrix * L);
GSL_FUN int gsl_linalg_cholesky_band_rcond (const gsl_matrix * LLT, double * rcond, gsl_vector * work);
/* L D L^T decomposition */
GSL_FUN int gsl_linalg_ldlt_decomp (gsl_matrix * A);
GSL_FUN int gsl_linalg_ldlt_solve (const gsl_matrix * LDLT, const gsl_vector * b, gsl_vector * x);
GSL_FUN int gsl_linalg_ldlt_svx (const gsl_matrix * LDLT, gsl_vector * x);
GSL_FUN int gsl_linalg_ldlt_rcond (const gsl_matrix * LDLT, double * rcond, gsl_vector * work);
/* Banded L D L^T decomposition */
GSL_FUN int gsl_linalg_ldlt_band_decomp (gsl_matrix * A);
GSL_FUN int gsl_linalg_ldlt_band_solve (const gsl_matrix * LDLT, const gsl_vector * b, gsl_vector * x);
GSL_FUN int gsl_linalg_ldlt_band_svx (const gsl_matrix * LDLT, gsl_vector * x);
GSL_FUN int gsl_linalg_ldlt_band_unpack (const gsl_matrix * LDLT, gsl_matrix * L, gsl_vector * D);
GSL_FUN int gsl_linalg_ldlt_band_rcond (const gsl_matrix * LDLT, double * rcond, gsl_vector * work);
/* Symmetric to symmetric tridiagonal decomposition */
GSL_FUN int gsl_linalg_symmtd_decomp (gsl_matrix * A,
gsl_vector * tau);
GSL_FUN int gsl_linalg_symmtd_unpack (const gsl_matrix * A,
const gsl_vector * tau,
gsl_matrix * Q,
gsl_vector * diag,
gsl_vector * subdiag);
GSL_FUN int gsl_linalg_symmtd_unpack_T (const gsl_matrix * A,
gsl_vector * diag,
gsl_vector * subdiag);
/* Hermitian to symmetric tridiagonal decomposition */
GSL_FUN int gsl_linalg_hermtd_decomp (gsl_matrix_complex * A,
gsl_vector_complex * tau);
GSL_FUN int gsl_linalg_hermtd_unpack (const gsl_matrix_complex * A,
const gsl_vector_complex * tau,
gsl_matrix_complex * U,
gsl_vector * diag,
gsl_vector * sudiag);
GSL_FUN int gsl_linalg_hermtd_unpack_T (const gsl_matrix_complex * A,
gsl_vector * diag,
gsl_vector * subdiag);
/* Linear Solve Using Householder Transformations
* exceptions:
*/
GSL_FUN int gsl_linalg_HH_solve (gsl_matrix * A, const gsl_vector * b, gsl_vector * x);
GSL_FUN int gsl_linalg_HH_svx (gsl_matrix * A, gsl_vector * x);
/* Linear solve for a symmetric tridiagonal system.
* The input vectors represent the NxN matrix as follows:
*
* diag[0] offdiag[0] 0 ...
* offdiag[0] diag[1] offdiag[1] ...
* 0 offdiag[1] diag[2] ...
* 0 0 offdiag[2] ...
* ... ... ... ...
*/
GSL_FUN int gsl_linalg_solve_symm_tridiag (const gsl_vector * diag,
const gsl_vector * offdiag,
const gsl_vector * b,
gsl_vector * x);
/* Linear solve for a nonsymmetric tridiagonal system.
* The input vectors represent the NxN matrix as follows:
*
* diag[0] abovediag[0] 0 ...
* belowdiag[0] diag[1] abovediag[1] ...
* 0 belowdiag[1] diag[2] ...
* 0 0 belowdiag[2] ...
* ... ... ... ...
*/
GSL_FUN int gsl_linalg_solve_tridiag (const gsl_vector * diag,
const gsl_vector * abovediag,
const gsl_vector * belowdiag,
const gsl_vector * b,
gsl_vector * x);
/* Linear solve for a symmetric cyclic tridiagonal system.
* The input vectors represent the NxN matrix as follows:
*
* diag[0] offdiag[0] 0 ..... offdiag[N-1]
* offdiag[0] diag[1] offdiag[1] .....
* 0 offdiag[1] diag[2] .....
* 0 0 offdiag[2] .....
* ... ...
* offdiag[N-1] ...
*/
GSL_FUN int gsl_linalg_solve_symm_cyc_tridiag (const gsl_vector * diag,
const gsl_vector * offdiag,
const gsl_vector * b,
gsl_vector * x);
/* Linear solve for a nonsymmetric cyclic tridiagonal system.
* The input vectors represent the NxN matrix as follows:
*
* diag[0] abovediag[0] 0 ..... belowdiag[N-1]
* belowdiag[0] diag[1] abovediag[1] .....
* 0 belowdiag[1] diag[2]
* 0 0 belowdiag[2] .....
* ... ...
* abovediag[N-1] ...
*/
GSL_FUN int gsl_linalg_solve_cyc_tridiag (const gsl_vector * diag,
const gsl_vector * abovediag,
const gsl_vector * belowdiag,
const gsl_vector * b,
gsl_vector * x);
/* Bidiagonal decomposition */
GSL_FUN int gsl_linalg_bidiag_decomp (gsl_matrix * A,
gsl_vector * tau_U,
gsl_vector * tau_V);
GSL_FUN int gsl_linalg_bidiag_unpack (const gsl_matrix * A,
const gsl_vector * tau_U,
gsl_matrix * U,
const gsl_vector * tau_V,
gsl_matrix * V,
gsl_vector * diag,
gsl_vector * superdiag);
GSL_FUN int gsl_linalg_bidiag_unpack2 (gsl_matrix * A,
gsl_vector * tau_U,
gsl_vector * tau_V,
gsl_matrix * V);
GSL_FUN int gsl_linalg_bidiag_unpack_B (const gsl_matrix * A,
gsl_vector * diag,
gsl_vector * superdiag);
/* Balancing */
GSL_FUN int gsl_linalg_balance_matrix (gsl_matrix * A, gsl_vector * D);
GSL_FUN int gsl_linalg_balance_accum (gsl_matrix * A, gsl_vector * D);
GSL_FUN int gsl_linalg_balance_columns (gsl_matrix * A, gsl_vector * D);
/* condition estimation */
GSL_FUN int gsl_linalg_tri_rcond(CBLAS_UPLO_t Uplo, const gsl_matrix * A, double * rcond, gsl_vector * work);
GSL_FUN int gsl_linalg_tri_upper_rcond(const gsl_matrix * A, double * rcond, gsl_vector * work);
GSL_FUN int gsl_linalg_tri_lower_rcond(const gsl_matrix * A, double * rcond, gsl_vector * work);
GSL_FUN int gsl_linalg_invnorm1(const size_t N,
int (* Ainvx)(CBLAS_TRANSPOSE_t TransA, gsl_vector * x, void * params),
void * params, double * Ainvnorm, gsl_vector * work);
/* triangular matrices */
GSL_FUN int gsl_linalg_tri_upper_invert(gsl_matrix * T);
GSL_FUN int gsl_linalg_tri_lower_invert(gsl_matrix * T);
GSL_FUN int gsl_linalg_tri_upper_unit_invert(gsl_matrix * T);
GSL_FUN int gsl_linalg_tri_lower_unit_invert(gsl_matrix * T);
GSL_FUN int gsl_linalg_tri_invert(CBLAS_UPLO_t Uplo, CBLAS_DIAG_t Diag, gsl_matrix * T);
GSL_FUN int gsl_linalg_complex_tri_invert(CBLAS_UPLO_t Uplo, CBLAS_DIAG_t Diag, gsl_matrix_complex * T);
GSL_FUN int gsl_linalg_tri_LTL(gsl_matrix * L);
GSL_FUN int gsl_linalg_tri_UL(gsl_matrix * LU);
GSL_FUN int gsl_linalg_complex_tri_LHL(gsl_matrix_complex * L);
GSL_FUN int gsl_linalg_complex_tri_UL(gsl_matrix_complex * LU);
GSL_FUN INLINE_DECL void gsl_linalg_givens (const double a, const double b,
double *c, double *s);
GSL_FUN INLINE_DECL void gsl_linalg_givens_gv (gsl_vector * v, const size_t i,
const size_t j, const double c,
const double s);
#ifdef HAVE_INLINE
/* Generate a Givens rotation (cos,sin) which takes v=(x,y) to (|v|,0)
From Golub and Van Loan, "Matrix Computations", Section 5.1.8 */
INLINE_FUN
void
gsl_linalg_givens (const double a, const double b, double *c, double *s)
{
if (b == 0)
{
*c = 1;
*s = 0;
}
else if (fabs (b) > fabs (a))
{
double t = -a / b;
double s1 = 1.0 / sqrt (1 + t * t);
*s = s1;
*c = s1 * t;
}
else
{
double t = -b / a;
double c1 = 1.0 / sqrt (1 + t * t);
*c = c1;
*s = c1 * t;
}
} /* gsl_linalg_givens() */
INLINE_FUN
void
gsl_linalg_givens_gv (gsl_vector * v, const size_t i, const size_t j,
const double c, const double s)
{
/* Apply rotation to vector v' = G^T v */
double vi = gsl_vector_get (v, i);
double vj = gsl_vector_get (v, j);
gsl_vector_set (v, i, c * vi - s * vj);
gsl_vector_set (v, j, s * vi + c * vj);
}
#endif /* HAVE_INLINE */
__END_DECLS
#endif /* __GSL_LINALG_H__ */
| 39.467059 | 122 | 0.593853 | [
"vector"
] |
ebe64a95f212e4cfd98d9a6dc8c6e828f94829fe | 2,584 | h | C | include/sequence.h | lskatz/quicktree | bc1f9d8b8e914a4dbb80b3427300b86e361e026d | [
"Apache-2.0"
] | 9 | 2017-04-09T10:55:03.000Z | 2022-02-08T22:47:03.000Z | include/sequence.h | lskatz/quicktree | bc1f9d8b8e914a4dbb80b3427300b86e361e026d | [
"Apache-2.0"
] | 7 | 2017-07-31T17:37:37.000Z | 2020-05-23T18:33:16.000Z | include/sequence.h | lskatz/quicktree | bc1f9d8b8e914a4dbb80b3427300b86e361e026d | [
"Apache-2.0"
] | 7 | 2017-04-09T08:20:57.000Z | 2021-02-05T20:44:00.000Z | /**********************************************************************
* File: sequence.h
* Author: Kevin Howe
* Copyright (C) Genome Research Limited, 2002-
*-------------------------------------------------------------------
* 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.
*-------------------------------------------------------------------
* NOTES:
* Functions and structures for the manipulation of protein
* sequences. Only minimal functionality is needed
**********************************************************************/
#ifndef _SEQUENCE
#define _SEQUENCE
#include <string.h>
#include "util.h"
#define MAX_NAME_LENGTH 25
/******************* structure definitions ****************************/
struct Sequence {
unsigned int length;
char *name;
char *seq;
char *sec_struct;
char *surf_acc;
char *trans_mem;
char *post_prob;
char *lig_bind;
};
/********************** function prototypes ***************************/
/**********************************************************************
FUNCTION: clone_Sequence
DESCRIPTION:
Performs a deep copy of the given Sequence and returns it
ARGS:
A Sequenced pointer (sequence.h)
RETURNS:
A pointer to a Sequence structure
NOTES:
**********************************************************************/
struct Sequence *clone_Sequence( struct Sequence *);
/**********************************************************************
FUNCTION: empty_Sequence
DESCRIPTION:
Creates and returns an new, empty Sequence object
ARGS:
RETURNS:
A pointer to a Sequence structure
NOTES:
**********************************************************************/
struct Sequence *empty_Sequence( void );
/**********************************************************************
FUNCTION: free_Sequence
DESCRIPTION:
frees the memory occupied by the given Sequence reference
ARGS:
A pointer to a struct Sequence
RETURNS:
The NULL pointer
NOTES:
**********************************************************************/
void *free_Sequence( struct Sequence *);
#endif
| 31.512195 | 75 | 0.508901 | [
"object"
] |
ebe6d4362d1ddeb1cb223acc36d97f95206745aa | 24,051 | c | C | SeggerEval_WIN32_MSVC_MinGW_GUI_V550/Sample/Application/WeatherForecast_480x272/MainTask.c | washingtonxr/Open_emWinDemo | ba370c00d4fbfe015740427e6002ca9b09a05b96 | [
"MIT"
] | null | null | null | SeggerEval_WIN32_MSVC_MinGW_GUI_V550/Sample/Application/WeatherForecast_480x272/MainTask.c | washingtonxr/Open_emWinDemo | ba370c00d4fbfe015740427e6002ca9b09a05b96 | [
"MIT"
] | null | null | null | SeggerEval_WIN32_MSVC_MinGW_GUI_V550/Sample/Application/WeatherForecast_480x272/MainTask.c | washingtonxr/Open_emWinDemo | ba370c00d4fbfe015740427e6002ca9b09a05b96 | [
"MIT"
] | 1 | 2020-04-29T18:22:32.000Z | 2020-04-29T18:22:32.000Z | /*********************************************************************
* SEGGER Microcontroller GmbH *
* Solutions for real time microcontroller applications *
**********************************************************************
* *
* (c) 1996 - 2019 SEGGER Microcontroller GmbH *
* *
* Internet: www.segger.com Support: support@segger.com *
* *
**********************************************************************
** emWin V5.50 - Graphical user interface for embedded applications **
emWin is protected by international copyright laws. Knowledge of the
source code may not be used to write a similar product. This file may
only be used in accordance with a license and should not be re-
distributed in any way. We appreciate your understanding and fairness.
----------------------------------------------------------------------
File : MainTask.c
Purpose : Weather forecast demo using multiple layers
Requirements: WindowManager - ( )
MemoryDevices - ( )
AntiAliasing - ( )
VNC-Server - ( )
PNG-Library - ( )
TrueTypeFonts - ( )
---------------------------END-OF-HEADER------------------------------
*/
#include <stddef.h>
#include "DIALOG.h"
#include "Resource.h"
/*********************************************************************
*
* Defines
*
**********************************************************************
*/
#define XOFF_TEXT0 50
#define XOFF_TEXT1 55
#define XOFF_IMAGE 10
#define JOB_ANIM_IN 1
#define JOB_ANIM_IN_DROP 2
#define JOB_ANIM_OUT 3
#define JOB_ANIM_IDLE 4
#define YPOS_DROP 150
#define YPOS_FORECAST 182
#define YSIZE_FORECAST 60
#define YSIZE_FORECAST_IMG 40
#define YSIZE_FORECAST_FRAME ((YSIZE_FORECAST - YSIZE_FORECAST_IMG) / 2)
#define YPOS_FORECAST_IMG (YPOS_FORECAST + YSIZE_FORECAST_FRAME)
#define XPOS_TEXT 100
#define YPOS_TEXT 50
#define XSIZE_TEXT 280
#define YSIZE_TEXT 60
#define INDICATOR_R 5
#define INDICATOR_XDIST 20
#define TIME_IDLE 5000
//
// Recommended memory to run the sample with adequate performance
//
#define RECOMMENDED_MEMORY (24 * 1024) // Should be adapted, value is too less
/*********************************************************************
*
* Types
*
**********************************************************************
*/
//
// Indices for _apBmSym
//
typedef enum {
INDEX_SYM_PARTLY_CLOUDY = 0,
INDEX_SYM_CLOUD_LIGHTING,
INDEX_SYM_RAIN,
INDEX_SYM_CHANCE_OF_STORM,
INDEX_SYM_SUN
} INDEX_SYM;
//
// Indices for images in _apBmBack
//
typedef enum {
INDEX_BK_BERLIN = 0,
INDEX_BK_MOSCOW,
INDEX_BK_NY,
INDEX_BK_TOKYO
} INDEX_BK;
//
// Positioning data for animated icons
//
typedef struct PARA PARA;
typedef struct WINDOW_DATA WINDOW_DATA;
struct PARA {
int xPos;
int xSizeScreen;
int xSize;
int OldPos;
WINDOW_DATA * pData;
int Index;
};
struct WINDOW_DATA {
int xSize;
int ySize;
int xPos;
int yOff;
U8 Alpha;
WM_HTIMER hTimer;
WM_HWIN hWin;
WM_HWIN hText;
GUI_ANIM_HANDLE hAnimSymbol;
GUI_ANIM_HANDLE hAnimBackground;
PARA aPara[5];
GUI_TIMER_TIME TimeLastTouch;
int Job;
int LastJob;
int IndexCity;
int IndexAnimIn;
int IndexAnimOut;
int HasStopped;
int Diff;
};
/*********************************************************************
*
* Static data
*
**********************************************************************
*/
GUI_CONST_STORAGE GUI_BITMAP * _apBmBack[] = {
&bmberlin_480x272,
&bmmoscow_480x272,
&bmnew_york_480x272,
&bmtokyo_480x272,
};
static GUI_CONST_STORAGE GUI_BITMAP * _apBmSym[] = {
&bmpartly_cloudy_day40x40,
&bmcloud_lighting40x40,
&bmrain40x40,
&bmchance_of_storm40x40,
&bmsun40x40,
};
static const char * _pDays[] = { "MON", "TUE", "WED", "THU", "FRI" };
static const struct CITY {
const char * pName;
const char * pTime;
int Temperature;
int Weather;
const unsigned aForeCast[5];
const unsigned aTemp[5];
} _aCity[] = {
{
"BERLIN",
"15:20",
26,
INDEX_BK_BERLIN,
{
INDEX_SYM_CHANCE_OF_STORM,
INDEX_SYM_CLOUD_LIGHTING,
INDEX_SYM_RAIN,
INDEX_SYM_SUN,
INDEX_SYM_PARTLY_CLOUDY,
},
{ 28, 24, 25, 29, 30 },
},
{
"TOKYO",
"23:20",
22,
INDEX_BK_TOKYO,
{
INDEX_SYM_PARTLY_CLOUDY,
INDEX_SYM_CLOUD_LIGHTING,
INDEX_SYM_RAIN,
INDEX_SYM_CHANCE_OF_STORM,
INDEX_SYM_SUN,
},
{ 20, 18, 16, 19, 23 },
},
{
"MOSCOW",
"17:20",
18,
INDEX_BK_MOSCOW,
{
INDEX_SYM_SUN,
INDEX_SYM_PARTLY_CLOUDY,
INDEX_SYM_SUN,
INDEX_SYM_CLOUD_LIGHTING,
INDEX_SYM_RAIN,
},
{ 21, 18, 16, 14, 14 },
},
{
"NEW YORK",
"10:20",
25,
INDEX_BK_NY,
{
INDEX_SYM_RAIN,
INDEX_SYM_PARTLY_CLOUDY,
INDEX_SYM_SUN,
INDEX_SYM_SUN,
INDEX_SYM_SUN,
},
{ 28, 30, 32, 33, 30 },
},
};
/*********************************************************************
*
* Static code
*
**********************************************************************
*/
/*********************************************************************
*
* _SliceInfo
*/
static void _SliceInfo(int State, void * pVoid) {
GUI_USE_PARA(pVoid);
//
// Avoid flickering of layer 1 during animation
//
switch (State) {
case GUI_ANIM_START:
GUI_MULTIBUF_BeginEx(1);
break;
case GUI_ANIM_END:
GUI_MULTIBUF_EndEx(1);
break;
}
}
/*********************************************************************
*
* _MakeSymRect
*/
static void _MakeSymRect(GUI_RECT * pRect, int xPos, int xSize) {
pRect->x0 = xPos;
pRect->x1 = pRect->x0 + xSize - 1;
pRect->y0 = YPOS_FORECAST_IMG;
pRect->y1 = pRect->y0 + YSIZE_FORECAST_IMG - 1;
}
/*********************************************************************
*
* _AnimDrawSym
*/
static void _AnimDrawSym(PARA * pPara, int xPos, int IndexCity) {
GUI_DrawBitmap(_apBmSym[_aCity[IndexCity].aForeCast[pPara->Index]], xPos + XOFF_IMAGE, YPOS_FORECAST_IMG);
GUI_SetFont(&GUI_Font20_AA4);
GUI_SetTextMode(GUI_TM_TRANS);
GUI_SetColor(GUI_MAKE_COLOR(0x00B56D30));
GUI_AA_PreserveTrans(1);
GUI_DispStringAt(_pDays[pPara->Index], xPos + XOFF_TEXT0, YPOS_FORECAST_IMG);
GUI_GotoXY(xPos + XOFF_TEXT1, YPOS_FORECAST_IMG + 20);
GUI_DispDecMin(_aCity[IndexCity].aTemp[pPara->Index]);
GUI_DispString("\xb0""C");
GUI_AA_PreserveTrans(0);
}
/*********************************************************************
*
* _DrawBar
*/
static void _DrawBar(int x0, int y0, int x1, int y1, int SkipBorder) {
int y;
y = (y1 + y0) / 2;
GUI_SetColor(GUI_MAKE_COLOR(0x55FFFFFF));
if (SkipBorder) {
//
// Draw only inner part
//
GUI_DrawGradientV(x0, y0, x1, y, GUI_MAKE_COLOR(0x55FFFFFF), GUI_MAKE_COLOR(0x20FFFFFF));
GUI_DrawGradientV(x0, y + 1, x1, y1, GUI_MAKE_COLOR(0x20FFFFFF), GUI_MAKE_COLOR(0x55FFFFFF));
} else {
//
// Draw frame and inner part
//
GUI_FillRect(x0, y0 + 1, x1, y0 + YSIZE_FORECAST_FRAME - 1);
GUI_DrawGradientV(x0, y0 + YSIZE_FORECAST_FRAME, x1, y, GUI_MAKE_COLOR(0x55FFFFFF), GUI_MAKE_COLOR(0x20FFFFFF));
GUI_DrawGradientV(x0, y + 1, x1, y1 - YSIZE_FORECAST_FRAME, GUI_MAKE_COLOR(0x20FFFFFF), GUI_MAKE_COLOR(0x55FFFFFF));
GUI_FillRect(x0, y1 - YSIZE_FORECAST_FRAME + 1, x1, y1 - 1);
GUI_SetColor(GUI_MAKE_COLOR(0x55555555));
GUI_DrawHLine(y0, x0, x1);
GUI_DrawHLine(y1, x0, x1);
}
}
/*********************************************************************
*
* _DrawBarEx
*/
static void _DrawBarEx(GUI_RECT * pRect) {
_DrawBar(pRect->x0, pRect->y0, pRect->x1, pRect->y1, 1);
}
/*********************************************************************
*
* _DrawIndicators
*/
static void _DrawIndicators(WINDOW_DATA * pData) {
int i, Index, NumItems, mx, my;
U32 Color;
GUI_RECT Rect;
WM_SelectWindow(pData->hWin);
GUI_SelectLayer(1);
Index = pData->xPos / pData->xSize;
NumItems = GUI_COUNTOF(_apBmBack);
mx = (pData->xSize - (INDICATOR_XDIST * (NumItems - 1))) / 2;
my = YPOS_FORECAST + YSIZE_FORECAST + (pData->ySize - (YPOS_FORECAST + YSIZE_FORECAST)) / 2;
Rect.x0 = mx - INDICATOR_R;
Rect.y0 = my - INDICATOR_R;
Rect.x1 = mx + INDICATOR_R + (INDICATOR_XDIST * (NumItems - 1));
Rect.y1 = my + INDICATOR_R;
GUI_SetBkColor(GUI_TRANSPARENT);
GUI_ClearRectEx(&Rect);
GUI_AA_PreserveTrans(1);
for (i = 0; i < NumItems; i++) {
Color = (Index == i) ? GUI_WHITE : GUI_MAKE_COLOR(0x00B56D30);
GUI_SetColor(Color);
GUI_AA_FillCircle(mx + i * INDICATOR_XDIST, my, INDICATOR_R);
}
GUI_AA_PreserveTrans(0);
GUI_SelectLayer(0);
}
/*********************************************************************
*
* _AnimSymbolFlyIn
*/
static void _AnimSymbolFlyIn(GUI_ANIM_INFO * pInfo, void * pVoid) {
PARA * pPara;
GUI_RECT Rect;
int Dyn, Fix, xPos;
pPara = (PARA *)pVoid;
WM_SelectWindow(pPara->pData->hWin);
GUI_SelectLayer(1);
GUI_SetBkColor(GUI_MAKE_COLOR(0x55FFFFFF));
Fix = pPara->xSizeScreen + pPara->xPos - pPara->xSize / 2;
if (pInfo->State != GUI_ANIM_START) {
Dyn = (pPara->xSizeScreen * pPara->OldPos) / GUI_ANIM_RANGE;
_MakeSymRect(&Rect, Fix - Dyn, pPara->xSize);
_DrawBarEx(&Rect);
}
pPara->OldPos = (pInfo->State == GUI_ANIM_END) ? 0 : pInfo->Pos;
Dyn = (pPara->xSizeScreen * pInfo->Pos) / GUI_ANIM_RANGE;
xPos = Fix - Dyn;
_AnimDrawSym(pPara, xPos, pPara->pData->IndexAnimIn);
}
/*********************************************************************
*
* _AnimSymbolFlyOut
*/
static void _AnimSymbolFlyOut(GUI_ANIM_INFO * pInfo, void * pVoid) {
PARA * pPara;
GUI_RECT Rect;
int Dyn, Fix, xPos;
pPara = (PARA *)pVoid;
WM_SelectWindow(pPara->pData->hWin);
GUI_SelectLayer(1);
GUI_SetBkColor(GUI_MAKE_COLOR(0x55FFFFFF));
Fix = pPara->xPos - pPara->xSize / 2 - pPara->xSizeScreen;
Dyn = (pPara->xSizeScreen * (GUI_ANIM_RANGE - pPara->OldPos)) / GUI_ANIM_RANGE;
_MakeSymRect(&Rect, Fix + Dyn, pPara->xSize);
_DrawBarEx(&Rect);
pPara->OldPos = pInfo->Pos;
Dyn = (pPara->xSizeScreen * (GUI_ANIM_RANGE - pInfo->Pos)) / GUI_ANIM_RANGE;
xPos = Fix + Dyn;
_AnimDrawSym(pPara, xPos, pPara->pData->IndexAnimOut);
}
/*********************************************************************
*
* _MakeTextRect
*/
static void _MakeTextRect(GUI_RECT * pRect, int yOff) {
pRect->x0 = XPOS_TEXT;
pRect->y0 = YPOS_TEXT - yOff;
pRect->x1 = pRect->x0 + XSIZE_TEXT - 1;
pRect->y1 = pRect->y0 + YSIZE_TEXT - 1;;
}
/*********************************************************************
*
* _cbText
*
* Purpose:
* Callback function of text window responsible for drawing
* city, time and temperature
*/
static void _cbText(WM_MESSAGE * pMsg) {
GUI_COLOR aColor[] = {
GUI_DARKGRAY, GUI_WHITE
};
unsigned int i;
GUI_RECT Rect;
WINDOW_DATA * pData;
static int yOffOld;
WM_GetUserData(pMsg->hWin, &pData, sizeof(WINDOW_DATA *));
switch (pMsg->MsgId) {
case WM_PAINT:
//
// Clear previous drawn text only
//
GUI_SetBkColor(GUI_TRANSPARENT);
_MakeTextRect(&Rect, yOffOld);
GUI_ClearRectEx(&Rect);
//
// Set alpha value (on demand) for fading effect
//
GUI_SetAlpha(GUI_MAKE_TRANS(pData->Alpha));
//
// Make sure transparency is available after blending operations
//
GUI_PreserveTrans(1);
//
// Draw text with 3D effect
//
GUI_SetTextMode(GUI_TM_TRANS);
for (i = 0; i < GUI_COUNTOF(aColor); i++) {
GUI_SetColor(aColor[i]);
GUI_SetFont(&GUI_Font32_AA4);
GUI_GotoXY(XPOS_TEXT + 1 + !i, YPOS_TEXT + 1 + !i - pData->yOff);
GUI_DispString(_aCity[pData->IndexCity].pName);
GUI_GotoXY(XPOS_TEXT + 1 + !i, YPOS_TEXT + 1 + 30 - pData->yOff + !i);
GUI_SetFont(&GUI_Font20_AA4);
GUI_DispString(_aCity[pData->IndexCity].pTime);
GUI_DispString(" SUNDAY 23 APR");
GUI_SetFont(&GUI_Font60_AA4);
GUI_GotoXY(XPOS_TEXT + 1 + 200 + !i, YPOS_TEXT + 1 - 5 - pData->yOff + !i);
GUI_DispDecMin(_aCity[pData->IndexCity].Temperature);
GUI_DispString("\xb0");
}
//
// Restore default behavior
//
GUI_PreserveTrans(0);
GUI_SetAlpha(GUI_MAKE_TRANS(0));
break;
case WM_POST_PAINT:
//
// Remember position for clearing operation
//
yOffOld = pData->yOff;
break;
default:
WM_DefaultProc(pMsg);
}
}
/*********************************************************************
*
* _AnimDropIn
*
* Purpose:
* Dropping text animation
*/
static void _AnimDropIn(GUI_ANIM_INFO * pInfo, void * pVoid) {
WINDOW_DATA * pData;
pData = (WINDOW_DATA *)pVoid;
//
// Only calculation of text position and invalidation required
//
pData->yOff = YPOS_DROP - (YPOS_DROP * pInfo->Pos) / GUI_ANIM_RANGE;
WM_InvalidateWindow(pData->hText);
}
/*********************************************************************
*
* _AnimBackground
*
* Purpose:
* Animation of background pictures. Done by feeding the PID buffer.
*/
static void _AnimBackground(GUI_ANIM_INFO * pInfo, void * pVoid) {
WINDOW_DATA * pData;
GUI_PID_STATE State;
static int Sign;
pData = (WINDOW_DATA *)pVoid;
pData->TimeLastTouch = GUI_GetTime();
if (pInfo->State == GUI_ANIM_START) {
Sign = ((GUI_GetTime() & 1) * 2) - 1;
}
State.Layer = 0;
State.Pressed = 1;
switch (Sign) {
case -1:
State.x = ((pData->xSize / 2 + 10) * pInfo->Pos) / GUI_ANIM_RANGE;
break;
case +1:
State.x = ((pData->xSize / 2 + 10) * (GUI_ANIM_RANGE - pInfo->Pos)) / GUI_ANIM_RANGE;
break;
}
State.y = 0;
GUI_PID_StoreState(&State);
if (pInfo->State == GUI_ANIM_END) {
State.Pressed = 0;
GUI_PID_StoreState(&State);
}
}
/*********************************************************************
*
* _OnDeleteAnimBackground
*
* Purpose:
* This function is called immediately before the animation object
* will be destroyed. It has only to set the animation handle to
* zero which is used in the application to check if the animation
* is running or not.
*/
static void _OnDeleteAnimBackground(void * pVoid) {
WINDOW_DATA * pData;
pData = (WINDOW_DATA *)pVoid;
pData->hAnimBackground = 0;
}
/*********************************************************************
*
* _OnDeleteAnimSymbol
*
* Purpose:
* (same as above...)
*/
static void _OnDeleteAnimSymbol(void * pVoid) {
WINDOW_DATA * pData;
pData = (WINDOW_DATA *)pVoid;
pData->hAnimSymbol = 0;
}
/*********************************************************************
*
* _OnTimer
*/
static void _OnTimer(WINDOW_DATA * pData) {
int NumItems, IndexCity, i;
if (pData->hAnimSymbol == 0) {
if (GUI_GetTime() >= (pData->TimeLastTouch + TIME_IDLE)) {
pData->Job = JOB_ANIM_IDLE;
} else {
if (pData->HasStopped) {
//
// After last move add 'Fly in of symbols' animation
//
if ((pData->LastJob != JOB_ANIM_IN) && (pData->LastJob != JOB_ANIM_IN_DROP)) {
IndexCity = pData->xPos / pData->xSize;
IndexCity = (IndexCity >= (int)GUI_COUNTOF(_aCity)) ? (int)GUI_COUNTOF(_aCity) - 1 : IndexCity;
pData->IndexAnimIn = pData->IndexCity;
if (pData->IndexCity != IndexCity) {
pData->Job = JOB_ANIM_IN_DROP;
pData->IndexCity = IndexCity;
pData->IndexAnimIn = IndexCity;
} else {
pData->Job = JOB_ANIM_IN;
}
WM_InvalidateWindow(pData->hWin);
}
}
}
//
// Create animations on demand
//
NumItems = GUI_COUNTOF(pData->aPara);
switch (pData->Job) {
case JOB_ANIM_IDLE:
if (pData->hAnimBackground == 0) {
pData->hAnimBackground = GUI_ANIM_Create(1000, 25, pData, NULL);
GUI_ANIM_AddItem(pData->hAnimBackground, 0, 1000, ANIM_ACCEL, pData, _AnimBackground);
GUI_ANIM_StartEx(pData->hAnimBackground, 1, _OnDeleteAnimBackground);
pData->Job = 0;
}
break;
case JOB_ANIM_IN_DROP:
case JOB_ANIM_IN:
pData->Alpha = 0;
if (pData->hAnimSymbol == 0) {
pData->hAnimSymbol = GUI_ANIM_Create(1000, 25, pData, _SliceInfo);
//
// Add 'Fly in of symbols' to animation
//
for (i = 0; i < NumItems; i++) {
GUI_ANIM_AddItem(pData->hAnimSymbol, i * 100, i * 100 + 500, ANIM_DECEL, &pData->aPara[i], _AnimSymbolFlyIn);
}
if (pData->Job == JOB_ANIM_IN_DROP) {
//
// Add 'Drop in text' to animation
//
GUI_ANIM_AddItem(pData->hAnimSymbol, 0, 300, ANIM_DECEL, pData, _AnimDropIn);
}
GUI_ANIM_StartEx(pData->hAnimSymbol, 1, _OnDeleteAnimSymbol);
pData->LastJob = pData->Job;
pData->Job = 0;
}
break;
case JOB_ANIM_OUT:
if (pData->hAnimSymbol == 0) {
pData->hAnimSymbol = GUI_ANIM_Create(1000, 25, pData, _SliceInfo);
//
// Add 'Fly out of symbols' to animation
//
for (i = 0; i < NumItems; i++) {
GUI_ANIM_AddItem(pData->hAnimSymbol, i * 100, i * 100 + 500, ANIM_ACCEL, &pData->aPara[i], _AnimSymbolFlyOut);
}
GUI_ANIM_StartEx(pData->hAnimSymbol, 1, _OnDeleteAnimSymbol);
pData->LastJob = pData->Job;
pData->Job = 0;
}
break;
}
}
WM_RestartTimer(pData->hTimer, 25);
}
/*********************************************************************
*
* _cbWin
*/
static void _cbWin(WM_MESSAGE * pMsg) {
WM_MOTION_INFO * pInfo;
WM_HWIN hWin;
WINDOW_DATA * pData;
GUI_PID_STATE State;
int i, x0, Index, NumItems;
hWin = pMsg->hWin;
NumItems = GUI_COUNTOF(_apBmBack);
WM_GetUserData(hWin, &pData, sizeof(WINDOW_DATA *));
if (pData) {
if (pData->hTimer == 0) {
pData->hTimer = WM_CreateTimer(hWin, 0, 0, 0);
pData->Job = JOB_ANIM_IN_DROP;
_DrawIndicators(pData);
}
}
switch (pMsg->MsgId) {
//
// Draw background image(s)
//
case WM_PAINT:
for (i = 0; i <= NumItems; i++) {
Index = (i == NumItems) ? 0 : i;
x0 = pData->xPos - i * pData->xSize;
if ((x0 > -(int)pData->xSize) && (x0 < (int)pData->xSize)) {
GUI_DrawBitmap(_apBmBack[_aCity[Index].Weather], x0, 0);
}
}
break;
//
// Timer keeps the demo alive
//
case WM_TIMER:
_OnTimer(pData);
break;
//
// React on window motion messages
//
case WM_MOTION:
//
// Stop idle animation if it is currently running
//
GUI_PID_GetCurrentState(&State);
if (State.Pressed) {
if (State.y != 0) {
if (pData->hAnimBackground) {
GUI_ANIM_Stop(pData->hAnimBackground);
GUI_ANIM_Delete(pData->hAnimBackground);
pData->hAnimBackground = 0;
}
}
}
//
// Remember moment of last touch event
//
pData->TimeLastTouch = GUI_GetTime();
//
// Process motion commands
//
pInfo = (WM_MOTION_INFO *)pMsg->Data.p;
switch (pInfo->Cmd) {
case WM_MOTION_INIT:
//
// Tell motion support that window manages motion messages by itself
//
pInfo->Flags = WM_MOTION_MANAGE_BY_WINDOW;
pInfo->SnapX = pData->xSize;
pInfo->Period = 300;
break;
case WM_MOTION_MOVE:
//
// Manage motion message
//
pData->xPos += pInfo->dx;
if (pData->xPos >= (int)(NumItems * pData->xSize)) {
pData->xPos -= NumItems * pData->xSize;
}
if (pData->xPos < 0) {
pData->xPos += NumItems * pData->xSize;
}
//
// Calculate distance
//
pData->Diff = pData->xPos - pData->IndexCity * pData->xSize;
if ((pData->IndexCity == 0) && (pData->Diff > pData->xSize)) {
pData->Diff -= pData->xSize * NumItems;
}
pData->Diff = (pData->Diff > 0) ? pData->Diff : -pData->Diff;
//
// Calculate alpha value in dependence of window position
//
if (pData->Diff < pData->xSize) {
pData->Alpha = (pData->Diff * 255) / pData->xSize;
} else {
pData->Alpha = 255;
}
WM_InvalidateWindow(pData->hText);
if (pInfo->FinalMove) {
//
// After last move timer method should show forecast
//
pData->HasStopped = 1;
_DrawIndicators(pData);
} else {
//
// On first move hide forecast
//
pData->HasStopped = 0;
if (pData->Diff > (pData->xSize / 3)) {
if (pData->LastJob != JOB_ANIM_OUT) {
pData->IndexAnimOut = pData->IndexCity;
pData->Job = JOB_ANIM_OUT;
}
}
}
//
// Make sure that WM redraws window
//
WM_Invalidate(hWin);
break;
case WM_MOTION_GETPOS:
pInfo->xPos = pData->xPos;
break;
}
break;
default:
WM_DefaultProc(pMsg);
}
}
/*********************************************************************
*
* _ClearScreen
*/
static void _ClearScreen(void) {
int xSizeScreen;
GUI_SelectLayer(0);
GUI_SetBkColor(GUI_BLACK);
GUI_Clear();
GUI_SelectLayer(1);
GUI_SetBkColor(GUI_TRANSPARENT);
GUI_Clear();
GUI_SetColor(GUI_MAKE_COLOR(0x55FFFFFF));
xSizeScreen = LCD_GetXSize();
_DrawBar(0, YPOS_FORECAST, xSizeScreen, YPOS_FORECAST + YSIZE_FORECAST - 1, 0);
GUI_SelectLayer(0);
}
/*********************************************************************
*
* _InitData
*/
static void _InitData(WINDOW_DATA * pData) {
int i, NumItems, xSizeScreen, xSize;
NumItems = GUI_COUNTOF(pData->aPara);
xSizeScreen = LCD_GetXSize();
xSize = xSizeScreen / NumItems;
for (i = 0; i < NumItems; i++) {
pData->aPara[i].xSizeScreen = xSizeScreen;
pData->aPara[i].xSize = xSize;
pData->aPara[i].xPos = (xSize * i) + xSize / 2;
pData->aPara[i].pData = pData;
pData->aPara[i].Index = i;
}
}
/*********************************************************************
*
* Public code
*
**********************************************************************
*/
/*********************************************************************
*
* MainTask
*/
void MainTask(void) {
WINDOW_DATA * pData;
static WINDOW_DATA Data;
pData = &Data;
GUI_Init();
//
// Check if recommended memory for the sample is available
//
if (GUI_ALLOC_GetNumFreeBytes() < RECOMMENDED_MEMORY) {
GUI_ErrorOut("Not enough memory available.");
return;
}
//
// Set up used tools
//
WM_MULTIBUF_Enable(1);
_ClearScreen();
WM_MOTION_Enable(1);
//
// Shrink desktop window
//
Data.xSize = LCD_GetXSize();
Data.ySize = LCD_GetYSize();
Data.TimeLastTouch = GUI_GetTime();
WM_SetSize(WM_HBKWIN, Data.xSize, Data.ySize);
//
// Create background window
//
pData->hWin = WM_CreateWindowAsChild(0, 0, Data.xSize, Data.ySize, WM_HBKWIN, WM_CF_MOTION_X | WM_CF_SHOW, _cbWin, sizeof(WINDOW_DATA *));
//
// Create text window
//
GUI_SelectLayer(1);
pData->hText = WM_CreateWindowAsChild(100, 0, 280, 135, WM_HBKWIN, WM_CF_SHOW, _cbText, sizeof(WINDOW_DATA *));
GUI_SelectLayer(0);
//
// Initialize animation data
//
_InitData(pData);
//
// Make WINDOW_DATA available for windows
//
WM_SetUserData(pData->hWin, &pData, sizeof(WINDOW_DATA *));
WM_SetUserData(pData->hText, &pData, sizeof(WINDOW_DATA *));
//
// Super loop
//
while (1) {
GUI_Delay(100);
}
}
/*************************** End of file ****************************/
| 27.330682 | 140 | 0.551786 | [
"object",
"3d"
] |
ebe6e311c66d3323a5b7464a2450ee1c5a61503b | 10,893 | c | C | src/botlib/bot.c | keilaoko/nuclide | d2e55dfa0f53546754e63e1dd65f7cce4d3144db | [
"ISC"
] | null | null | null | src/botlib/bot.c | keilaoko/nuclide | d2e55dfa0f53546754e63e1dd65f7cce4d3144db | [
"ISC"
] | null | null | null | src/botlib/bot.c | keilaoko/nuclide | d2e55dfa0f53546754e63e1dd65f7cce4d3144db | [
"ISC"
] | null | null | null | /*
* Copyright (c) 2016-2020 Marco Hladik <marco@icculus.org>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF MIND, 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.
*/
#define BOTROUTE_DESTINATION -1
#define BOTROUTE_END -2
void SV_SendChat(entity sender, string msg, entity eEnt, float fType);
void
bot::ChatSay(string msg)
{
SV_SendChat(this, msg, world, 0);
}
void
bot::ChatSayTeam(string msg)
{
entity a;
for (a = world; (a = find(a, ::classname, "player"));) {
if (a.team == this.team) {
SV_SendChat(self, msg, a, 1);
}
}
}
void
bot::Pain(void)
{
player::Pain();
/* might as well target our attacker */
m_eTarget = g_dmg_eAttacker;
}
void
bot::RouteClear(void)
{
if (!m_iNodes)
return;
m_iCurNode = BOTROUTE_END;
m_iNodes = 0;
m_flNodeGiveup = 0.0f;
memfree(m_pRoute);
}
void
bot::WeaponThink(void)
{
/* clip empty */
if (a_ammo1 == 0) {
/* still got ammo left, reload! */
if (a_ammo2 != 0) {
input_buttons &= ~INPUT_BUTTON0;
input_buttons |= INPUT_BUTTON4;
} else {
Weapons_SwitchBest(this);
}
}
}
void
bot::WeaponAttack(void)
{
if (m_flAttackTime < time) {
if (!m_iAttackMode) {
input_buttons |= INPUT_BUTTON0; // Attack
}
m_flAttackTime = time + 0.1f;
}
m_iAttackMode = 1 - m_iAttackMode;
}
void
bot::BrainThink(int enemyvisible, int enemydistant)
{
/* we had a target and it's now dead. now what? */
if (m_eTarget && m_eTarget.health <= 0) {
m_eTarget = __NULL__;
RouteClear();
} else if (m_eTarget && enemyvisible && enemydistant) {
/* we can see the player, but are too far away, plot a route */
route_calculate(this, m_eTarget.origin, 0, Bot_RouteCB);
}
}
void
bot::UseButton(void)
{
#if 1
float best;
func_button best_button = __NULL__;
best = COST_INFINITE;
for (entity e = world; (e = find(e, ::classname, "func_button"));) {
float dist;
vector pos;
pos[0] = e.absmin[0] + (0.5 * (e.absmax[0] - e.absmin[0]));
pos[1] = e.absmin[1] + (0.5 * (e.absmax[1] - e.absmin[1]));
pos[2] = e.absmin[2] + (0.5 * (e.absmax[2] - e.absmin[2]));
dist = vlen(origin - pos);
if (dist < best) {
best = dist;
best_button = (func_button)e;
}
}
if (best_button == __NULL__)
return;
best_button.Trigger(this, TRIG_TOGGLE);
sound(this, CHAN_ITEM, "common/wpn_select.wav", 0.25, ATTN_IDLE);
#else
float best;
vector foo;
best = COST_INFINITE;
for (entity e = world; (e = find(e, ::classname, "func_button"));) {
float dist;
vector pos;
pos[0] = e.absmin[0] + (0.5 * (e.absmax[0] - e.absmin[0]));
pos[1] = e.absmin[1] + (0.5 * (e.absmax[1] - e.absmin[1]));
pos[2] = e.absmin[2] + (0.5 * (e.absmax[2] - e.absmin[2]));
dist = vlen(origin - pos);
if (dist < best) {
best = dist;
foo = pos;
}
}
v_angle = vectoangles(origin - foo);
Player_UseDown();
#endif
}
void
bot::SeeThink(void)
{
if (m_eTarget)
return;
if (m_flSeeTime > time)
return;
if (autocvar_bot_pacifist)
return;
m_flSeeTime = time + 0.25f;
for (entity w = world; (w = findfloat(w, ::takedamage, DAMAGE_YES));) {
float flDot;
if (!(w.flags & FL_CLIENT))
continue;
if (w.health <= 0)
continue;
/* ain't go hurt our brothers and sisters */
if (Rules_IsTeamPlay() == TRUE)
if (team == w.team)
continue;
/* first, is the potential enemy in our field of view? */
makevectors(v_angle);
vector v = normalize(w.origin - origin);
flDot = v * v_forward;
if (flDot < 90/180)
continue;
other = world;
traceline(origin, w.origin, MOVE_OTHERONLY, this);
if (trace_fraction == 1.0f) {
m_eTarget = w;
return;
}
}
}
void
bot::CheckRoute(void)
{
float flDist;
vector evenpos;
float rad;
if (!m_iNodes) {
return;
}
/* level out position/node stuff */
if (m_iCurNode < 0) {
evenpos = m_vecLastNode - origin;
rad = 64;
} else {
evenpos = m_pRoute[m_iCurNode].m_vecDest - origin;
rad = m_pRoute[m_iCurNode].m_flRadius;
}
flDist = floor(vlen(evenpos));
if (flDist <= rad) {
dprint(sprintf("^2bot::^3CheckRoute^7: " \
"%s reached node\n", this.targetname));
m_iCurNode--;
if (m_iCurNode >= 0) {
if (m_pRoute[m_iCurNode].m_iFlags)
print(sprintf("NODE FLAGS: %i\n", m_pRoute[m_iCurNode].m_iFlags));
/* if a node is flagged as jumpy, jump! */
if (m_pRoute[m_iCurNode].m_iFlags & LF_JUMP)
input_buttons |= INPUT_BUTTON2;
/* find the nearest usable item (func_button) and use them */
if (m_pRoute[m_iCurNode].m_iFlags & LF_USER)
UseButton();
}
#if 0
/* we've still traveling and from this node we may be able to walk
* directly to our end-destination */
if (m_iCurNode > -1) {
tracebox(origin, mins, maxs, m_vecLastNode, MOVE_NORMAL, this);
/* can we walk directly to our target destination? */
if (trace_fraction == 1.0) {
dprint("^2bot::^3CheckRoute^7: " \
"Walking directly to last node\n");
m_iCurNode = -1;
}
}
#endif
} else {
traceline(origin + view_ofs, m_pRoute[m_iCurNode].m_vecDest, MOVE_NORMAL, this);
/* we can't trace against our next waypoint... that should never happen */
if (trace_fraction != 1.0f) {
m_flNodeGiveup += frametime;
} else {
/* if we're literally stuck in a corner aiming at something we should
* not, also give up */
if (flDist == m_flLastDist) {
m_flNodeGiveup += frametime;
} else {
m_flNodeGiveup = bound(0, m_flNodeGiveup - frametime, 1.0);
}
}
}
m_flLastDist = flDist;
/* after one second, also give up the route */
if (m_flNodeGiveup >= 1.0f || m_iCurNode <= BOTROUTE_END) {
RouteClear();
} else if (m_flNodeGiveup >= 0.5f) {
/* attempt a jump after half a second */
input_buttons |= INPUT_BUTTON2;
} else {
/* entire way-link needs to be crouched. that's the law of the land */
if (m_pRoute[m_iCurNode].m_iFlags & LF_CROUCH)
input_buttons |= INPUT_BUTTON8;
}
}
void
bot::CreateObjective(void)
{
route_calculate(this, Route_SelectDestination(this), 0, Bot_RouteCB);
}
void
bot::RunAI(void)
{
vector aimdir, aimpos;
int enemyvisible, enemydistant;
float flLerp;
/* reset input frame */
input_buttons = 0;
input_movevalues = [0,0,0];
input_angles = [0,0,0];
/* attempt to respawn when dead */
if (health <= 0) {
RouteClear();
WeaponAttack();
m_eTarget = __NULL__;
return;
}
/* freeze the bot */
if (autocvar_bot_wait)
return;
/* create our first route */
if (!m_iNodes && autocvar_bot_aimless == 0) {
CreateObjective();
dprint(sprintf("bot::RunAI: %s is calculating first bot route\n",
this.netname));
/* our route probably has not been processed yet */
if (!m_iNodes) {
return;
}
}
WeaponThink();
SeeThink();
enemyvisible = FALSE;
enemydistant = FALSE;
if (m_eTarget != __NULL__) {
traceline(origin + view_ofs, m_eTarget.origin, TRUE, this);
enemyvisible = (trace_ent == m_eTarget || trace_fraction == 1.0f);
if (vlen(trace_endpos - origin) > 1024) {
enemydistant = TRUE;
}
if (enemyvisible) {
WeaponAttack();
}
}
BrainThink(enemyvisible, enemydistant);
CheckRoute();
if (m_iNodes) {
vector vecNewAngles;
vector vecDirection;
if (!m_eTarget || !enemyvisible) {
/* aim at the next node */
if (m_iCurNode == BOTROUTE_DESTINATION)
aimpos = m_vecLastNode;
else {
if (m_iCurNode > 0 && !(m_pRoute[m_iCurNode].m_iFlags & LF_AIM))
aimpos = m_pRoute[m_iCurNode - 1].m_vecDest;
else
aimpos = m_pRoute[m_iCurNode].m_vecDest;
}
} else {
/* aim towards the enemy */
aimpos = m_eTarget.origin;
}
/* lerping speed, faster when we've got a target */
if (m_eTarget && enemyvisible)
flLerp = bound(0.0f, frametime * 45, 1.0f);
else
flLerp = bound(0.0f, frametime * 30, 1.0f);
/* that's the old angle */
makevectors(v_angle);
vecNewAngles = v_forward;
/* aimdir = new final angle */
aimdir = vectoangles(aimpos - origin);
makevectors(aimdir);
/* slowly lerp towards the final angle */
vecNewAngles[0] = Math_Lerp(vecNewAngles[0], v_forward[0], flLerp);
vecNewAngles[1] = Math_Lerp(vecNewAngles[1], v_forward[1], flLerp);
vecNewAngles[2] = Math_Lerp(vecNewAngles[2], v_forward[2], flLerp);
/* make sure we're aiming tight */
v_angle = vectoangles(vecNewAngles);
v_angle[0] = Math_FixDelta(v_angle[0]);
v_angle[1] = Math_FixDelta(v_angle[1]);
v_angle[2] = Math_FixDelta(v_angle[2]);
angles[0] = Math_FixDelta(v_angle[0]);
angles[1] = Math_FixDelta(v_angle[1]);
angles[2] = Math_FixDelta(v_angle[2]);
input_angles = v_angle;
/* now that aiming is sorted, we need to correct the movement */
if ((m_eTarget && enemyvisible && !enemydistant) && vlen(aimpos - origin) > 256) {
/* we are far away, inch closer */
aimpos = m_eTarget.origin;
} else {
if (m_iCurNode <= BOTROUTE_DESTINATION)
aimpos = m_vecLastNode;
else
aimpos = m_pRoute[m_iCurNode].m_vecDest;
}
/* now we'll set the movevalues relative to the input_angle */
if ((m_iCurNode >= 0 && m_pRoute[m_iCurNode].m_iFlags & LF_WALK) || m_eTarget && enemyvisible && vlen(aimpos-origin) < 512)
vecDirection = normalize(aimpos - origin) * 120;
else
vecDirection = normalize(aimpos - origin) * 240;
makevectors(input_angles);
input_movevalues = [v_forward * vecDirection, v_right * vecDirection, v_up * vecDirection];
/* duck and stand still when our enemy is far away */
if (m_eTarget && enemyvisible && vlen(aimpos-origin) > 512) {
input_buttons |= INPUT_BUTTON8;
input_movevalues = [0,0,0];
}
}
/* press any buttons needed */
button0 = input_buttons & INPUT_BUTTON0; // attack
button2 = input_buttons & INPUT_BUTTON2; // jump
button3 = input_buttons & INPUT_BUTTON3; // tertiary
button4 = input_buttons & INPUT_BUTTON4; // reload
button5 = input_buttons & INPUT_BUTTON5; // secondary
button6 = input_buttons & INPUT_BUTTON6; // use
button7 = input_buttons & INPUT_BUTTON7; // unused
button8 = input_buttons & INPUT_BUTTON8; // duck
movement = input_movevalues;
}
void
bot::PreFrame(void)
{
}
void
bot::PostFrame(void)
{
/* we've picked something new up */
if (m_iOldItems != g_items) {
Weapons_SwitchBest(this);
print(sprintf("%s is now using %s (%d)\n", netname, g_weapons[activeweapon].name, activeweapon));
m_iOldItems = g_items;
}
}
void
bot::bot(void)
{
classname = "player";
targetname = "_nuclide_bot_";
}
| 23.888158 | 125 | 0.663821 | [
"vector"
] |
ebe90441955b7ab81b68be9a89333d6021f16549 | 4,978 | h | C | vpr/src/draw/draw.h | umarcor/vtr-verilog-to-routing | d58f993d07fe752dbe254132e739ce2d62abc9e5 | [
"MIT"
] | 682 | 2015-07-10T00:39:26.000Z | 2022-03-30T05:24:53.000Z | vpr/src/draw/draw.h | umarcor/vtr-verilog-to-routing | d58f993d07fe752dbe254132e739ce2d62abc9e5 | [
"MIT"
] | 1,399 | 2015-07-24T22:09:09.000Z | 2022-03-29T06:22:48.000Z | vpr/src/draw/draw.h | umarcor/vtr-verilog-to-routing | d58f993d07fe752dbe254132e739ce2d62abc9e5 | [
"MIT"
] | 311 | 2015-07-09T13:59:48.000Z | 2022-03-28T00:15:20.000Z | #ifndef DRAW_H
#define DRAW_H
#include "timing_info.h"
#include "physical_types.h"
#ifndef NO_GRAPHICS
# include "draw_global.h"
# include "ezgl/point.hpp"
# include "ezgl/application.hpp"
# include "ezgl/graphics.hpp"
# include "draw_color.h"
# include "search_bar.h"
# include "draw_debug.h"
# include "manual_moves.h"
extern ezgl::application::settings settings;
extern ezgl::application application;
#endif /* NO_GRAPHICS */
void update_screen(ScreenUpdatePriority priority, const char* msg, enum pic_type pic_on_screen_val, std::shared_ptr<SetupTimingInfo> timing_info);
//Initializes the drawing locations.
//FIXME: Currently broken if no rr-graph is loaded
void init_draw_coords(float clb_width);
void init_graphics_state(bool show_graphics_val, int gr_automode_val, enum e_route_type route_type, bool save_graphics, std::string graphics_commands);
void alloc_draw_structs(const t_arch* arch);
void free_draw_structs();
#ifndef NO_GRAPHICS
void draw_get_rr_pin_coords(int inode, float* xcen, float* ycen, const e_side& pin_side);
void draw_get_rr_pin_coords(const t_rr_node& node, float* xcen, float* ycen, const e_side& pin_side);
void draw_triangle_along_line(ezgl::renderer* g, ezgl::point2d start, ezgl::point2d end, float relative_position = 1., float arrow_size = DEFAULT_ARROW_SIZE);
void draw_triangle_along_line(ezgl::renderer* g, ezgl::point2d loc, ezgl::point2d start, ezgl::point2d end, float arrow_size = DEFAULT_ARROW_SIZE);
void draw_triangle_along_line(ezgl::renderer* g, float xend, float yend, float x1, float x2, float y1, float y2, float arrow_size = DEFAULT_ARROW_SIZE);
const ezgl::color SELECTED_COLOR = ezgl::GREEN;
const ezgl::color DRIVES_IT_COLOR = ezgl::RED;
const ezgl::color DRIVEN_BY_IT_COLOR = ezgl::LIGHT_MEDIUM_BLUE;
const float WIRE_DRAWING_WIDTH = 0.5;
//Returns the drawing coordinates of the specified pin
ezgl::point2d atom_pin_draw_coord(AtomPinId pin);
//Returns the drawing coordinates of the specified tnode
ezgl::point2d tnode_draw_coord(tatum::NodeId node);
void annotate_draw_rr_node_costs(ClusterNetId net, int sink_rr_node);
void clear_draw_rr_annotations();
ezgl::color to_ezgl_color(vtr::Color<float> color);
void draw_screen();
// search bar related functions
ezgl::rectangle draw_get_rr_chan_bbox(int inode);
void draw_highlight_blocks_color(t_logical_block_type_ptr type, ClusterBlockId blk_id);
void highlight_nets(char* message, int hit_node);
void draw_highlight_fan_in_fan_out(const std::set<int>& nodes);
std::set<int> draw_expand_non_configurable_rr_nodes(int hit_node);
void deselect_all();
// toggle functions
void toggle_nets(GtkWidget* /*widget*/, gint /*response_id*/, gpointer /*data*/);
void toggle_rr(GtkWidget* /*widget*/, gint /*response_id*/, gpointer /*data*/);
void toggle_congestion(GtkWidget* /*widget*/, gint /*response_id*/, gpointer /*data*/);
void toggle_routing_congestion_cost(GtkWidget* /*widget*/, gint /*response_id*/, gpointer /*data*/);
void toggle_routing_bounding_box(GtkWidget* /*widget*/, gint /*response_id*/, gpointer /*data*/);
void toggle_routing_util(GtkWidget* /*widget*/, gint /*response_id*/, gpointer /*data*/);
void toggle_crit_path(GtkWidget* /*widget*/, gint /*response_id*/, gpointer /*data*/);
void toggle_block_pin_util(GtkWidget* /*widget*/, gint /*response_id*/, gpointer /*data*/);
void toggle_router_expansion_costs(GtkWidget* /*widget*/, gint /*response_id*/, gpointer /*data*/);
void toggle_placement_macros(GtkWidget* /*widget*/, gint /*response_id*/, gpointer /*data*/);
void net_max_fanout(GtkWidget* /*widget*/, gint /*response_id*/, gpointer /*data*/);
void set_net_alpha_value(GtkWidget* widget, gint /*response_id*/, gpointer /*data*/);
void set_net_alpha_value_with_enter(GtkWidget* widget, gint /*response_id*/, gpointer /*data*/);
float get_net_alpha();
ezgl::color get_block_type_color(t_physical_tile_type_ptr type);
/* This routine highlights the blocks affected in the latest move *
* It highlights the old and new locations of the moved blocks *
* It also highlights the moved block input and output terminals *
* Currently, it is used in placer debugger when breakpoint is reached */
void highlight_moved_block_and_its_terminals(const t_pl_blocks_to_be_moved&);
// pass in an (x,y,subtile) location and the color in which it should be drawn.
// This overrides the color of any block placed in that location, and also applies if the location is empty.
void set_draw_loc_color(t_pl_loc, ezgl::color);
// clear the colored_locations vector
void clear_colored_locations();
// This routine takes in a (x,y) location.
// If the input loc is marked in colored_locations vector, the function will return true and the correspnding color is sent back in loc_color
// otherwise, the function returns false (the location isn't among the highlighted locations)
bool highlight_loc_with_specific_color(int x, int y, ezgl::color& loc_color);
#endif /* NO_GRAPHICS */
#endif /* DRAW_H */
| 45.669725 | 158 | 0.773001 | [
"vector"
] |
ebeda466ad0349ffaafec8ae009967412b15f304 | 4,655 | h | C | examples/Demo/src/TestUserShader2.h | chuckvalenza/oxygine-framework | e6cd7b78091e75e0dc5900fcdeadba4b97197d40 | [
"MIT"
] | null | null | null | examples/Demo/src/TestUserShader2.h | chuckvalenza/oxygine-framework | e6cd7b78091e75e0dc5900fcdeadba4b97197d40 | [
"MIT"
] | null | null | null | examples/Demo/src/TestUserShader2.h | chuckvalenza/oxygine-framework | e6cd7b78091e75e0dc5900fcdeadba4b97197d40 | [
"MIT"
] | null | null | null | #pragma once
#include "test.h"
#include "core/UberShaderProgram.h"
#include "core/gl/VideoDriverGLES20.h"
#include "core/gl/oxgl.h"
#include "core/gl/ShaderProgramGL.h"
class LightningMaterial : public Material
{
public:
const VertexDeclaration* _vdecl;
ShaderProgramGL* _lightShader;
Vector2 _light;
vector<vertexPCT2T2> _vertices;
AnimationFrame _normal;
spNativeTexture _base;
LightningMaterial()
{
_normal = resources.getResAnim("normal")->getFrame(0);
_light = getStage()->getSize() / 2;
IVideoDriver* driver = IVideoDriver::instance;
_vdecl = driver->getVertexDeclaration(vertexPCT2T2::FORMAT);
//load vertex shader
file::buffer vsdata;
file::read("light_vs.glsl", vsdata);
vsdata.push_back(0);///null terminating string
unsigned int vs = ShaderProgramGL::createShader(GL_VERTEX_SHADER, (const char*)&vsdata.front(), "", "");
//load fragment shader
file::buffer fsdata;
file::read("light_fs.glsl", fsdata);
fsdata.push_back(0);///null terminating string
unsigned int ps = ShaderProgramGL::createShader(GL_FRAGMENT_SHADER, (const char*)&fsdata.front(), "", "");
//link into 1 shader program
unsigned int pr = ShaderProgramGL::createProgram(vs, ps, static_cast<const VertexDeclarationGL*>(IVideoDriver::instance->getVertexDeclaration(vertexPCT2T2::FORMAT)));
_lightShader = new ShaderProgramGL(pr);
//set shader and apply samplers uniforms
driver->setShaderProgram(_lightShader);
driver->setUniformInt("base_texture", 0);
driver->setUniformInt("normal_texture", 1);
}
void apply(Material* prev) OVERRIDE
{
IVideoDriver* driver = IVideoDriver::instance;
driver->setShaderProgram(_lightShader);
Vector2 light = getStage()->getDescendant("light")->getPosition();
driver->setUniform("light", &light, 1);
driver->setUniform("mat", &STDMaterial::instance->getRenderer()->getViewProjection());
driver->setTexture(1, _normal.getDiffuse().base);
driver->setState(IVideoDriver::STATE_BLEND, 0);
driver->setBlendFunc(IVideoDriver::BT_ONE, IVideoDriver::BT_ONE_MINUS_SRC_ALPHA);
driver->setBlendFunc(IVideoDriver::BT_SRC_ALPHA, IVideoDriver::BT_ONE_MINUS_SRC_ALPHA);
}
void finish() OVERRIDE
{
drawBatch(IVideoDriver::instance);
}
void drawBatch(IVideoDriver* driver)
{
size_t count = _vertices.size();
if (!count)
return;
size_t indices = (count * 3) / 2;
driver->setTexture(0, _base);
driver->draw(IVideoDriver::PT_TRIANGLES, _vdecl, &_vertices.front(), (unsigned int)count, &STDRenderer::indices16.front(), (unsigned int)indices);
_vertices.clear();
}
void doRender(Sprite* sprite, const RenderState& rs) OVERRIDE
{
Material::setCurrent(this);
vertexPCT2T2 v[4];
const AnimationFrame& frame = sprite->getAnimFrame();
if (frame.getDiffuse().base != _base)
{
drawBatch(IVideoDriver::instance);
_base = frame.getDiffuse().base;
}
fillQuadT2(v, frame.getSrcRect(), _normal.getSrcRect(), sprite->getDestRect(), rs.transform, 0xffFFffFF);
_vertices.insert(_vertices.end(), v, v + 4);
}
};
class TestUserShader2 : public Test
{
public:
Draggable drag;
TestUserShader2()
{
LightningMaterial* mat = new LightningMaterial;
spSprite spr = new Sprite();
spr->setResAnim(resources.getResAnim("tiled2"));
spr->setScale(2);
spr->setAnchor(0.5f, 0.5f);
spr->setPosition(content->getSize() / 2);
spr->attachTo(content);
spr->setMaterial(mat);
spr = new Sprite();
spr->setResAnim(resources.getResAnim("tiled2"));
spr->setScale(2);
spr->setAnchor(0.5f, 0.5f);
spr->setPosition(content->getSize() / 2 + Vector2(300, 50));
spr->attachTo(content);
spr->setMaterial(mat);
spr = new Sprite();
spr->setResAnim(resources.getResAnim("tiled2"));
spr->setScale(2);
spr->setAnchor(0.5f, 0.5f);
spr->setPosition(content->getSize() / 2 + Vector2(-200, 50));
spr->attachTo(content);
spr->setMaterial(mat);
spSprite light = new Sprite;
light->setName("light");
light->setResAnim(resources.getResAnim("light"));
light->setAnchor(0.5f, 0.5f);
drag.init(light.get());
light->setPosition(getSize() / 2);
content->addChild(light);
}
}; | 30.625 | 174 | 0.631364 | [
"vector",
"transform"
] |
ebef543fc863a6c5ffef11080ae5129a5894ea22 | 3,868 | h | C | libevmasm/ControlFlowGraph.h | qoire/aion-solidity | 1675436f12a2bb2cb96ab060e17bc3f13587e4a1 | [
"MIT"
] | null | null | null | libevmasm/ControlFlowGraph.h | qoire/aion-solidity | 1675436f12a2bb2cb96ab060e17bc3f13587e4a1 | [
"MIT"
] | null | null | null | libevmasm/ControlFlowGraph.h | qoire/aion-solidity | 1675436f12a2bb2cb96ab060e17bc3f13587e4a1 | [
"MIT"
] | null | null | null | /*
This file is part of solidity.
solidity 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 3 of the License, or
(at your option) any later version.
solidity 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 solidity. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* @file ControlFlowGraph.h
* @author Christian <c@ethdev.com>
* @date 2015
* Control flow analysis for the optimizer.
*/
#pragma once
#include <vector>
#include <memory>
#include <libdevcore/Common.h>
#include <libdevcore/Assertions.h>
#include <libevmasm/ExpressionClasses.h>
namespace dev
{
namespace eth
{
class KnownState;
using KnownStatePointer = std::shared_ptr<KnownState>;
/**
* Identifier for a block, coincides with the tag number of an AssemblyItem but adds a special
* ID for the inital block.
*/
class BlockId
{
public:
BlockId() { *this = invalid(); }
explicit BlockId(unsigned _id): m_id(_id) {}
explicit BlockId(u256 const& _id);
static BlockId initial() { return BlockId(-2); }
static BlockId invalid() { return BlockId(-1); }
bool operator==(BlockId const& _other) const { return m_id == _other.m_id; }
bool operator!=(BlockId const& _other) const { return m_id != _other.m_id; }
bool operator<(BlockId const& _other) const { return m_id < _other.m_id; }
explicit operator bool() const { return *this != invalid(); }
private:
unsigned m_id;
};
/**
* Control flow block inside which instruction counter is always incremented by one
* (except for possibly the last instruction).
*/
struct BasicBlock
{
/// Start index into assembly item list.
unsigned begin = 0;
/// End index (excluded) inte assembly item list.
unsigned end = 0;
/// Tags pushed inside this block, with multiplicity.
std::vector<BlockId> pushedTags;
/// ID of the block that always follows this one (either non-branching part of JUMPI or flow
/// into new block), or BlockId::invalid() otherwise
BlockId next = BlockId::invalid();
/// ID of the block that has to precede this one (because control flows into it).
BlockId prev = BlockId::invalid();
enum class EndType { JUMP, JUMPI, STOP, HANDOVER };
EndType endType = EndType::HANDOVER;
/// Knowledge about the state when this block is entered. Intersection of all possible ways
/// to enter this block.
KnownStatePointer startState;
/// Knowledge about the state at the end of this block.
KnownStatePointer endState;
};
using BasicBlocks = std::vector<BasicBlock>;
/**
* Control flow graph optimizer.
* ASSUMES THAT WE ONLY JUMP TO TAGS THAT WERE PREVIOUSLY PUSHED. THIS IS NOT TRUE ANYMORE
* NOW THAT FUNCTION TAGS CAN BE STORED IN STORAGE.
*/
class ControlFlowGraph
{
public:
/// Initializes the control flow graph.
/// @a _items has to persist across the usage of this class.
/// @a _joinKnowledge if true, reduces state knowledge to common base at the join of two paths
explicit ControlFlowGraph(AssemblyItems const& _items, bool _joinKnowledge = true):
m_items(_items),
m_joinKnowledge(_joinKnowledge)
{}
/// @returns vector of basic blocks in the order they should be used in the final code.
/// Should be called only once.
BasicBlocks optimisedBlocks();
private:
void findLargestTag();
void splitBlocks();
void resolveNextLinks();
void removeUnusedBlocks();
void gatherKnowledge();
void setPrevLinks();
BasicBlocks rebuildCode();
BlockId generateNewId();
unsigned m_lastUsedId = 0;
AssemblyItems const& m_items;
bool m_joinKnowledge = true;
std::map<BlockId, BasicBlock> m_blocks;
};
}
}
| 29.526718 | 95 | 0.73759 | [
"vector"
] |
ebf23f6fddbc77d6cd7280df6bd497e1a919a1b6 | 3,049 | h | C | src/core/testing/plg_node_editor_test/implements/PrintNode.h | wgsyd/wgtf | d8cacb43e2c5d40080d33c18a8c2f5bd27d21bed | [
"BSD-3-Clause"
] | 28 | 2016-06-03T05:28:25.000Z | 2019-02-14T12:04:31.000Z | src/core/testing/plg_node_editor_test/implements/PrintNode.h | karajensen/wgtf | 740397bcfdbc02bc574231579d57d7c9cd5cc26d | [
"BSD-3-Clause"
] | null | null | null | src/core/testing/plg_node_editor_test/implements/PrintNode.h | karajensen/wgtf | 740397bcfdbc02bc574231579d57d7c9cd5cc26d | [
"BSD-3-Clause"
] | 14 | 2016-06-03T05:52:27.000Z | 2019-03-21T09:56:03.000Z | #ifndef __PRINT_NODE_H__
#define __PRINT_NODE_H__
#include "core_data_model/collection_model.hpp"
#include "core_dependency_system/i_interface.hpp"
#include "core_reflection/object_handle.hpp"
#include "core_object/i_object_manager.hpp"
#include "plugins/plg_node_editor/interfaces/i_node.hpp"
#include "EventSlot.h"
#include "StringSlot.h"
#include "CustomGraph.h"
namespace wgt
{
class PrintNode : public Implements<INode>, public Depends<IObjectManager, IDefinitionManager>
{
DECLARE_REFLECTED
public:
PrintNode(const std::string &nodeClass);
~PrintNode();
void Init() override;
size_t Id() const override { return m_id; }
std::string Class() const override { return m_class; }
std::string Title() const override { return m_title; }
std::string SubTitle() const override { return m_subTitle; }
std::string Category() const override { return m_category; }
std::string Icon() const override { return m_icon; }
std::string Color() const override { return m_color; }
float X() const override { return m_x; }
float Y() const override { return m_y; }
void SetPos(float x, float y) override;
ObjectHandleT<ISlot> GetSlotById(size_t slotId) const override;
bool Enabled() const override;
void SetEnabled(bool enabled) override;
bool Minimized() const override;
void SetMinimized(bool minimized) override;
bool CanConnect(ObjectHandleT<ISlot> mySlot, ObjectHandleT<ISlot> otherSlot) override;
bool Validate(std::string &errorMessage) override;
void OnConnect(ObjectHandleT<ISlot> mySlot, ObjectHandleT<ISlot> otherSlot) override;
void OnDisconnect(ObjectHandleT<ISlot> mySlot, ObjectHandleT<ISlot> otherSlot) override;
const CollectionModel* GetInputSlots() const override { return &inputSlotsModel_; }
const CollectionModel* GetOutputSlots() const override { return &outputSlotsModel_; }
private:
const AbstractListModel* GetInputSlotsModel() const override { return &inputSlotsModel_; }
const AbstractListModel* GetOutputSlotsModel() const override { return &outputSlotsModel_; }
mutable ObjectHandleT<INode> thisNode_;
ObjectHandleT<INode> getThis() const
{
if (thisNode_ != nullptr)
{
return thisNode_;
}
auto thisObject = get<IObjectManager>()->getObject(this);
assert(thisObject != nullptr);
thisNode_ = reflectedCast<INode>(thisObject, *get<IDefinitionManager>());
assert(thisNode_ != nullptr);
return thisNode_;
}
private:
float m_x;
float m_y;
size_t m_id;
std::string m_class;
std::string m_title;
std::string m_subTitle;
std::string m_category;
std::string m_icon;
std::string m_color;
bool m_enabled;
bool m_minimized;
std::vector<ManagedObject<ISlot>> ownedSlots_;
std::vector<ObjectHandleT<ISlot>> inputSlots_;
std::vector<ObjectHandleT<ISlot>> outputSlots_;
CollectionModel inputSlotsModel_;
CollectionModel outputSlotsModel_;
};
} // end namespace wgt
#endif // __PRINT_NODE_H__
| 31.43299 | 96 | 0.725156 | [
"vector"
] |
ebf83bb3b71a75ebca71c95d6ef50453e7bc9ac5 | 23,965 | h | C | src/hg/cirm/cdw/inc/cdwLib.h | psteinb/kent | 3ff439f4e5194805359405bb4452c8d96a343932 | [
"IJG"
] | null | null | null | src/hg/cirm/cdw/inc/cdwLib.h | psteinb/kent | 3ff439f4e5194805359405bb4452c8d96a343932 | [
"IJG"
] | null | null | null | src/hg/cirm/cdw/inc/cdwLib.h | psteinb/kent | 3ff439f4e5194805359405bb4452c8d96a343932 | [
"IJG"
] | null | null | null | /* cdwLib - routines shared by various cdw programs. See also cdw
* module for tables and routines to access structs built on tables. */
/* Copyright (C) 2014 The Regents of the University of California
* See README in this or parent directory for licensing information. */
#ifndef CDWLIB_H
#define CDWLIB_H
#ifndef DYSTRING_H
#include "dystring.h"
#endif
#ifndef JKSQL_H
#include "jksql.h"
#endif
#ifndef BASICBED_H
#include "basicBed.h"
#endif
#ifndef CDW_H
#include "cdw.h"
#endif
#include "cart.h"
#define cdwRandomString "175d5bc99f7bb7312812c47d236791879BAEXzusIsdklnw86d73<*#$*(#)!DSFOUIHLjksdf"
extern char *cdwDatabase; /* Name of database we connect to. */
extern char *cdwRootDir; /* Name of root directory for our files, including trailing '/' */
extern char *eapRootDir; /* Name of root directory for analysis pipeline */
extern char *cdwValDataDir; /* Data files we need for validation go here. */
extern char *cdwDaemonEmail; /* Email address of our automatic user. */
extern int cdwSingleFileTimeout; // How many seconds we give ourselves to fetch a single file
#define cdwMinMapQual 3 //Above this -10log10 theshold we have >50% chance of being right
#define CDW_WEB_REFRESH_5_SEC 5000
struct sqlConnection *cdwConnect();
/* Returns a read only connection to database. */
struct sqlConnection *cdwConnectReadWrite();
/* Returns read/write connection to database. */
long long cdwGotFile(struct sqlConnection *conn, char *submitDir, char *submitFileName,
char *md5, long long size);
/* See if we already got file. Return fileId if we do, otherwise 0. This returns
* TRUE based mostly on the MD5sum. For short files (less than 100k) then we also require
* the submitDir and submitFileName to match. This is to cover the case where you might
* have legitimate empty files duplicated even though they were computed based on different
* things. For instance coming up with no peaks is a legitimate result for many chip-seq
* experiments. */
long long cdwGettingFile(struct sqlConnection *conn, char *submitDir, char *submitFileName);
/* See if we are in process of getting file. Return file record id if it exists even if
* it's not complete so long as it's not too old. Return -1 if record does not exist. */
char *cdwPathForFileId(struct sqlConnection *conn, long long fileId);
/* Return full path (which eventually should be freeMem'd) for fileId */
char *cdwTempDir();
/* Returns pointer to cdwTempDir. This is shared, so please don't modify. */
char *cdwTempDirForToday(char dir[PATH_LEN]);
/* Fills in dir with temp dir of the day, and returns a pointer to it. */
long long cdwNow();
/* Return current time in seconds since Epoch. */
struct cdwUser *cdwUserFromUserName(struct sqlConnection *conn, char* userName);
/* Return user associated with that username or NULL if not found */
struct cdwUser *cdwUserFromEmail(struct sqlConnection *conn, char *email);
/* Return user associated with that email or NULL if not found */
struct cdwUser *cdwMustGetUserFromEmail(struct sqlConnection *conn, char *email);
/* Return user associated with email or put up error message. */
struct cdwUser *cdwUserFromId(struct sqlConnection *conn, int id);
/* Return user associated with that id or NULL if not found */
int cdwUserIdFromFileId(struct sqlConnection *conn, int fId);
/* Return user id who submit the file originally */
char *cdwUserNameFromFileId(struct sqlConnection *conn, int fId);
/* Return user who submit the file originally */
struct cdwUser *cdwFindUserFromFileId(struct sqlConnection *conn, int fId);
/* Return user who submit the file originally */
char *cdwFindOwnerNameFromFileId(struct sqlConnection *conn, int fId);
/* Return name of submitter. Return "an unknown user" if name is NULL */
int cdwFindUserIdFromEmail(struct sqlConnection *conn, char *userEmail);
/* Return true id of this user */
boolean cdwUserIsAdmin(struct sqlConnection *conn, char *userEmail);
/* Return true if the user is an admin */
void cdwWarnUnregisteredUser(char *email);
/* Put up warning message about unregistered user and tell them how to register. */
struct cdwGroup *cdwGroupFromName(struct sqlConnection *conn, char *name);
/* Return cdwGroup of given name or NULL if not found. */
struct cdwGroup *cdwNeedGroupFromName(struct sqlConnection *conn, char *groupName);
/* Get named group or die trying */
boolean cdwFileInGroup(struct sqlConnection *conn, unsigned int fileId, unsigned int groupId);
/* Return TRUE if file is in group */
int cdwUserFileGroupsIntersect(struct sqlConnection *conn, long long fileId, int userId);
/* Return the number of groups file and user have in common, zero for no match */
#define cdwAccessRead 1
#define cdwAccessWrite 2
boolean cdwCheckAccess(struct sqlConnection *conn, struct cdwFile *ef,
struct cdwUser *user, int accessType);
/* See if user should be allowed this level of access. The accessType is one of
* cdwAccessRead or cdwAccessWrite. Write access implies read access too.
* This can be called with user as NULL, in which case only access to shared-with-all
* files is granted. This function takes almost a millisecond. If you are doing it
* to many files consider using cdwQuickCheckAccess instead. */
boolean cdwQuickCheckAccess(struct rbTree *groupedFiles, struct cdwFile *ef,
struct cdwUser *user, int accessType);
/* See if user should be allowed this level of access. The groupedFiles is
* the result of a call to cdwFilesWithSharedGroup. The other parameters are as
* cdwCheckAccess. If you are querying thousands of files, this function is hundreds
* of times faster though. */
struct rbTree *cdwFilesWithSharedGroup(struct sqlConnection *conn, int userId);
/* Make an intVal type tree where the keys are fileIds and the val is null
* This contains all files that are associated with any group that user is part of.
* Can be used to do quicker version of cdwCheckAccess. */
long long cdwCountAccessible(struct sqlConnection *conn, struct cdwUser *user);
/* Return total number of files associated user can access */
struct cdwFile *cdwAccessibleFileList(struct sqlConnection *conn, struct cdwUser *user);
/* Get list of all files user can access. Null user means just publicly accessible. */
struct rbTree *cdwAccessTreeForUser(struct sqlConnection *conn, struct cdwUser *user,
struct cdwFile *efList, struct rbTree *groupedFiles);
/* Construct intVal tree of files from efList that we have access to. The
* key is the fileId, the value is the cdwFile object */
int cdwGetHost(struct sqlConnection *conn, char *hostName);
/* Look up host name in table and return associated ID. If not found
* make up new host table entry. */
int cdwGetSubmitDir(struct sqlConnection *conn, int hostId, char *submitDir);
/* Get submitDir from database, creating it if it doesn't already exist. */
#define cdwMaxPlateSize 16 /* Max size of license plate including prefix and trailing 0. */
void cdwMakeLicensePlate(char *prefix, int ix, char *out, int outSize);
/* Make a license-plate type string composed of prefix + funky coding of ix
* and put result in out. */
void cdwMakeBabyName(unsigned long id, char *baseName, int baseNameSize);
/* Given a numerical ID, make an easy to pronouce file name */
void cdwDirForTime(time_t sinceEpoch, char dir[PATH_LEN]);
/* Return the output directory for a given time. */
char *cdwFindDoubleFileSuffix(char *path);
/* Return pointer to second from last '.' in part of path between last / and end.
* If there aren't two dots, just return pointer to normal single dot suffix. */
void cdwMakeFileNameAndPath(int cdwFileId, char *submitFileName, char cdwFile[PATH_LEN], char serverPath[PATH_LEN]);
/* Convert file id to local file name, and full file path. Make any directories needed
* along serverPath. */
char *cdwSetting(struct sqlConnection *conn, char *name);
/* Return named settings value, or NULL if setting doesn't exist. */
char *cdwRequiredSetting(struct sqlConnection *conn, char *name);
/* Returns setting, abort if it isn't found. */
char *cdwLicensePlateHead(struct sqlConnection *conn);
/* Return license plate prefix for current database - something like TST or DEV or ENCFF */
struct cdwFile *cdwGetLocalFile(struct sqlConnection *conn, char *localAbsolutePath,
char *symLinkMd5Sum);
/* Get record of local file from database, adding it if it doesn't already exist.
* Can make it a symLink rather than a copy in which case pass in valid MD5 sum
* for symLinkM5dSum. */
void cdwUpdateFileTags(struct sqlConnection *conn, long long fileId, struct dyString *tags);
/* Update tags field in cdwFile with given value */
struct cdwFile *cdwFileLoadAllValid(struct sqlConnection *conn);
/* Get list of cdwFiles that have been validated with no error */
struct cdwFile *cdwFileAllIntactBetween(struct sqlConnection *conn, int startId, int endId);
/* Return list of all files that are intact (finished uploading and MD5 checked)
* with file IDs between startId and endId - including endId*/
long long cdwFindInSameSubmitDir(struct sqlConnection *conn,
struct cdwFile *ef, char *submitFileName);
/* Return fileId of most recent file of given submitFileName from submitDir
* associated with file */
struct cdwValidFile *cdwValidFileFromFileId(struct sqlConnection *conn, long long fileId);
/* Return cdwValidFile give fileId - returns NULL if not validated. */
struct cdwValidFile *cdwValidFileFromLicensePlate(struct sqlConnection *conn, char *licensePlate);
/* Return cdwValidFile from license plate - returns NULL if not found. */
void cdwValidFileUpdateDb(struct sqlConnection *conn, struct cdwValidFile *el, long long id);
/* Save cdwValidFile as a row to the table specified by tableName, replacing existing record at
* id. */
struct cgiParsedVars; // Forward declare this so don't have to include cheapcgi
void cdwValidFileFieldsFromTags(struct cdwValidFile *vf, struct cgiParsedVars *tags);
/* Fill in many of vf's fields from tags. */
struct cdwExperiment *cdwExperimentFromAccession(struct sqlConnection *conn, char *acc);
/* Given something like 'ENCSR123ABC' return associated experiment. */
struct cdwFile *cdwFileFromId(struct sqlConnection *conn, long long fileId);
/* Return cdwFile given fileId - return NULL if not found. */
struct cdwFile *cdwFileFromIdOrDie(struct sqlConnection *conn, long long fileId);
/* Return cdwFile given fileId - aborts if not found. */
int cdwFileIdFromPathSuffix(struct sqlConnection *conn, char *suf);
/* return most recent fileId for file where submitDir.url+submitFname ends with suf. 0 if not found. */
struct genomeRangeTree *cdwMakeGrtFromBed3List(struct bed3 *bedList);
/* Make up a genomeRangeTree around bed file. */
struct cdwAssembly *cdwAssemblyForUcscDb(struct sqlConnection *conn, char *ucscDb);
/* Get assembly for given UCSC ID or die trying */
struct cdwAssembly *cdwAssemblyForId(struct sqlConnection *conn, long long id);
/* Get assembly of given ID. */
char *cdwSimpleAssemblyName(char *assembly);
/* Given compound name like male.hg19 return just hg19 */
struct genomeRangeTree *cdwGrtFromBigBed(char *fileName);
/* Return genome range tree for simple (unblocked) bed */
boolean cdwIsSupportedBigBedFormat(char *format);
/* Return TRUE if it's one of the bigBed formats we support. */
void cdwWriteErrToTable(struct sqlConnection *conn, char *table, int id, char *err);
/* Write out error message to errorMessage field of table. */
void cdwWriteErrToStderrAndTable(struct sqlConnection *conn, char *table, int id, char *err);
/* Write out error message to errorMessage field of table. */
void cdwAddJob(struct sqlConnection *conn, char *command, int submitId);
/* Add job to queue to run. */
void cdwAddQaJob(struct sqlConnection *conn, long long fileId, int submitId);
/* Create job to do QA on this and add to queue */
struct cdwSubmitDir *cdwSubmitDirFromId(struct sqlConnection *conn, long long id);
/* Return submissionDir with given ID or NULL if no such submission. */
struct cdwSubmit *cdwSubmitFromId(struct sqlConnection *conn, long long id);
/* Return submission with given ID or NULL if no such submission. */
struct cdwSubmit *cdwMostRecentSubmission(struct sqlConnection *conn, char *url);
/* Return most recent submission, possibly in progress, from this url */
long long cdwSubmitMaxStartTime(struct cdwSubmit *submit, struct sqlConnection *conn);
/* Figure out when we started most recent single file in the upload, or when
* we started if not files started yet. */
int cdwSubmitCountNewValid(struct cdwSubmit *submit, struct sqlConnection *conn);
/* Count number of new files in submission that have been validated. */
boolean cdwSubmitIsValidated(struct cdwSubmit *submit, struct sqlConnection *conn);
/* Return TRUE if validation has run. This does not mean that they all passed validation.
* It just means the validator has run and has made a decision on each file in the submission. */
void cdwAddSubmitJob(struct sqlConnection *conn, char *userEmail, char *url, boolean update);
/* Add submission job to table and wake up daemon. If update is set allow submission to
* include new metadata on old files. */
int cdwSubmitPositionInQueue(struct sqlConnection *conn, char *url, unsigned *retJobId);
/* Return position of our URL in submission queue. Optionally return id in cdwSubmitJob
* table of job. */
struct cdwValidFile *cdwFindElderReplicates(struct sqlConnection *conn, struct cdwValidFile *vf);
/* Find all replicates of same output and format type for experiment that are elder
* (fileId less than your file Id). Younger replicates are responsible for taking care
* of correlations with older ones. Sorry younguns, it's like social security. */
void cdwWebHeaderWithPersona(char *title);
/* Print out HTTP and HTML header through <BODY> tag with persona info */
void cdwWebFooterWithPersona();
/* Print out end tags and persona script stuff */
char *cdwGetEmailAndVerify();
/* Get email from persona-managed cookies and validate them.
* Return email address if all is good and user is logged in.
* If user not logged in return NULL. If user logged in but
* otherwise things are wrong abort. */
/* This is size of base64 encoded hash plus 1 for the terminating zero. */
#define CDW_SID_SIZE 65
void cdwMakeSid(char *user, char sid[CDW_SID_SIZE]);
/* Convert users to sid */
void cdwCreateNewUser(char *email);
/* Create new user, checking that user does not already exist. */
void cdwPrintLogOutButton();
/* Print log out button */
struct dyString *cdwFormatDuration(long long seconds);
/* Convert seconds to days/hours/minutes. Return result in a dyString you can free */
struct cdwFile *cdwFileInProgress(struct sqlConnection *conn, int submitId);
/* Return file in submission in process of being uploaded if any. */
struct cdwScriptRegistry *cdwScriptRegistryFromCgi();
/* Get script registery from cgi variables. Does authentication too. */
void cdwFileResetTags(struct sqlConnection *conn, struct cdwFile *ef, char *newTags,
boolean revalidate, int submitId);
/* Reset tags on file, strip out old validation and QA, optionally schedule new validation
* and QA. */
#define cdwSampleTargetSize 250000 /* We target this many samples */
void cdwReserveTempFile(char *path);
/* Call mkstemp on path. This will fill in terminal XXXXXX in path with file name
* and create an empty file of that name. Generally that empty file doesn't stay empty for long. */
void cdwIndexPath(struct cdwAssembly *assembly, char indexPath[PATH_LEN]);
/* Fill in path to a bowtie index (originally bwa index). */
void cdwAsPath(char *format, char path[PATH_LEN]);
/* Convert something like "narrowPeak" in format to full path involving
* encValDir/as/narrowPeak.as */
void cdwAlignFastqMakeBed(struct cdwFile *ef, struct cdwAssembly *assembly,
char *fastqPath, struct cdwValidFile *vf, FILE *bedF,
double *retMapRatio, double *retDepth, double *retSampleCoverage,
double *retUniqueMapRatio, char *assay);
/* Take a sample fastq and run bwa on it, and then convert that file to a bed. */
void cdwMakeTempFastqSample(char *source, int size, char dest[PATH_LEN]);
/* Copy size records from source into a new temporary dest. Fills in dest */
void cdwCleanupTrimReads(char *fastqPath, char trimmedPath[PATH_LEN]);
/* Remove trimmed sample file. Does nothing if fastqPath and trimmedPath the same. */
boolean cdwTrimReadsForAssay(char *fastqPath, char trimmedPath[PATH_LEN], char *assay);
/* Look at assay and see if it's one that needs trimming. If so make a new trimmed
* file and put file name in trimmedPath. Otherwise just copy fastqPath to trimmed
* path and return FALSE. */
void cdwMakeFastqStatsAndSample(struct sqlConnection *conn, long long fileId);
/* Run fastqStatsAndSubsample, and put results into cdwFastqFile table. */
struct cdwFastqFile *cdwFastqFileFromFileId(struct sqlConnection *conn, long long fileId);
/* Get cdwFastqFile with given fileId or NULL if none such */
struct cdwBamFile * cdwMakeBamStatsAndSample(struct sqlConnection *conn, long long fileId,
char sampleBed[PATH_LEN]);
/* Run cdwBamStats and put results into cdwBamFile table, and also a sample bed.
* The sampleBed will be filled in by this routine. */
struct cdwBamFile *cdwBamFileFromFileId(struct sqlConnection *conn, long long fileId);
/* Get cdwBamFile with given fileId or NULL if none such */
struct cdwQaWigSpot *cdwMakeWigSpot(struct sqlConnection *conn, long long wigId, long long spotId);
/* Create a new cdwQaWigSpot record in database based on comparing wig file to spot file
* (specified by id's in cdwFile table). */
struct cdwQaWigSpot *cdwQaWigSpotFor(struct sqlConnection *conn,
long long wigFileId, long long spotFileId);
/* Return wigSpot relationship if any we have in database for these two files. */
struct cdwVcfFile * cdwMakeVcfStatsAndSample(struct sqlConnection *conn, long long fileId,
char sampleBed[PATH_LEN]);
/* Run cdwVcfStats and put results into cdwVcfFile table, and also a sample bed.
* The sampleBed will be filled in by this routine. */
struct cdwVcfFile *cdwVcfFileFromFileId(struct sqlConnection *conn, long long fileId);
/* Get cdwVcfFile with given fileId or NULL if none such */
char *cdwOppositePairedEndString(char *end);
/* Return "1" for "2" and vice versa */
struct cdwValidFile *cdwOppositePairedEnd(struct sqlConnection *conn, struct cdwFile *ef, struct cdwValidFile *vf);
/* Given one file of a paired end set of fastqs, find the file with opposite ends. */
struct cdwQaPairedEndFastq *cdwQaPairedEndFastqFromVfs(struct sqlConnection *conn,
struct cdwValidFile *vfA, struct cdwValidFile *vfB,
struct cdwValidFile **retVf1, struct cdwValidFile **retVf2);
/* Return pair record if any for the two fastq files. */
void cdwMd5File(char *fileName, char md5Hex[33]);
/* call md5sum utility to calculate md5 for file and put result in hex format md5Hex
* This ends up being about 30% faster than library routine md5HexForFile,
* however since there's popen() weird interactions with stdin involved
* it's not suitable for a general purpose library. Environment inside cdw
* is controlled enough it should be ok. */
void cdwPathForCommand(char *command, char path[PATH_LEN]);
/* Figure out path associated with command */
void cdwPokeFifo(char *fifoName);
/* Send '\n' to fifo to wake up associated daemon */
FILE *cdwPopen(char *command, char *mode);
/* do popen or die trying */
void cdwOneLineSystemResult(char *command, char *line, int maxLineSize);
/* Execute system command and return one line result from it in line */
boolean cdwOneLineSystemAttempt(char *command, char *line, int maxLineSize);
/* Execute system command and return one line result from it in line */
/***/
/* Shared functions for CDW web CGI's.
Mostly wrappers for javascript tweaks */
void cdwWebAutoRefresh(int msec);
/* Refresh page after msec. Use 0 to cancel autorefresh */
/***/
/* Navigation bar */
void cdwWebNavBarStart();
/* Layout navigation bar */
void cdwWebNavBarEnd();
/* Close layout after navigation bar */
void cdwWebBrowseMenuItem(boolean on);
/* Toggle visibility of 'Browse submissions' link on navigation menu */
void cdwWebSubmitMenuItem(boolean on);
/* Toggle visibility of 'Submit data' link on navigation menu */
/***/
/* Metadata queries */
/* Declarations of some structures so don't need all the include files */
struct rqlStatement;
struct tagStorm;
struct tagStanza;
struct tagStorm *cdwTagStorm(struct sqlConnection *conn);
/* Load cdwMetaTags.tags, cdwFile.tags, and select other fields into a tag
* storm for searching */
char *cdwLookupTag(struct cgiParsedVars *list, char *tag);
/* Return first occurence of tag on list, or empty string if not found */
struct tagStorm *cdwUserTagStorm(struct sqlConnection *conn, struct cdwUser *user);
/* Return tag storm just for files user has access to. */
struct tagStorm *cdwUserTagStormFromList(struct sqlConnection *conn,
struct cdwUser *user, struct cdwFile *validList ,struct rbTree *groupedFiles);
void cdwCheckRqlFields(struct rqlStatement *rql, struct slName *tagFieldList);
/* Make sure that rql query only includes fields that exist in tags */
char *cdwRqlLookupField(void *record, char *key);
/* Lookup a field in a tagStanza. */
boolean cdwRqlStatementMatch(struct rqlStatement *rql, struct tagStanza *stanza,
struct lm *lm);
/* Return TRUE if where clause and tableList in statement evaluates true for stanza. */
struct slRef *tagStanzasMatchingQuery(struct tagStorm *tags, char *query);
/* Return list of references to stanzas that match RQL query */
void cdwPrintMatchingStanzas(char *rqlQuery, int limit, struct tagStorm *tags, char *format);
/* Show stanzas that match query */
struct cgiParsedVars *cdwMetaVarsList(struct sqlConnection *conn, struct cdwFile *ef);
/* Return list of cgiParsedVars dictionaries for metadata for file. Free this up
* with cgiParsedVarsFreeList() */
char *testOriginalSymlink(char *submitFileName, char *submitDir);
/* Follows submitted symlinks to real file.
* Aborts if real file path starts with cdwRootDir
* since it should not point to a file already under cdwRoot. */
void replaceOriginalWithSymlink(char *submitFileName, char *submitDir, char *cdwPath);
/* For a file that was just copied, remove original and symlink to new one instead
* to save space. Follows symlinks if any to the real file and replaces it with a symlink */
int findSubmitSymlinkExt(char *submitFileName, char *submitDir, char **pPath, char **pLastPath, int *pSymlinkLevels);
/* Find the last symlink and real file in the chain from submitDir/submitFileName.
* This is useful for when target of symlink in cdw/ gets renamed
* (e.g. license plate after passes validation), or removed (e.g. cdwReallyRemove* commands).
* Returns 0 for success. /
* Returns -1 if path does not exist. */
char *findSubmitSymlink(char *submitFileName, char *submitDir, char *oldPath);
/* Find the last symlink in the chain from submitDir/submitFileName.
* This is useful for when target of symlink in cdw/ gets renamed
* (e.g. license plate after passes validation), or removed (e.g. cdwReallyRemove* commands). */
void cdwReallyRemoveFile(struct sqlConnection *conn, char *submitDir, long long fileId, boolean unSymlinkOnly, boolean really);
/* Remove all records of file from database and from Unix file system if
* the really flag is set. Otherwise just print some info on the file. */
char *cdwLocalMenuBar(struct cart *cart, boolean makeAbsolute);
/* Return menu bar string. Optionally make links in menubar to point to absolute URLs, not relative. */
char *fileExtFromFormat(char *format);
/* return file extension given the cdwFile format as defined in cdwValid.c. Result has to be freed */
void printMatchingStanzas(char *rqlQuery, int limit, struct tagStorm *tags, char *format);
/* Show stanzas that match query */
#endif /* CDWLIB_H */
| 45.474383 | 127 | 0.765324 | [
"object"
] |
2306df0b62d3b1c5ec4a92f5e6334685c535514d | 5,158 | h | C | src/rpc/message_data_structs.h | KyleMcMaster/ryo-currency | f698e11c88be33aaf89c316ac68baa0cb80a9c91 | [
"BSD-3-Clause"
] | 5 | 2019-06-17T01:43:39.000Z | 2022-02-15T11:17:17.000Z | src/rpc/message_data_structs.h | KyleMcMaster/ryo-currency | f698e11c88be33aaf89c316ac68baa0cb80a9c91 | [
"BSD-3-Clause"
] | 1 | 2018-08-12T19:48:29.000Z | 2018-08-12T19:48:29.000Z | src/rpc/message_data_structs.h | KyleMcMaster/ryo-currency | f698e11c88be33aaf89c316ac68baa0cb80a9c91 | [
"BSD-3-Clause"
] | 2 | 2019-08-13T10:06:29.000Z | 2020-04-01T16:43:00.000Z | // Copyright (c) 2019, Ryo Currency Project
// Portions copyright (c) 2014-2018, The Monero Project
//
// Portions of this file are available under BSD-3 license. Please see ORIGINAL-LICENSE for details
// All rights reserved.
//
// Authors and copyright holders give permission for following:
//
// 1. Redistribution and use in source and binary forms WITHOUT modification.
//
// 2. Modification of the source form for your own personal use.
//
// As long as the following conditions are met:
//
// 3. You must not distribute modified copies of the work to third parties. This includes
// posting the work online, or hosting copies of the modified work for download.
//
// 4. Any derivative version of this work is also covered by this license, including point 8.
//
// 5. Neither the name of the copyright holders nor the names of the authors may be
// used to endorse or promote products derived from this software without specific
// prior written permission.
//
// 6. You agree that this licence is governed by and shall be construed in accordance
// with the laws of England and Wales.
//
// 7. You agree to submit all disputes arising out of or in connection with this licence
// to the exclusive jurisdiction of the Courts of England and Wales.
//
// Authors and copyright holders agree that:
//
// 8. This licence expires and the work covered by it is released into the
// public domain on 1st of February 2020
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
// THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
// THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#pragma once
#include "crypto/hash.h"
#include "cryptonote_basic/cryptonote_basic.h"
#include "ringct/rctSigs.h"
#include <unordered_map>
#include <vector>
namespace cryptonote
{
namespace rpc
{
struct block_with_transactions
{
cryptonote::block block;
std::unordered_map<crypto::hash, cryptonote::transaction> transactions;
};
typedef std::vector<uint64_t> tx_output_indices;
typedef std::vector<tx_output_indices> block_output_indices;
struct transaction_info
{
cryptonote::transaction transaction;
bool in_pool;
uint64_t height;
};
struct output_key_and_amount_index
{
uint64_t amount_index;
crypto::public_key key;
};
typedef std::vector<output_key_and_amount_index> outputs_for_amount;
struct amount_with_random_outputs
{
uint64_t amount;
outputs_for_amount outputs;
};
struct peer
{
uint64_t id;
uint32_t ip;
uint16_t port;
uint64_t last_seen;
};
struct tx_in_pool
{
cryptonote::transaction tx;
crypto::hash tx_hash;
uint64_t blob_size;
uint64_t fee;
crypto::hash max_used_block_hash;
uint64_t max_used_block_height;
bool kept_by_block;
crypto::hash last_failed_block_hash;
uint64_t last_failed_block_height;
uint64_t receive_time;
uint64_t last_relayed_time;
bool relayed;
bool do_not_relay;
bool double_spend_seen;
};
typedef std::unordered_map<crypto::key_image, std::vector<crypto::hash>> key_images_with_tx_hashes;
struct output_amount_count
{
uint64_t amount;
uint64_t total_count;
uint64_t unlocked_count;
uint64_t recent_count;
};
struct output_amount_and_index
{
uint64_t amount;
uint64_t index;
};
struct output_key_mask_unlocked
{
crypto::public_key key;
rct::key mask;
bool unlocked;
};
struct hard_fork_info
{
uint8_t version;
bool enabled;
uint32_t window;
uint32_t votes;
uint32_t threshold;
uint8_t voting;
uint32_t state;
uint64_t earliest_height;
};
//required by JSON-RPC 2.0 spec
struct error
{
// not really using code, maybe later.
error() : use(false), code(1) {}
bool use; // do not serialize
int32_t code;
// not required by spec, but int error codes aren't perfect
std::string error_str;
std::string message;
//TODO: data member? not required, may want later.
};
struct BlockHeaderResponse
{
uint64_t major_version;
uint64_t minor_version;
uint64_t timestamp;
crypto::hash prev_id;
uint32_t nonce;
uint64_t height;
uint64_t depth;
crypto::hash hash;
uint64_t difficulty;
uint64_t reward;
};
struct DaemonInfo
{
uint64_t height;
uint64_t target_height;
uint64_t difficulty;
uint64_t target;
uint64_t tx_count;
uint64_t tx_pool_size;
uint64_t alt_blocks_count;
uint64_t outgoing_connections_count;
uint64_t incoming_connections_count;
uint64_t white_peerlist_size;
uint64_t grey_peerlist_size;
bool mainnet;
bool testnet;
bool stagenet;
crypto::hash top_block_hash;
uint64_t cumulative_difficulty;
uint64_t block_size_limit;
uint64_t start_time;
};
} // namespace rpc
} // namespace cryptonote
| 24.679426 | 99 | 0.772199 | [
"vector"
] |
230b2f135c2a1be4df616ebe1787893e140320b1 | 1,864 | h | C | pseudoSO/include/processos.h | LSantos06/PseudoOS | a107dc184b7bed6020c96f5bd74aa464f04012de | [
"MIT"
] | null | null | null | pseudoSO/include/processos.h | LSantos06/PseudoOS | a107dc184b7bed6020c96f5bd74aa464f04012de | [
"MIT"
] | 1 | 2017-12-04T13:54:56.000Z | 2017-12-04T13:54:56.000Z | pseudoSO/include/processos.h | LSantos06/PseudoOS | a107dc184b7bed6020c96f5bd74aa464f04012de | [
"MIT"
] | null | null | null | #ifndef PROCESSOS_H
#define PROCESSOS_H
#include <string.h>
#include <stdbool.h>
#include <iostream>
#include <vector>
using namespace std;
class Processo{
// 0 tempo_inicializacao
// 1 prioridade
// 2 tempo_processador
// 3 blocos_memoria
// 4 numero_impressora
// 5 requisicao_scanner
// 6 requisicao_modem
// 7 numero_disco
// 8 ProcessoID
// 9 memory_offset
public:
string atributos[10];
Processo(string valores_entrada[10]);
//Funcoes para mexer com atributos de processo
//Retorna, em inteiro, o tempo de inicializacao
int getTempoInicializacao();
//Recebe a prioridade do processo
int getPrioridade();
//Permite mudanca da prioridade de um processo dinamicamente
void setPrioridade(int prioridade);
//Obtencao do tempo de processador atual de um processo
int getTempoProcessador();
void setTempoProcessador(int tempo);
//Obtencao e modificacao dos blocos de memoria do processo
int getBlocos();
void setBlocos(int blocos);
//Retorna numero da impressora
int getImpressora();
//Seta numero da impressora requisitada
void setImpressora(int impressora);
//Verifica se Processo requsitou o Scanner
bool getScanner();
void setScanner(bool scanner);
//Verifica se Processo requsitou o Modem
bool getModem();
void setModem(bool modem);
//Obtencao e modificacao do numer de disco
int getDisco();
void setDisco(int disco);
//ID do processo (apenas acesso)
int getID();
//Obtencao do offset de memoria do processo
int getMemOffset();
void setMemOffset(int offset);
//Para debug
void print();
//Verifica se processo eh usuario
bool eh_usuario();
};
// Função de inicialização do vetor de processos
vector<Processo*> montarVetorProcessos(char *);
#endif // PROCESS_H
| 23.594937 | 64 | 0.697425 | [
"vector"
] |
23128281ec0c3800293d9df8d529b5d5298d9e3d | 106,912 | c | C | gpAux/extensions/gpmapreduce/src/mapred.c | lintzc/GPDB | b48c8b97da18f495c10065d0853db87960aebae2 | [
"PostgreSQL",
"Apache-2.0"
] | 1 | 2017-09-15T06:09:56.000Z | 2017-09-15T06:09:56.000Z | gpAux/extensions/gpmapreduce/src/mapred.c | guofengrichard/gpdb | 29bdd6ef38d8d9b9cb04ca31d44e279eb9f640d3 | [
"PostgreSQL",
"Apache-2.0"
] | null | null | null | gpAux/extensions/gpmapreduce/src/mapred.c | guofengrichard/gpdb | 29bdd6ef38d8d9b9cb04ca31d44e279eb9f640d3 | [
"PostgreSQL",
"Apache-2.0"
] | 1 | 2018-12-04T09:13:57.000Z | 2018-12-04T09:13:57.000Z | #include <mapred.h>
#include <except.h>
#include <mapred_errors.h>
#include <stdio.h>
#include <stdarg.h>
#include <unistd.h> /* for file "access" test */
#include <errno.h>
#define scalarfree(x) \
do { \
if (x) { \
free(x); \
x = NULL; \
} \
} while (0)
/* instantiate the extern from mapred.h */
const char *mapred_kind_name[MAPRED_MAXKIND+1] =
{
"<NULL>",
"DOCUMENT",
"INPUT",
"OUTPUT",
"MAP",
"TRANSITION",
"CONSOLIDATE",
"FINALIZE",
"REDUCE",
"TASK",
"RUN",
"INTERNAL"
};
/* instantiate default parameter names from mapred.h */
const char *default_parameter_names[MAPRED_MAXKIND+1][2] =
{
{NULL, NULL}, /* MAPRED_NO_KIND */
{NULL, NULL}, /* MAPRED_DOCUMENT */
{NULL, NULL}, /* MAPRED_INPUT */
{NULL, NULL}, /* MAPRED_OUTPUT */
{"key", "value"}, /* MAPRED_MAPPER */
{"state", "value"}, /* MAPRED_TRANSITION */
{"state1", "state2"}, /* MAPRED_COMBINER */
{"state", NULL}, /* MAPRED_FINALIZER */
{NULL, NULL}, /* MAPRED_REDUCER */
{NULL, NULL}, /* MAPRED_TASK */
{NULL, NULL}, /* MAPRED_EXECUTION */
{NULL, NULL} /* MAPRED_ADT */
};
/* instantiate default parameter names from mapred.h */
const char *default_return_names[MAPRED_MAXKIND+1][2] =
{
{NULL, NULL}, /* MAPRED_NO_KIND */
{NULL, NULL}, /* MAPRED_DOCUMENT */
{NULL, NULL}, /* MAPRED_INPUT */
{NULL, NULL}, /* MAPRED_OUTPUT */
{"key", "value"}, /* MAPRED_MAPPER */
{"value", NULL}, /* MAPRED_TRANSITION */
{"value", NULL}, /* MAPRED_COMBINER */
{"value", NULL}, /* MAPRED_FINALIZER */
{NULL, NULL}, /* MAPRED_REDUCER */
{NULL, NULL}, /* MAPRED_TASK */
{NULL, NULL}, /* MAPRED_EXECUTION */
{NULL, NULL} /* MAPRED_ADT */
};
/*
* libpq Errors that we care about
* (would be better to add <errcodes.h> to the include path)
*/
const char *IN_FAILED_SQL_TRANSACTION = "25P02";
const char *OBJ_DOES_NOT_EXIST = "42P01";
const char *SCHEMA_DOES_NOT_EXIST = "3F000";
const char *DISTRIBUTION_NOTICE = "NOTICE: Table doesn't have 'DISTRIBUTED BY' clause";
/* local prototypes */
void * mapred_malloc(int size);
void mapred_free(void *ptr);
buffer_t * makebuffer(size_t bufsize, size_t grow);
void bufreset(buffer_t *b);
void bufcat(buffer_t **bufp, char* fmt);
void ignore_notice_handler(void *arg, const PGresult *res);
void print_notice_handler(void *arg, const PGresult *res);
void mapred_setup_columns(PGconn *conn, mapred_object_t *obj);
boolean mapred_create_object(PGconn *conn, mapred_document_t *doc,
mapred_object_t *obj);
void mapred_remove_object(PGconn *conn, mapred_document_t *doc,
mapred_object_t *obj);
void mapred_run_queries(PGconn *conn, mapred_document_t *doc);
void mapred_resolve_dependencies(PGconn *conn, mapred_document_t *doc);
void mapred_resolve_ref(mapred_olist_t *olist, mapred_reference_t *ref);
void mapred_resolve_object(PGconn *conn, mapred_document_t *doc,
mapred_object_t *obj, int *exec_count);
void lookup_function_in_catalog(PGconn *conn, mapred_document_t *doc,
mapred_object_t *obj);
/* Wrappers around malloc/free to handle error conditions more cleanly */
void *mapred_malloc(int size)
{
void *m;
XASSERT(size > 0);
#ifdef INTERNAL_BUILD
if (global_debug_flag && global_verbose_flag)
fprintf(stderr, "Allocating %d bytes: ", size);
#endif
m = malloc(size);
if (!m)
XRAISE(MEMORY_ERROR, "Memory allocation failure");
#ifdef INTERNAL_BUILD
if (global_debug_flag && global_verbose_flag)
fprintf(stderr, "%p\n", m);
#endif
return m;
}
#define copyscalar(s) \
strcpy(mapred_malloc(strlen(s)+1), s)
void mapred_free(void *ptr)
{
XASSERT(ptr);
#ifdef INTERNAL_BUILD
if (global_debug_flag && global_verbose_flag)
fprintf(stderr, "Freeing memory: %p\n", ptr);
#endif
free(ptr);
}
int mapred_obj_error(mapred_object_t *obj, char *fmt, ...)
{
va_list arg;
if (global_verbose_flag)
fprintf(stderr, " - ");
fprintf(stderr, "Error: ");
if (obj && obj->name)
fprintf(stderr, "%s '%s': ", mapred_kind_name[obj->kind], obj->name);
if (obj && !obj->name)
fprintf(stderr, "%s: ", mapred_kind_name[obj->kind]);
va_start(arg, fmt);
vfprintf(stderr, fmt, arg);
va_end(arg);
if (obj->line > 0)
fprintf(stderr, ", at line %d\n", obj->line);
else
fprintf(stderr, "\n");
return MAPRED_PARSE_ERROR;
}
static void mapred_obj_debug(mapred_object_t *obj)
{
mapred_plist_t *plist;
if (!obj)
{
fprintf(stderr, "Object is NULL");
return;
}
fprintf(stderr, "%s: \n", mapred_kind_name[obj->kind]);
fprintf(stderr, " NAME: '%s': \n", obj->name ? obj->name : "-");
switch (obj->kind)
{
case MAPRED_NO_KIND:
case MAPRED_DOCUMENT:
case MAPRED_ADT:
case MAPRED_INPUT:
case MAPRED_OUTPUT:
case MAPRED_TASK:
case MAPRED_EXECUTION:
case MAPRED_REDUCER:
{
fprintf(stderr, " DEBUG: 'debug output not yet implemented'\n");
break;
}
case MAPRED_MAPPER:
case MAPRED_TRANSITION:
case MAPRED_COMBINER:
case MAPRED_FINALIZER:
{
fprintf(stderr, " LANGUAGE: %s\n", obj->u.function.language ?
obj->u.function.language : "-");
fprintf(stderr, " PARAMETERS: [");
for (plist = obj->u.function.parameters; plist; plist = plist->next)
{
fprintf(stderr, "%s %s%s", plist->name, plist->type,
plist->next ? ", " : "");
}
fprintf(stderr,"]\n");
fprintf(stderr, " RETURNS: [");
for (plist = obj->u.function.returns; plist; plist = plist->next)
{
fprintf(stderr, "%s %s%s", plist->name, plist->type,
plist->next ? ", " : "");
}
fprintf(stderr,"]\n");
fprintf(stderr, " LIBRARY: %s\n", obj->u.function.library ?
obj->u.function.library : "-");
fprintf(stderr, " FUNCTION: %s\n", obj->u.function.body ?
obj->u.function.body : "-");
break;
}
}
}
/* -------------------------------------------------------------------------- */
/* Functions that play with buffers */
/* -------------------------------------------------------------------------- */
buffer_t *makebuffer(size_t bufsize, size_t grow)
{
buffer_t *b;
XASSERT(bufsize > 0 && grow > 0);
b = mapred_malloc(sizeof(buffer_t) + bufsize);
b->buffer = (char*)(b+1);
b->bufsize = bufsize;
b->grow = grow;
b->position = 0;
b->buffer[0] = '\0';
return b;
}
/* to re-use a buffer just "reset" it */
void bufreset(buffer_t *b)
{
XASSERT(b && b->bufsize > 0 && b->grow > 0);
b->position = 0;
b->buffer[0] = '\0';
}
/*
* A simple wrapper around a strncpy that handles resizing an input buffer
* when needed.
*/
void bufcat(buffer_t **bufp, char* str)
{
buffer_t *b;
size_t len;
XASSERT(bufp && *bufp);
XASSERT(str);
b = *bufp;
len = strlen(str);
/* If the buffer is too small, grow it */
if (b->bufsize <= b->position + len)
{
buffer_t *newbuf;
/* use the minumum of "grow" and the new length for the grow amount */
if (b->grow <= len)
b->grow = len+1;
newbuf = makebuffer(b->bufsize + b->grow, b->grow);
memcpy(newbuf->buffer, b->buffer, b->position+1);
newbuf->position = b->position;
*bufp = newbuf;
mapred_free(b);
b = newbuf;
}
/* We are now guaranteed that we have enough space in the buffer */
XASSERT( b->bufsize - b->position > len );
strcpy(b->buffer+b->position, str);
b->position += len;
b->buffer[b->position] = '\0';
}
/*
* Currently we just ignore all warnings, may eventually do something
* smarter, but this is preferable to dumping them to libpq's default
* of dumping them to stderr.
*/
void ignore_notice_handler(void *arg, const PGresult *res)
{
}
void print_notice_handler(void *arg, const PGresult *res)
{
char *error = PQresultErrorMessage(res);
if (!strncmp(error, DISTRIBUTION_NOTICE, strlen(DISTRIBUTION_NOTICE)-1))
return;
if (global_verbose_flag)
fprintf(stderr, " - ");
fprintf(stderr, "%s", error);
}
/*
* If a function is already defined in the database we need to be able to
* lookup the function information directly from the catalog. This is
* fairly similar to func_get_detail in backend/parser/parse_func.c, but
* the lookup from yaml is slightly different because we don't know the
* context that the function is in, but we _might_ have been told some
* of the parameter information already.
*/
void lookup_function_in_catalog(PGconn *conn, mapred_document_t *doc,
mapred_object_t *obj)
{
PGresult *result = NULL;
PGresult *result2 = NULL;
mapred_plist_t *plist, *plist2;
mapred_plist_t *newitem = NULL;
mapred_plist_t *returns = NULL;
buffer_t *buffer = NULL;
char *tmp1 = NULL;
char *tmp2 = NULL;
char *tmp3 = NULL;
const int STR_LEN = 50;
char str[STR_LEN];
int i, nargs;
XASSERT(doc);
XASSERT(obj);
XASSERT(obj->kind == MAPRED_MAPPER ||
obj->kind == MAPRED_TRANSITION ||
obj->kind == MAPRED_COMBINER ||
obj->kind == MAPRED_FINALIZER);
obj->internal = true;
obj->u.function.internal_returns = NULL;
XTRY
{
buffer = makebuffer(1024, 1024);
/* Try to lookup the specified function */
bufcat(&buffer,
"SELECT proretset, prorettype::regtype, pronargs,\n"
" proargnames, proargmodes, \n"
" (proargtypes::regtype[])[0:pronargs] as proargtypes,\n"
" proallargtypes::regtype[],\n");
/*
* If we have return types defined in the yaml then we want to resolve
* them to their authorative names for comparison purposes.
*/
if (obj->u.function.returns)
{
bufcat(&buffer, " ARRAY[");
for (plist = obj->u.function.returns; plist; plist = plist->next)
{
if (plist->type)
{
bufcat(&buffer, "'");
bufcat(&buffer, plist->type);
bufcat(&buffer, "'::regtype");
}
else
{
/* If we don't know the type, punt */
bufcat(&buffer, "'-'::regtype");
}
if (plist->next)
bufcat(&buffer, ", ");
}
bufcat(&buffer, "] as yaml_rettypes\n");
}
else
{
bufcat(&buffer, " null::regtype[] as yaml_rettypes\n");
}
bufcat(&buffer,
"FROM pg_proc\n"
"WHERE not proisagg and not proiswin\n"
" AND proname = lower('");
bufcat(&buffer, obj->name);
bufcat(&buffer, "')\n");
/* Fill in the known parameter types */
nargs = 0;
if (obj->u.function.parameters)
{
bufcat(&buffer, " AND (proargtypes::regtype[])[0:pronargs] = ARRAY[");
for (plist = obj->u.function.parameters; plist; plist = plist->next)
{
nargs++;
bufcat(&buffer, "'");
bufcat(&buffer, plist->type);
bufcat(&buffer, "'::regtype");
if (plist->next)
bufcat(&buffer, ", ");
}
snprintf(str, STR_LEN, "]\n AND pronargs=%d\n", nargs);
bufcat(&buffer, str);
}
/* Run the SQL */
if (global_print_flag || global_debug_flag)
printf("%s", buffer->buffer);
result = PQexec(conn, buffer->buffer);
bufreset(buffer);
if (PQresultStatus(result) != PGRES_TUPLES_OK)
{
/*
* The SQL statement failed:
* Most likely scenario is a bad datatype causing the regtype cast
* to fail.
*/
char *code = PQresultErrorField(result, PG_DIAG_SQLSTATE);
char *error = PQresultErrorMessage(result);
printf("errcode=\"%s\"\n", code); /* Todo: validate expected error code */
mapred_obj_error(obj, "SQL Error resolving function: \n %s",
error);
XRAISE(MAPRED_PARSE_ERROR, "Object creation Failure");
}
else if (PQntuples(result) == 0)
{
/* No such function */
mapred_obj_error(obj, "No such function");
XRAISE(MAPRED_PARSE_ERROR, "Object creation Failure");
}
else if (PQntuples(result) > 1)
{
XASSERT(!obj->u.function.parameters);
mapred_obj_error(obj, "Ambiguous function, supply a function "
"prototype for disambiguation");
XRAISE(MAPRED_PARSE_ERROR, "Object creation Failure");
}
else
{
char *value;
int len;
boolean retset;
int nargs;
char *argtypes = NULL;
char *argnames = "";
char *argmodes = "";
char *allargtypes = "";
char *rettype = NULL;
char *yaml_rettypes = "";
char *type, *typetokens = NULL;
char *name, *nametokens = NULL;
char *mode, *modetokens = NULL;
boolean name_end, mode_end;
value = PQgetvalue(result, 0, 0); /* Column 0: proretset */
retset = (value[0] == 't');
value = PQgetvalue(result, 0, 1); /* Column 1: prorettype */
rettype = value;
value = PQgetvalue(result, 0, 2); /* Column 2: pronargs */
nargs = (int) strtol(value, (char **) NULL, 10);
/*
* Arrays are formatted as: "{value,value,...}"
* of which we only want "value,value, ..."
* so find the part of the string between the braces
*/
if (!PQgetisnull(result, 0, 3)) /* Column 3: proargnames */
{
value = PQgetvalue(result, 0, 3);
argnames = value+1;
len = strlen(argnames);
if (len > 0)
argnames[len-1] = '\0';
}
if (!PQgetisnull(result, 0, 4)) /* Column 4: proargmodes */
{
value = PQgetvalue(result, 0, 4);
argmodes = value+1;
len = strlen(argmodes);
if (len > 0)
argmodes[len-1] = '\0';
}
if (!PQgetisnull(result, 0, 5)) /* Column 5: proargtypes */
{
value = PQgetvalue(result, 0, 5);
argtypes = value+1;
len = strlen(argtypes);
if (len > 0)
argtypes[len-1] = '\0';
}
if (!PQgetisnull(result, 0, 6)) /* Column 6: proallargtypes */
{
value = PQgetvalue(result, 0, 6);
allargtypes = value+1;
len = strlen(allargtypes);
if (len > 0)
allargtypes[len-1] = '\0';
}
if (!PQgetisnull(result, 0, 7)) /* Column 7: yaml_rettypes */
{
value = PQgetvalue(result, 0, 7);
yaml_rettypes = value+1;
len = strlen(yaml_rettypes);
if (len > 0)
yaml_rettypes[len-1] = '\0';
}
/*
* These constraints should all be enforced in the catalog, so
* if something is wrong then it's a coding error above.
*/
XASSERT(rettype);
XASSERT(argtypes);
XASSERT(nargs >= 0);
/*
* If we just derived the parameters from the catalog then we
* need complete our internal metadata.
*/
plist = NULL;
if (!obj->u.function.parameters)
{
/* strtok is destructive and we need to preserve the original
* string, so we make some annoying copies prior to strtok.
*/
tmp1 = copyscalar(argtypes);
tmp2 = copyscalar(argnames);
tmp3 = copyscalar(argmodes);
type = strtok_r(tmp1, ",", &typetokens);
name = strtok_r(tmp2, ",", &nametokens);
mode = strtok_r(tmp3, ",", &modetokens);
/*
* Name and mode are used for IN/OUT parameters and may not be
* present. In the event that they are we are looking for:
* - the "i" (in) arguments
* - the "b" (inout) arguments
* we skip over:
* - the "o" (out) arguments.
* - the "t" (table out) arguments.
*
* Further it is possible for some of the arguments to be named
* and others to be unnamed. The unnamed arguments will show
* up as "" (two quotes, not an empty string) if there is an
* argnames defined.
*
* If argmodes is not defined then all names in proargnames
* refer to input arguments.
*/
while (mode && strcmp(mode, "i") && strcmp(mode, "b"))
{
name = strtok_r(NULL, ",", &nametokens);
mode = strtok_r(NULL, ",", &modetokens);
}
name_end = (NULL == name);
mode_end = (NULL == mode);
i = 0;
while (type)
{
/* Keep track of which parameter we are on */
i++;
XASSERT(i <= nargs);
/*
* If a name was not specified by the user, and was not
* specified by the in/out parameters then we assign it a
* default name.
*/
if (!name)
{
/* single argument functions always default to "value" */
if (i == 1 && nargs == 1)
name = (char*) "value";
/* Base name on default parameter names for the first
* two arguments */
else if (i <= 2)
name = (char*) default_parameter_names[obj->kind][i-1];
/*
* If we still didn't decide on a name, make up
* something useless.
*/
if (!name)
{
snprintf(str, STR_LEN, "parameter%d", i);
name = str;
}
}
if (!plist)
{
plist = mapred_malloc(sizeof(mapred_plist_t));
plist->name = copyscalar(name);
plist->type = copyscalar(type);
plist->next = (mapred_plist_t *) NULL;
obj->u.function.parameters = plist;
}
else
{
plist->next = mapred_malloc(sizeof(mapred_plist_t));
plist = plist->next;
plist->name = copyscalar(name);
plist->type = copyscalar(type);
plist->next = (mapred_plist_t *) NULL;
}
/* Procede to the next parameter */
type = strtok_r(NULL, ",", &typetokens);
if (!name_end)
{
name = strtok_r(NULL, ",", &nametokens);
name_end = (NULL == name);
}
if (!mode_end)
{
mode = strtok_r(NULL, ",", &modetokens);
mode_end = (NULL == mode);
}
while (mode && strcmp(mode, "i") && strcmp(mode, "b"))
{
if (!name_end)
{
name = strtok_r(NULL, ",", &nametokens);
name_end = (NULL == name);
}
if (!mode_end)
{
mode = strtok_r(NULL, ",", &modetokens);
mode_end = (NULL == mode);
}
}
}
mapred_free(tmp1);
mapred_free(tmp2);
mapred_free(tmp3);
tmp1 = NULL;
tmp2 = NULL;
tmp3 = NULL;
}
/*
* Check that the number of parameters received is appropriate.
* This would be better moved to a generalized validation routine.
*/
switch (obj->kind)
{
case MAPRED_MAPPER:
/*
* It would probably be possible to start supporting zero
* argument mappers, but:
* 1) It would require more modifications
* 2) Doesn't currently have a known use case
* 3) Has easy workarounds
*/
if (nargs < 1)
{
mapred_obj_error(obj, "Transition functions require "
"two or more parameters");
XRAISE(MAPRED_PARSE_ERROR, "Object creation Failure");
}
break;
case MAPRED_TRANSITION:
if (nargs < 2)
{
mapred_obj_error(obj, "Transition functions require "
"two or more parameters");
XRAISE(MAPRED_PARSE_ERROR, "Object creation Failure");
}
if (retset)
{
mapred_obj_error(obj, "Transition functions cannot "
"be table functions");
XRAISE(MAPRED_PARSE_ERROR, "Object creation Failure");
}
break;
case MAPRED_COMBINER:
if (nargs != 2)
{
mapred_obj_error(obj, "Consolidate functions require "
"exactly two parameters");
XRAISE(MAPRED_PARSE_ERROR, "Object creation Failure");
}
if (retset)
{
mapred_obj_error(obj, "Consolidate functions cannot "
"be table functions");
XRAISE(MAPRED_PARSE_ERROR, "Object creation Failure");
}
break;
case MAPRED_FINALIZER:
if (nargs != 1)
{
mapred_obj_error(obj, "Finalize functions require "
"exactly one parameter");
XRAISE(MAPRED_PARSE_ERROR, "Object creation Failure");
}
break;
default:
XASSERT(false);
}
/* Fill in return type information */
if (retset)
obj->u.function.mode = MAPRED_MODE_MULTI;
else
obj->u.function.mode = MAPRED_MODE_SINGLE;
/*
* Determine the return type information, there are 3 primary
* subcases:
*
* 1) Function is defined with OUT/TABLE parameters.
* 2) Function returns a simple type.
* 3) Function returns a complex type.
* 4) Return type is void [error]
*/
plist = returns = NULL;
if (argmodes && strlen(argmodes) > 0)
{
/* strtok is destructive and we need to preserve the original
* string, so we make some annoying copies prior to strtok.
*/
tmp1 = copyscalar(allargtypes);
tmp2 = copyscalar(argnames);
tmp3 = copyscalar(argmodes);
type = strtok_r(tmp1, ",", &typetokens);
name = strtok_r(tmp2, ",", &nametokens);
mode = strtok_r(tmp3, ",", &modetokens);
i = 1;
while (mode)
{
while (mode &&
strcmp(mode, "o") &&
strcmp(mode, "b") &&
strcmp(mode, "t"))
{
/* skip input parameters */
type = strtok_r(NULL, ",", &typetokens);
name = strtok_r(NULL, ",", &nametokens);
mode = strtok_r(NULL, ",", &modetokens);
}
if (mode)
{
XASSERT(type);
newitem = mapred_malloc(sizeof(mapred_plist_t));
/*
* Note we haven't made local copies of these, we will
* do this after resolution when validating against any
* RETURNS defined in the yaml, if any.
*/
if( NULL != name &&
0 != strcmp(name, "") &&
0 != strcmp(name, "\"\"") )
{
/*if name defined in db, just use it*/
newitem->name = copyscalar(name);
}
else
{
/*else just obey the default name in db*/
snprintf( str, STR_LEN, "column%d", i);
newitem->name = copyscalar(str);
}
newitem->type = copyscalar(type);
newitem->next = NULL;
if (plist)
plist->next = newitem;
else
returns = newitem;
plist = newitem;
++i;
}
type = strtok_r(NULL, ",", &typetokens);
name = strtok_r(NULL, ",", &nametokens);
mode = strtok_r(NULL, ",", &modetokens);
}
mapred_free(tmp1);
mapred_free(tmp2);
mapred_free(tmp3);
tmp1 = NULL;
tmp2 = NULL;
tmp3 = NULL;
}
/*
* If the arguments were not defined in the function definition then
* we check to see if this was a complex type by looking up the type
* information in pg_attribute.
*/
if (!returns)
{
bufcat(&buffer,
"SELECT attname, atttypid::regtype\n"
"FROM pg_attribute a\n"
"JOIN pg_class c on (a.attrelid = c.oid)\n"
"WHERE not a.attisdropped\n"
" AND a.attnum > 0\n"
" AND c.reltype = '");
bufcat(&buffer, rettype);
bufcat(&buffer,
"'::regtype\n"
"ORDER BY -attnum");
result2 = PQexec(conn, buffer->buffer);
bufreset(buffer);
if (PQresultStatus(result2) != PGRES_TUPLES_OK)
{
char *error = PQresultErrorMessage(result);
mapred_obj_error(obj, "Error resolving function: %s", error);
XRAISE(MAPRED_PARSE_ERROR, "Object creation Failure");
}
else if (PQntuples(result2) > 0)
{
/* We have a complex type, build the return list */
for (i = 0; i < PQntuples(result2); i++)
{
name = PQgetvalue(result2, i, 0);
type = PQgetvalue(result2, i, 1);
newitem = mapred_malloc(sizeof(mapred_plist_t));
newitem->name = copyscalar(name);
newitem->type = copyscalar(type);
newitem->next = returns;
returns = newitem;
}
}
}
/*
* If the return types were not defined in either the argument list
* nor the catalog then we assume it is a simple type.
*/
if (!returns)
{
/* Check against "void" which is a special return type that
* means there is no return value - which we don't support for
* mapreduce.
*/
if (!strcmp(rettype, "void"))
{
mapred_obj_error(obj, "Function returns void");
XRAISE(MAPRED_PARSE_ERROR, "Object creation Failure");
}
returns = mapred_malloc(sizeof(mapred_plist_t));
returns->type = copyscalar(rettype);
returns->name = NULL;
returns->next = NULL;
}
/*
* We now should have a returns list, compare it against the RETURNS
* list given in the yaml. The yaml overrides return names, but can
* not override return types. If the return types are incompatible
* raise an error.
*/
obj->u.function.internal_returns = returns;
if (obj->u.function.returns)
{
/*
* The first thing to do is normalize the given return types
* with their formal names. This will, for example turn a type
* like "float8" => "double precision". The input name might
* be correct (float8) but we need it represented as the formal
* name so that we can compare against the formal name we got
* when we looked up the function in the catalog.
*/
plist = obj->u.function.returns;
type = strtok_r(yaml_rettypes, ",", &typetokens);
while (plist)
{
XASSERT(type); /* should be an equal number */
/*
* If we have a type specified replace it with the one we
* resolved from the select stmt, otherwise just keep it
* as NULL and fill it in during the compare against what
* was in the catalog.
*/
if (plist->type)
{
mapred_free(plist->type);
/*
* When in an array the typname may get wrapped in
* double quotes, if so we need to strip them back out.
*/
if (type[0] == '"')
{
plist->type = copyscalar(type+1);
plist->type[strlen(plist->type)-1] = '\0';
}
else
{
plist->type = copyscalar(type);
}
}
plist = plist->next;
type = strtok_r(NULL, ",", &typetokens);
}
/* Compare against actual function return types */
plist = obj->u.function.returns;
plist2 = returns;
while (plist && plist2)
{
XASSERT(plist->name); /* always defined in YAML */
XASSERT(plist2->type); /* always defined in SQL */
/*
* In the YAML it is possible to have a name without a type,
* if that is the case then simply take the SQL type.
*/
if (!plist->type)
plist->type = copyscalar(plist2->type);
else if (strcmp(plist->type, plist2->type))
break;
plist = plist->next;
plist2 = plist2->next;
}
if (plist || plist2)
{
mapred_obj_error(obj, "RETURN parameter '%s %s' != '%s %s'",
plist ? plist->name : "\"\"",
plist ? plist->type : "-",
plist2 ? (plist2->name ? plist2->name : plist->name) : "\"\"",
plist2 ? plist2->type : "-");
XRAISE(MAPRED_PARSE_ERROR, "Object creation Failure");
}
}
else
{
obj->u.function.returns = returns;
i = 0;
for (plist = returns; plist; plist = plist->next)
{
XASSERT(plist->type);
i++;
plist->type = copyscalar(plist->type);
/*
* if plist->name is not null and empty string,
* then use that name
*/
if (plist->name &&
0 != strcmp(plist->name, "") &&
0 != strcmp(plist->name, "\"\"") )
{
plist->name = copyscalar(plist->name);
}
/*
* else We need generate a name anyway
*/
else
{
/*
* Manufacture a name for a column based on default
* naming rules.
*/
name = (char*) NULL;
if (i <= 2)
name = (char*) default_return_names[obj->kind][i-1];
if (!name)
{
snprintf(str, STR_LEN, "parameter%d", i);
name = str;
}
plist->name = copyscalar(name);
}
}
}
}
}
XFINALLY
{
if (result)
PQclear(result);
if (result2)
PQclear(result2);
if (buffer)
mapred_free(buffer);
if (tmp1)
mapred_free(tmp1);
if (tmp2)
mapred_free(tmp2);
if (tmp3)
mapred_free(tmp3);
}
XTRY_END;
}
void mapred_run_document(PGconn *conn, mapred_document_t *doc)
{
PGresult *result;
mapred_olist_t *olist;
boolean done;
boolean executes;
/* Ignore NOTICE messages from database */
PQsetNoticeReceiver(conn, ignore_notice_handler, NULL);
/* Establish a name-prefix for temporary objects */
doc->prefix = mapred_malloc(64);
snprintf(doc->prefix, 64, "mapreduce_%d_", PQbackendPID(conn));
/*
* Resolution of dependecies was defered until now so that
* a database connection could be available to look up any
* dependencies that are not defined within the YAML document.
*/
if (global_verbose_flag)
fprintf(stderr, " - Resolving Dependencies:\n");
mapred_resolve_dependencies(conn, doc);
if (global_verbose_flag)
fprintf(stderr, " - DONE\n");
XTRY
{
/*
* Setting gp_mapreduce_define will disable logging of sql
* statements.
*/
#ifndef INTERNAL_BUILD
result = PQexec(conn, "set gp_mapreduce_define=true");
PQclear(result);
#endif
/*
* By running things within a transaction we can effectively
* obscure the mapreduce sql definitions. They could still
* be exposed by a savy user via mapreduce views that access
* the catalog tables, but it's a cleaner method of handling
* things.
*/
result = PQexec(conn, "BEGIN TRANSACTION");
if (PQresultStatus(result) != PGRES_COMMAND_OK)
{
PQclear(result);
XRAISE(MAPRED_SQL_ERROR, NULL);
}
PQclear(result);
/* With dependencies resolved we can now try creating objects */
if (global_verbose_flag)
fprintf(stderr, " - Creating Objects\n");
/*
* we don't try to create any executes until all non-executes are
* successfully created
*/
executes = false;
do
{
boolean progress = false;
/*
* We keep a buffer of errors during parsing, and display them at
* the end if they haven't been resolved.
*/
if (!doc->errors)
doc->errors = makebuffer(1024, 1024);
else
bufreset(doc->errors);
/*
* Loop through the objects, creating each in turn.
* If an object has dependencies that have not been created yet
* it will return false and we will make additional passes through
* the object list
*/
done = true;
for (olist = doc->objects; olist; olist = olist->next)
{
mapred_object_t *obj = olist->object;
if (!obj->created &&
(executes || obj->kind != MAPRED_EXECUTION))
{
if (global_verbose_flag && obj->kind != MAPRED_ADT)
{
fprintf(stderr, " - %s:\n",
mapred_kind_name[obj->kind]);
fprintf(stderr, " NAME: %s\n", obj->name);
}
if (!mapred_create_object(conn, doc, obj))
done = false;
else
progress = true;
}
}
/*
* If all non-execute objects have been created then switch over
* and start creating the execution jobs
*/
if (done && !executes)
{
executes = true;
done = false;
}
/*
* If we looped through the list, we are not done, and no progress
* was made then we have an infinite cycle and should probably stop.
*/
if (!done && !progress)
{
if (doc->errors && doc->errors->position > 0)
fprintf(stderr, "%s", doc->errors->buffer);
XRAISE(MAPRED_PARSE_ERROR,
"Unable to make forward progress creating objects\n");
}
} while (!done);
/*
* Re-enable statement logging before we try running queries
*/
#ifndef INTERNAL_BUILD
result = PQexec(conn, "set gp_mapreduce_define=false");
PQclear(result);
#endif
/* objects created, execute queries */
mapred_run_queries(conn, doc);
}
XCATCH(MAPRED_SQL_ERROR)
{
if (global_verbose_flag)
fprintf(stderr, " - ");
fprintf(stderr, "%s", PQerrorMessage(conn));
XRERAISE();
}
XFINALLY
{
/*
* disable statement logging before deleting objects
*/
#ifndef INTERNAL_BUILD
result = PQexec(conn, "set gp_mapreduce_define=true");
PQclear(result);
#endif
/* Remove all the objects that we created */
if (global_print_flag || global_debug_flag)
printf("\n");
for (olist = doc->objects; olist; olist = olist->next)
mapred_remove_object(conn, doc, olist->object);
if (global_print_flag || global_debug_flag)
printf("\n");
/*
* We always commit the transaction, even on failure since the failure
* may have occured after we generated some output tables and we want
* to keep the partial results.
*/
result = PQexec(conn, "COMMIT TRANSACTION");
if (PQresultStatus(result) != PGRES_COMMAND_OK)
{
if (global_verbose_flag)
fprintf(stderr, " - ");
fprintf(stderr, "%s", PQerrorMessage(conn));
}
}
XTRY_END;
}
void mapred_resolve_dependencies(PGconn *conn, mapred_document_t *doc)
{
mapred_olist_t *olist;
int exec_count = 0;
/* Walk the list of objects */
for (olist = doc->objects; olist; olist = olist->next)
mapred_resolve_object(conn, doc, olist->object, &exec_count);
}
void mapred_resolve_object(PGconn *conn, mapred_document_t *doc,
mapred_object_t *obj, int *exec_count)
{
mapred_olist_t *newlist;
mapred_object_t *sub; /* sub-object */
size_t len;
switch (obj->kind)
{
/* Objects with no dependencies */
case MAPRED_OUTPUT:
case MAPRED_ADT:
break;
case MAPRED_INPUT:
/*
* For FILE/GPFDIST/EXEC inputs we will create a name-prefixed
* version of the object to prevent name collisions, and then
* create a second temporary view over the external table to
* support access to the input by "name". This involves creating
* a second copy of the input which we place directly after the
* original input in the document object list.
*/
if (obj->u.input.type == MAPRED_INPUT_GPFDIST ||
obj->u.input.type == MAPRED_INPUT_FILE ||
obj->u.input.type == MAPRED_INPUT_EXEC)
{
mapred_object_t *newinput;
mapred_olist_t *parent;
newinput = mapred_malloc(sizeof(mapred_object_t));
memset(newinput, 0, sizeof(mapred_object_t));
newinput->kind = MAPRED_INPUT;
len = strlen(obj->name) + 1;
newinput->name = mapred_malloc(len);
sprintf(newinput->name, "%s", obj->name);
newinput->u.input.type = MAPRED_INPUT_QUERY;
len = strlen(doc->prefix) + strlen(obj->name) + 16;
newinput->u.input.desc = mapred_malloc(len);
snprintf(newinput->u.input.desc, len,
"select * from %s%s",
doc->prefix, obj->name);
/*
* Find parent input in the doclist and add the new object
* immediately after it.
*/
for (parent = doc->objects;
parent && parent->object != obj;
parent = parent->next);
XASSERT(parent);
newlist = mapred_malloc(sizeof(mapred_olist_t));
newlist->object = newinput;
newlist->next = parent->next;
parent->next = newlist;
}
break;
case MAPRED_MAPPER:
case MAPRED_TRANSITION:
case MAPRED_COMBINER:
case MAPRED_FINALIZER:
/*
* If the function is an internal function then we try to resolve
* the function by looking it up in the catalog.
*/
obj->u.function.internal_returns = NULL;
obj->internal = false;
if (!obj->u.function.language)
{
obj->internal = true;
lookup_function_in_catalog(conn, doc, obj);
}
/* ??? */
else if (!obj->u.function.returns)
{
XASSERT(false);
}
/*
* The function types may manufacture a dependency on an adt,
* but have no other dependencies.
*/
else if (obj->u.function.returns->next)
{
sub = mapred_malloc(sizeof(mapred_object_t));
memset(sub, 0, sizeof(mapred_object_t));
sub->kind = MAPRED_ADT;
len = strlen(doc->prefix) + strlen(obj->name) + 7;
sub->name = mapred_malloc(len);
snprintf(sub->name, len, "%s%s_rtype",
doc->prefix, obj->name);
sub->u.adt.returns = obj->u.function.returns;
obj->u.function.rtype.name = sub->name;
obj->u.function.rtype.object = sub;
/* Add the ADT to the list of document objects */
newlist = mapred_malloc(sizeof(mapred_olist_t));
newlist->object = sub;
newlist->next = doc->objects;
doc->objects = newlist;
/* And resolve the sub-object */
mapred_resolve_object(conn, doc, sub, exec_count);
}
else
{
obj->u.function.rtype.name = obj->u.function.returns->type;
obj->u.function.rtype.object = NULL;
}
break;
case MAPRED_REDUCER:
{
/*
* If we have a function, but no object then we assume that it is
* a database function. Create a dummy object to handle this case.
*/
mapred_resolve_ref(doc->objects, &obj->u.reducer.transition);
if (obj->u.reducer.transition.name &&
!obj->u.reducer.transition.object)
{
len = strlen(obj->u.reducer.transition.name) + 1;
sub = mapred_malloc(sizeof(mapred_object_t));
memset(sub, 0, sizeof(mapred_object_t));
sub->kind = MAPRED_TRANSITION;
sub->name = mapred_malloc(len);
sub->line = obj->line;
strncpy(sub->name, obj->u.reducer.transition.name, len);
newlist = mapred_malloc(sizeof(mapred_olist_t));
newlist->object = sub;
newlist->next = doc->objects;
doc->objects = newlist;
obj->u.reducer.transition.object = sub;
/* And resolve the sub-object */
mapred_resolve_object(conn, doc, sub, exec_count);
}
mapred_resolve_ref(doc->objects, &obj->u.reducer.combiner);
if (obj->u.reducer.combiner.name &&
!obj->u.reducer.combiner.object)
{
len = strlen(obj->u.reducer.combiner.name) + 1;
sub = mapred_malloc(sizeof(mapred_object_t));
memset(sub, 0, sizeof(mapred_object_t));
sub->kind = MAPRED_COMBINER;
sub->name = mapred_malloc(len);
sub->line = obj->line;
strncpy(sub->name, obj->u.reducer.combiner.name, len);
newlist = mapred_malloc(sizeof(mapred_olist_t));
newlist->object = sub;
newlist->next = doc->objects;
doc->objects = newlist;
obj->u.reducer.combiner.object = sub;
/* And resolve the sub-object */
mapred_resolve_object(conn, doc, sub, exec_count);
}
mapred_resolve_ref(doc->objects, &obj->u.reducer.finalizer);
if (obj->u.reducer.finalizer.name &&
!obj->u.reducer.finalizer.object)
{
len = strlen(obj->u.reducer.finalizer.name) + 1;
sub = mapred_malloc(sizeof(mapred_object_t));
memset(sub, 0, sizeof(mapred_object_t));
sub->kind = MAPRED_FINALIZER;
sub->name = mapred_malloc(len);
sub->line = obj->line;
strncpy(sub->name, obj->u.reducer.finalizer.name, len);
newlist = mapred_malloc(sizeof(mapred_olist_t));
newlist->object = sub;
newlist->next = doc->objects;
doc->objects = newlist;
obj->u.reducer.finalizer.object = sub;
/* And resolve the sub-object */
mapred_resolve_object(conn, doc, sub, exec_count);
}
break;
}
case MAPRED_TASK:
case MAPRED_EXECUTION:
{
/*
* Resolving a task may require recursion to resolve other
* tasks to work out parameter lists. We keep track of
* our resolution state in order to detect potential
* infinite recursion issues.
*/
if (obj->u.task.flags & mapred_task_resolved)
return;
/* Assign a name to anonymous executions */
if (!obj->name)
{
size_t len;
XASSERT(obj->u.task.execute);
/* 10 characters for max int digits, 4 for "run_" */
len = strlen(doc->prefix) + 16;
obj->name = mapred_malloc(len);
snprintf(obj->name, len, "%srun_%d",
doc->prefix, ++(*exec_count));
}
/* Check for infinite recursion */
if (obj->u.task.flags & mapred_task_resolving)
{
mapred_obj_error(obj, "Infinite recursion detected while "
"trying to resove TASK");
XRAISE(MAPRED_PARSE_ERROR, "Object creation Failure");
}
obj->u.task.flags |= mapred_task_resolving;
/* Validate object types */
if (obj->u.task.input.name)
{
mapred_resolve_ref(doc->objects, &obj->u.task.input);
sub = obj->u.task.input.object;
/* If we can't find the input, throw an error */
if (!sub)
{
/* Can't find INPUT object */
mapred_obj_error(obj, "SOURCE '%s' not found in document",
obj->u.task.input.name);
XRAISE(MAPRED_PARSE_ERROR, "Object Resolution Failure");
}
/*
* The input must either be an INPUT or a TASK
*/
switch (sub->kind)
{
case MAPRED_INPUT:
break;
case MAPRED_TASK:
/* This objects input is the sub objects output */
mapred_resolve_object(conn, doc, sub, exec_count);
break;
/* Otherwise generate an error */
default:
/* SOURCE wasn't an INPUT */
mapred_obj_error(obj, "SOURCE '%s' is neither an INPUT nor a TASK",
obj->u.task.input.name);
XRAISE(MAPRED_PARSE_ERROR, "Object Resolution Failure");
}
}
if (obj->u.task.mapper.name)
{
mapred_resolve_ref(doc->objects, &obj->u.task.mapper);
sub = obj->u.task.mapper.object;
if (!sub)
{
/* Create an internal map function */
len = strlen(obj->u.task.mapper.name) + 1;
sub = mapred_malloc(sizeof(mapred_object_t));
memset(sub, 0, sizeof(mapred_object_t));
sub->kind = MAPRED_MAPPER;
sub->name = mapred_malloc(len);
sub->line = obj->line;
strncpy(sub->name, obj->u.task.mapper.name, len);
newlist = mapred_malloc(sizeof(mapred_olist_t));
newlist->object = sub;
newlist->next = doc->objects;
doc->objects = newlist;
obj->u.task.mapper.object = sub;
/* And resolve the sub-object */
mapred_resolve_object(conn, doc, sub, exec_count);
}
else
{
/* Allow any function type */
switch (sub->kind)
{
case MAPRED_MAPPER:
case MAPRED_TRANSITION:
case MAPRED_COMBINER:
case MAPRED_FINALIZER:
break;
default:
mapred_obj_error(obj, "MAP '%s' is not a MAP object",
obj->u.task.mapper.name);
XRAISE(MAPRED_PARSE_ERROR, "Object Resolution Failure");
}
}
}
if (obj->u.task.reducer.name)
{
mapred_resolve_ref(doc->objects, &obj->u.task.reducer);
sub = obj->u.task.reducer.object;
if (!sub)
{
/* FIXME: non-yaml reducers */
}
else if (sub->kind == MAPRED_REDUCER)
{ /* Validate Reducer */
mapred_resolve_object(conn, doc, sub, exec_count);
}
else
{ /* It's an object, but not a REDUCER */
mapred_obj_error(obj, "REDUCE '%s' is not a REDUCE object",
obj->u.task.reducer.name);
XRAISE(MAPRED_PARSE_ERROR, "Object Resolution Failure");
}
}
if (obj->u.task.output.name)
{
mapred_resolve_ref(doc->objects, &obj->u.task.output);
sub = obj->u.task.output.object;
if (sub && sub->kind != MAPRED_OUTPUT)
{
mapred_obj_error(obj, "TARGET '%s' is not an OUTPUT object",
obj->u.task.output.name);
XRAISE(MAPRED_PARSE_ERROR, "Object Resolution Failure");
}
if (!sub && obj->u.task.output.name)
{
mapred_obj_error(obj, "TARGET '%s' is not defined in "
"document",
obj->u.task.output.name);
XRAISE(MAPRED_PARSE_ERROR, "Object Resolution Failure");
}
}
/* clear resolving bit and set resolved bit */
obj->u.task.flags &= !mapred_task_resolving;
obj->u.task.flags |= mapred_task_resolved;
break;
}
default:
XASSERT(false);
}
if (global_debug_flag)
mapred_obj_debug(obj);
}
/*
* mapred_setup_columns -
* setup column lists (input, output, grouping, etc)
*
* This is usually able to be determined directly from the YAML,
* but for some things (defined in the database rather than in
* the YAML, eg QUERY INPUTS) we can not determine the columns
* until the object has been created. Which can trickle down to
* any object that depends on it.
*
* For this reason we don't setup the columns during the parse phase,
* but rather just before or just after we actually create the object
* once we know that all the dependencies have already been created.
*/
void mapred_setup_columns(PGconn *conn, mapred_object_t *obj)
{
mapred_object_t *sub;
PGresult *result;
/* switch based on object type */
switch (obj->kind)
{
case MAPRED_ADT:
break;
case MAPRED_INPUT:
/*
* Should be called after creation, otherwise catalog queries
* could fail.
*/
XASSERT(obj->created);
/* setup the column list for database defined inputs */
if (obj->u.input.type == MAPRED_INPUT_TABLE ||
obj->u.input.type == MAPRED_INPUT_QUERY)
{
/*
* This gets the ordered list of columns for the first
* input of the given name in the user's search path.
*/
buffer_t *buffer = makebuffer(1024, 1024);
bufcat(&buffer,
"SELECT attname, "
" pg_catalog.format_type(atttypid, atttypmod)\n"
"FROM pg_catalog.pg_attribute\n"
"WHERE attnum > 0 AND attrelid = lower('");
if (obj->u.input.type == MAPRED_INPUT_TABLE)
bufcat(&buffer, obj->u.input.desc);
else
bufcat(&buffer, obj->name);
bufcat(&buffer,
"')::regclass\n"
"ORDER BY -attnum;\n\n");
if (global_debug_flag)
printf("%s", buffer->buffer);
result = PQexec(conn, buffer->buffer);
mapred_free(buffer);
if (PQresultStatus(result) == PGRES_TUPLES_OK &&
PQntuples(result) > 0)
{
mapred_plist_t *newitem;
int i;
/* Destroy any previous default values we setup */
mapred_destroy_plist(&obj->u.input.columns);
/*
* The columns were sorted reverse order above so
* the list can be generated back -> front
*/
for (i = 0; i < PQntuples(result); i++)
{
char *name = PQgetvalue(result, i, 0);
char *type = PQgetvalue(result, i, 1);
/* Add the column to the list */
newitem = mapred_malloc(sizeof(mapred_plist_t));
newitem->name = mapred_malloc(strlen(name)+1);
strncpy(newitem->name, name, strlen(name)+1);
newitem->type = mapred_malloc(strlen(type)+1);
strncpy(newitem->type, type, strlen(type)+1);
newitem->next = obj->u.input.columns;
obj->u.input.columns = newitem;
}
}
else
{
char *error = PQresultErrorField(result, PG_DIAG_SQLSTATE);
char *name;
if (obj->u.input.type == MAPRED_INPUT_TABLE)
name = obj->u.input.desc;
else
name = obj->name;
if (PQresultStatus(result) == PGRES_TUPLES_OK)
{
mapred_obj_error(obj, "Table '%s' contains no rows", name);
}
else if (!strcmp(error, OBJ_DOES_NOT_EXIST) ||
!strcmp(error, SCHEMA_DOES_NOT_EXIST) )
{
mapred_obj_error(obj, "Table '%s' not found", name);
}
else
{
mapred_obj_error(obj, "Table '%s' unknown error: %s", name, error);
}
XRAISE(MAPRED_PARSE_ERROR, "Object creation Failure");
}
PQclear(result);
}
break;
case MAPRED_OUTPUT:
break;
case MAPRED_MAPPER:
case MAPRED_TRANSITION:
case MAPRED_COMBINER:
case MAPRED_FINALIZER:
XASSERT(obj->u.function.parameters);
XASSERT(obj->u.function.returns);
break;
case MAPRED_REDUCER:
{
mapred_object_t *transition = obj->u.reducer.transition.object;
XASSERT(transition);
XASSERT(transition->u.function.parameters);
obj->u.reducer.parameters =
transition->u.function.parameters->next;
/*
* Use the return result of:
* 1) The finalizer
* 2) The combiner, or
* 3) The transition
*
* in that order, if the return is not derivable then
* fall into the default value of a single text column
* named "value"
*/
if (obj->u.reducer.finalizer.name)
sub = obj->u.reducer.finalizer.object;
else if (obj->u.reducer.combiner.name)
sub = obj->u.reducer.combiner.object;
else
sub = obj->u.reducer.transition.object;
if (sub)
obj->u.reducer.returns = sub->u.function.returns;
if (!obj->u.reducer.returns)
{
/*
* If unable to determine the returns based on the reducer
* components (generally due to use of SQL functions) then
* use the default of a single text column named "value".
*/
obj->u.reducer.returns = mapred_malloc(sizeof(mapred_plist_t));
obj->u.reducer.returns->name = "value";
obj->u.reducer.returns->type = "text";
obj->u.reducer.returns->next = NULL;
}
break;
}
case MAPRED_TASK:
case MAPRED_EXECUTION:
{
mapred_plist_t *scan;
mapred_plist_t *last = NULL;
/*
* The input must either be an INPUT or a TASK
*/
sub = obj->u.task.input.object;
switch (sub->kind)
{
case MAPRED_INPUT:
obj->u.task.parameters = sub->u.input.columns;
break;
case MAPRED_TASK:
/* union the input tasks returns and grouping */
for (scan = sub->u.task.grouping;
scan;
scan = scan->next)
{
if (!last)
{
obj->u.task.parameters =
mapred_malloc(sizeof(mapred_plist_t));
last = obj->u.task.parameters;
}
else
{
last->next =
mapred_malloc(sizeof(mapred_plist_t));
last = last->next;
}
last->name = scan->name;
last->type = scan->type;
last->next = NULL;
}
for (scan = sub->u.task.returns;
scan;
scan = scan->next)
{
if (!last)
{
obj->u.task.parameters =
mapred_malloc(sizeof(mapred_plist_t));
last = obj->u.task.parameters;
}
else
{
last->next =
mapred_malloc(sizeof(mapred_plist_t));
last = last->next;
}
last->name = scan->name;
last->type = scan->type;
last->next = NULL;
}
break;
default:
/* Should have already been validated */
XASSERT(false);
}
if (obj->u.task.mapper.name)
{
sub = obj->u.task.mapper.object;
if (!sub)
{
/* FIXME: Lookup function in database */
/* for now... do nothing */
}
else
{
/* Allow any function type */
switch (sub->kind)
{
case MAPRED_MAPPER:
case MAPRED_TRANSITION:
case MAPRED_COMBINER:
case MAPRED_FINALIZER:
break;
default:
/* Should have already been validated */
XASSERT(false);
}
}
}
if (obj->u.task.reducer.name)
{
mapred_clist_t *keys;
mapred_plist_t *source;
/*
* The grouping columns for a task are the columns produced
* by the input/mapper that are not consumed by the reducer.
*
* A special exception is made for a column named "key" which
* is always a grouping column.
*
* FIXME: deal with non-yaml map functions
*
* FIXME: deal with KEY specifications
*/
if (obj->u.task.mapper.object)
source = obj->u.task.mapper.object->u.function.returns;
else
source = obj->u.task.parameters;
sub = obj->u.task.reducer.object;
if (!sub)
{
/*
* The output of a built in function is defined to be
* "value", with an input of "value", everything else
* is defined to be a grouping column.
*/
last = NULL;
for (scan = source; scan; scan = scan->next)
{
if (strcasecmp(scan->name, "value"))
{
if (!last)
{
obj->u.task.grouping =
mapred_malloc(sizeof(mapred_plist_t));
last = obj->u.task.grouping;
}
else
{
last->next =
mapred_malloc(sizeof(mapred_plist_t));
last = last->next;
}
last->name = scan->name;
last->type = scan->type;
last->next = NULL;
}
}
}
else
{
/* Validate Reducer */
XASSERT(sub->kind == MAPRED_REDUCER);
/*
* source is the set of input columns that the reducer has
* to work with.
*
* Loop the reducer "keys" clause to determine what keys are
* present.
*/
last = NULL;
for (keys = sub->u.reducer.keys; keys; keys = keys->next)
{
/*
* If there is a '*' in the keys then it catches all
* unreferenced columns.
*/
if (keys->value[0] == '*' && keys->value[1] == '\0')
{
/*
* Add all sources not found in either parameters,
* or explicitly mentioned in keys
*/
for (scan = source; scan; scan = scan->next)
{
mapred_plist_t *pscan;
mapred_clist_t *kscan;
for (pscan = sub->u.reducer.parameters;
pscan;
pscan = pscan->next)
{
if (!strcasecmp(scan->name, pscan->name))
break;
}
if (pscan)
continue; /* found in parameters */
for (kscan = sub->u.reducer.keys;
kscan;
kscan = kscan->next)
{
if (!strcasecmp(scan->name, kscan->value))
break;
}
if (kscan)
continue; /* found in keys */
/* we have an unmatched source, add to grouping */
if (!last)
{
obj->u.task.grouping =
mapred_malloc(sizeof(mapred_plist_t));
last = obj->u.task.grouping;
}
else
{
last->next =
mapred_malloc(sizeof(mapred_plist_t));
last = last->next;
}
last->name = scan->name;
last->type = scan->type;
last->next = NULL;
}
}
else
{
/* Look for the referenced key in the source list */
for (scan = source; scan; scan = scan->next)
if (!strcasecmp(keys->value, scan->name))
{
/* we have a match, add the key to grouping */
if (!last)
{
obj->u.task.grouping =
mapred_malloc(sizeof(mapred_plist_t));
last = obj->u.task.grouping;
}
else
{
last->next =
mapred_malloc(sizeof(mapred_plist_t));
last = last->next;
}
last->name = scan->name;
last->type = scan->type;
last->next = NULL;
break;
}
}
}
}
}
/*
* If there is a reducer then the "returns" columns are the
* output of the reducer, and must be unioned with the grouping
* columns for final output.
*
* If there is no reducer then the returns columns are the
* returns columns of the mapper or the input
*/
if (obj->u.task.reducer.name)
{
/*
* If it is a built in function then we'll just fall into the
* default of a single text column named "value".
*/
sub = obj->u.task.reducer.object;
if (sub)
obj->u.task.returns = sub->u.reducer.returns;
}
else if (obj->u.task.mapper.name)
{
sub = obj->u.task.mapper.object;
if (sub)
obj->u.task.returns = sub->u.function.returns;
}
else
{
obj->u.task.returns = obj->u.task.parameters;
}
if (!obj->u.task.returns)
{
/*
* If unable to determine the returns based on the reducer
* components (generally due to use of SQL functions) then
* use the default of a single text column named "value".
*/
obj->u.task.returns = mapred_malloc(sizeof(mapred_plist_t));
obj->u.task.returns->name = "value";
obj->u.task.returns->type = "text";
obj->u.task.returns->next = NULL;
}
break;
}
default:
XASSERT(false);
}
}
void mapred_resolve_ref(mapred_olist_t *olist, mapred_reference_t *ref)
{
XASSERT(ref);
if (!ref->name)
return;
/* Scan the list of objects until we find one with a matching name */
for (; olist; olist = olist->next)
{
if (olist->object->name && !strcasecmp(ref->name, olist->object->name))
{
ref->object = olist->object;
return;
}
}
}
/* Some basic destructors */
void mapred_destroy_object(mapred_object_t **objh)
{
mapred_object_t *obj;
/*
* We are passed a handle to the object, get the actual pointer and point
* the handle to NULL so that it is not stale once we free the list below.
*/
if (!objh || !*objh)
return;
obj = *objh;
*objh = (mapred_object_t *) NULL;
/* What fields are valid is dependent on what kind of object it is */
scalarfree(obj->name);
switch (obj->kind)
{
case MAPRED_NO_KIND:
break;
case MAPRED_DOCUMENT:
scalarfree(obj->u.document.version);
scalarfree(obj->u.document.database);
scalarfree(obj->u.document.user);
scalarfree(obj->u.document.host);
mapred_destroy_olist(&obj->u.document.objects);
mapred_destroy_olist(&obj->u.document.execute);
break;
case MAPRED_INPUT:
scalarfree(obj->u.input.desc);
scalarfree(obj->u.input.delimiter);
scalarfree(obj->u.input.encoding);
mapred_destroy_clist(&obj->u.input.files);
mapred_destroy_plist(&obj->u.input.columns);
break;
case MAPRED_OUTPUT:
scalarfree(obj->u.output.desc);
break;
case MAPRED_MAPPER:
case MAPRED_TRANSITION:
case MAPRED_COMBINER:
case MAPRED_FINALIZER:
scalarfree(obj->u.function.body);
scalarfree(obj->u.function.language);
mapred_destroy_plist(&obj->u.function.parameters);
if( obj->internal &&
obj->u.function.internal_returns != obj->u.function.returns )
mapred_destroy_plist(&obj->u.function.internal_returns);
mapred_destroy_plist(&obj->u.function.returns);
break;
case MAPRED_REDUCER:
scalarfree(obj->u.reducer.transition.name);
scalarfree(obj->u.reducer.combiner.name);
scalarfree(obj->u.reducer.finalizer.name);
scalarfree(obj->u.reducer.initialize);
break;
case MAPRED_TASK:
case MAPRED_EXECUTION:
scalarfree(obj->u.task.input.name);
scalarfree(obj->u.task.mapper.name);
scalarfree(obj->u.task.reducer.name);
scalarfree(obj->u.task.output.name);
break;
/*
* ADT just borrowed the parameter list from the owning function,
* so it has nothing else to delete.
*/
case MAPRED_ADT:
break;
default:
XASSERT(false);
}
}
void mapred_destroy_olist(mapred_olist_t **olisth)
{
mapred_olist_t *olist;
mapred_olist_t *next;
/*
* We are passed a handle to the olist, get the actual pointer and point
* the handle to NULL so that it is not stale once we free the list below.
*/
if (!olisth || !*olisth)
return;
olist = *olisth;
*olisth = (mapred_olist_t *) NULL;
/* Walk the list destroying each item as we come to it. */
while (olist)
{
mapred_destroy_object(&olist->object);
next = olist->next;
mapred_free(olist);
olist = next;
}
}
void mapred_destroy_clist(mapred_clist_t **clisth)
{
mapred_clist_t *clist;
mapred_clist_t *next;
/*
* We are passed a handle to the olist, get the actual pointer and point
* the handle to NULL so that it is not stale once we free the list below.
*/
if (!clisth || !*clisth)
return;
clist = *clisth;
*clisth = (mapred_clist_t *) NULL;
/* Walk the list destroying each item as we come to it. */
while (clist)
{
scalarfree(clist->value);
next = clist->next;
mapred_free(clist);
clist = next;
}
}
void mapred_destroy_plist(mapred_plist_t **plisth)
{
mapred_plist_t *plist;
mapred_plist_t *next;
/*
* We are passed a handle to the olist, get the actual pointer and point
* the handle to NULL so that it is not stale once we free the list below.
*/
if (!plisth || !*plisth)
return;
plist = *plisth;
*plisth = (mapred_plist_t *) NULL;
/* Walk the list destroying each item as we come to it. */
while (plist)
{
scalarfree(plist->name);
scalarfree(plist->type);
next = plist->next;
mapred_free(plist);
plist = next;
}
}
/* -------------------------------------------------------------------------- */
/* Functions that get things done */
/* -------------------------------------------------------------------------- */
void mapred_run_queries(PGconn *conn, mapred_document_t *doc)
{
mapred_olist_t *olist;
mapred_plist_t *columns;
mapred_object_t *output;
PGresult *result = NULL;
FILE *outfile = stdout;
buffer_t *buffer = NULL;
XTRY
{
/* allocates 512 bytes, extending by 512 bytes if we run out. */
buffer = makebuffer(512, 512);
/* Loop through all objects */
for (olist = doc->objects; olist; olist = olist->next)
{
if (olist->object->kind == MAPRED_EXECUTION)
{
boolean exists = false;
XASSERT(olist->object->name);
/* Reset the buffer from any previous executions */
bufreset(buffer);
output = olist->object->u.task.output.object;
/*
* [CREATE TABLE <name> AS ]
* SELECT * FROM <name>
* ORDER BY <column-list>
*/
if (output && output->u.output.type == MAPRED_OUTPUT_TABLE)
{
/* does the table already exist? */
bufcat(&buffer,
"SELECT n.nspname \n"
"FROM pg_catalog.pg_class c JOIN \n"
" pg_catalog.pg_namespace n on \n"
" (c.relnamespace = n.oid) \n"
"WHERE n.nspname = ANY(current_schemas(true)) \n"
" AND c.relname = lower('");
bufcat(&buffer, output->u.output.desc);
bufcat(&buffer, "')");
result = PQexec(conn, buffer->buffer);
if (PQresultStatus(result) == PGRES_TUPLES_OK &&
PQntuples(result) > 0)
exists = true;
bufreset(buffer);
if (exists && output->u.output.mode == MAPRED_OUTPUT_MODE_REPLACE)
{
bufcat(&buffer, "DROP TABLE ");
bufcat(&buffer, output->u.output.desc);
PQexec(conn, "SAVEPOINT mapreduce_save");
result = PQexec(conn, buffer->buffer);
if (PQresultStatus(result) == PGRES_COMMAND_OK)
{
PQexec(conn, "RELEASE SAVEPOINT mapreduce_save");
}
else
{
/* rollback to savepoint */
PQexec(conn, "ROLLBACK TO SAVEPOINT mapreduce_save");
PQexec(conn, "RELEASE SAVEPOINT mapreduce_save");
if (global_verbose_flag)
fprintf(stderr, " - ");
fprintf(stderr, "Error: %s\n",
PQresultErrorField(result, PG_DIAG_MESSAGE_PRIMARY));
mapred_obj_error(output, "Table '%s' can't be replaced",
output->u.output.desc);
XRAISE(MAPRED_PARSE_ERROR, "Object creation Failure");
}
bufreset(buffer);
exists = false;
}
/* Handle Explain for OUTPUT TABLE */
if (global_explain_flag & global_analyze)
bufcat(&buffer, "EXPLAIN ANALYZE ");
else if (global_explain_flag)
bufcat(&buffer, "EXPLAIN ");
if (!exists)
{
bufcat(&buffer, "CREATE TABLE ");
bufcat(&buffer, output->u.output.desc);
bufcat(&buffer, " AS ");
}
else if (output->u.output.mode == MAPRED_OUTPUT_MODE_APPEND)
{
bufcat(&buffer, "INSERT INTO ");
bufcat(&buffer, output->u.output.desc);
bufcat(&buffer, " (");
}
else
{
/* exists, mode is neither replace or append => error */
mapred_obj_error(output, "Table '%s' already exists",
output->u.output.desc);
XRAISE(MAPRED_PARSE_ERROR, "Object creation Failure");
}
}
/* Handle Explain for non-table output */
else if (global_explain_flag & global_analyze)
{
bufcat(&buffer, "EXPLAIN ANALYZE ");
}
else if (global_explain_flag)
{
bufcat(&buffer, "EXPLAIN ");
}
bufcat(&buffer, "SELECT * FROM ");
bufcat(&buffer, olist->object->name);
/*
* add the DISTRIBUTED BY clause for output tables
* OR, the ORDER BY clause for other output formats
*/
if (output && output->u.output.type == MAPRED_OUTPUT_TABLE)
{
/*
* If there are no key columns then leave off the
* distributed by clause and let the server choose.
*/
if (exists)
bufcat(&buffer, ")");
else if (olist->object->u.task.grouping)
{
bufcat(&buffer, " DISTRIBUTED BY (");
columns = olist->object->u.task.grouping;
while (columns)
{
bufcat(&buffer, columns->name);
if (columns->next)
bufcat(&buffer, ", ");
columns = columns->next;
}
bufcat(&buffer, ")");
}
else
{
/*
* don't have any hints for what the distribution keys
* should be, so we do nothing and let the database
* decide
*/
}
}
else
{
if (olist->object->u.task.returns ||
olist->object->u.task.grouping)
{
bufcat(&buffer, " ORDER BY ");
columns = olist->object->u.task.grouping;
while (columns)
{
bufcat(&buffer, columns->name);
if (columns->next || olist->object->u.task.returns)
bufcat(&buffer, ", ");
columns = columns->next;
}
columns = olist->object->u.task.returns;
while (columns)
{
bufcat(&buffer, columns->name);
if (columns->next)
bufcat(&buffer, ", ");
columns = columns->next;
}
}
}
bufcat(&buffer, ";\n");
/* Tell the user what job we are running */
if (global_verbose_flag)
fprintf(stderr, " - RUN: ");
if (global_print_flag || global_debug_flag)
fprintf(stderr, "%s", buffer->buffer);
else
fprintf(stderr, "%s\n", olist->object->name);
/* But we only execute it if we are not in "print-only" mode */
if (!global_print_flag)
{
/* If we have an output file, open it for write now */
if (output && output->u.output.type == MAPRED_OUTPUT_FILE)
{
switch (output->u.output.mode)
{
case MAPRED_OUTPUT_MODE_NONE:
/* check if the file exists */
if (access(output->u.output.desc, F_OK) == 0)
{
mapred_obj_error(output, "file '%s' already exists",
output->u.output.desc);
XRAISE(MAPRED_PARSE_ERROR, "Object creation Failure");
}
/* Fallthrough */
case MAPRED_OUTPUT_MODE_REPLACE:
outfile = fopen(output->u.output.desc, "wb");
break;
case MAPRED_OUTPUT_MODE_APPEND:
outfile = fopen(output->u.output.desc, "ab");
break;
default:
XASSERT(false);
}
if (!outfile)
{
mapred_obj_error(output, "could not open file '%s' for write",
output->u.output.desc);
XRAISE(MAPRED_PARSE_ERROR, "Object creation Failure");
}
}
else
{
outfile = stdout;
}
/*
* Enable notices for user queries since they may contain
* debugging info.
*/
PQsetNoticeReceiver(conn, print_notice_handler, NULL);
result = PQexec(conn, buffer->buffer);
PQsetNoticeReceiver(conn, ignore_notice_handler, NULL);
switch (PQresultStatus(result))
{
/* Output is STDOUT or FILE */
case PGRES_TUPLES_OK:
{
PQprintOpt options;
memset(&options, 0, sizeof(options));
/*
* Formatting:
* STDOUT = fancy formatting
* FILE = plain formatting
*/
if (outfile == stdout)
{
options.header = true;
options.align = true;
options.fieldSep = "|";
}
else if (output->u.output.delimiter)
{
options.fieldSep = output->u.output.delimiter;
}
else
{
/* "\t" is our default delimiter */
options.fieldSep = "\t";
}
PQprint(outfile, result, &options);
break;
}
/* OUTPUT is a table */
case PGRES_COMMAND_OK:
fprintf(stderr, "DONE\n");
break;
/* An error of some kind */
default:
XRAISE(MAPRED_SQL_ERROR, "Execution Failure");
}
PQclear(result);
result = NULL;
if (NULL != outfile && outfile != stdout)
{
fclose(outfile);
outfile = stdout;
}
}
}
}
}
XFINALLY
{
if (result)
PQclear(result);
if (NULL != outfile && outfile != stdout)
{
fclose(outfile);
outfile = stdout;
}
if (buffer)
mapred_free(buffer);
}
XTRY_END;
}
boolean mapred_create_object(PGconn *conn, mapred_document_t *doc,
mapred_object_t *obj)
{
mapred_clist_t *clist = NULL;
mapred_plist_t *plist = NULL;
mapred_plist_t *plist2 = NULL;
const char *ckind = NULL;
buffer_t *buffer = NULL;
buffer_t *qbuffer = NULL;
PGresult *result = NULL;
/* If the object was created in a prior pass, then do nothing */
if (obj->created)
return true;
/* Otherwise attempt to create the object */
XTRY
{
/* allocates 1024 bytes, extending by 1024 bytes if we run out */
buffer = makebuffer(1024, 1024);
switch (obj->kind)
{
case MAPRED_INPUT:
XASSERT(obj->name);
switch (obj->u.input.type)
{
case MAPRED_INPUT_TABLE:
/* Nothing to actually create */
obj->created = true;
break;
case MAPRED_INPUT_FILE:
case MAPRED_INPUT_GPFDIST:
XASSERT(obj->u.input.files);
/* Allocate and produce buffer */
bufcat(&buffer, "CREATE EXTERNAL TABLE ");
bufcat(&buffer, doc->prefix);
bufcat(&buffer, obj->name);
bufcat(&buffer, "(");
for (plist = obj->u.input.columns;
plist;
plist = plist->next)
{
bufcat(&buffer, plist->name);
bufcat(&buffer, " ");
bufcat(&buffer, plist->type);
if (plist->next)
bufcat(&buffer, ", ");
}
bufcat(&buffer, ")\n");
bufcat(&buffer, " LOCATION(");
for (clist = obj->u.input.files;
clist;
clist = clist->next)
{
char *domain_port, *path, *p = NULL;
if (obj->u.input.type == MAPRED_INPUT_GPFDIST)
bufcat(&buffer, "'gpfdist://");
else
bufcat(&buffer, "'file://");
/*
* The general syntax of a URL is scheme://domain:port/path?query_string#fragment_id
* clist->value should contain just domain:port/path?query_string#fragment_id
*/
p = strchr(clist->value, '/');
if (p == NULL)
{
mapred_obj_error(obj, "Failed to find '/' indicating start of path (%s)",
clist->value);
XRAISE(MAPRED_PARSE_ERROR,
"Invalid INPUT source specification");
}
if (p == clist->value)
{
mapred_obj_error(obj, "Missing domain and port before '/' indicating start of path (%s)",
clist->value);
XRAISE(MAPRED_PARSE_ERROR,
"Invalid INPUT source specification");
}
domain_port = clist->value;
path = p+1;
/*
* Overwrite the / separating the domain:port from the path
* with a nul and move back one byte to check for a trailing ':'.
* We put the / back in when copying into the destination buffer.
*/
*p-- = '\0';
if (strlen(path) < 1)
{
mapred_obj_error(obj, "Missing path after '/' (%s)",
clist->value);
XRAISE(MAPRED_PARSE_ERROR,
"Invalid INPUT source specification");
}
/*
* We allow a trailing ':' (e.g. host:/filepath)
* but we must not copy it into the external table url.
*/
if (*p == ':')
*p = '\0';
if (strlen(domain_port) < 1)
{
mapred_obj_error(obj, "Missing host before '/' (%s)",
clist->value);
XRAISE(MAPRED_PARSE_ERROR,
"Invalid INPUT source specification");
}
bufcat(&buffer, domain_port);
bufcat(&buffer, "/");
bufcat(&buffer, path);
if (clist->next)
bufcat(&buffer, "',\n ");
}
bufcat(&buffer, "')\n");
if (obj->u.input.format == MAPRED_FORMAT_CSV)
bufcat(&buffer, " FORMAT 'CSV'");
else
bufcat(&buffer, " FORMAT 'TEXT'");
if (obj->u.input.delimiter ||
obj->u.input.escape ||
obj->u.input.quote ||
obj->u.input.null)
{
bufcat(&buffer, " ( ");
if (obj->u.input.delimiter)
{
bufcat(&buffer, "DELIMITER '");
bufcat(&buffer, obj->u.input.delimiter);
bufcat(&buffer, "' ");
}
if (obj->u.input.escape)
{
bufcat(&buffer, "ESCAPE '");
bufcat(&buffer, obj->u.input.escape);
bufcat(&buffer, "' ");
}
if (obj->u.input.quote)
{
bufcat(&buffer, "QUOTE '");
bufcat(&buffer, obj->u.input.quote);
bufcat(&buffer, "' ");
}
if (obj->u.input.null)
{
bufcat(&buffer, "NULL '");
bufcat(&buffer, obj->u.input.null);
bufcat(&buffer, "' ");
}
bufcat(&buffer, ")");
}
if (obj->u.input.error_limit > 0)
{
char intbuf[11];
snprintf(intbuf, 11, "%d",
obj->u.input.error_limit);
bufcat(&buffer, "\n SEGMENT REJECT LIMIT ");
bufcat(&buffer, intbuf);
}
bufcat(&buffer, ";\n\n");
break;
case MAPRED_INPUT_EXEC:
XASSERT(obj->u.input.desc);
bufcat(&buffer, "CREATE EXTERNAL WEB TABLE ");
bufcat(&buffer, doc->prefix);
bufcat(&buffer, obj->name);
bufcat(&buffer, "(");
for (plist = obj->u.input.columns;
plist;
plist = plist->next)
{
bufcat(&buffer, plist->name);
bufcat(&buffer, " ");
bufcat(&buffer, plist->type);
if (plist->next)
bufcat(&buffer, ", ");
}
bufcat(&buffer, ")\n");
bufcat(&buffer, "EXECUTE '");
bufcat(&buffer, obj->u.input.desc);
bufcat(&buffer, "'\n");
if (obj->u.input.format == MAPRED_FORMAT_CSV)
bufcat(&buffer, " FORMAT 'CSV'");
else
bufcat(&buffer, " FORMAT 'TEXT'");
if (obj->u.input.delimiter ||
obj->u.input.quote ||
obj->u.input.null)
{
bufcat(&buffer, " ( ");
if (obj->u.input.delimiter)
{
bufcat(&buffer, "DELIMITER '");
bufcat(&buffer, obj->u.input.delimiter);
bufcat(&buffer, "' ");
}
if (obj->u.input.quote)
{
bufcat(&buffer, "QUOTE '");
bufcat(&buffer, obj->u.input.quote);
bufcat(&buffer, "' ");
}
if (obj->u.input.null)
{
bufcat(&buffer, "NULL '");
bufcat(&buffer, obj->u.input.null);
bufcat(&buffer, "' ");
}
bufcat(&buffer, ")");
}
if (obj->u.input.error_limit > 0)
{
char intbuf[11];
snprintf(intbuf, 11, "%d",
obj->u.input.error_limit);
bufcat(&buffer, "\n SEGMENT REJECT LIMIT ");
bufcat(&buffer, intbuf);
}
bufcat(&buffer, ";\n\n");
break;
case MAPRED_INPUT_QUERY:
XASSERT(obj->u.input.desc);
/*
* CREATE TEMPORARY VIEW <name> AS
* <desc>;
*/
bufcat(&buffer, "CREATE TEMPORARY VIEW ");
bufcat(&buffer, obj->name);
bufcat(&buffer, " AS\n");
bufcat(&buffer, obj->u.input.desc);
bufcat(&buffer, ";\n\n");
break;
case MAPRED_INPUT_NONE:
default:
XASSERT(false);
}
if (global_print_flag || global_debug_flag)
printf("-- INPUT %s\n", obj->name);
break;
case MAPRED_OUTPUT:
/*
* Outputs have no backend objects created directly.
* For output tables we may issue a create table as
* select, but that occurs at run-time.
*/
obj->created = true;
mapred_setup_columns(conn, obj);
break;
/*
* The function types have different defaults and generate
* slightly different error messages, but basically do the
* same thing.
*/
case MAPRED_MAPPER:
case MAPRED_TRANSITION:
case MAPRED_COMBINER:
case MAPRED_FINALIZER:
ckind = mapred_kind_name[obj->kind];
XASSERT(obj->name);
/*
* 'kind' specific initialization accomplished above, now handle
* the generic function creation.
*/
if (global_print_flag || global_debug_flag)
printf("-- %s %s\n", ckind, obj->name);
/*
* Nothing to do if we already looked up the function in the
* catalog.
*/
if (obj->internal)
{
obj->created = true;
break;
}
/* Non-internal functions should have these defined */
XASSERT(obj->u.function.body);
XASSERT(obj->u.function.language);
mapred_setup_columns(conn, obj);
XASSERT(obj->u.function.parameters);
XASSERT(obj->u.function.rtype.name);
XASSERT(NULL == obj->u.function.internal_returns);
/*
* fill in the buffer:
*
* CREATE FUNCTION <name>(<parameters>)
* RETURNS [SETOF] <rtype> LANGUAGE <lang> AS
* $$
* <body>
* $$ [STRICT] [IMMUTABLE];
*
*/
bufcat(&buffer, "CREATE FUNCTION ");
bufcat(&buffer, doc->prefix);
bufcat(&buffer, obj->name);
bufcat(&buffer, "(");
/* Handle parameter list */
for (plist = obj->u.function.parameters;
plist;
plist = plist->next)
{
bufcat(&buffer, plist->name);
bufcat(&buffer, " ");
bufcat(&buffer, plist->type);
if (plist->next)
bufcat(&buffer, ", ");
}
/* Handle Return clause */
bufcat(&buffer, ")\nRETURNS ");
if (obj->u.function.mode == MAPRED_MODE_MULTI)
bufcat(&buffer, "SETOF ");
bufcat(&buffer, obj->u.function.rtype.name);
/*
* Handle LANGUAGE clause, every langauge but 'C' and 'SQL'
* has 'pl' prefixing it
*/
if (!strcasecmp("C", obj->u.function.language) ||
!strcasecmp("SQL", obj->u.function.language) ||
!strncasecmp("PL", obj->u.function.language, 2))
{
bufcat(&buffer, " LANGUAGE ");
bufcat(&buffer, obj->u.function.language);
}
else
{
bufcat(&buffer, " LANGUAGE pl");
bufcat(&buffer, obj->u.function.language);
}
/* python only has an untrusted form */
if (!strcasecmp("python", obj->u.function.language))
bufcat(&buffer, "u");
bufcat(&buffer, " AS ");
/*
* Handle procedural language specific formatting for the
* function definition.
*
* C language functions are defined using the two parameter
* form: AS "library", "function".
*
* Perl functions append the yaml file line number via a
* #line declaration.
*
* Python functions try to append the yaml file line number
* by inserting a bunch of newlines. (only works for runtime
* errors, not compiletime errors).
*/
if (!strcasecmp("C", obj->u.function.language))
{
bufcat(&buffer, "$$");
bufcat(&buffer, obj->u.function.library);
bufcat(&buffer, "$$, $$");
bufcat(&buffer, obj->u.function.body);
bufcat(&buffer, "$$");
}
else if (!strncasecmp("plperl", obj->u.function.language, 6) ||
!strncasecmp("perl", obj->u.function.language, 4))
{
char lineno[10];
snprintf(lineno, sizeof(lineno), "%d", obj->u.function.lineno);
bufcat(&buffer, "$$\n#line ");
bufcat(&buffer, lineno);
bufcat(&buffer, "\n");
bufcat(&buffer, obj->u.function.body);
if (buffer->buffer[buffer->position-1] != '\n')
bufcat(&buffer, "\n");
bufcat(&buffer, "$$");
}
else if (!strncasecmp("plpython", obj->u.function.language, 8) ||
!strncasecmp("python", obj->u.function.language, 6))
{
/*
* Python very stubborn about not letting you manually
* adjust line number. So instead we take the stupid route
* and just insert N newlines.
*/
int i;
bufcat(&buffer, "$$\n");
for (i = 1; i < obj->u.function.lineno-2; i++)
bufcat(&buffer, "\n");
bufcat(&buffer, obj->u.function.body);
if (buffer->buffer[buffer->position-1] != '\n')
bufcat(&buffer, "\n");
bufcat(&buffer, "$$");
}
else
{
/* Some generic other language, take our best guess */
bufcat(&buffer, "$$");
bufcat(&buffer, obj->u.function.body);
bufcat(&buffer, "$$");
}
/* Handle options */
if (obj->u.function.flags & mapred_function_strict)
bufcat(&buffer, " STRICT");
if (obj->u.function.flags & mapred_function_immutable)
bufcat(&buffer, " IMMUTABLE");
/* All done */
bufcat(&buffer, ";\n\n");
break;
case MAPRED_REDUCER:
{
mapred_object_t *transition = obj->u.reducer.transition.object;
mapred_object_t *combiner = obj->u.reducer.combiner.object;
mapred_object_t *finalizer = obj->u.reducer.finalizer.object;
char *state;
XASSERT(obj->name);
XASSERT(transition);
XASSERT(transition->name);
/*
* If the reducer depends on an object that hasn't been created
* then return false, it will be resolved during a second pass
*/
if ((transition && !transition->created) ||
(combiner && !combiner->created) ||
(finalizer && !finalizer->created))
{
if (global_print_flag && global_debug_flag)
printf("-- deferring REDUCE %s\n", obj->name);
break;
}
if (global_print_flag || global_debug_flag)
printf("-- REDUCE %s\n", obj->name);
/* Now, set things up to create the thing */
mapred_setup_columns(conn, obj);
plist = transition->u.function.parameters;
XASSERT(plist); /* state */
XASSERT(plist->next); /* parameters */
if (obj->u.reducer.ordering)
bufcat(&buffer, "CREATE ORDERED AGGREGATE ");
else
bufcat(&buffer, "CREATE AGGREGATE ");
bufcat(&buffer, doc->prefix);
bufcat(&buffer, obj->name);
bufcat(&buffer, " (");
/*
* Get the state type, and write out the aggregate parameters
* based on the parameter list of the transition function.
*/
plist = transition->u.function.parameters;
state = plist->type;
for (plist = plist->next; plist; plist = plist->next)
{
bufcat(&buffer, plist->type);
if (plist->next)
bufcat(&buffer, ", ");
}
bufcat(&buffer, ") (\n");
bufcat(&buffer, " stype = ");
bufcat(&buffer, state);
if (obj->u.reducer.initialize)
{
bufcat(&buffer, ",\n initcond = '");
bufcat(&buffer, obj->u.reducer.initialize);
bufcat(&buffer, "'");
}
bufcat(&buffer, ",\n sfunc = ");
if (!transition->internal)
bufcat(&buffer, doc->prefix);
bufcat(&buffer, transition->name);
if (combiner)
{
bufcat(&buffer, ",\n prefunc = ");
if (!combiner->internal)
bufcat(&buffer, doc->prefix);
bufcat(&buffer, combiner->name);
}
/*
* To handle set returning finalizers the finalizer is pushed
* into the task definition rather than being placed in the
* uda where it belongs.
*/
/*
if (obj->u.reducer.finalizer.name)
{
bufcat(&buffer, ",\n finalfunc = ");
bufcat(&buffer, obj->u.reducer.finalizer.name);
}
*/
bufcat(&buffer, "\n);\n\n");
break;
}
case MAPRED_TASK:
case MAPRED_EXECUTION:
{
mapred_object_t *input = obj->u.task.input.object;
mapred_object_t *mapper = obj->u.task.mapper.object;
mapred_object_t *reducer = obj->u.task.reducer.object;
mapred_plist_t *columns = NULL;
mapred_plist_t *ingrouping = NULL;
mapred_plist_t *newitem = NULL;
mapred_plist_t *grouping = NULL;
mapred_plist_t *last = NULL;
mapred_plist_t *scan = NULL;
buffer_t *swap;
if (!obj->u.task.execute)
XASSERT(obj->name);
XASSERT(obj->u.task.input.name);
if (!qbuffer)
qbuffer = makebuffer(1024, 1024);
else
bufreset(qbuffer);
/*
* If the task depends on an object that hasn't been created then
* return false, it will be resolved during a second pass
*/
if ((input && !input->created) ||
(mapper && !mapper->created) ||
(reducer && !reducer->created))
{
if (global_print_flag && global_debug_flag)
{
if (obj->u.task.execute)
printf("-- deferring EXECUTION\n");
else
printf("-- deferring TASK %s\n", obj->name);
}
break;
}
if (global_print_flag || global_debug_flag)
{
if (obj->u.task.execute)
printf("-- EXECUTION\n");
else
printf("-- TASK %s\n", obj->name);
}
/*
* 1) Handle the INPUT, two cases:
* 1a) There is no MAP/REDUCE: "SELECT * FROM <input>"
* 1b) There is a MAP and/or REDUCE: "<input>"
*/
mapred_setup_columns(conn, obj);
if (!obj->u.task.mapper.name && !obj->u.task.reducer.name)
{
/* Allocate the buffer for the input. */
if (input->u.input.type == MAPRED_INPUT_TABLE)
{
bufcat(&qbuffer, "SELECT * FROM ");
bufcat(&qbuffer, input->u.input.desc);
}
else
{
bufcat(&qbuffer, "SELECT * FROM ");
bufcat(&qbuffer, input->name);
}
}
else
{
/* Input is just the name or description of the input */
if (input->u.input.type == MAPRED_INPUT_TABLE)
bufcat(&qbuffer, input->u.input.desc);
else
bufcat(&qbuffer, input->name);
}
/*
* How we get the columns depends a bit on the input.
* Is the input actually an "MAPRED_INPUT" object, or is it
* a "MAPRED_TASK" object?
*/
switch (input->kind)
{
case MAPRED_INPUT:
columns = input->u.input.columns;
break;
case MAPRED_TASK:
columns = input->u.task.returns;
ingrouping = input->u.task.grouping;
if (!columns)
{
mapred_obj_error(obj, "Unable to determine return "
"columns for TASK '%s'",
obj->u.task.input.name);
XRAISE(MAPRED_PARSE_INTERNAL, NULL);
}
break;
default:
mapred_obj_error(obj, "SOURCE '%s' is not an INPUT or "
"TASK object",
obj->u.task.input.name);
XRAISE(MAPRED_PARSE_ERROR, "Object creation Error");
break;
}
XASSERT(columns);
/*
* 2) Handle the MAPPER, two cases
* 2a) The Mapper returns an generated ADT that needs extraction
* "SELECT key(m), ...
* FROM (SELECT <map(...) as m FROM <input>) mapsubq
* 2b) The Mapper returns a single column:
* "SELECT <map>(...) FROM <input>"
*/
XASSERT(mapper || !obj->u.task.mapper.name);
if (mapper)
{
plist = mapper->u.function.returns;
plist2 = mapper->u.function.internal_returns;
XASSERT(plist);
if (plist->next)
{ /* 2a */
bufcat(&buffer, "SELECT ");
for (; plist; plist = plist->next )
{
if( obj->internal )
{
XASSERT(plist2 != NULL);
bufcat(&buffer, plist2->name);
plist2 = plist2->next;
}
else
{
bufcat(&buffer, plist->name);
}
bufcat(&buffer, "(m)");
bufcat(&buffer, " as ");
bufcat(&buffer, plist->name);
if (plist->next)
bufcat(&buffer, ", ");
}
bufcat(&buffer, "\nFROM (");
}
/* shared code */
bufcat(&buffer, "SELECT ");
if (!mapper->internal)
bufcat(&buffer, doc->prefix);
bufcat(&buffer, mapper->name);
bufcat(&buffer, "(");
plist = mapper->u.function.parameters;
for (; plist; plist = plist->next)
{
/* Check if this parameter is one of the input columns */
for (scan = columns; scan; scan = scan->next)
if (!strcasecmp(plist->name, scan->name))
{
bufcat(&buffer, plist->name);
break;
}
/* Task inputs also need to scan the grouping columns */
if (!scan)
for (scan = ingrouping; scan; scan = scan->next)
if (!strcasecmp(plist->name, scan->name))
{
bufcat(&buffer, plist->name);
break;
}
/* Check if this parameter is in global_plist */
if (!scan)
for (scan = global_plist; scan; scan = scan->next)
if (!strcasecmp(plist->name, scan->name))
{
/*
* (HACK)
* Note that global_plist overloads the
* plist structure using the "type" field
* to store "value".
* (HACK)
*/
bufcat(&buffer, "'");
bufcat(&buffer, scan->type);
bufcat(&buffer, "'::");
bufcat(&buffer, plist->type);
break;
}
/*
* If we couldn't find it issue a warning and
* set to NULL
*/
if (!scan)
{
if (global_verbose_flag)
fprintf(stderr, " ");
fprintf(stderr,
"WARNING: unset parameter - "
"%s(%s => NULL)\n",
mapper->name, plist->name);
bufcat(&buffer, "NULL::");
bufcat(&buffer, plist->type);
}
/* Add a comma if there is another parameter */
if (plist->next)
bufcat(&buffer, ", ");
}
bufcat(&buffer, ") as ");
/* break into cases again */
plist = mapper->u.function.returns;
if (plist->next)
{ /* 2a */
bufcat(&buffer, "m FROM ");
bufcat(&buffer, qbuffer->buffer);
bufcat(&buffer, ") mapxq\n");
/*
* Need to work this through, it seems that m is true
* whenever a column is null, which is not the desired
* behavior.
*
* Look more closely at "grep" code for why we want it,
* and "oreilly" code for why we don't.
*
* For the moment the compromise is that we do it only
* for SINGLE mode functions, since MULTI mode can
* control it's own filtering without this.
*/
if (mapper->u.function.mode != MAPRED_MODE_MULTI)
bufcat(&buffer, "WHERE m is not null");
}
else
{
bufcat(&buffer, plist->name);
bufcat(&buffer, " FROM ");
bufcat(&buffer, qbuffer->buffer);
}
/*
* Swap the buffer into the qbuffer for input as the next
* stage of the query pipeline.
*/
swap = qbuffer;
qbuffer = buffer;
buffer = swap;
bufreset(buffer);
/* Columns are now the output of the mapper */
columns = mapper->u.function.returns;
ingrouping = NULL;
}
/*
* 3) Handle the Reducer, several sub-cases:
*/
if (obj->u.task.reducer.name)
{
/*
* Step 1: Determine grouping columns
* Find which columns are returned from the previous
* stage that are NOT parameters to the reducer.
*/
grouping = last = NULL;
if (!reducer)
{
/*
* We have a reducer, but it isn't listed in the YAML.
* How to work out parameter handling still needs to
* be worked out. For now we just assume that this
* sort of function always takes a single "value" column
* and returns a "value" column.
*/
for (plist = columns; plist; plist = plist->next)
{
if (strcasecmp(plist->name, "value"))
{
if (grouping)
{
last->next =
mapred_malloc(sizeof(mapred_plist_t));
last = last->next;
}
else
{
grouping =
mapred_malloc(sizeof(mapred_plist_t));
last = grouping;
}
last->name = plist->name;
last->type = plist->type;
last->next = NULL;
}
}
}
else
{ /* The reducer exists in the YAML */
/* We precalculated the grouping columns */
grouping = obj->u.task.grouping;
}
/* Fill in the buffer */
bufcat(&buffer, "SELECT ");
for (plist = grouping; plist; plist = plist->next)
{
bufcat(&buffer, plist->name);
bufcat(&buffer, ", ");
}
/* Call the aggregation function */
if (reducer && !reducer->internal)
bufcat(&buffer, doc->prefix);
bufcat(&buffer, obj->u.task.reducer.name);
bufcat(&buffer, "(");
if (reducer)
{
plist = reducer->u.reducer.parameters;
for (; plist; plist = plist->next)
{
/* Check if parameter is one of the input columns */
for (scan = columns; scan; scan = scan->next)
if (!strcasecmp(plist->name, scan->name))
{
bufcat(&buffer, plist->name);
break;
}
/* Task inputs need to scan the grouping columns */
if (!scan)
for (scan = ingrouping; scan; scan = scan->next)
if (!strcasecmp(plist->name, scan->name))
{
bufcat(&buffer, plist->name);
break;
}
/* Check if this parameter is in global_plist */
if (!scan)
{
for (scan = global_plist;
scan;
scan = scan->next)
{
if (!strcasecmp(plist->name, scan->name))
{
/*
* (HACK)
* Note that global_plist overloads the
* plist structure using the "type"
* field to store "value".
* (HACK)
*/
bufcat(&buffer, "'");
bufcat(&buffer, scan->type);
bufcat(&buffer, "'::");
bufcat(&buffer, plist->type);
break;
}
}
}
/*
* If we couldn't find it issue a warning
* and set to NULL
*/
if (!scan)
{
if (global_verbose_flag)
fprintf(stderr, " ");
fprintf(stderr,
"WARNING: unset parameter - "
"%s(%s => NULL)\n",
reducer->name, plist->name);
bufcat(&buffer, "NULL::");
bufcat(&buffer, plist->type);
}
if (plist->next)
bufcat(&buffer, ", ");
}
/* Handle ORDERING, if specified */
clist = reducer->u.reducer.ordering;
if (clist)
bufcat(&buffer, " ORDER BY ");
for(; clist; clist = clist->next)
{
bufcat(&buffer, clist->value);
if (clist->next)
bufcat(&buffer, ", ");
}
}
else
{
/*
* non-yaml reducer always takes "value" as the
* input column
*/
/* Check if "value" is one of the input columns */
for (scan = columns; scan; scan = scan->next)
if (!strcasecmp(scan->name, "value"))
{
bufcat(&buffer, "value");
break;
}
/* Task inputs also need to scan the grouping columns */
if (!scan)
for (scan = ingrouping; scan; scan = scan->next)
if (!strcasecmp(plist->name, scan->name))
{
bufcat(&buffer, "value");
break;
}
/* Check if this parameter is in global_plist */
if (!scan)
for (scan = global_plist; scan; scan = scan->next)
if (!strcasecmp(scan->name, "value"))
{
/*
* (HACK)
* Note that global_plist overloads the
* plist structure using the "type" field
* to store "value".
* (HACK)
*/
bufcat(&buffer, "'");
bufcat(&buffer, scan->type);
bufcat(&buffer, "'::");
bufcat(&buffer, plist->type);
break;
}
if (!scan)
{
if (global_verbose_flag)
fprintf(stderr, " ");
fprintf(stderr,
"WARNING: unset parameter - "
"%s(value => NULL)\n",
obj->u.task.reducer.name);
bufcat(&buffer, "NULL");
}
}
bufcat(&buffer, ") as ");
if (reducer)
{
plist = reducer->u.reducer.returns;
XASSERT(plist); /* Need to have a return! */
/*
* If the reducer has a finalizer we push it outside of
* the context of the UDA so that we can properly handle
* set returning/column returning functions.
*/
if (reducer->u.reducer.finalizer.name)
bufcat(&buffer, "r");
else
bufcat(&buffer, plist->name);
}
else
{
/*
* non-yaml reducer always return a single column
* named "value"
*/
bufcat(&buffer, "value");
}
bufcat(&buffer, "\nFROM ");
if (mapper)
{
bufcat(&buffer, "(");
bufcat(&buffer, qbuffer->buffer);
bufcat(&buffer, ") mapsubq");
}
else
{
bufcat(&buffer, qbuffer->buffer);
}
if (grouping)
{
bufcat(&buffer, "\nGROUP BY ");
for (plist = grouping; plist; plist = plist->next)
{
bufcat(&buffer, plist->name);
if (plist->next)
bufcat(&buffer, ", ");
}
}
/*
* Swap the buffer into the qbuffer for input as the next
* stage of the query pipeline.
*/
swap = qbuffer;
qbuffer = buffer;
buffer = swap;
bufreset(buffer);
/*
* Add the return columns to the grouping columns and set
* it to the current columns.
*
* Note that unlike the columns set by the mapper or the
* input this is a list that must be de-allocated.
*/
columns = mapred_malloc(sizeof(mapred_plist_t));
columns->name = "value"; /* FIXME */
columns->type = "text"; /* FIXME */
columns->next = grouping;
columns = last;
/*
* If the reducer had a finalizer we push it into another
* nested subquery since user defined aggregates aren't
* allowed to return sets.
*
* NOTE: this code mostly duplicates the MAP code above
*/
if (reducer && reducer->u.reducer.finalizer.name)
{
mapred_object_t *finalizer;
finalizer = reducer->u.reducer.finalizer.object;
XASSERT(finalizer); /* FIXME */
XASSERT(finalizer->u.function.returns);
/*
* If the finalizer returns multiple columns then we
* need an extra layer of wrapping to extract them.
*/
plist = finalizer->u.function.returns;
if (plist->next)
{
bufcat(&buffer, "SELECT ");
/* the grouping columns */
for (plist = grouping;
plist;
plist = plist->next)
{
bufcat(&buffer, plist->name);
bufcat(&buffer, ", ");
}
plist2 = finalizer->u.function.internal_returns;
for (plist = finalizer->u.function.returns;
plist;
plist = plist->next)
{
if( finalizer->internal )
{
XASSERT( plist2 != NULL );
bufcat(&buffer, plist2->name);
plist2 = plist2->next;
}
else
{
bufcat(&buffer, plist->name);
}
bufcat(&buffer, "(r)");
bufcat(&buffer, " as ");
bufcat(&buffer, plist->name);
if (plist->next)
bufcat(&buffer, ", ");
}
bufcat(&buffer, "\nFROM (");
}
/*
* Call the function on the returned state from
* the reducer.
*/
bufcat(&buffer, "SELECT ");
/* grouping columns */
for (plist = grouping;
plist;
plist = plist->next)
{
bufcat(&buffer, plist->name);
bufcat(&buffer, ", ");
}
if (!finalizer->internal)
bufcat(&buffer, doc->prefix);
bufcat(&buffer, finalizer->name);
bufcat(&buffer, "(r) as ");
/* break into cases again */
plist = finalizer->u.function.returns;
if (plist->next)
bufcat(&buffer, "r");
else
bufcat(&buffer, plist->name);
bufcat(&buffer, " FROM (");
bufcat(&buffer, qbuffer->buffer);
bufcat(&buffer, ") redxq\n");
/*
* If we have that extra layer of wrapping
* then close it off
*/
if (finalizer->u.function.returns->next)
bufcat(&buffer, ") redsubq\n");
/*
* Swap the buffer into the qbuffer for input as the next
* stage of the query pipeline.
*/
swap = qbuffer;
qbuffer = buffer;
buffer = swap;
bufreset(buffer);
}
}
/*
* 4) Handle the final transform into the view definition:
* "CREATE TEMPORARY VIEW . AS .;"
*/
bufcat(&buffer, "CREATE TEMPORARY VIEW ");
bufcat(&buffer, obj->name);
bufcat(&buffer, " AS\n");
bufcat(&buffer, qbuffer->buffer);
bufcat(&buffer, ";\n\n");
/*
* If there was a reducer then we have to release the columns
* list, otherwise it is a pointer to an existing list and can
* be ignored.
*/
if (obj->u.task.reducer.name)
{
plist = columns;
while (plist && plist != grouping)
{
newitem = plist;
plist = plist->next;
mapred_free(newitem);
}
}
break;
}
case MAPRED_ADT:
XASSERT(obj->name);
mapred_setup_columns(conn, obj);
/*
* ADT's have generated names that already include the
* document prefix
*/
bufcat(&buffer, "CREATE TYPE ");
bufcat(&buffer, obj->name);
bufcat(&buffer, " as (");
for (plist = obj->u.adt.returns; plist; plist = plist->next)
{
bufcat(&buffer, plist->name);
bufcat(&buffer, " ");
bufcat(&buffer, plist->type);
if (plist->next)
bufcat(&buffer, ", ");
}
bufcat(&buffer, ");\n\n");
break;
default:
XASSERT(false);
}
if (buffer->position > 0)
{
/*
* In print-only mode we do everything but run the queries
* ie, we still create and destroy objects.
*/
if (global_print_flag || global_debug_flag)
printf("%s", buffer->buffer);
/*
* Try to create the object, but failure should not terminate
* the transaction, so wrap it in a savepoint.
*/
PQexec(conn, "SAVEPOINT mapreduce_save");
result = PQexec(conn, buffer->buffer);
if (PQresultStatus(result) == PGRES_COMMAND_OK)
{
obj->created = true;
PQexec(conn, "RELEASE SAVEPOINT mapreduce_save");
}
else
{
char *error = PQresultErrorField(result, PG_DIAG_SQLSTATE);
/* rollback to savepoint */
PQexec(conn, "ROLLBACK TO SAVEPOINT mapreduce_save");
PQexec(conn, "RELEASE SAVEPOINT mapreduce_save");
/*
* If we have an "object does not exist" error from a SQL input
* then it may just be a dependency issue, so we don't error
* right away.
*/
if (obj->kind != MAPRED_INPUT ||
obj->u.input.type != MAPRED_INPUT_QUERY ||
strcmp(error, OBJ_DOES_NOT_EXIST))
{
if (global_verbose_flag)
fprintf(stderr, " - ");
fprintf(stderr, "%s", PQresultErrorMessage(result));
XRAISE(MAPRED_SQL_ERROR, "Object creation Failure");
}
if (global_verbose_flag)
fprintf(stderr, " Error: %s\n",
PQresultErrorField(result, PG_DIAG_MESSAGE_PRIMARY));
/*
* If it is an error that we think we can recover from then we don't
* log the error immediately, but write it to a buffer in the event
* that recovery wasn't successful.
*/
if (doc->errors)
{
if (global_verbose_flag)
bufcat(&doc->errors, " - ");
bufcat(&doc->errors, "Error: ");
bufcat(&doc->errors, (char*) mapred_kind_name[obj->kind]);
if (obj->name)
{
bufcat(&doc->errors, " '");
bufcat(&doc->errors, obj->name);
bufcat(&doc->errors, "'");
}
bufcat(&doc->errors, ": ");
bufcat(&doc->errors, PQresultErrorField(result, PG_DIAG_MESSAGE_PRIMARY));
if (obj->line > 0)
{
char numbuf[64];
sprintf(numbuf, ", at line %d", obj->line);
bufcat(&doc->errors, numbuf);
}
bufcat(&doc->errors, "\n");
}
}
}
/*
* INPUTS setup columns AFTER creation.
* All other objects handle it above prior to creation.
*/
if (obj->kind == MAPRED_INPUT && obj->created)
mapred_setup_columns(conn, obj);
}
XFINALLY
{
if (buffer)
mapred_free(buffer);
if (qbuffer)
mapred_free(qbuffer);
}
XTRY_END;
return obj->created;
}
void mapred_remove_object(PGconn *conn, mapred_document_t *doc, mapred_object_t *obj)
{
mapred_plist_t *plist = NULL;
const char *ckind = NULL;
buffer_t *buffer = NULL;
/* If the object wasn't created, then do nothing */
if (!obj->created)
return;
if (obj->internal)
{
obj->created = false;
return;
}
XTRY
{
buffer = makebuffer(100, 100);
/* Otherwise attempt to create the object */
switch (obj->kind)
{
case MAPRED_INPUT:
XASSERT(obj->name);
switch (obj->u.input.type)
{
case MAPRED_INPUT_TABLE:
obj->created = false;
break; /* do nothing */
case MAPRED_INPUT_FILE:
case MAPRED_INPUT_GPFDIST:
case MAPRED_INPUT_EXEC:
bufcat(&buffer, "DROP EXTERNAL TABLE IF EXISTS ");
bufcat(&buffer, doc->prefix);
bufcat(&buffer, obj->name);
bufcat(&buffer, " CASCADE;\n");
break;
case MAPRED_INPUT_QUERY:
bufcat(&buffer, "DROP VIEW IF EXISTS ");
bufcat(&buffer, obj->name);
bufcat(&buffer, " CASCADE;\n");
break;
case MAPRED_INPUT_NONE:
default:
XASSERT(false);
}
break;
case MAPRED_OUTPUT:
/* nothing to do for outputs */
obj->created = false;
break;
/*
* The function types have different defaults and generate
* slightly different error messages, but basically do the
* same thing.
*/
case MAPRED_MAPPER:
case MAPRED_TRANSITION:
case MAPRED_COMBINER:
case MAPRED_FINALIZER:
ckind = mapred_kind_name[obj->kind];
bufcat(&buffer, "DROP FUNCTION IF EXISTS ");
if (!obj->internal)
bufcat(&buffer, doc->prefix);
bufcat(&buffer, obj->name);
bufcat(&buffer, "(");
for (plist = obj->u.function.parameters;
plist;
plist = plist->next)
{ /* Handle parameter list */
bufcat(&buffer, plist->type);
if (plist->next)
bufcat(&buffer, ", ");
}
bufcat(&buffer, ") CASCADE;\n");
break;
case MAPRED_REDUCER:
{
mapred_object_t *transition = obj->u.reducer.transition.object;
XASSERT(obj->name);
XASSERT(transition); /* is this a good assumption? */
if (!transition->u.function.parameters)
break; /* FIXME */
XASSERT(transition->u.function.parameters);
bufcat(&buffer, "DROP AGGREGATE IF EXISTS ");
if (!obj->internal)
bufcat(&buffer, doc->prefix);
bufcat(&buffer, obj->name);
bufcat(&buffer, "(");
/*
* The first parameter of the transition function is the 'state'
* and is not listed as a parameter of the reducer, but all the
* rest of the parameters are
*/
plist = transition->u.function.parameters;
for (plist = plist->next; plist; plist = plist->next)
{
bufcat(&buffer, plist->type);
if (plist->next)
bufcat(&buffer, ", ");
}
bufcat(&buffer, ") CASCADE;\n");
break;
}
case MAPRED_TASK:
case MAPRED_EXECUTION:
XASSERT(obj->name);
bufcat(&buffer, "DROP VIEW IF EXISTS ");
bufcat(&buffer, obj->name);
bufcat(&buffer, " CASCADE;\n");
break;
case MAPRED_ADT:
bufcat(&buffer, "DROP TYPE IF EXISTS ");
bufcat(&buffer, obj->name);
bufcat(&buffer, " CASCADE;\n");
break;
default:
XASSERT(false);
}
if (buffer->position > 0)
{
PGresult *result;
/*
* In print-only mode we do everything but run the queries
* ie, we still create and destroy objects.
*/
if (global_print_flag || global_debug_flag)
printf("%s", buffer->buffer);
/* Try to delete the object, but don't raise exception on error */
result = PQexec(conn, buffer->buffer);
if (PQresultStatus(result) == PGRES_COMMAND_OK)
obj->created = false;
else
{
char *error = PQresultErrorField(result, PG_DIAG_SQLSTATE);
/*
* Errors that we can expect/ignore:
*
* IN_FAILED_SQL_TRANSACTION -
* another error has occured and the transaction was
* aborted
*
*/
if (strcmp(error, IN_FAILED_SQL_TRANSACTION))
{
if (global_verbose_flag)
fprintf(stderr, " - ");
if (obj->name)
fprintf(stderr,
"[WARNING] Error dropping '%s'\n", obj->name);
else
fprintf(stderr,
"[WARNING] Error dropping unnamed object\n");
if (global_verbose_flag)
fprintf(stderr, " - ");
fprintf(stderr, "%s", PQerrorMessage(conn));
}
}
PQclear(result);
}
}
XFINALLY
{
if (buffer)
mapred_free(buffer);
}
XTRY_END;
}
| 26.509298 | 97 | 0.581385 | [
"object",
"transform"
] |
2313fd459673d7578ac7a1dcbe4c81e71dc33908 | 1,551 | h | C | Sources/GameObject.h | badcast/night-fear-game | efc548a06a6c690b32cff47acfb1906e7dfdaf3c | [
"MIT"
] | null | null | null | Sources/GameObject.h | badcast/night-fear-game | efc548a06a6c690b32cff47acfb1906e7dfdaf3c | [
"MIT"
] | null | null | null | Sources/GameObject.h | badcast/night-fear-game | efc548a06a6c690b32cff47acfb1906e7dfdaf3c | [
"MIT"
] | null | null | null | #pragma once
#include "Object.h"
#include "Transform.h"
#include "framework.h"
namespace RoninEngine {
namespace Runtime {
//[attrib class]
template <typename T>
class AttribGetTypeHelper {
public:
static T* getType(list<Component*>& container) {
decltype(end(container)) iter =
find_if(begin(container), end(container), [](Component* c) { return dynamic_cast<T*>(c) != 0; });
if (iter != end(container)) return dynamic_cast<T*>(*iter);
return nullptr;
}
static T* getComponent(GameObject* obj);
};
class GameObject final : public Object {
friend Camera2D;
friend GameObject* Instantiate(GameObject* obj);
friend GameObject* Instantiate(GameObject* obj, Vec2 position, float angle);
friend GameObject* Instantiate(GameObject* obj, Vec2 position, Transform* parent, bool worldPositionState);
friend void Destroy(Object* obj);
friend void Destroy(Object* obj, float t);
friend void Destroy_Immediate(Object* obj);
private:
list<Component*> m_components;
public:
GameObject();
GameObject(const string&);
// GameObject(const GameObject&) = delete;
virtual ~GameObject();
Transform* transform();
Component* Add_Component(Component* component);
template <typename T>
std::enable_if_t<std::is_base_of<Component, T>::value, T*> Add_Component();
template <typename T>
T* Get_Component() {
return AttribGetTypeHelper<T>::getType(this->m_components);
}
};
} // namespace Runtime
} // namespace RoninEngine
| 26.741379 | 111 | 0.681496 | [
"object",
"transform"
] |
232545b70ce0499c17bf342667b448f34622a0e7 | 152 | h | C | source/application/PathTracer/raytracing/util/RTUtil.h | compix/Monte-Carlo-Raytracer | f27842c40dd380aee78f1579873341ad6cfe0834 | [
"MIT"
] | 3 | 2018-09-23T03:12:36.000Z | 2021-12-01T08:30:43.000Z | source/application/PathTracer/raytracing/util/RTUtil.h | compix/Monte-Carlo-Raytracer | f27842c40dd380aee78f1579873341ad6cfe0834 | [
"MIT"
] | null | null | null | source/application/PathTracer/raytracing/util/RTUtil.h | compix/Monte-Carlo-Raytracer | f27842c40dd380aee78f1579873341ad6cfe0834 | [
"MIT"
] | 1 | 2018-09-19T01:49:24.000Z | 2018-09-19T01:49:24.000Z | #pragma once
#include <engine/geometry/Ray.h>
namespace RTUtil
{
/**
* pixelOffset is jittering for TAA.
*/
Ray screenToRay(const glm::vec3& p);
} | 15.2 | 37 | 0.690789 | [
"geometry"
] |
2325f4a04b07df002494d2fc8c3896e87e377ea4 | 2,605 | h | C | main/include/hal/config.h | intentfulmotion/firmware-amp | fecd97ae3882907af10e05e7e688786110da0461 | [
"MIT"
] | null | null | null | main/include/hal/config.h | intentfulmotion/firmware-amp | fecd97ae3882907af10e05e7e688786110da0461 | [
"MIT"
] | null | null | null | main/include/hal/config.h | intentfulmotion/firmware-amp | fecd97ae3882907af10e05e7e688786110da0461 | [
"MIT"
] | null | null | null | #pragma once
#include <common.h>
#include <string>
#include <vector>
#include <map>
#include <algorithm>
#define ARDUINOJSON_ENABLE_STD_STRING 1
#include <ArduinoJson.h>
#include <models/light.h>
#include <models/motion.h>
#include <models/config.h>
#include <interfaces/config-listener.h>
#include <interfaces/lifecycle.h>
#if defined(AMP_1_0_x)
#include <hal/amp-1.0.0/amp-storage.h>
#endif
static const char* CONFIG_TAG = "config";
struct MsgPackFileWriter {
FILE *_file;
size_t write(uint8_t c) { return fputc(c, _file); }
size_t write(const uint8_t *buffer, size_t length) { return fwrite(buffer, sizeof(uint8_t), length, _file); }
MsgPackFileWriter(FILE *file) : _file(file) { }
};
struct MsgPackFileReader {
FILE *_file;
int read() { return fgetc(_file); }
size_t readBytes(char* buffer, size_t length) { return fread((void*) buffer, sizeof(uint8_t), length, _file); }
MsgPackFileReader(FILE *file) : _file(file) { }
};
class Config : public LifecycleBase {
std::vector<ConfigListener*> configListeners;
AmpStorage ampStorage;
std::string rawConfig;
std::string renderer;
bool _filesystemError = false;
bool _valid = false;
bool _isUserConfig = false;
std::string configPath = "/spiffs/config.mp";
std::string userConfigPath = "/spiffs/config.user.mp";
JsonObject serializeEffects();
static bool parseEffect(std::string data, LightingParameters *params);
static ColorOption parseColorOption(std::string data);
StaticJsonDocument<10000> document;
bool loadConfigFile(std::string path);
public:
static AmpConfig ampConfig;
void onPowerUp();
void onPowerDown();
void process();
static DeviceInfo getDeviceInfo();
void loadConfig();
void saveConfig();
void saveUserConfig(std::string data, bool load = false);
void loadActionConfig(JsonObject actionJson);
void loadMotionConfig(JsonObject motionJson);
void loadLightsConfig(JsonObject lightsJson);
std::string readFile(std::string filename);
void addConfigListener(ConfigListener *listener);
void notifyConfigListeners();
void updateDeviceName(std::string name);
bool addEffect(std::string action, std::string region, std::string data, bool updateJson = false);
// void removeEffect(std::string, std::string region, bool updateJson = false);
std::vector<LightingParameters>* getActionEffects(std::string action);
bool isValid() { return _valid; }
std::string getRawConfig() { std::string data; serializeMsgPack(document, data); return data; }
static FreeRTOS::Semaphore effectsUpdating;
}; | 28.315217 | 113 | 0.724376 | [
"vector"
] |
23262953f52734052169a6a06f8ea1df256729c2 | 11,594 | h | C | aws-cpp-sdk-ecs/include/aws/ecs/model/UpdateServiceRequest.h | capeanalytics/aws-sdk-cpp | e88f75add5a9433601b6d46fe738e493da56ac3b | [
"Apache-2.0"
] | null | null | null | aws-cpp-sdk-ecs/include/aws/ecs/model/UpdateServiceRequest.h | capeanalytics/aws-sdk-cpp | e88f75add5a9433601b6d46fe738e493da56ac3b | [
"Apache-2.0"
] | null | null | null | aws-cpp-sdk-ecs/include/aws/ecs/model/UpdateServiceRequest.h | capeanalytics/aws-sdk-cpp | e88f75add5a9433601b6d46fe738e493da56ac3b | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2010-2017 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.
*/
#pragma once
#include <aws/ecs/ECS_EXPORTS.h>
#include <aws/ecs/ECSRequest.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/ecs/model/DeploymentConfiguration.h>
#include <utility>
namespace Aws
{
namespace ECS
{
namespace Model
{
/**
*/
class AWS_ECS_API UpdateServiceRequest : public ECSRequest
{
public:
UpdateServiceRequest();
Aws::String SerializePayload() const override;
Aws::Http::HeaderValueCollection GetRequestSpecificHeaders() const override;
/**
* <p>The short name or full Amazon Resource Name (ARN) of the cluster that your
* service is running on. If you do not specify a cluster, the default cluster is
* assumed.</p>
*/
inline const Aws::String& GetCluster() const{ return m_cluster; }
/**
* <p>The short name or full Amazon Resource Name (ARN) of the cluster that your
* service is running on. If you do not specify a cluster, the default cluster is
* assumed.</p>
*/
inline void SetCluster(const Aws::String& value) { m_clusterHasBeenSet = true; m_cluster = value; }
/**
* <p>The short name or full Amazon Resource Name (ARN) of the cluster that your
* service is running on. If you do not specify a cluster, the default cluster is
* assumed.</p>
*/
inline void SetCluster(Aws::String&& value) { m_clusterHasBeenSet = true; m_cluster = std::move(value); }
/**
* <p>The short name or full Amazon Resource Name (ARN) of the cluster that your
* service is running on. If you do not specify a cluster, the default cluster is
* assumed.</p>
*/
inline void SetCluster(const char* value) { m_clusterHasBeenSet = true; m_cluster.assign(value); }
/**
* <p>The short name or full Amazon Resource Name (ARN) of the cluster that your
* service is running on. If you do not specify a cluster, the default cluster is
* assumed.</p>
*/
inline UpdateServiceRequest& WithCluster(const Aws::String& value) { SetCluster(value); return *this;}
/**
* <p>The short name or full Amazon Resource Name (ARN) of the cluster that your
* service is running on. If you do not specify a cluster, the default cluster is
* assumed.</p>
*/
inline UpdateServiceRequest& WithCluster(Aws::String&& value) { SetCluster(std::move(value)); return *this;}
/**
* <p>The short name or full Amazon Resource Name (ARN) of the cluster that your
* service is running on. If you do not specify a cluster, the default cluster is
* assumed.</p>
*/
inline UpdateServiceRequest& WithCluster(const char* value) { SetCluster(value); return *this;}
/**
* <p>The name of the service to update.</p>
*/
inline const Aws::String& GetService() const{ return m_service; }
/**
* <p>The name of the service to update.</p>
*/
inline void SetService(const Aws::String& value) { m_serviceHasBeenSet = true; m_service = value; }
/**
* <p>The name of the service to update.</p>
*/
inline void SetService(Aws::String&& value) { m_serviceHasBeenSet = true; m_service = std::move(value); }
/**
* <p>The name of the service to update.</p>
*/
inline void SetService(const char* value) { m_serviceHasBeenSet = true; m_service.assign(value); }
/**
* <p>The name of the service to update.</p>
*/
inline UpdateServiceRequest& WithService(const Aws::String& value) { SetService(value); return *this;}
/**
* <p>The name of the service to update.</p>
*/
inline UpdateServiceRequest& WithService(Aws::String&& value) { SetService(std::move(value)); return *this;}
/**
* <p>The name of the service to update.</p>
*/
inline UpdateServiceRequest& WithService(const char* value) { SetService(value); return *this;}
/**
* <p>The number of instantiations of the task to place and keep running in your
* service.</p>
*/
inline int GetDesiredCount() const{ return m_desiredCount; }
/**
* <p>The number of instantiations of the task to place and keep running in your
* service.</p>
*/
inline void SetDesiredCount(int value) { m_desiredCountHasBeenSet = true; m_desiredCount = value; }
/**
* <p>The number of instantiations of the task to place and keep running in your
* service.</p>
*/
inline UpdateServiceRequest& WithDesiredCount(int value) { SetDesiredCount(value); return *this;}
/**
* <p>The <code>family</code> and <code>revision</code>
* (<code>family:revision</code>) or full Amazon Resource Name (ARN) of the task
* definition to run in your service. If a <code>revision</code> is not specified,
* the latest <code>ACTIVE</code> revision is used. If you modify the task
* definition with <code>UpdateService</code>, Amazon ECS spawns a task with the
* new version of the task definition and then stops an old task after the new
* version is running.</p>
*/
inline const Aws::String& GetTaskDefinition() const{ return m_taskDefinition; }
/**
* <p>The <code>family</code> and <code>revision</code>
* (<code>family:revision</code>) or full Amazon Resource Name (ARN) of the task
* definition to run in your service. If a <code>revision</code> is not specified,
* the latest <code>ACTIVE</code> revision is used. If you modify the task
* definition with <code>UpdateService</code>, Amazon ECS spawns a task with the
* new version of the task definition and then stops an old task after the new
* version is running.</p>
*/
inline void SetTaskDefinition(const Aws::String& value) { m_taskDefinitionHasBeenSet = true; m_taskDefinition = value; }
/**
* <p>The <code>family</code> and <code>revision</code>
* (<code>family:revision</code>) or full Amazon Resource Name (ARN) of the task
* definition to run in your service. If a <code>revision</code> is not specified,
* the latest <code>ACTIVE</code> revision is used. If you modify the task
* definition with <code>UpdateService</code>, Amazon ECS spawns a task with the
* new version of the task definition and then stops an old task after the new
* version is running.</p>
*/
inline void SetTaskDefinition(Aws::String&& value) { m_taskDefinitionHasBeenSet = true; m_taskDefinition = std::move(value); }
/**
* <p>The <code>family</code> and <code>revision</code>
* (<code>family:revision</code>) or full Amazon Resource Name (ARN) of the task
* definition to run in your service. If a <code>revision</code> is not specified,
* the latest <code>ACTIVE</code> revision is used. If you modify the task
* definition with <code>UpdateService</code>, Amazon ECS spawns a task with the
* new version of the task definition and then stops an old task after the new
* version is running.</p>
*/
inline void SetTaskDefinition(const char* value) { m_taskDefinitionHasBeenSet = true; m_taskDefinition.assign(value); }
/**
* <p>The <code>family</code> and <code>revision</code>
* (<code>family:revision</code>) or full Amazon Resource Name (ARN) of the task
* definition to run in your service. If a <code>revision</code> is not specified,
* the latest <code>ACTIVE</code> revision is used. If you modify the task
* definition with <code>UpdateService</code>, Amazon ECS spawns a task with the
* new version of the task definition and then stops an old task after the new
* version is running.</p>
*/
inline UpdateServiceRequest& WithTaskDefinition(const Aws::String& value) { SetTaskDefinition(value); return *this;}
/**
* <p>The <code>family</code> and <code>revision</code>
* (<code>family:revision</code>) or full Amazon Resource Name (ARN) of the task
* definition to run in your service. If a <code>revision</code> is not specified,
* the latest <code>ACTIVE</code> revision is used. If you modify the task
* definition with <code>UpdateService</code>, Amazon ECS spawns a task with the
* new version of the task definition and then stops an old task after the new
* version is running.</p>
*/
inline UpdateServiceRequest& WithTaskDefinition(Aws::String&& value) { SetTaskDefinition(std::move(value)); return *this;}
/**
* <p>The <code>family</code> and <code>revision</code>
* (<code>family:revision</code>) or full Amazon Resource Name (ARN) of the task
* definition to run in your service. If a <code>revision</code> is not specified,
* the latest <code>ACTIVE</code> revision is used. If you modify the task
* definition with <code>UpdateService</code>, Amazon ECS spawns a task with the
* new version of the task definition and then stops an old task after the new
* version is running.</p>
*/
inline UpdateServiceRequest& WithTaskDefinition(const char* value) { SetTaskDefinition(value); return *this;}
/**
* <p>Optional deployment parameters that control how many tasks run during the
* deployment and the ordering of stopping and starting tasks.</p>
*/
inline const DeploymentConfiguration& GetDeploymentConfiguration() const{ return m_deploymentConfiguration; }
/**
* <p>Optional deployment parameters that control how many tasks run during the
* deployment and the ordering of stopping and starting tasks.</p>
*/
inline void SetDeploymentConfiguration(const DeploymentConfiguration& value) { m_deploymentConfigurationHasBeenSet = true; m_deploymentConfiguration = value; }
/**
* <p>Optional deployment parameters that control how many tasks run during the
* deployment and the ordering of stopping and starting tasks.</p>
*/
inline void SetDeploymentConfiguration(DeploymentConfiguration&& value) { m_deploymentConfigurationHasBeenSet = true; m_deploymentConfiguration = std::move(value); }
/**
* <p>Optional deployment parameters that control how many tasks run during the
* deployment and the ordering of stopping and starting tasks.</p>
*/
inline UpdateServiceRequest& WithDeploymentConfiguration(const DeploymentConfiguration& value) { SetDeploymentConfiguration(value); return *this;}
/**
* <p>Optional deployment parameters that control how many tasks run during the
* deployment and the ordering of stopping and starting tasks.</p>
*/
inline UpdateServiceRequest& WithDeploymentConfiguration(DeploymentConfiguration&& value) { SetDeploymentConfiguration(std::move(value)); return *this;}
private:
Aws::String m_cluster;
bool m_clusterHasBeenSet;
Aws::String m_service;
bool m_serviceHasBeenSet;
int m_desiredCount;
bool m_desiredCountHasBeenSet;
Aws::String m_taskDefinition;
bool m_taskDefinitionHasBeenSet;
DeploymentConfiguration m_deploymentConfiguration;
bool m_deploymentConfigurationHasBeenSet;
};
} // namespace Model
} // namespace ECS
} // namespace Aws
| 43.586466 | 169 | 0.689322 | [
"model"
] |
2338f8974aae5071207b5482c0424eefd646cf2d | 9,379 | h | C | src/operator/nn/fully_connected-inl.h | noob0/incubator-mxnet | 5a8b873343495c2d54a6c005d006b58be3978cb6 | [
"Apache-2.0"
] | 4 | 2018-10-25T23:05:25.000Z | 2019-06-29T11:44:07.000Z | src/operator/nn/fully_connected-inl.h | noob0/incubator-mxnet | 5a8b873343495c2d54a6c005d006b58be3978cb6 | [
"Apache-2.0"
] | 27 | 2017-07-04T17:45:51.000Z | 2019-09-12T06:56:27.000Z | src/operator/nn/fully_connected-inl.h | noob0/incubator-mxnet | 5a8b873343495c2d54a6c005d006b58be3978cb6 | [
"Apache-2.0"
] | 5 | 2017-07-04T17:41:20.000Z | 2020-01-30T07:40:59.000Z | /*
* 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.
*/
/*!
* Copyright (c) 2015 by Contributors
* \file fully_connect_op-inl.h
* \brief fully connect operator and symbol
*/
#ifndef MXNET_OPERATOR_NN_FULLY_CONNECTED_INL_H_
#define MXNET_OPERATOR_NN_FULLY_CONNECTED_INL_H_
#include <dmlc/logging.h>
#include <dmlc/parameter.h>
#include <mxnet/operator.h>
#include <map>
#include <vector>
#include <string>
#include <utility>
#include "../operator_common.h"
#include "../elemwise_op_common.h"
#include "../linalg.h"
#include "../../common/utils.h"
namespace mxnet {
namespace op {
// Declare enumeration of input order to make code more intuitive.
// These enums are only visible within this header
namespace fullc {
enum FullyConnectedOpInputs {kData, kWeight, kBias};
enum FullyConnectedOpResource {kTempSpace};
enum FullyConnectedOpOutputs {kOut};
} // fullc
struct FullyConnectedParam : public dmlc::Parameter<FullyConnectedParam> {
int num_hidden;
bool no_bias;
bool flatten;
DMLC_DECLARE_PARAMETER(FullyConnectedParam) {
// TODO(bing) add support for boolean
DMLC_DECLARE_FIELD(num_hidden).set_lower_bound(1)
.describe("Number of hidden nodes of the output.");
DMLC_DECLARE_FIELD(no_bias).set_default(false)
.describe("Whether to disable bias parameter.");
DMLC_DECLARE_FIELD(flatten).set_default(true)
.describe("Whether to collapse all but the first axis of the input data tensor.");
}
};
template<typename xpu, typename DType>
void FCForward(const OpContext &ctx, const FullyConnectedParam ¶m,
const std::vector<TBlob> &in_data, const std::vector<OpReqType> &req,
const std::vector<TBlob> &out_data) {
using namespace mshadow;
using namespace mshadow::expr;
if (req[fullc::kOut] == kNullOp) return;
CHECK_EQ(req[fullc::kOut], kWriteTo);
// TODO(bing): check the BLAS Handle, be careful
// maybe need blas handle from context
// TODO(bing): judge shape to remove flatten op
Stream<xpu> *s = ctx.get_stream<xpu>();
#if defined(__CUDACC__)
CHECK_EQ(s->blas_handle_ownership_, Stream<xpu>::OwnHandle)
<< "Must init CuBLAS handle in stream";
#endif // __CUDACC__
const TShape& ishape = in_data[fullc::kData].shape_;
const TShape& oshape = out_data[fullc::kOut].shape_;
Tensor<xpu, 2, DType> wmat = in_data[fullc::kWeight].get<xpu, 2, DType>(s);
Tensor<xpu, 2, DType> data, out;
if (!param.flatten) {
data = in_data[fullc::kData].get_with_shape<xpu, 2, DType>(
Shape2(ishape.ProdShape(0, ishape.ndim()-1), ishape[ishape.ndim()-1]), s);
out = out_data[fullc::kOut].get_with_shape<xpu, 2, DType>(
Shape2(oshape.ProdShape(0, oshape.ndim()-1), oshape[oshape.ndim()-1]), s);
} else {
data = in_data[fullc::kData].get_with_shape<xpu, 2, DType>(
Shape2(ishape[0], ishape.ProdShape(1, ishape.ndim())), s);
out = out_data[fullc::kOut].get_with_shape<xpu, 2, DType>(
Shape2(oshape[0], oshape.ProdShape(1, oshape.ndim())), s);
}
CHECK_EQ(data.shape_[1], wmat.shape_[1])
<< "Incomplete weight tensor detected: weight.data().shape[1] != prod(data.data().shape[1:])."
" This is not supported by FCForward. If weight is in row_sparse format,"
" please make sure all row ids are present.";
// Legacy approach shown here for comparison:
// out = dot(data, wmat.T());
linalg_gemm(data, wmat, out, false, true, s);
if (!param.no_bias) {
Tensor<xpu, 1, DType> bias = in_data[fullc::kBias].get_with_shape<xpu, 1, DType>(
Shape1(wmat.shape_[0]), s);
CHECK_EQ(bias.shape_[0], wmat.shape_[0])
<< "Incomplete bias tensor detected: bias.data().shape[1] != weight.data().shape[0]."
" This is not supported by FCForward. If bias is in row_sparse format, please"
" make sure all row ids are present.";
out += repmat(bias, data.size(0));
}
}
template<typename xpu, typename DType>
void FCBackward(const OpContext &ctx, const FullyConnectedParam ¶m,
const std::vector<TBlob> &out_grad, const std::vector<TBlob> &in_data,
const std::vector<OpReqType> &req, const std::vector<TBlob> &in_grad) {
using namespace mshadow;
using namespace mshadow::expr;
// TODO(bing): check the BLAS Handle, be careful
// maybe need blas handle from context
Stream<xpu> *s = ctx.get_stream<xpu>();
const TShape& ishape = in_data[fullc::kData].shape_;
const TShape& oshape = out_grad[fullc::kOut].shape_;
Tensor<xpu, 2, DType> wmat = in_data[fullc::kWeight].get<xpu, 2, DType>(s);
Tensor<xpu, 2, DType> data, grad, gdata;
if (!param.flatten) {
data = in_data[fullc::kData].get_with_shape<xpu, 2, DType>(
Shape2(ishape.ProdShape(0, ishape.ndim()-1), ishape[ishape.ndim()-1]), s);
grad = out_grad[fullc::kOut].get_with_shape<xpu, 2, DType>(
Shape2(oshape.ProdShape(0, oshape.ndim()-1), oshape[oshape.ndim()-1]), s);
gdata = in_grad[fullc::kData].get_with_shape<xpu, 2, DType>(
Shape2(ishape.ProdShape(0, ishape.ndim()-1), ishape[ishape.ndim()-1]), s);
} else {
data = in_data[fullc::kData].get_with_shape<xpu, 2, DType>(
Shape2(ishape[0], ishape.ProdShape(1, ishape.ndim())), s);
grad = out_grad[fullc::kOut].get_with_shape<xpu, 2, DType>(
Shape2(oshape[0], oshape.ProdShape(1, oshape.ndim())), s);
gdata = in_grad[fullc::kData].get_with_shape<xpu, 2, DType>(
Shape2(ishape[0], ishape.ProdShape(1, ishape.ndim())), s);
}
#if defined(__CUDACC__)
CHECK_EQ(s->blas_handle_ownership_, Stream<xpu>::OwnHandle)
<< "Must init CuBLAS handle in stream";
#endif
// backprop
CHECK_NE(req[fullc::kWeight], kWriteInplace) << "cannot write weight inplace";
// gradient of weight
Tensor<xpu, 2, DType> gwmat = in_grad[fullc::kWeight].get<xpu, 2, DType>(s);
// Legacy approach shown here for comparison:
// out = Assign(gwmat, req[fullc::kWeight], dot(grad.T(), data));
linalg_gemm(grad, data, gwmat, true, false, s, req[fullc::kWeight]);
// gradient of bias
if (!param.no_bias) {
Tensor<xpu, 1, DType> gbias = in_grad[fullc::kBias].get<xpu, 1, DType>(s);
Assign(gbias, req[fullc::kBias], sum_rows(grad));
}
// gradient of data
// Legacy approach shown here for comparison:
// Assign(gdata, req[fullc::kData], dot(grad, wmat));
linalg_gemm(grad, wmat, gdata, false, false, s, req[fullc::kData]);
}
template<typename xpu>
void FullyConnectedCompute(const nnvm::NodeAttrs& attrs,
const OpContext& ctx,
const std::vector<TBlob>& inputs,
const std::vector<OpReqType>& req,
const std::vector<TBlob>& outputs) {
const FullyConnectedParam& param = nnvm::get<FullyConnectedParam>(attrs.parsed);
uint32_t in_expected = param.no_bias ? 2 : 3;
CHECK_EQ(inputs.size(), in_expected);
CHECK_EQ(outputs.size(), 1U);
int dtype = inputs[0].type_flag_;
switch (dtype) {
case mshadow::kFloat32:
FCForward<xpu, float>(ctx, param, inputs, req, outputs);
break;
case mshadow::kFloat64:
FCForward<xpu, double>(ctx, param, inputs, req, outputs);
break;
case mshadow::kFloat16:
LOG(FATAL) << "float16 fully connected layer is currently"
"only supported by CuDNN version.";
break;
default:
LOG(FATAL) << "Unsupported type " << dtype;
}
}
template<typename xpu>
void FullyConnectedGradCompute(const nnvm::NodeAttrs& attrs,
const OpContext& ctx,
const std::vector<TBlob>& inputs,
const std::vector<OpReqType>& req,
const std::vector<TBlob>& outputs) {
const FullyConnectedParam& param = nnvm::get<FullyConnectedParam>(attrs.parsed);
uint32_t out_expected = param.no_bias ? 2 : 3;
CHECK_EQ(inputs.size(), 3U);
CHECK_EQ(outputs.size(), out_expected);
CHECK_EQ(req.size(), out_expected);
std::vector<TBlob> out_grad{inputs[0]};
std::vector<TBlob> in_data(inputs.begin() + 1, inputs.end());
int dtype = inputs[0].type_flag_;
switch (dtype) {
case mshadow::kFloat32:
FCBackward<xpu, float>(ctx, param, out_grad, in_data, req, outputs);
break;
case mshadow::kFloat64:
FCBackward<xpu, double>(ctx, param, out_grad, in_data, req, outputs);
break;
case mshadow::kFloat16:
LOG(FATAL) << "float16 fully connected layer is currently"
"only supported by CuDNN version.";
break;
default:
LOG(FATAL) << "Unsupported type " << dtype;
}
}
} // namespace op
} // namespace mxnet
#endif // MXNET_OPERATOR_NN_FULLY_CONNECTED_INL_H_
| 40.426724 | 98 | 0.673633 | [
"shape",
"vector"
] |
233a016615b7387037e40c5774ce1d7b1b1d5cbd | 11,714 | h | C | examples/Utilities/SystemInfoDemo.h | studiobee/JUCE6-Svalbard-Fork | 2bcd2101811f6a3a803a7f68d3bac2d0d53f4146 | [
"ISC"
] | 2,270 | 2020-04-15T15:14:37.000Z | 2022-03-31T19:13:53.000Z | examples/Utilities/SystemInfoDemo.h | studiobee/JUCE6-Svalbard-Fork | 2bcd2101811f6a3a803a7f68d3bac2d0d53f4146 | [
"ISC"
] | 471 | 2017-04-25T07:57:02.000Z | 2020-04-08T21:06:47.000Z | examples/Utilities/SystemInfoDemo.h | studiobee/JUCE6-Svalbard-Fork | 2bcd2101811f6a3a803a7f68d3bac2d0d53f4146 | [
"ISC"
] | 633 | 2020-04-15T16:45:55.000Z | 2022-03-31T13:32:29.000Z | /*
==============================================================================
This file is part of the JUCE examples.
Copyright (c) 2020 - Raw Material Software Limited
The code included in this file is provided under the terms of the ISC license
http://www.isc.org/downloads/software-support-policy/isc-license. Permission
To use, copy, modify, and/or distribute this software for any purpose with or
without fee is hereby granted provided that the above copyright notice and
this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES,
WHETHER EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR
PURPOSE, ARE DISCLAIMED.
==============================================================================
*/
/*******************************************************************************
The block below describes the properties of this PIP. A PIP is a short snippet
of code that can be read by the Projucer and used to generate a JUCE project.
BEGIN_JUCE_PIP_METADATA
name: SystemInfoDemo
version: 1.0.0
vendor: JUCE
website: http://juce.com
description: Displays system information.
dependencies: juce_core, juce_data_structures, juce_events, juce_graphics,
juce_gui_basics
exporters: xcode_mac, vs2019, linux_make, androidstudio, xcode_iphone
moduleFlags: JUCE_STRICT_REFCOUNTEDPOINTER=1
type: Component
mainClass: SystemInfoDemo
useLocalCopy: 1
END_JUCE_PIP_METADATA
*******************************************************************************/
#pragma once
#include "../Assets/DemoUtilities.h"
//==============================================================================
static String getMacAddressList()
{
String addressList;
for (auto& addr : MACAddress::getAllAddresses())
addressList << addr.toString() << newLine;
return addressList;
}
static String getFileSystemRoots()
{
Array<File> roots;
File::findFileSystemRoots (roots);
StringArray rootList;
for (auto& r : roots)
rootList.add (r.getFullPathName());
return rootList.joinIntoString (", ");
}
static String getIPAddressList()
{
String addressList;
for (auto& addr : IPAddress::getAllAddresses())
addressList << " " << addr.toString() << newLine;
return addressList;
}
static const char* getDisplayOrientation()
{
switch (Desktop::getInstance().getCurrentOrientation())
{
case Desktop::upright: return "Upright";
case Desktop::upsideDown: return "Upside-down";
case Desktop::rotatedClockwise: return "Rotated Clockwise";
case Desktop::rotatedAntiClockwise: return "Rotated Anti-clockwise";
case Desktop::allOrientations: return "All";
default: jassertfalse; break;
}
return nullptr;
}
static String getDisplayInfo()
{
auto& displays = Desktop::getInstance().getDisplays();
String displayDesc;
for (int i = 0; i < displays.displays.size(); ++i)
{
auto display = displays.displays.getReference (i);
displayDesc << "Display " << (i + 1) << (display.isMain ? " (main)" : "") << ":" << newLine
<< " Total area: " << display.totalArea.toString() << newLine
<< " User area: " << display.userArea .toString() << newLine
<< " DPI: " << display.dpi << newLine
<< " Scale: " << display.scale << newLine
<< newLine;
}
displayDesc << "Orientation: " << getDisplayOrientation() << newLine;
return displayDesc;
}
static String getAllSystemInfo()
{
String systemInfo;
systemInfo
<< "Here are a few system statistics..." << newLine
<< newLine
<< "Time and date: " << Time::getCurrentTime().toString (true, true) << newLine
<< "System up-time: " << RelativeTime::milliseconds ((int64) Time::getMillisecondCounterHiRes()).getDescription() << newLine
<< "Compilation date: " << Time::getCompilationDate().toString (true, false) << newLine
<< newLine
<< "Operating system: " << SystemStats::getOperatingSystemName() << newLine
<< "Host name: " << SystemStats::getComputerName() << newLine
<< "Device type: " << SystemStats::getDeviceDescription() << newLine
<< "Manufacturer: " << SystemStats::getDeviceManufacturer() << newLine
<< "User logon name: " << SystemStats::getLogonName() << newLine
<< "Full user name: " << SystemStats::getFullUserName() << newLine
<< "User region: " << SystemStats::getUserRegion() << newLine
<< "User language: " << SystemStats::getUserLanguage() << newLine
<< "Display language: " << SystemStats::getDisplayLanguage() << newLine
<< newLine;
systemInfo
<< "Number of logical CPUs: " << SystemStats::getNumCpus() << newLine
<< "Number of physical CPUs: " << SystemStats::getNumPhysicalCpus() << newLine
<< "Memory size: " << SystemStats::getMemorySizeInMegabytes() << " MB" << newLine
<< "CPU vendor: " << SystemStats::getCpuVendor() << newLine
<< "CPU model: " << SystemStats::getCpuModel() << newLine
<< "CPU speed: " << SystemStats::getCpuSpeedInMegahertz() << " MHz" << newLine
<< "CPU has MMX: " << (SystemStats::hasMMX() ? "yes" : "no") << newLine
<< "CPU has FMA3: " << (SystemStats::hasFMA3() ? "yes" : "no") << newLine
<< "CPU has FMA4: " << (SystemStats::hasFMA4() ? "yes" : "no") << newLine
<< "CPU has SSE: " << (SystemStats::hasSSE() ? "yes" : "no") << newLine
<< "CPU has SSE2: " << (SystemStats::hasSSE2() ? "yes" : "no") << newLine
<< "CPU has SSE3: " << (SystemStats::hasSSE3() ? "yes" : "no") << newLine
<< "CPU has SSSE3: " << (SystemStats::hasSSSE3() ? "yes" : "no") << newLine
<< "CPU has SSE4.1: " << (SystemStats::hasSSE41() ? "yes" : "no") << newLine
<< "CPU has SSE4.2: " << (SystemStats::hasSSE42() ? "yes" : "no") << newLine
<< "CPU has 3DNOW: " << (SystemStats::has3DNow() ? "yes" : "no") << newLine
<< "CPU has AVX: " << (SystemStats::hasAVX() ? "yes" : "no") << newLine
<< "CPU has AVX2: " << (SystemStats::hasAVX2() ? "yes" : "no") << newLine
<< "CPU has AVX512F: " << (SystemStats::hasAVX512F() ? "yes" : "no") << newLine
<< "CPU has AVX512BW: " << (SystemStats::hasAVX512BW() ? "yes" : "no") << newLine
<< "CPU has AVX512CD: " << (SystemStats::hasAVX512CD() ? "yes" : "no") << newLine
<< "CPU has AVX512DQ: " << (SystemStats::hasAVX512DQ() ? "yes" : "no") << newLine
<< "CPU has AVX512ER: " << (SystemStats::hasAVX512ER() ? "yes" : "no") << newLine
<< "CPU has AVX512IFMA: " << (SystemStats::hasAVX512IFMA() ? "yes" : "no") << newLine
<< "CPU has AVX512PF: " << (SystemStats::hasAVX512PF() ? "yes" : "no") << newLine
<< "CPU has AVX512VBMI: " << (SystemStats::hasAVX512VBMI() ? "yes" : "no") << newLine
<< "CPU has AVX512VL: " << (SystemStats::hasAVX512VL() ? "yes" : "no") << newLine
<< "CPU has AVX512VPOPCNTDQ: " << (SystemStats::hasAVX512VPOPCNTDQ() ? "yes" : "no") << newLine
<< "CPU has Neon: " << (SystemStats::hasNeon() ? "yes" : "no") << newLine
<< newLine;
systemInfo
<< "Current working directory: " << File::getCurrentWorkingDirectory().getFullPathName() << newLine
<< "Current application file: " << File::getSpecialLocation (File::currentApplicationFile).getFullPathName() << newLine
<< "Current executable file: " << File::getSpecialLocation (File::currentExecutableFile) .getFullPathName() << newLine
<< "Invoked executable file: " << File::getSpecialLocation (File::invokedExecutableFile) .getFullPathName() << newLine
<< newLine;
systemInfo
<< "User home folder: " << File::getSpecialLocation (File::userHomeDirectory) .getFullPathName() << newLine
<< "User desktop folder: " << File::getSpecialLocation (File::userDesktopDirectory) .getFullPathName() << newLine
<< "User documents folder: " << File::getSpecialLocation (File::userDocumentsDirectory) .getFullPathName() << newLine
<< "User application data folder: " << File::getSpecialLocation (File::userApplicationDataDirectory) .getFullPathName() << newLine
<< "User music folder: " << File::getSpecialLocation (File::userMusicDirectory) .getFullPathName() << newLine
<< "User movies folder: " << File::getSpecialLocation (File::userMoviesDirectory) .getFullPathName() << newLine
<< "User pictures folder: " << File::getSpecialLocation (File::userPicturesDirectory) .getFullPathName() << newLine
<< "Common application data folder: " << File::getSpecialLocation (File::commonApplicationDataDirectory).getFullPathName() << newLine
<< "Common documents folder: " << File::getSpecialLocation (File::commonDocumentsDirectory) .getFullPathName() << newLine
<< "Local temp folder: " << File::getSpecialLocation (File::tempDirectory) .getFullPathName() << newLine
<< newLine;
systemInfo
<< "File System roots: " << getFileSystemRoots() << newLine
<< "Free space in home folder: " << File::descriptionOfSizeInBytes (File::getSpecialLocation (File::userHomeDirectory)
.getBytesFreeOnVolume()) << newLine
<< newLine
<< getDisplayInfo() << newLine
<< "Network IP addresses: " << newLine << getIPAddressList() << newLine
<< "Network card MAC addresses: " << newLine << getMacAddressList() << newLine;
DBG (systemInfo);
return systemInfo;
}
class SystemInfoDemo : public Component
{
public:
SystemInfoDemo()
{
addAndMakeVisible (resultsBox);
resultsBox.setReadOnly (true);
resultsBox.setMultiLine (true);
resultsBox.setColour (TextEditor::backgroundColourId, Colours::transparentBlack);
resultsBox.setFont ({ Font::getDefaultMonospacedFontName(), 12.0f, Font::plain });
resultsBox.setText (getAllSystemInfo());
setSize (500, 500);
}
void paint (Graphics& g) override
{
g.fillAll (getUIColourIfAvailable (LookAndFeel_V4::ColourScheme::UIColour::windowBackground,
Colour::greyLevel (0.93f)));
}
void resized() override
{
resultsBox.setBounds (getLocalBounds().reduced (8));
}
private:
TextEditor resultsBox;
void lookAndFeelChanged() override
{
resultsBox.applyFontToAllText (resultsBox.getFont());
}
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (SystemInfoDemo)
};
| 47.617886 | 140 | 0.551562 | [
"model"
] |
233c244c13f12f85f223a97912ab48c638e24e66 | 5,172 | h | C | GTE/Mathematics/DistTriangle3Rectangle3.h | lakinwecker/GeometricTools | cff3e3fcb52d714afe0b6789839c460437c10b27 | [
"BSL-1.0"
] | null | null | null | GTE/Mathematics/DistTriangle3Rectangle3.h | lakinwecker/GeometricTools | cff3e3fcb52d714afe0b6789839c460437c10b27 | [
"BSL-1.0"
] | 1 | 2022-03-18T00:34:13.000Z | 2022-03-18T00:34:13.000Z | GTE/Mathematics/DistTriangle3Rectangle3.h | lakinwecker/GeometricTools | cff3e3fcb52d714afe0b6789839c460437c10b27 | [
"BSL-1.0"
] | 1 | 2022-03-17T21:54:55.000Z | 2022-03-17T21:54:55.000Z | // David Eberly, Geometric Tools, Redmond WA 98052
// Copyright (c) 1998-2022
// Distributed under the Boost Software License, Version 1.0.
// https://www.boost.org/LICENSE_1_0.txt
// https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt
// Version: 6.0.2022.01.06
#pragma once
#include <Mathematics/DistSegment3Rectangle3.h>
#include <Mathematics/DistSegment3Triangle3.h>
// Compute the distance between a solid triangle and a solid rectangle in 3D.
//
// The triangle has vertices <V[0],V[1],V[2]>. A triangle point is
// X = sum_{i=0}^2 b[i] * V[i], where 0 <= b[i] <= 1 for all i and
// sum_{i=0}^2 b[i] = 1.
//
// The rectangle has center C, unit-length axis directions W[0] and W[1], and
// extents e[0] and e[1]. A rectangle point is X = C + sum_{i=0}^2 s[i] * W[i]
// where |s[i]| <= e[i] for all i.
//
// The closest point on the triangle is stored in closest[0] with barycentric
// coordinates (b[0],b[1],b[2]). The closest point on the rectangle is stoed
// closest[1] with cartesian[] coordinates (s[0],s[1]). When there are
// infinitely many choices for the pair of closest points, only one of them is
// returned.
//
// TODO: Modify to support non-unit-length W[].
namespace gte
{
template <typename T>
class DCPQuery<T, Triangle3<T>, Rectangle3<T>>
{
public:
struct Result
{
Result()
:
distance(static_cast<T>(0)),
sqrDistance(static_cast<T>(0)),
barycentric{ static_cast<T>(0), static_cast<T>(0), static_cast<T>(0) },
cartesian{ static_cast<T>(0), static_cast<T>(0) },
closest{ Vector3<T>::Zero(), Vector3<T>::Zero() }
{
}
T distance, sqrDistance;
std::array<T, 3> barycentric;
std::array<T, 2> cartesian;
std::array<Vector3<T>, 2> closest;
};
Result operator()(Triangle3<T> const& triangle, Rectangle3<T> const& rectangle)
{
Result result{};
DCPQuery<T, Segment3<T>, Triangle3<T>> stQuery{};
typename DCPQuery<T, Segment3<T>, Triangle3<T>>::Result stResult{};
DCPQuery<T, Segment3<T>, Rectangle3<T>> srQuery{};
typename DCPQuery<T, Segment3<T>, Rectangle3<T>>::Result srResult{};
Segment3<T> segment{};
T const zero = static_cast<T>(0);
T const one = static_cast<T>(1);
T const negOne = static_cast<T>(-1);
T const two = static_cast<T>(2);
T const invalid = static_cast<T>(-1);
result.distance = invalid;
result.sqrDistance = invalid;
std::array<T, 4> const sign{ negOne, one, negOne, one };
std::array<int32_t, 4> j0{ 0, 0, 1, 1 };
std::array<int32_t, 4> j1{ 1, 1, 0, 0 };
std::array<std::array<size_t, 2>, 4> const edges
{{
// horizontal edges (y = -e1, +e1)
{ 0, 1 }, { 2, 3 },
// vertical edges (x = -e0, +e0)
{ 0, 2 }, { 1, 3 }
}};
std::array<Vector3<T>, 4> vertices{};
// Compare edges of triangle to the interior of rectangle.
for (size_t i0 = 2, i1 = 0, i2 = 1; i1 < 3; i2 = i0, i0 = i1++)
{
segment.p[0] = triangle.v[i0];
segment.p[1] = triangle.v[i1];
srResult = srQuery(segment, rectangle);
if (result.sqrDistance == invalid ||
srResult.sqrDistance < result.sqrDistance)
{
result.distance = srResult.distance;
result.sqrDistance = srResult.sqrDistance;
result.barycentric[i0] = one - srResult.parameter;
result.barycentric[i1] = srResult.parameter;
result.barycentric[i2] = zero;
result.cartesian = srResult.cartesian;
result.closest = srResult.closest;
}
}
// Compare edges of rectangle to the interior of triangle.
rectangle.GetVertices(vertices);
for (size_t i = 0; i < 4; ++i)
{
auto const& edge = edges[i];
segment.p[0] = vertices[edge[0]];
segment.p[1] = vertices[edge[1]];
stResult = stQuery(segment, triangle);
if (result.sqrDistance == invalid ||
stResult.sqrDistance < result.sqrDistance)
{
result.distance = stResult.distance;
result.sqrDistance = stResult.sqrDistance;
result.barycentric = stResult.barycentric;
T const scale = two * stResult.parameter - one;
result.cartesian[j0[i]] = scale * rectangle.extent[j0[i]];
result.cartesian[j1[i]] = sign[i] * rectangle.extent[j1[i]];
result.closest[0] = stResult.closest[1];
result.closest[1] = stResult.closest[0];
}
}
return result;
}
};
}
| 39.480916 | 87 | 0.527649 | [
"3d",
"solid"
] |
233e52027ba106f5b411a80dbc800d917cdd041e | 675 | h | C | src/MeshAsset.h | WienerTakesAll/WienerTakesAll | 6accbf6f0ac04cf990134072474e71f2bc59e7d0 | [
"Apache-2.0"
] | 2 | 2018-01-07T02:26:22.000Z | 2018-04-06T16:07:01.000Z | src/MeshAsset.h | WienerTakesAll/WienerTakesAll | 6accbf6f0ac04cf990134072474e71f2bc59e7d0 | [
"Apache-2.0"
] | 39 | 2018-01-12T00:21:12.000Z | 2018-04-13T12:08:20.000Z | src/MeshAsset.h | WienerTakesAll/WienerTakesAll | 6accbf6f0ac04cf990134072474e71f2bc59e7d0 | [
"Apache-2.0"
] | null | null | null | #pragma once
#include <vector>
#include "GL/glew.h"
#include "SDL_opengl.h"
#include "glm/glm.hpp"
struct MeshAsset {
struct MeshData {
struct VertexData {
glm::vec3 position_;
glm::vec3 normal_;
glm::vec3 colors_;
glm::vec3 uv_;
};
std::vector<VertexData> vertices_;
std::vector<GLuint> indices_;
struct VolumeVertexData {
glm::vec4 position_;
glm::vec3 normal_;
};
std::vector<VolumeVertexData> shadow_volume_vertices_;
std::vector<GLuint> shadow_volume_indices_;
};
bool valid_;
std::vector<MeshData> meshes_;
};
| 20.454545 | 62 | 0.580741 | [
"vector"
] |
234d4eb4b60486298b4fe9822e446fb28a6b4a61 | 3,540 | h | C | Core/DianYing/Include/Dy/Meta/Information/MetaInfoTexture.h | liliilli/DianYing | 6e19f67e5d932e346a0ce63a648bed1a04ef618e | [
"MIT"
] | 4 | 2019-03-17T19:46:54.000Z | 2019-12-09T20:11:01.000Z | Core/DianYing/Include/Dy/Meta/Information/MetaInfoTexture.h | liliilli/DianYing | 6e19f67e5d932e346a0ce63a648bed1a04ef618e | [
"MIT"
] | null | null | null | Core/DianYing/Include/Dy/Meta/Information/MetaInfoTexture.h | liliilli/DianYing | 6e19f67e5d932e346a0ce63a648bed1a04ef618e | [
"MIT"
] | null | null | null | #ifndef GUARD_DY_META_INFORMATION_METAINFOTEXTURE_H
#define GUARD_DY_META_INFORMATION_METAINFOTEXTURE_H
///
/// MIT License
/// Copyright (c) 2018-2019 Jongmin Yun
///
/// 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 <variant>
#include <nlohmann/json_fwd.hpp>
#include <Dy/Helper/Type/DVector2.h>
#include <Dy/Meta/Information/CommonResourceMetaInfo.h>
#include <Dy/Meta/Type/EDyTextureParameter.h>
#include <Dy/Core/Resource/Internal/ETextureEnums.h>
#include <Dy/Helper/Type/DColorRGBA.h>
#include <Dy/Helper/Internal/DImageBinaryBuffer.h>
namespace dy
{
///
/// @class PDyTextureInstanceMetaInfo
/// @brief Texture construction & meta descriptor.
///
struct PDyTextureInstanceMetaInfo final : public PDyCommonResourceMetaInfo
{
struct DCubemapFilePath
{
std::string mTopPath = MDY_INITIALIZE_EMPTYSTR;
std::string mBottomPath = MDY_INITIALIZE_EMPTYSTR;
std::string mFrontPath = MDY_INITIALIZE_EMPTYSTR;
std::string mBackPath = MDY_INITIALIZE_EMPTYSTR;
std::string mRightPath = MDY_INITIALIZE_EMPTYSTR;
std::string mLeftPath = MDY_INITIALIZE_EMPTYSTR;
};
/// Texture specification name.
std::string mSpecifierName = MDY_INITIALIZE_EMPTYSTR;
/// Texture external file path.
/// DCubemapFilePath only applied when `mTextureType` is ETextureStyleType::D2Cubemap;
std::variant<std::string, DCubemapFilePath> mExternalFilePath = MDY_INITIALIZE_EMPTYSTR;
/// Texture is 1D or 2D?
ETextureStyleType mTextureType = ETextureStyleType::NoneError;
/// Border color
DColorRGBA mBorderColor = DColorRGBA::Black;
/// as R, RG, RGB, RGBA
EDyImageColorFormatStyle mTextureColorType = EDyImageColorFormatStyle::NoneError;
///
EDyGlImagePixelReadType mPixelReadType = EDyGlImagePixelReadType::UnsignedByte;
/// Texture parameters
TTextureParameterList mParameterList = {};
/// Use default opengl generated mipmap if true.
bool mIsUsingDefaultMipmapGeneration = false;
/// Use customized texture parameters (PDyTextureConstructionBaseDesc::mParameterList)
bool mIsEnabledCustomedTextureParameter = false;
/// Integer size builtin buffer container.
DIVec2 mBuiltinBufferSize = {};
/// Built-In buffer pointer of texture.
std::vector<TU8>* mPtrBuiltinBuffer = MDY_INITIALIZE_NULL;
/// @deprecated NOT USED NOW
std::string mTextureFileAbsolutePath_Deprecated = MDY_INITIALIZE_EMPTYSTR;
/// @deprecated NOT USED NOW
bool mIsEnabledAbsolutePath_Deprecated = true;
/// @deprecated NOT USED NOW.
ETextureMapType mTextureMapType_Deprecated = ETextureMapType::Unknown;
};
void to_json(_MINOUT_ nlohmann::json& j, _MIN_ const PDyTextureInstanceMetaInfo& p);
void from_json(_MIN_ const nlohmann::json& j, _MINOUT_ PDyTextureInstanceMetaInfo& p);
void to_json(_MINOUT_ nlohmann::json& j, _MIN_ const PDyTextureInstanceMetaInfo::DCubemapFilePath& p);
void from_json(_MIN_ const nlohmann::json& j, _MINOUT_ PDyTextureInstanceMetaInfo::DCubemapFilePath& p);
} /// ::dy namespace
#endif /// GUARD_DY_META_INFORMATION_METAINFOTEXTURE_H | 42.142857 | 104 | 0.760169 | [
"vector"
] |
234ea75e244ed2b3e328478d0cd53e26cb3b2da9 | 21,362 | h | C | flecs-1.1/src/types.h | tang1024/vflecs | 7d438aa18d207193eb4ad2aefabe2c95cb3d3a4d | [
"MIT"
] | 1 | 2022-02-14T21:09:38.000Z | 2022-02-14T21:09:38.000Z | flecs-1.1/src/types.h | tang1024/vflecs | 7d438aa18d207193eb4ad2aefabe2c95cb3d3a4d | [
"MIT"
] | null | null | null | flecs-1.1/src/types.h | tang1024/vflecs | 7d438aa18d207193eb4ad2aefabe2c95cb3d3a4d | [
"MIT"
] | null | null | null | #ifndef FLECS_TYPES_PRIVATE_H
#define FLECS_TYPES_PRIVATE_H
#ifndef __MACH__
#define _POSIX_C_SOURCE 200809L
#endif
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <stdarg.h>
#include <stdio.h>
#include <time.h>
#include <ctype.h>
#include <math.h>
#ifdef _MSC_VER
//FIXME
#else
#include <sys/param.h> /* attempt to define endianness */
#endif
#ifdef linux
# include <endian.h> /* attempt to define endianness */
#endif
#include <flecs.h>
#define ECS_WORLD_INITIAL_TABLE_COUNT (2)
#define ECS_WORLD_INITIAL_ENTITY_COUNT (2)
#define ECS_WORLD_INITIAL_STAGING_COUNT (0)
#define ECS_WORLD_INITIAL_COL_SYSTEM_COUNT (1)
#define ECS_WORLD_INITIAL_OTHER_SYSTEM_COUNT (0)
#define ECS_WORLD_INITIAL_ADD_SYSTEM_COUNT (0)
#define ECS_WORLD_INITIAL_REMOVE_SYSTEM_COUNT (0)
#define ECS_WORLD_INITIAL_SET_SYSTEM_COUNT (0)
#define ECS_WORLD_INITIAL_PREFAB_COUNT (0)
#define ECS_MAP_INITIAL_NODE_COUNT (4)
#define ECS_TABLE_INITIAL_ROW_COUNT (0)
#define ECS_SYSTEM_INITIAL_TABLE_COUNT (0)
#define ECS_MAX_JOBS_PER_WORKER (16)
/* This is _not_ the max number of entities that can be of a given type. This
* constant defines the maximum number of components, prefabs and parents can be
* in one type. This limit serves two purposes: detect errors earlier (assert on
* very large types) and allow for more efficient allocation strategies (like
* using alloca for temporary buffers). */
#define ECS_MAX_ENTITIES_IN_TYPE (256)
#define ECS_WORLD_MAGIC (0x65637377)
#define ECS_THREAD_MAGIC (0x65637374)
/* -- Builtin component types -- */
/** Metadata of an explicitly created type (ECS_TYPE or ecs_new_type) */
typedef struct EcsTypeComponent {
ecs_type_t type; /* Preserved nested families */
ecs_type_t resolved; /* Resolved nested families */
} EcsTypeComponent;
/* For prefabs with child entities, the parent prefab must be marked so that
* flecs knows not to share components from it, as adding a prefab as a parent
* is stored in the same way as adding a prefab for sharing components.
* There are two mechanisms required to accomplish this. The first one is to set
* the 'parent' member in the EcsPrefab component, for the child entity of the
* prefab. This acts as a front-end for another mechanism, that ensures that
* child entities for different prefab parents are added to different tables. As
* a result of setting a parent in EcsPrefab, Flecs will:
*
* - Add the prefab to the entity type
* - Find or create a prefab parent flag entity
* - Set the EcsPrefabParent component on the prefab parent flag entity
* - Add the prefab parent flag entity to the child
*
* The last step ensures that the type of the child entity is associated with at
* most one prefab parent. If the mechanism would just rely on the EcsPrefab
* parent field, it would theoretically be possible that childs for different
* prefab parents end up in the same table.
*/
typedef struct EcsPrefabParent {
ecs_entity_t parent;
} EcsPrefabParent;
typedef struct ecs_builder_op_t {
const char *id;
ecs_type_t type;
} ecs_builder_op_t;
typedef struct EcsPrefabBuilder {
ecs_vector_t *ops; /* ecs_builder_op_t */
} EcsPrefabBuilder;
/** Type that is used by systems to indicate where to fetch a component from */
typedef enum ecs_system_expr_elem_kind_t {
EcsFromSelf, /* Get component from self (default) */
EcsFromOwned, /* Get owned component from self */
EcsFromShared, /* Get shared component from self */
EcsFromContainer, /* Get component from container */
EcsFromSystem, /* Get component from system */
EcsFromEmpty, /* Get entity handle by id */
EcsFromEntity, /* Get component from other entity */
EcsCascade /* Walk component in cascading (hierarchy) order */
} ecs_system_expr_elem_kind_t;
/** Type describing an operator used in an signature of a system signature */
typedef enum ecs_system_expr_oper_kind_t {
EcsOperAnd = 0,
EcsOperOr = 1,
EcsOperNot = 2,
EcsOperOptional = 3,
EcsOperLast = 4
} ecs_system_expr_oper_kind_t;
/** Callback used by the system signature expression parser */
typedef int (*ecs_parse_action_t)(
ecs_world_t *world,
ecs_system_expr_elem_kind_t elem_kind,
ecs_system_expr_oper_kind_t oper_kind,
const char *component,
const char *source,
void *ctx);
/** Type that describes a single column in the system signature */
typedef struct ecs_system_column_t {
ecs_system_expr_elem_kind_t kind; /* Element kind (Entity, Component) */
ecs_system_expr_oper_kind_t oper_kind; /* Operator kind (AND, OR, NOT) */
union {
ecs_type_t type; /* Used for OR operator */
ecs_entity_t component; /* Used for AND operator */
} is;
ecs_entity_t source; /* Source entity (used with FromEntity) */
} ecs_system_column_t;
/** A table column describes a single column in a table (archetype) */
typedef struct ecs_table_column_t {
ecs_vector_t *data; /* Column data */
uint16_t size; /* Column size (saves component lookups) */
} ecs_table_column_t;
#define EcsTableIsStaged (1)
#define EcsTableIsPrefab (2)
#define EcsTableHasPrefab (4)
/** A table is the Flecs equivalent of an archetype. Tables store all entities
* with a specific set of components. Tables are automatically created when an
* entity has a set of components not previously observed before. When a new
* table is created, it is automatically matched with existing column systems */
typedef struct ecs_table_t {
ecs_table_column_t *columns; /* Columns storing components of array */
ecs_vector_t *frame_systems; /* Frame systems matched with table */
ecs_type_t type; /* Identifies table type in type_index */
uint32_t flags; /* Flags for testing table properties */
} ecs_table_t;
/** Type containing data for a table matched with a system */
typedef struct ecs_matched_table_t {
ecs_table_t *table; /* Reference to the table */
int32_t *columns; /* Mapping of system columns to table */
ecs_entity_t *components; /* Actual components of system columns */
ecs_vector_t *references; /* Reference columns and cached pointers */
int32_t depth; /* Depth of table (when using CASCADE) */
} ecs_matched_table_t;
/** Base type for a system */
typedef struct EcsSystem {
ecs_system_action_t action; /* Callback to be invoked for matching rows */
const char *signature; /* Signature with which system was created */
ecs_vector_t *columns; /* Column components */
void *ctx; /* User data */
/* Precomputed types for quick comparisons */
ecs_type_t not_from_self; /* Exclude components from self */
ecs_type_t not_from_owned; /* Exclude components from self only if owned */
ecs_type_t not_from_shared; /* Exclude components from self only if shared */
ecs_type_t not_from_component; /* Exclude components from components */
ecs_type_t and_from_self; /* Which components are required from entity */
ecs_type_t and_from_owned; /* Which components are required from entity */
ecs_type_t and_from_shared; /* Which components are required from entity */
ecs_type_t and_from_system; /* Used to auto-add components to system */
int32_t cascade_by; /* CASCADE column index */
EcsSystemKind kind; /* Kind of system */
double time_spent; /* Time spent on running system */
bool enabled; /* Is system enabled or not */
bool has_refs; /* Does the system have reference columns */
bool needs_tables; /* Does the system need table matching */
bool match_prefab; /* Should this system match prefabs */
bool match_disabled; /* Should this system match disabled entities */
} EcsSystem;
/** A column system is a system that is ran periodically (default = every frame)
* on all entities that match the system signature expression. Column systems
* are prematched with tables (archetypes) that match the system signature
* expression. Each time a column system is invoked, it iterates over the
* matched list of tables (the 'tables' member).
*
* For each table, the system stores a list of the components that were matched
* with the system. This list may differ from the component list of the table,
* when OR expressions or optional expressions are used.
*
* A column system keeps track of tables that are empty. These tables are stored
* in the 'inactive_tables' array. This prevents the system from iterating over
* tables in the main loop that have no data.
*
* For each table, a column system stores an index that translates between the
* a column in the system signature, and the matched table. This information is
* stored, alongside with an index that identifies the table, in the 'tables'
* member. This is an array of an array of integers, per table.
*
* Additionally, the 'tables' member contains information on where a component
* should be fetched from. By default, components are fetched from an entity,
* but a system may specify that a component must be resolved from a container,
* or must be fetched from a prefab. In this case, the index to lookup a table
* column from system column contains a negative number, which identifies an
* element in the 'refs' array.
*
* The 'refs' array contains elements of type 'EcsRef', and stores references
* to external entities. References can vary per table, but not per entity/row,
* as prefabs / containers are part of the entity type, which in turn
* identifies the table in which the entity is stored.
*
* The 'period' and 'time_passed' members are used for periodic systems. An
* application may specify that a system should only run at a specific interval,
* like once per second. This interval is stored in the 'period' member. Each
* time the system is evaluated but not ran, the delta_time is added to the
* time_passed member, until it exceeds 'period'. In that case, the system is
* ran, and 'time_passed' is decreased by 'period'.
*/
typedef struct EcsColSystem {
EcsSystem base;
ecs_entity_t entity; /* Entity id of system, used for ordering */
ecs_vector_t *jobs; /* Jobs for this system */
ecs_vector_t *tables; /* Vector with matched tables */
ecs_vector_t *inactive_tables; /* Inactive tables */
ecs_vector_params_t column_params; /* Parameters for table_columns */
ecs_vector_params_t component_params; /* Parameters for components */
ecs_vector_params_t ref_params; /* Parameters for refs */
float period; /* Minimum period inbetween system invocations */
float time_passed; /* Time passed since last invocation */
} EcsColSystem;
/** A row system is a system that is ran on 1..n entities for which a certain
* operation has been invoked. The system kind determines on what kind of
* operation the row system is invoked. Example operations are ecs_add,
* ecs_remove and ecs_set. */
typedef struct EcsRowSystem {
EcsSystem base;
ecs_vector_t *components; /* Components in order of signature */
} EcsRowSystem;
/** The ecs_row_t struct is a 64-bit value that describes in which table
* (identified by a type) is stored, at which index. Entries in the
* world::entity_index are of type ecs_row_t. */
typedef struct ecs_row_t {
ecs_type_t type; /* Identifies a type (and table) in world */
int32_t index; /* Index of the entity in its table */
} ecs_row_t;
#define ECS_TYPE_DB_MAX_CHILD_NODES (256)
#define ECS_TYPE_DB_BUCKET_COUNT (256)
/** The ecs_type_node_t type is a node in a hierarchical structure that allows
* for quick lookups of types. A node represents a type, and its direct children
* represent types with one additional entity. For example, given a node [A],
* [A, B] would be a child node.
*
* Child nodes are looked up directly using the entity id. For example, node [A]
* will be stored at root.nodes[A]. Children entity ids are offset by their
* parent, such that [A, B] is stored at root.nodes[A].nodes[B - A].
*
* If the offset exceeds ECS_TYPE_DB_MAX_CHILD_NODES, the type will be stored in
* the types map. This map is keyed by the hash of the type relative to its
* parent. For example, the hash for type [A, B, C] will be computed on [B, C]
* if its parent is [A]. */
typedef struct ecs_type_link_t {
ecs_type_t type; /* type of current node */
struct ecs_type_link_t *next; /* next link (for iterating linearly) */
} ecs_type_link_t;
typedef struct ecs_type_node_t {
ecs_vector_t *nodes; /* child nodes - <ecs_entity_t, ecs_type_node_t> */
ecs_vector_t **types; /* child types w/large entity offsets - <hash, vector<ecs_type_link_t>> */
ecs_type_link_t link;
} ecs_type_node_t;
/** A stage is a data structure in which delta's are stored until it is safe to
* merge those delta's with the main world stage. A stage allows flecs systems
* to arbitrarily add/remove/set components and create/delete entities while
* iterating. Additionally, worker threads have their own stage that lets them
* mutate the state of entities without requiring locks. */
typedef struct ecs_stage_t {
/* If this is not main stage,
* changes to the entity index
* are buffered here */
ecs_map_t *entity_index; /* Entity lookup table for (table, row) */
/* If this is not a thread
* stage, these are the same
* as the main stage */
ecs_type_node_t type_root; /* Hierarchical type store (& first link) */
ecs_type_link_t *last_link; /* Link to last registered type */
ecs_chunked_t *tables; /* Tables created while >1 threads running */
ecs_map_t *table_index; /* Lookup table by type */
/* These occur only in
* temporary stages, and
* not on the main stage */
ecs_map_t *data_stage; /* Arrays with staged component values */
ecs_map_t *remove_merge; /* All removed components before merge */
/* Keep track of changes so
* code knows when entity
* info is invalidated */
uint32_t commit_count;
ecs_type_t from_type;
ecs_type_t to_type;
/* Is entity range checking enabled? */
bool range_check_enabled;
} ecs_stage_t;
/** Supporting type that internal functions pass around to ensure that data
* related to an entity is only looked up once. */
typedef struct ecs_entity_info_t {
ecs_entity_t entity;
ecs_type_t type;
int32_t index;
ecs_table_t *table;
ecs_table_column_t *columns;
bool is_watched;
/* Used for determining if ecs_entity_info_t should be invalidated */
ecs_stage_t *stage;
uint32_t commit_count;
} ecs_entity_info_t;
/** A type describing a unit of work to be executed by a worker thread. */
typedef struct ecs_job_t {
ecs_entity_t system; /* System handle */
EcsColSystem *system_data; /* System to run */
uint32_t offset; /* Start index in row chunk */
uint32_t limit; /* Total number of rows to process */
} ecs_job_t;
/** A type desribing a worker thread. When a system is invoked by a worker
* thread, it receives a pointer to an ecs_thread_t instead of a pointer to an
* ecs_world_t (provided by the ecs_rows_t type). When this ecs_thread_t is passed down
* into the flecs API, the API functions are able to tell whether this is an
* ecs_thread_t or an ecs_world_t by looking at the 'magic' number. This allows the
* API to transparently resolve the stage to which updates should be written,
* without requiring different API calls when working in multi threaded mode. */
typedef struct ecs_thread_t {
uint32_t magic; /* Magic number to verify thread pointer */
uint32_t job_count; /* Number of jobs scheduled for thread */
ecs_world_t *world; /* Reference to world */
ecs_job_t *jobs[ECS_MAX_JOBS_PER_WORKER]; /* Array with jobs */
ecs_stage_t *stage; /* Stage for thread */
ecs_os_thread_t thread; /* Thread handle */
uint16_t index; /* Index of thread */
} ecs_thread_t;
/** The world stores and manages all ECS data. An application can have more than
* one world, but data is not shared between worlds. */
struct ecs_world {
uint32_t magic; /* Magic number to verify world pointer */
float delta_time; /* Time passed to or computed by ecs_progress */
void *context; /* Application context */
/* -- Column systems -- */
ecs_vector_t *on_load_systems;
ecs_vector_t *post_load_systems;
ecs_vector_t *pre_update_systems;
ecs_vector_t *on_update_systems;
ecs_vector_t *on_validate_systems;
ecs_vector_t *post_update_systems;
ecs_vector_t *pre_store_systems;
ecs_vector_t *on_store_systems;
ecs_vector_t *on_demand_systems;
ecs_vector_t *inactive_systems;
/* -- Row systems -- */
ecs_vector_t *add_systems; /* Systems invoked on ecs_stage_add */
ecs_vector_t *remove_systems; /* Systems invoked on ecs_stage_remove */
ecs_vector_t *set_systems; /* Systems invoked on ecs_set */
/* -- Tasks -- */
ecs_vector_t *fini_tasks; /* Tasks to execute on ecs_fini */
/* -- Lookup Indices -- */
ecs_map_t *prefab_parent_index; /* Index to find flag for prefab parent */
ecs_map_t *type_sys_add_index; /* Index to find add row systems for type */
ecs_map_t *type_sys_remove_index; /* Index to find remove row systems for type*/
ecs_map_t *type_sys_set_index; /* Index to find set row systems for type */
ecs_map_t *type_handles; /* Handles to named families */
/* -- Staging -- */
ecs_stage_t main_stage; /* Main storage */
ecs_stage_t temp_stage; /* Stage for when processing systems */
ecs_vector_t *worker_stages; /* Stages for worker threads */
/* -- Multithreading -- */
ecs_vector_t *worker_threads; /* Worker threads */
ecs_os_cond_t thread_cond; /* Signal that worker threads can start */
ecs_os_mutex_t thread_mutex; /* Mutex for thread condition */
ecs_os_cond_t job_cond; /* Signal that worker thread job is done */
ecs_os_mutex_t job_mutex; /* Mutex for protecting job counter */
uint32_t jobs_finished; /* Number of jobs finished */
uint32_t threads_running; /* Number of threads running */
ecs_entity_t last_handle; /* Last issued handle */
ecs_entity_t min_handle; /* First allowed handle */
ecs_entity_t max_handle; /* Last allowed handle */
/* -- Handles to builtin components families -- */
ecs_type_t t_component;
ecs_type_t t_type;
ecs_type_t t_prefab;
ecs_type_t t_row_system;
ecs_type_t t_col_system;
ecs_type_t t_builtins;
/* -- Time management -- */
uint32_t tick; /* Number of computed frames by world */
ecs_time_t frame_start; /* Starting timestamp of frame */
float frame_time; /* Time spent processing a frame */
float system_time; /* Time spent processing systems */
float merge_time; /* Time spent on merging */
float target_fps; /* Target fps */
float fps_sleep; /* Sleep time to prevent fps overshoot */
float world_time; /* Time since start of simulation */
/* -- Settings from command line arguments -- */
int arg_fps;
int arg_threads;
/* -- World state -- */
bool valid_schedule; /* Is job schedule still valid */
bool quit_workers; /* Signals worker threads to quit */
bool in_progress; /* Is world being progressed */
bool is_merging; /* Is world currently being merged */
bool auto_merge; /* Are stages auto-merged by ecs_progress */
bool measure_frame_time; /* Time spent on each frame */
bool measure_system_time; /* Time spent by each system */
bool should_quit; /* Did a system signal that app should quit */
bool should_match; /* Should tablea be rematched */
bool should_resolve; /* If a table reallocd, resolve system refs */
};
/* Parameters for various array types */
extern const ecs_vector_params_t handle_arr_params;
extern const ecs_vector_params_t stage_arr_params;
extern const ecs_vector_params_t table_arr_params;
extern const ecs_vector_params_t thread_arr_params;
extern const ecs_vector_params_t job_arr_params;
extern const ecs_vector_params_t builder_params;
extern const ecs_vector_params_t system_column_params;
extern const ecs_vector_params_t matched_table_params;
extern const ecs_vector_params_t matched_column_params;
extern const ecs_vector_params_t reference_params;
#endif
| 44.319502 | 102 | 0.690572 | [
"vector"
] |
235c7e5a081ea570fc784892b899aa29c03398c5 | 9,342 | c | C | 3party/gtk+-3.12.1/gtk/gtkcolorchooserdialog.c | kongaraju/antkorp | 3453d543d659e3420d5bc4b536016bb1d097d7ec | [
"CC-BY-3.0",
"Apache-2.0"
] | 1 | 2016-01-02T14:39:07.000Z | 2016-01-02T14:39:07.000Z | 3party/gtk+-3.12.1/gtk/gtkcolorchooserdialog.c | kongaraju/antkorp | 3453d543d659e3420d5bc4b536016bb1d097d7ec | [
"CC-BY-3.0",
"Apache-2.0"
] | 4 | 2019-12-20T06:13:24.000Z | 2021-07-03T16:28:18.000Z | 3party/gtk+-3.12.1/gtk/gtkcolorchooserdialog.c | kongaraju/antkorp | 3453d543d659e3420d5bc4b536016bb1d097d7ec | [
"CC-BY-3.0",
"Apache-2.0"
] | 2 | 2015-09-17T16:40:10.000Z | 2016-11-17T15:56:42.000Z | /* GTK - The GIMP Toolkit
* Copyright (C) 2012 Red Hat, Inc.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library. If not, see <http://www.gnu.org/licenses/>.
*/
#include "config.h"
#include "gtkdialog.h"
#include "gtkdialogprivate.h"
#include "gtkbutton.h"
#include "gtkbox.h"
#include "gtkprivate.h"
#include "gtkintl.h"
#include "gtksettings.h"
#include "gtkcolorchooserprivate.h"
#include "gtkcolorchooserdialog.h"
#include "gtkcolorchooserwidget.h"
/**
* SECTION:gtkcolorchooserdialog
* @Short_description: A dialog for choosing colors
* @Title: GtkColorChooserDialog
* @See_also: #GtkColorChooser, #GtkDialog
*
* The #GtkColorChooserDialog widget is a dialog for choosing
* a color. It implements the #GtkColorChooser interface.
*
* Since: 3.4
*/
struct _GtkColorChooserDialogPrivate
{
GtkWidget *chooser;
};
enum
{
PROP_ZERO,
PROP_RGBA,
PROP_USE_ALPHA,
PROP_SHOW_EDITOR
};
static void gtk_color_chooser_dialog_iface_init (GtkColorChooserInterface *iface);
G_DEFINE_TYPE_WITH_CODE (GtkColorChooserDialog, gtk_color_chooser_dialog, GTK_TYPE_DIALOG,
G_ADD_PRIVATE (GtkColorChooserDialog)
G_IMPLEMENT_INTERFACE (GTK_TYPE_COLOR_CHOOSER,
gtk_color_chooser_dialog_iface_init))
static void
propagate_notify (GObject *o,
GParamSpec *pspec,
GtkColorChooserDialog *cc)
{
g_object_notify (G_OBJECT (cc), pspec->name);
}
static void
save_color (GtkColorChooserDialog *dialog)
{
GdkRGBA color;
/* This causes the color chooser widget to save the
* selected and custom colors to GSettings.
*/
gtk_color_chooser_get_rgba (GTK_COLOR_CHOOSER (dialog), &color);
gtk_color_chooser_set_rgba (GTK_COLOR_CHOOSER (dialog), &color);
}
static void
color_activated_cb (GtkColorChooser *chooser,
GdkRGBA *color,
GtkDialog *dialog)
{
save_color (GTK_COLOR_CHOOSER_DIALOG (dialog));
gtk_dialog_response (dialog, GTK_RESPONSE_OK);
}
static void
gtk_color_chooser_dialog_response (GtkDialog *dialog,
gint response_id,
gpointer user_data)
{
if (response_id == GTK_RESPONSE_OK)
save_color (GTK_COLOR_CHOOSER_DIALOG (dialog));
}
static void
gtk_color_chooser_dialog_init (GtkColorChooserDialog *cc)
{
cc->priv = gtk_color_chooser_dialog_get_instance_private (cc);
gtk_widget_init_template (GTK_WIDGET (cc));
gtk_dialog_set_use_header_bar_from_setting (GTK_DIALOG (cc));
gtk_dialog_add_buttons (GTK_DIALOG (cc),
_("_Cancel"), GTK_RESPONSE_CANCEL,
_("_Select"), GTK_RESPONSE_OK,
NULL);
gtk_dialog_set_default_response (GTK_DIALOG (cc), GTK_RESPONSE_OK);
G_GNUC_BEGIN_IGNORE_DEPRECATIONS
gtk_dialog_set_alternative_button_order (GTK_DIALOG (cc),
GTK_RESPONSE_OK,
GTK_RESPONSE_CANCEL,
-1);
G_GNUC_END_IGNORE_DEPRECATIONS
g_signal_connect (cc, "response",
G_CALLBACK (gtk_color_chooser_dialog_response), NULL);
}
static void
gtk_color_chooser_dialog_map (GtkWidget *widget)
{
/* We never want the dialog to come up with the editor,
* even if it was showing the editor the last time it was used.
*/
g_object_set (GTK_COLOR_CHOOSER_DIALOG (widget)->priv->chooser,
"show-editor", FALSE, NULL);
GTK_WIDGET_CLASS (gtk_color_chooser_dialog_parent_class)->map (widget);
}
static void
gtk_color_chooser_dialog_get_property (GObject *object,
guint prop_id,
GValue *value,
GParamSpec *pspec)
{
GtkColorChooserDialog *cd = GTK_COLOR_CHOOSER_DIALOG (object);
GtkColorChooser *cc = GTK_COLOR_CHOOSER (object);
switch (prop_id)
{
case PROP_RGBA:
{
GdkRGBA color;
gtk_color_chooser_get_rgba (cc, &color);
g_value_set_boxed (value, &color);
}
break;
case PROP_USE_ALPHA:
g_value_set_boolean (value, gtk_color_chooser_get_use_alpha (GTK_COLOR_CHOOSER (cd->priv->chooser)));
break;
case PROP_SHOW_EDITOR:
{
gboolean show_editor;
g_object_get (cd->priv->chooser, "show-editor", &show_editor, NULL);
g_value_set_boolean (value, show_editor);
}
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
break;
}
}
static void
gtk_color_chooser_dialog_set_property (GObject *object,
guint prop_id,
const GValue *value,
GParamSpec *pspec)
{
GtkColorChooserDialog *cd = GTK_COLOR_CHOOSER_DIALOG (object);
GtkColorChooser *cc = GTK_COLOR_CHOOSER (object);
switch (prop_id)
{
case PROP_RGBA:
gtk_color_chooser_set_rgba (cc, g_value_get_boxed (value));
break;
case PROP_USE_ALPHA:
gtk_color_chooser_set_use_alpha (GTK_COLOR_CHOOSER (cd->priv->chooser), g_value_get_boolean (value));
break;
case PROP_SHOW_EDITOR:
g_object_set (cd->priv->chooser,
"show-editor", g_value_get_boolean (value),
NULL);
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
break;
}
}
static void
gtk_color_chooser_dialog_class_init (GtkColorChooserDialogClass *class)
{
GObjectClass *object_class = G_OBJECT_CLASS (class);
GtkWidgetClass *widget_class = GTK_WIDGET_CLASS (class);
object_class->get_property = gtk_color_chooser_dialog_get_property;
object_class->set_property = gtk_color_chooser_dialog_set_property;
widget_class->map = gtk_color_chooser_dialog_map;
g_object_class_override_property (object_class, PROP_RGBA, "rgba");
g_object_class_override_property (object_class, PROP_USE_ALPHA, "use-alpha");
g_object_class_install_property (object_class, PROP_SHOW_EDITOR,
g_param_spec_boolean ("show-editor", P_("Show editor"), P_("Show editor"),
FALSE, GTK_PARAM_READWRITE));
/* Bind class to template
*/
gtk_widget_class_set_template_from_resource (widget_class,
"/org/gtk/libgtk/ui/gtkcolorchooserdialog.ui");
gtk_widget_class_bind_template_child_private (widget_class, GtkColorChooserDialog, chooser);
gtk_widget_class_bind_template_callback (widget_class, propagate_notify);
gtk_widget_class_bind_template_callback (widget_class, color_activated_cb);
}
static void
gtk_color_chooser_dialog_get_rgba (GtkColorChooser *chooser,
GdkRGBA *color)
{
GtkColorChooserDialog *cc = GTK_COLOR_CHOOSER_DIALOG (chooser);
gtk_color_chooser_get_rgba (GTK_COLOR_CHOOSER (cc->priv->chooser), color);
}
static void
gtk_color_chooser_dialog_set_rgba (GtkColorChooser *chooser,
const GdkRGBA *color)
{
GtkColorChooserDialog *cc = GTK_COLOR_CHOOSER_DIALOG (chooser);
gtk_color_chooser_set_rgba (GTK_COLOR_CHOOSER (cc->priv->chooser), color);
}
static void
gtk_color_chooser_dialog_add_palette (GtkColorChooser *chooser,
GtkOrientation orientation,
gint colors_per_line,
gint n_colors,
GdkRGBA *colors)
{
GtkColorChooserDialog *cc = GTK_COLOR_CHOOSER_DIALOG (chooser);
gtk_color_chooser_add_palette (GTK_COLOR_CHOOSER (cc->priv->chooser),
orientation, colors_per_line, n_colors, colors);
}
static void
gtk_color_chooser_dialog_iface_init (GtkColorChooserInterface *iface)
{
iface->get_rgba = gtk_color_chooser_dialog_get_rgba;
iface->set_rgba = gtk_color_chooser_dialog_set_rgba;
iface->add_palette = gtk_color_chooser_dialog_add_palette;
}
/**
* gtk_color_chooser_dialog_new:
* @title: (allow-none): Title of the dialog, or %NULL
* @parent: (allow-none): Transient parent of the dialog, or %NULL
*
* Creates a new #GtkColorChooserDialog.
*
* Returns: a new #GtkColorChooserDialog
*
* Since: 3.4
*/
GtkWidget *
gtk_color_chooser_dialog_new (const gchar *title,
GtkWindow *parent)
{
GtkColorChooserDialog *dialog;
dialog = g_object_new (GTK_TYPE_COLOR_CHOOSER_DIALOG,
"title", title,
"transient-for", parent,
NULL);
return GTK_WIDGET (dialog);
}
| 32.213793 | 107 | 0.664312 | [
"object"
] |
2360beafd9bb4ef866435e985897701301f7f561 | 6,788 | h | C | tiems/include/tencentcloud/tiems/v20190416/model/PredictInput.h | li5ch/tencentcloud-sdk-cpp | 12ebfd75a399ee2791f6ac1220a79ce8a9faf7c4 | [
"Apache-2.0"
] | 43 | 2019-08-14T08:14:12.000Z | 2022-03-30T12:35:09.000Z | tiems/include/tencentcloud/tiems/v20190416/model/PredictInput.h | li5ch/tencentcloud-sdk-cpp | 12ebfd75a399ee2791f6ac1220a79ce8a9faf7c4 | [
"Apache-2.0"
] | 12 | 2019-07-15T10:44:59.000Z | 2021-11-02T12:35:00.000Z | tiems/include/tencentcloud/tiems/v20190416/model/PredictInput.h | li5ch/tencentcloud-sdk-cpp | 12ebfd75a399ee2791f6ac1220a79ce8a9faf7c4 | [
"Apache-2.0"
] | 28 | 2019-07-12T09:06:22.000Z | 2022-03-30T08:04:18.000Z | /*
* Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. 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 TENCENTCLOUD_TIEMS_V20190416_MODEL_PREDICTINPUT_H_
#define TENCENTCLOUD_TIEMS_V20190416_MODEL_PREDICTINPUT_H_
#include <string>
#include <vector>
#include <map>
#include <tencentcloud/core/utils/rapidjson/document.h>
#include <tencentcloud/core/utils/rapidjson/writer.h>
#include <tencentcloud/core/utils/rapidjson/stringbuffer.h>
#include <tencentcloud/core/AbstractModel.h>
namespace TencentCloud
{
namespace Tiems
{
namespace V20190416
{
namespace Model
{
/**
* 预测输入
*/
class PredictInput : public AbstractModel
{
public:
PredictInput();
~PredictInput() = default;
void ToJsonObject(rapidjson::Value &value, rapidjson::Document::AllocatorType& allocator) const;
CoreInternalOutcome Deserialize(const rapidjson::Value &value);
/**
* 获取输入路径,支持 cos 格式路径文件夹或文件
* @return InputPath 输入路径,支持 cos 格式路径文件夹或文件
*/
std::string GetInputPath() const;
/**
* 设置输入路径,支持 cos 格式路径文件夹或文件
* @param InputPath 输入路径,支持 cos 格式路径文件夹或文件
*/
void SetInputPath(const std::string& _inputPath);
/**
* 判断参数 InputPath 是否已赋值
* @return InputPath 是否已赋值
*/
bool InputPathHasBeenSet() const;
/**
* 获取输出路径,支持 cos 格式路径
* @return OutputPath 输出路径,支持 cos 格式路径
*/
std::string GetOutputPath() const;
/**
* 设置输出路径,支持 cos 格式路径
* @param OutputPath 输出路径,支持 cos 格式路径
*/
void SetOutputPath(const std::string& _outputPath);
/**
* 判断参数 OutputPath 是否已赋值
* @return OutputPath 是否已赋值
*/
bool OutputPathHasBeenSet() const;
/**
* 获取输入数据格式,目前支持:JSON
* @return InputDataFormat 输入数据格式,目前支持:JSON
*/
std::string GetInputDataFormat() const;
/**
* 设置输入数据格式,目前支持:JSON
* @param InputDataFormat 输入数据格式,目前支持:JSON
*/
void SetInputDataFormat(const std::string& _inputDataFormat);
/**
* 判断参数 InputDataFormat 是否已赋值
* @return InputDataFormat 是否已赋值
*/
bool InputDataFormatHasBeenSet() const;
/**
* 获取输出数据格式,目前支持:JSON
* @return OutputDataFormat 输出数据格式,目前支持:JSON
*/
std::string GetOutputDataFormat() const;
/**
* 设置输出数据格式,目前支持:JSON
* @param OutputDataFormat 输出数据格式,目前支持:JSON
*/
void SetOutputDataFormat(const std::string& _outputDataFormat);
/**
* 判断参数 OutputDataFormat 是否已赋值
* @return OutputDataFormat 是否已赋值
*/
bool OutputDataFormatHasBeenSet() const;
/**
* 获取预测批大小,默认为 64
* @return BatchSize 预测批大小,默认为 64
*/
uint64_t GetBatchSize() const;
/**
* 设置预测批大小,默认为 64
* @param BatchSize 预测批大小,默认为 64
*/
void SetBatchSize(const uint64_t& _batchSize);
/**
* 判断参数 BatchSize 是否已赋值
* @return BatchSize 是否已赋值
*/
bool BatchSizeHasBeenSet() const;
/**
* 获取模型签名
注意:此字段可能返回 null,表示取不到有效值。
* @return SignatureName 模型签名
注意:此字段可能返回 null,表示取不到有效值。
*/
std::string GetSignatureName() const;
/**
* 设置模型签名
注意:此字段可能返回 null,表示取不到有效值。
* @param SignatureName 模型签名
注意:此字段可能返回 null,表示取不到有效值。
*/
void SetSignatureName(const std::string& _signatureName);
/**
* 判断参数 SignatureName 是否已赋值
* @return SignatureName 是否已赋值
*/
bool SignatureNameHasBeenSet() const;
private:
/**
* 输入路径,支持 cos 格式路径文件夹或文件
*/
std::string m_inputPath;
bool m_inputPathHasBeenSet;
/**
* 输出路径,支持 cos 格式路径
*/
std::string m_outputPath;
bool m_outputPathHasBeenSet;
/**
* 输入数据格式,目前支持:JSON
*/
std::string m_inputDataFormat;
bool m_inputDataFormatHasBeenSet;
/**
* 输出数据格式,目前支持:JSON
*/
std::string m_outputDataFormat;
bool m_outputDataFormatHasBeenSet;
/**
* 预测批大小,默认为 64
*/
uint64_t m_batchSize;
bool m_batchSizeHasBeenSet;
/**
* 模型签名
注意:此字段可能返回 null,表示取不到有效值。
*/
std::string m_signatureName;
bool m_signatureNameHasBeenSet;
};
}
}
}
}
#endif // !TENCENTCLOUD_TIEMS_V20190416_MODEL_PREDICTINPUT_H_
| 32.792271 | 116 | 0.450059 | [
"vector",
"model"
] |
23689476b491329d4c7fda370aceee46131ab6cc | 703 | h | C | weightedgraph.h | dezelin/algo | 359d1db863e0613ff212f77f72b5437bd656efe3 | [
"BSD-3-Clause"
] | null | null | null | weightedgraph.h | dezelin/algo | 359d1db863e0613ff212f77f72b5437bd656efe3 | [
"BSD-3-Clause"
] | null | null | null | weightedgraph.h | dezelin/algo | 359d1db863e0613ff212f77f72b5437bd656efe3 | [
"BSD-3-Clause"
] | null | null | null | #ifndef GRAPH_H
#define GRAPH_H
#include <vector>
class WeightedGraph
{
public:
typedef std::pair<int, double> Edge;
typedef std::vector<int> VerticesList;
typedef std::vector<Edge> AdjacencyList;
typedef std::vector<AdjacencyList> EdgesList;
public:
WeightedGraph(const EdgesList& edges);
void Add(int v, const AdjacencyList& adj);
const AdjacencyList& Adj(int v) const;
VerticesList DfsPreOrder(int src) const;
VerticesList DfsPreOrderRec(int src) const;
VerticesList DijkstraShortP(int src, int dest) const;
private:
VerticesList DfsPreOrderRecHelper(int src, std::vector<bool>& color) const;
private:
EdgesList _vertices;
};
#endif // GRAPH_H
| 21.96875 | 79 | 0.728307 | [
"vector"
] |
236d2ad3c1c00ace85be237c81c06a8861dcd226 | 8,916 | h | C | local_addons/ofxFaceTracker2/libs/dlib/include/dlib/svm/rvm_abstract.h | yxcde/RTP_MIT_RECODED | 181deb2e3228484fa9d4ed0e6bf3f4a639d99419 | [
"MIT"
] | 11,719 | 2015-01-03T22:38:57.000Z | 2022-03-30T21:45:04.000Z | local_addons/ofxFaceTracker2/libs/dlib/include/dlib/svm/rvm_abstract.h | yxcde/RTP_MIT_RECODED | 181deb2e3228484fa9d4ed0e6bf3f4a639d99419 | [
"MIT"
] | 2,518 | 2015-01-04T04:38:06.000Z | 2022-03-31T11:55:43.000Z | local_addons/ofxFaceTracker2/libs/dlib/include/dlib/svm/rvm_abstract.h | yxcde/RTP_MIT_RECODED | 181deb2e3228484fa9d4ed0e6bf3f4a639d99419 | [
"MIT"
] | 3,308 | 2015-01-01T14:34:16.000Z | 2022-03-31T07:20:07.000Z | // Copyright (C) 2008 Davis E. King (davis@dlib.net)
// License: Boost Software License See LICENSE.txt for the full license.
#undef DLIB_RVm_ABSTRACT_
#ifdef DLIB_RVm_ABSTRACT_
#include <cmath>
#include <limits>
#include "../matrix.h"
#include "../algs.h"
#include "function.h"
#include "kernel.h"
namespace dlib
{
// ----------------------------------------------------------------------------------------
template <
typename kern_type
>
class rvm_trainer
{
/*!
REQUIREMENTS ON kern_type
is a kernel function object as defined in dlib/svm/kernel_abstract.h
WHAT THIS OBJECT REPRESENTS
This object implements a trainer for a relevance vector machine for
solving binary classification problems.
The implementation of the RVM training algorithm used by this object is based
on the following excellent paper:
Tipping, M. E. and A. C. Faul (2003). Fast marginal likelihood maximisation
for sparse Bayesian models. In C. M. Bishop and B. J. Frey (Eds.), Proceedings
of the Ninth International Workshop on Artificial Intelligence and Statistics,
Key West, FL, Jan 3-6.
!*/
public:
typedef kern_type kernel_type;
typedef typename kernel_type::scalar_type scalar_type;
typedef typename kernel_type::sample_type sample_type;
typedef typename kernel_type::mem_manager_type mem_manager_type;
typedef decision_function<kernel_type> trained_function_type;
rvm_trainer (
);
/*!
ensures
- This object is properly initialized and ready to be used
to train a relevance vector machine.
- #get_epsilon() == 0.001
- #get_max_iterations() == 2000
!*/
void set_epsilon (
scalar_type eps
);
/*!
requires
- eps > 0
ensures
- #get_epsilon() == eps
!*/
const scalar_type get_epsilon (
) const;
/*!
ensures
- returns the error epsilon that determines when training should stop.
Generally a good value for this is 0.001. Smaller values may result
in a more accurate solution but take longer to execute.
!*/
void set_kernel (
const kernel_type& k
);
/*!
ensures
- #get_kernel() == k
!*/
const kernel_type& get_kernel (
) const;
/*!
ensures
- returns a copy of the kernel function in use by this object
!*/
unsigned long get_max_iterations (
) const;
/*!
ensures
- returns the maximum number of iterations the RVM optimizer is allowed to
run before it is required to stop and return a result.
!*/
void set_max_iterations (
unsigned long max_iter
);
/*!
ensures
- #get_max_iterations() == max_iter
!*/
template <
typename in_sample_vector_type,
typename in_scalar_vector_type
>
const decision_function<kernel_type> train (
const in_sample_vector_type& x,
const in_scalar_vector_type& y
) const;
/*!
requires
- is_binary_classification_problem(x,y) == true
- x == a matrix or something convertible to a matrix via mat().
Also, x should contain sample_type objects.
- y == a matrix or something convertible to a matrix via mat().
Also, y should contain scalar_type objects.
ensures
- trains a relevance vector classifier given the training samples in x and
labels in y.
- returns a decision function F with the following properties:
- if (new_x is a sample predicted have +1 label) then
- F(new_x) >= 0
- else
- F(new_x) < 0
throws
- std::bad_alloc
!*/
void swap (
rvm_trainer& item
);
/*!
ensures
- swaps *this and item
!*/
};
// ----------------------------------------------------------------------------------------
template <typename K>
void swap (
rvm_trainer<K>& a,
rvm_trainer<K>& b
) { a.swap(b); }
/*!
provides a global swap
!*/
// ----------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------
template <
typename kern_type
>
class rvm_regression_trainer
{
/*!
REQUIREMENTS ON kern_type
is a kernel function object as defined in dlib/svm/kernel_abstract.h
WHAT THIS OBJECT REPRESENTS
This object implements a trainer for a relevance vector machine for
solving regression problems.
The implementation of the RVM training algorithm used by this object is based
on the following excellent paper:
Tipping, M. E. and A. C. Faul (2003). Fast marginal likelihood maximisation
for sparse Bayesian models. In C. M. Bishop and B. J. Frey (Eds.), Proceedings
of the Ninth International Workshop on Artificial Intelligence and Statistics,
Key West, FL, Jan 3-6.
!*/
public:
typedef kern_type kernel_type;
typedef typename kernel_type::scalar_type scalar_type;
typedef typename kernel_type::sample_type sample_type;
typedef typename kernel_type::mem_manager_type mem_manager_type;
typedef decision_function<kernel_type> trained_function_type;
rvm_regression_trainer (
);
/*!
ensures
- This object is properly initialized and ready to be used
to train a relevance vector machine.
- #get_epsilon() == 0.001
!*/
void set_epsilon (
scalar_type eps
);
/*!
requires
- eps > 0
ensures
- #get_epsilon() == eps
!*/
const scalar_type get_epsilon (
) const;
/*!
ensures
- returns the error epsilon that determines when training should stop.
Generally a good value for this is 0.001. Smaller values may result
in a more accurate solution but take longer to execute.
!*/
void set_kernel (
const kernel_type& k
);
/*!
ensures
- #get_kernel() == k
!*/
const kernel_type& get_kernel (
) const;
/*!
ensures
- returns a copy of the kernel function in use by this object
!*/
template <
typename in_sample_vector_type,
typename in_scalar_vector_type
>
const decision_function<kernel_type> train (
const in_sample_vector_type& x,
const in_scalar_vector_type& y
) const;
/*!
requires
- x == a matrix or something convertible to a matrix via mat().
Also, x should contain sample_type objects.
- y == a matrix or something convertible to a matrix via mat().
Also, y should contain scalar_type objects.
- is_learning_problem(x,y) == true
- x.size() > 0
ensures
- trains a RVM given the training samples in x and
labels in y and returns the resulting decision_function.
throws
- std::bad_alloc
!*/
void swap (
rvm_regression_trainer& item
);
/*!
ensures
- swaps *this and item
!*/
};
// ----------------------------------------------------------------------------------------
template <typename K>
void swap (
rvm_regression_trainer<K>& a,
rvm_regression_trainer<K>& b
) { a.swap(b); }
/*!
provides a global swap
!*/
// ----------------------------------------------------------------------------------------
}
#endif // DLIB_RVm_ABSTRACT_
| 31.956989 | 99 | 0.491027 | [
"object",
"vector"
] |
d6be2aa3691972a21ea936fae179f1c892d66208 | 8,021 | h | C | netbsd/sys/arch/news68k/include/cpu.h | MarginC/kame | 2ef74fe29e4cca9b4a87a1d5041191a9e2e8be30 | [
"BSD-3-Clause"
] | 91 | 2015-01-05T15:18:31.000Z | 2022-03-11T16:43:28.000Z | netbsd/sys/arch/news68k/include/cpu.h | MarginC/kame | 2ef74fe29e4cca9b4a87a1d5041191a9e2e8be30 | [
"BSD-3-Clause"
] | 1 | 2016-02-25T15:57:55.000Z | 2016-02-25T16:01:02.000Z | netbsd/sys/arch/news68k/include/cpu.h | MarginC/kame | 2ef74fe29e4cca9b4a87a1d5041191a9e2e8be30 | [
"BSD-3-Clause"
] | 21 | 2015-02-07T08:23:07.000Z | 2021-12-14T06:01:49.000Z | /* $NetBSD: cpu.h,v 1.4 2000/05/26 21:20:00 thorpej Exp $ */
/*
* Copyright (c) 1988 University of Utah.
* Copyright (c) 1982, 1990, 1993
* The Regents of the University of California. All rights reserved.
*
* This code is derived from software contributed to Berkeley by
* the Systems Programming Group of the University of Utah Computer
* Science Department.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by the University of
* California, Berkeley and its contributors.
* 4. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* from: Utah $Hdr: cpu.h 1.16 91/03/25$
*
* @(#)cpu.h 8.4 (Berkeley) 1/5/94
*/
#ifndef _NEWS68K_CPU_H_
#define _NEWS68K_CPU_H_
/*
* Exported definitions unique to news68k cpu support.
*/
#if defined(_KERNEL) && !defined(_LKM)
#include "opt_lockdebug.h"
#endif
/*
* Get common m68k CPU definitions.
*/
#include <m68k/cpu.h>
#ifdef news1700
/*
* XXX news1700 L2 cache would be corrupted with DC_BE and IC_BE...
* XXX Should these be defined in machine/cpu.h?
*/
#undef CACHE_ON
#undef CACHE_CLR
#undef IC_CLEAR
#undef DC_CLEAR
#define CACHE_ON (DC_WA|DC_CLR|DC_ENABLE|IC_CLR|IC_ENABLE)
#define CACHE_CLR CACHE_ON
#define IC_CLEAR (DC_WA|DC_ENABLE|IC_CLR|IC_ENABLE)
#define DC_CLEAR (DC_WA|DC_CLR|DC_ENABLE|IC_ENABLE)
#endif
/*
* Get interrupt glue.
*/
#include <machine/intr.h>
#include <sys/sched.h>
struct cpu_info {
struct schedstate_percpu ci_schedstate; /* scheduler state */
#if defined(DIAGNOSTIC) || defined(LOCKDEBUG)
u_long ci_spin_locks; /* # of spin locks held */
u_long ci_simple_locks; /* # of simple locks held */
#endif
};
#ifdef _KERNEL
extern struct cpu_info cpu_info_store;
#define curcpu() (&cpu_info_store)
/*
* definitions of cpu-dependent requirements
* referenced in generic code
*/
#define cpu_swapin(p) /* nothing */
#define cpu_wait(p) /* nothing */
#define cpu_swapout(p) /* nothing */
#define cpu_number() 0
/*
* Arguments to hardclock and gatherstats encapsulate the previous
* machine state in an opaque clockframe. One the hp300, we use
* what the hardware pushes on an interrupt (frame format 0).
*/
struct clockframe {
u_short sr; /* sr at time of interrupt */
u_long pc; /* pc at time of interrupt */
u_short vo; /* vector offset (4-word frame) */
};
#define CLKF_USERMODE(framep) (((framep)->sr & PSL_S) == 0)
#define CLKF_BASEPRI(framep) (((framep)->sr & PSL_IPL) == 0)
#define CLKF_PC(framep) ((framep)->pc)
#if 0
/* We would like to do it this way... */
#define CLKF_INTR(framep) (((framep)->sr & PSL_M) == 0)
#else
/* but until we start using PSL_M, we have to do this instead */
#define CLKF_INTR(framep) (0) /* XXX */
#endif
/*
* Preempt the current process if in interrupt from user mode,
* or after the current trap/syscall if in system mode.
*/
extern int want_resched; /* resched() was called */
#define need_resched() do { want_resched++; aston(); } while(0)
/*
* Give a profiling tick to the current process when the user profiling
* buffer pages are invalid. On the hp300, request an ast to send us
* through trap, marking the proc as needing a profiling tick.
*/
#define need_proftick(p) do { (p)->p_flag |= P_OWEUPC; aston(); } while(0)
/*
* Notify the current process (p) that it has a signal pending,
* process as soon as possible.
*/
#define signotify(p) aston()
extern int astpending; /* need to trap before returning to user mode */
extern volatile u_char *ctrl_ast;
#define aston() do { astpending++; *ctrl_ast = 0xff; } while(0)
#endif /* _KERNEL */
/*
* CTL_MACHDEP definitions.
*/
#define CPU_CONSDEV 1 /* dev_t: console terminal device */
#define CPU_MAXID 2 /* number of valid machdep ids */
#define CTL_MACHDEP_NAMES { \
{ 0, 0 }, \
{ "console_device", CTLTYPE_STRUCT }, \
}
#ifdef _KERNEL
#if defined(news1700) || defined(news1200)
#ifndef M68030
#define M68030
#endif
#define M68K_MMU_MOTOROLA
#endif
#if defined(news1700)
#define CACHE_HAVE_PAC
#endif
#endif
#ifdef _KERNEL
extern int systype;
#define NEWS1700 0
#define NEWS1200 1
extern int cpuspeed;
extern char *intiobase, *intiolimit;
extern u_int intiobase_phys, intiotop_phys;
extern u_int extiobase_phys, extiotop_phys;
extern u_int intrcnt[];
extern void (*vectab[]) __P((void));
struct frame;
struct fpframe;
struct pcb;
/* locore.s functions */
void m68881_save __P((struct fpframe *));
void m68881_restore __P((struct fpframe *));
void DCIA __P((void));
void DCIS __P((void));
void DCIU __P((void));
void ICIA __P((void));
void ICPA __P((void));
void PCIA __P((void));
void TBIA __P((void));
void TBIS __P((vaddr_t));
void TBIAS __P((void));
void TBIAU __P((void));
int suline __P((caddr_t, caddr_t));
void savectx __P((struct pcb *));
void switch_exit __P((struct proc *));
void proc_trampoline __P((void));
void loadustp __P((int));
void badtrap __P((void));
void intrhand_vectored __P((void));
int getsr __P((void));
void doboot __P((int))
__attribute__((__noreturn__));
void nmihand __P((struct frame *));
void ecacheon __P((void));
void ecacheoff __P((void));
/* machdep.c functions */
int badaddr __P((caddr_t, int));
int badbaddr __P((caddr_t));
/* sys_machdep.c functions */
int cachectl1 __P((unsigned long, vaddr_t, size_t, struct proc *));
/* vm_machdep.c functions */
void physaccess __P((caddr_t, caddr_t, int, int));
void physunaccess __P((caddr_t, int));
int kvtop __P((caddr_t));
/* trap.c functions */
void child_return __P((void *));
#endif
/* physical memory sections */
#define ROMBASE (0xe0000000)
#define INTIOBASE1700 (0xe0c00000)
#define INTIOTOP1700 (0xe1d00000) /* XXX */
#define EXTIOBASE1700 (0xf0f00000)
#define EXTIOTOP1700 (0xf1000000) /* XXX */
#define INTIOBASE1200 (0xe1000000)
#define INTIOTOP1200 (0xe1d00000) /* XXX */
#define EXTIOBASE1200 (0xe4000000)
#define EXTIOTOP1200 (0xe4020000) /* XXX */
#define MAXADDR (0xfffff000)
/*
* Internal IO space:
*
* Internal IO space is mapped in the kernel from ``intiobase'' to
* ``intiolimit'' (defined in locore.s). Since it is always mapped,
* conversion between physical and kernel virtual addresses is easy.
*/
#define ISIIOVA(va) \
((char *)(va) >= intiobase && (char *)(va) < intiolimit)
#define IIOV(pa) (((u_int)(pa) - intiobase_phys) + (u_int)intiobase)
#define ISIIOPA(pa) \
((u_int)(pa) >= intiobase_phys && (u_int)(pa) < intiotop_phys)
#define IIOP(va) (((u_int)(va) - (u_int)intiobase) + intiobase_phys)
#define IIOPOFF(pa) ((u_int)(pa) - intiobase_phys)
#endif /* !_NEWS68K_CPU_H_ */
| 29.167273 | 77 | 0.720359 | [
"vector"
] |
d6c66fc19716bb164bd90ce6b93d3e8d6d114f2c | 10,361 | c | C | net/mac80211/led.c | fergy/aplit_linux-5 | a6ef4cb0e17e1eec9743c064e65f730c49765711 | [
"MIT"
] | 3 | 2020-11-06T05:17:03.000Z | 2020-11-06T07:32:34.000Z | net/mac80211/led.c | fergy/aplit_linux-5 | a6ef4cb0e17e1eec9743c064e65f730c49765711 | [
"MIT"
] | null | null | null | net/mac80211/led.c | fergy/aplit_linux-5 | a6ef4cb0e17e1eec9743c064e65f730c49765711 | [
"MIT"
] | 2 | 2019-06-04T11:02:20.000Z | 2021-12-07T03:08:02.000Z | /*
* Copyright 2006, Johannes Berg <johannes@sipsolutions.net>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
/* just for IFNAMSIZ */
#include <linux/if.h>
#include <linux/slab.h>
#include <linux/export.h>
#include "led.h"
void ieee80211_led_assoc(struct ieee80211_local *local, bool associated)
{
if (!atomic_read(&local->assoc_led_active))
return;
if (associated)
led_trigger_event(&local->assoc_led, LED_FULL);
else
led_trigger_event(&local->assoc_led, LED_OFF);
}
void ieee80211_led_radio(struct ieee80211_local *local, bool enabled)
{
if (!atomic_read(&local->radio_led_active))
return;
if (enabled)
led_trigger_event(&local->radio_led, LED_FULL);
else
led_trigger_event(&local->radio_led, LED_OFF);
}
void ieee80211_alloc_led_names(struct ieee80211_local *local)
{
local->rx_led.name = kasprintf(GFP_KERNEL, "%srx",
wiphy_name(local->hw.wiphy));
local->tx_led.name = kasprintf(GFP_KERNEL, "%stx",
wiphy_name(local->hw.wiphy));
local->assoc_led.name = kasprintf(GFP_KERNEL, "%sassoc",
wiphy_name(local->hw.wiphy));
local->radio_led.name = kasprintf(GFP_KERNEL, "%sradio",
wiphy_name(local->hw.wiphy));
}
void ieee80211_free_led_names(struct ieee80211_local *local)
{
kfree(local->rx_led.name);
kfree(local->tx_led.name);
kfree(local->assoc_led.name);
kfree(local->radio_led.name);
}
static int ieee80211_tx_led_activate(struct led_classdev *led_cdev)
{
struct ieee80211_local *local = container_of(led_cdev->trigger,
struct ieee80211_local,
tx_led);
atomic_inc(&local->tx_led_active);
return 0;
}
static void ieee80211_tx_led_deactivate(struct led_classdev *led_cdev)
{
struct ieee80211_local *local = container_of(led_cdev->trigger,
struct ieee80211_local,
tx_led);
atomic_dec(&local->tx_led_active);
}
static int ieee80211_rx_led_activate(struct led_classdev *led_cdev)
{
struct ieee80211_local *local = container_of(led_cdev->trigger,
struct ieee80211_local,
rx_led);
atomic_inc(&local->rx_led_active);
return 0;
}
static void ieee80211_rx_led_deactivate(struct led_classdev *led_cdev)
{
struct ieee80211_local *local = container_of(led_cdev->trigger,
struct ieee80211_local,
rx_led);
atomic_dec(&local->rx_led_active);
}
static int ieee80211_assoc_led_activate(struct led_classdev *led_cdev)
{
struct ieee80211_local *local = container_of(led_cdev->trigger,
struct ieee80211_local,
assoc_led);
atomic_inc(&local->assoc_led_active);
return 0;
}
static void ieee80211_assoc_led_deactivate(struct led_classdev *led_cdev)
{
struct ieee80211_local *local = container_of(led_cdev->trigger,
struct ieee80211_local,
assoc_led);
atomic_dec(&local->assoc_led_active);
}
static int ieee80211_radio_led_activate(struct led_classdev *led_cdev)
{
struct ieee80211_local *local = container_of(led_cdev->trigger,
struct ieee80211_local,
radio_led);
atomic_inc(&local->radio_led_active);
return 0;
}
static void ieee80211_radio_led_deactivate(struct led_classdev *led_cdev)
{
struct ieee80211_local *local = container_of(led_cdev->trigger,
struct ieee80211_local,
radio_led);
atomic_dec(&local->radio_led_active);
}
static int ieee80211_tpt_led_activate(struct led_classdev *led_cdev)
{
struct ieee80211_local *local = container_of(led_cdev->trigger,
struct ieee80211_local,
tpt_led);
atomic_inc(&local->tpt_led_active);
return 0;
}
static void ieee80211_tpt_led_deactivate(struct led_classdev *led_cdev)
{
struct ieee80211_local *local = container_of(led_cdev->trigger,
struct ieee80211_local,
tpt_led);
atomic_dec(&local->tpt_led_active);
}
void ieee80211_led_init(struct ieee80211_local *local)
{
atomic_set(&local->rx_led_active, 0);
local->rx_led.activate = ieee80211_rx_led_activate;
local->rx_led.deactivate = ieee80211_rx_led_deactivate;
if (local->rx_led.name && led_trigger_register(&local->rx_led)) {
kfree(local->rx_led.name);
local->rx_led.name = NULL;
}
atomic_set(&local->tx_led_active, 0);
local->tx_led.activate = ieee80211_tx_led_activate;
local->tx_led.deactivate = ieee80211_tx_led_deactivate;
if (local->tx_led.name && led_trigger_register(&local->tx_led)) {
kfree(local->tx_led.name);
local->tx_led.name = NULL;
}
atomic_set(&local->assoc_led_active, 0);
local->assoc_led.activate = ieee80211_assoc_led_activate;
local->assoc_led.deactivate = ieee80211_assoc_led_deactivate;
if (local->assoc_led.name && led_trigger_register(&local->assoc_led)) {
kfree(local->assoc_led.name);
local->assoc_led.name = NULL;
}
atomic_set(&local->radio_led_active, 0);
local->radio_led.activate = ieee80211_radio_led_activate;
local->radio_led.deactivate = ieee80211_radio_led_deactivate;
if (local->radio_led.name && led_trigger_register(&local->radio_led)) {
kfree(local->radio_led.name);
local->radio_led.name = NULL;
}
atomic_set(&local->tpt_led_active, 0);
if (local->tpt_led_trigger) {
local->tpt_led.activate = ieee80211_tpt_led_activate;
local->tpt_led.deactivate = ieee80211_tpt_led_deactivate;
if (led_trigger_register(&local->tpt_led)) {
kfree(local->tpt_led_trigger);
local->tpt_led_trigger = NULL;
}
}
}
void ieee80211_led_exit(struct ieee80211_local *local)
{
if (local->radio_led.name)
led_trigger_unregister(&local->radio_led);
if (local->assoc_led.name)
led_trigger_unregister(&local->assoc_led);
if (local->tx_led.name)
led_trigger_unregister(&local->tx_led);
if (local->rx_led.name)
led_trigger_unregister(&local->rx_led);
if (local->tpt_led_trigger) {
led_trigger_unregister(&local->tpt_led);
kfree(local->tpt_led_trigger);
}
}
const char *__ieee80211_get_radio_led_name(struct ieee80211_hw *hw)
{
struct ieee80211_local *local = hw_to_local(hw);
return local->radio_led.name;
}
EXPORT_SYMBOL(__ieee80211_get_radio_led_name);
const char *__ieee80211_get_assoc_led_name(struct ieee80211_hw *hw)
{
struct ieee80211_local *local = hw_to_local(hw);
return local->assoc_led.name;
}
EXPORT_SYMBOL(__ieee80211_get_assoc_led_name);
const char *__ieee80211_get_tx_led_name(struct ieee80211_hw *hw)
{
struct ieee80211_local *local = hw_to_local(hw);
return local->tx_led.name;
}
EXPORT_SYMBOL(__ieee80211_get_tx_led_name);
const char *__ieee80211_get_rx_led_name(struct ieee80211_hw *hw)
{
struct ieee80211_local *local = hw_to_local(hw);
return local->rx_led.name;
}
EXPORT_SYMBOL(__ieee80211_get_rx_led_name);
static unsigned long tpt_trig_traffic(struct ieee80211_local *local,
struct tpt_led_trigger *tpt_trig)
{
unsigned long traffic, delta;
traffic = tpt_trig->tx_bytes + tpt_trig->rx_bytes;
delta = traffic - tpt_trig->prev_traffic;
tpt_trig->prev_traffic = traffic;
return DIV_ROUND_UP(delta, 1024 / 8);
}
static void tpt_trig_timer(struct timer_list *t)
{
struct tpt_led_trigger *tpt_trig = from_timer(tpt_trig, t, timer);
struct ieee80211_local *local = tpt_trig->local;
struct led_classdev *led_cdev;
unsigned long on, off, tpt;
int i;
if (!tpt_trig->running)
return;
mod_timer(&tpt_trig->timer, round_jiffies(jiffies + HZ));
tpt = tpt_trig_traffic(local, tpt_trig);
/* default to just solid on */
on = 1;
off = 0;
for (i = tpt_trig->blink_table_len - 1; i >= 0; i--) {
if (tpt_trig->blink_table[i].throughput < 0 ||
tpt > tpt_trig->blink_table[i].throughput) {
off = tpt_trig->blink_table[i].blink_time / 2;
on = tpt_trig->blink_table[i].blink_time - off;
break;
}
}
read_lock(&local->tpt_led.leddev_list_lock);
list_for_each_entry(led_cdev, &local->tpt_led.led_cdevs, trig_list)
led_blink_set(led_cdev, &on, &off);
read_unlock(&local->tpt_led.leddev_list_lock);
}
const char *
__ieee80211_create_tpt_led_trigger(struct ieee80211_hw *hw,
unsigned int flags,
const struct ieee80211_tpt_blink *blink_table,
unsigned int blink_table_len)
{
struct ieee80211_local *local = hw_to_local(hw);
struct tpt_led_trigger *tpt_trig;
if (WARN_ON(local->tpt_led_trigger))
return NULL;
tpt_trig = kzalloc(sizeof(struct tpt_led_trigger), GFP_KERNEL);
if (!tpt_trig)
return NULL;
snprintf(tpt_trig->name, sizeof(tpt_trig->name),
"%stpt", wiphy_name(local->hw.wiphy));
local->tpt_led.name = tpt_trig->name;
tpt_trig->blink_table = blink_table;
tpt_trig->blink_table_len = blink_table_len;
tpt_trig->want = flags;
tpt_trig->local = local;
timer_setup(&tpt_trig->timer, tpt_trig_timer, 0);
local->tpt_led_trigger = tpt_trig;
return tpt_trig->name;
}
EXPORT_SYMBOL(__ieee80211_create_tpt_led_trigger);
static void ieee80211_start_tpt_led_trig(struct ieee80211_local *local)
{
struct tpt_led_trigger *tpt_trig = local->tpt_led_trigger;
if (tpt_trig->running)
return;
/* reset traffic */
tpt_trig_traffic(local, tpt_trig);
tpt_trig->running = true;
tpt_trig_timer(&tpt_trig->timer);
mod_timer(&tpt_trig->timer, round_jiffies(jiffies + HZ));
}
static void ieee80211_stop_tpt_led_trig(struct ieee80211_local *local)
{
struct tpt_led_trigger *tpt_trig = local->tpt_led_trigger;
struct led_classdev *led_cdev;
if (!tpt_trig->running)
return;
tpt_trig->running = false;
del_timer_sync(&tpt_trig->timer);
read_lock(&local->tpt_led.leddev_list_lock);
list_for_each_entry(led_cdev, &local->tpt_led.led_cdevs, trig_list)
led_set_brightness(led_cdev, LED_OFF);
read_unlock(&local->tpt_led.leddev_list_lock);
}
void ieee80211_mod_tpt_led_trig(struct ieee80211_local *local,
unsigned int types_on, unsigned int types_off)
{
struct tpt_led_trigger *tpt_trig = local->tpt_led_trigger;
bool allowed;
WARN_ON(types_on & types_off);
if (!tpt_trig)
return;
tpt_trig->active &= ~types_off;
tpt_trig->active |= types_on;
/*
* Regardless of wanted state, we shouldn't blink when
* the radio is disabled -- this can happen due to some
* code ordering issues with __ieee80211_recalc_idle()
* being called before the radio is started.
*/
allowed = tpt_trig->active & IEEE80211_TPT_LEDTRIG_FL_RADIO;
if (!allowed || !(tpt_trig->active & tpt_trig->want))
ieee80211_stop_tpt_led_trig(local);
else
ieee80211_start_tpt_led_trig(local);
}
| 26.703608 | 73 | 0.747611 | [
"solid"
] |
d6cd7970cc414542b04a26cef2abd624efc5bb8c | 12,127 | c | C | plugins/payz/tester/tester.c | ZmnSCPxj/payz | 40e955d9feeaa3f90bbb34a062e373fa63d6451a | [
"MIT"
] | null | null | null | plugins/payz/tester/tester.c | ZmnSCPxj/payz | 40e955d9feeaa3f90bbb34a062e373fa63d6451a | [
"MIT"
] | null | null | null | plugins/payz/tester/tester.c | ZmnSCPxj/payz | 40e955d9feeaa3f90bbb34a062e373fa63d6451a | [
"MIT"
] | null | null | null | #include"tester.h"
#include<assert.h>
#include<ccan/err/err.h>
#include<ccan/json_out/json_out.h>
#include<ccan/take/take.h>
#include<ccan/tal/str/str.h>
#include<common/json.h>
#include<common/json_stream.h>
#include<common/utils.h>
#include<plugins/payz/json_equal.h>
#include<plugins/payz/tester/command.h>
#include<plugins/payz/tester/loop.h>
#include<plugins/payz/tester/rpc.h>
#include<plugins/payz/tester/spawn.h>
#include<signal.h>
#include<stdlib.h>
#include<string.h>
/*-----------------------------------------------------------------------------
Constants
-----------------------------------------------------------------------------*/
#define TESTER_TIMEOUT (time_from_sec(60))
/*-----------------------------------------------------------------------------
Top Object
-----------------------------------------------------------------------------*/
struct payz_tester {
/* Sub-objects. */
struct payz_tester_spawn *spawn;
struct payz_tester_rpc *rpc;
struct payz_tester_command *command;
/* Command counter ID. */
u64 id;
/* Spare buffers. */
char *buffer;
jsmntok_t *toks;
};
static bool wait_for_response(struct payz_tester *tester);
static struct payz_tester *
payz_tester_new(const tal_t *ctx,
struct payz_tester_spawn **spawn)
{
struct timemono start = time_mono();
struct payz_tester *tester;
struct json_stream *js;
const char *init_params;
size_t init_params_len;
tester = tal(ctx, struct payz_tester);
tester->rpc = payz_tester_rpc_new(tester, TESTER_TIMEOUT);
tester->command = payz_tester_command_new(tester,
TESTER_TIMEOUT,
payz_tester_spawn_stdin(*spawn),
payz_tester_spawn_stdout(*spawn));
tester->id = 1;
tester->buffer = NULL;
tester->toks = NULL;
/* Grab control of the spawn. */
tester->spawn = tal_steal(tester, *spawn);
*spawn = NULL;
/* Manifest the plugin. */
payz_tester_command_send(tester->command, start, tester->id,
"getmanifest",
"{\"allow-deprecated-apis\": true}");
payz_tester_loop("getmanifest",
tester->command, tester->rpc, tester->spawn,
TESTER_TIMEOUT,
&wait_for_response, tester);
tester->buffer = tal_free(tester->buffer);
tester->toks = tal_free(tester->toks);
/* Init the plugin, this requires a more complicated params object.
*/
js = new_json_stream(tmpctx, NULL, NULL);
json_object_start(js, NULL);
/* Configuration. */
json_object_start(js, "configuration");
json_add_string(js, "lightning-dir", payz_tester_rpc_dir(tester->rpc));
json_add_string(js, "rpc-file", "lightning-rpc");
json_add_string(js, "network", "testnet");
json_object_start(js, "feature_set");
json_object_end(js);
json_object_end(js);
/* Dummy options object. */
json_object_start(js, "options");
json_object_end(js);
json_object_end(js);
json_out_finished(js->jout);
/* Send the init command. */
init_params = json_out_contents(js->jout, &init_params_len);
payz_tester_command_send(tester->command, start, tester->id,
"init",
tal_strndup(tmpctx,
init_params, init_params_len));
/* Wait for response.
* Warning: payz_tester_loop will clean tmpctx, so the js is already
* freed after this point.
*/
payz_tester_loop("init",
tester->command, tester->rpc, tester->spawn,
TESTER_TIMEOUT,
&wait_for_response, tester);
tester->buffer = tal_free(tester->buffer);
tester->toks = tal_free(tester->toks);
return tester;
}
static bool
payz_tester_command_impl(struct payz_tester *tester,
const char **buffer,
const jsmntok_t **toks,
const char *method,
const char *params)
{
struct timemono start = time_mono();
const jsmntok_t *result;
const jsmntok_t *error;
char *source = tal_fmt(NULL, "payz_tester_command(%s, %s)", method, params);
tester->buffer = tal_free(tester->buffer);
tester->toks = tal_free(tester->toks);
payz_tester_command_send(tester->command, start, tester->id,
method, params);
payz_tester_loop(source,
tester->command, tester->rpc, tester->spawn,
TESTER_TIMEOUT,
&wait_for_response, tester);
*buffer = tester->buffer;
result = json_get_member(tester->buffer, tester->toks,
"result");
error = json_get_member(tester->buffer, tester->toks,
"error");
if (result) {
tal_free(source);
*toks = result;
return true;
}
if (error) {
tal_free(source);
*toks = error;
return false;
}
errx(1,
"%s: Response from plugin did not have "
"result or error: %.*s",
source,
json_tok_full_len(tester->toks),
json_tok_full(tester->buffer, tester->toks));
}
static bool wait_for_response(struct payz_tester *tester)
{
const char *error;
u64 id;
if (!payz_tester_command_get_response(tester,
tester->command,
&tester->buffer,
&tester->toks))
/* Keep going. */
return true;
/* Check response, it should match the id. */
error = json_scan(tmpctx, tester->buffer, tester->toks,
"{id:%}",
JSON_SCAN(json_to_u64, &id));
if (!error && id != tester->id)
error = tal_fmt(tmpctx,
"incorrrect 'id': expected %"PRIu64", "
"got %"PRIu64,
tester->id, id);
if (error)
errx(1, "Plugin handshake: Response: %s", error);
/* *Now* increment the id. */
tester->id++;
/* We can finish now. */
return false;
}
/*-----------------------------------------------------------------------------
Static Top Object
-----------------------------------------------------------------------------*/
static struct payz_tester *payz_tester = NULL;
static struct payz_tester_spawn *spawn = NULL;
static void payz_tester_atexit(void);
void payz_tester_init(const char *argv0)
{
int res;
/* Call this before anything else, to reduce any garbage in
* the spawned process.
*/
spawn = payz_tester_spawn_new(TESTER_TIMEOUT);
if (!spawn) {
err_set_progname(argv0);
errx(1, "Unable to spawn sub-provess for plugin.");
}
/* Set up exit handler. */
res = atexit(&payz_tester_atexit);
if (res != 0) {
spawn = tal_free(spawn);
err_set_progname(argv0);
errx(1, "Unable to set atexit handler.");
}
/* Set up various necessary things. */
setup_locale();
err_set_progname(argv0);
setup_tmpctx();
signal(SIGPIPE, SIG_IGN);
signal(SIGCHLD, SIG_IGN);
/* Hand over control of spawn. */
payz_tester = payz_tester_new(NULL, &spawn);
}
/* Exit. */
static void payz_tester_atexit(void)
{
const char *p = taken_any();
if (p)
errx(1, "outstanding taken(): %s", p);
take_cleanup();
tmpctx = tal_free(tmpctx);
spawn = tal_free(spawn);
payz_tester = tal_free(payz_tester);
}
/*-----------------------------------------------------------------------------
Commands to the plugin
-----------------------------------------------------------------------------*/
bool payz_tester_command(const char **buffer,
const jsmntok_t **toks,
const char *method,
const char *params)
{
return payz_tester_command_impl(payz_tester,
buffer, toks,
method, params);
}
void payz_tester_command_expect(const char *method,
const char *params,
const char *expected)
{
bool ret;
const char *buffer;
const jsmntok_t *result;
jsmntok_t *exptoks;
ret = payz_tester_command(&buffer, &result, method, params);
if (!ret)
errx(1, "payz_tester_command_expect(%s, %s, %s): "
"Command failed with: %.*s",
method, params, expected,
json_tok_full_len(result),
json_tok_full(buffer, result));
/* Parse expected. */
exptoks = json_parse_simple(tmpctx, expected, strlen(expected));
if (!json_equal(buffer, result, expected, exptoks))
errx(1, "payz_tester_command_expect(%s, %s, %s): "
"Unexpected 'result': %.*s",
method, params, expected,
json_tok_full_len(result),
json_tok_full(buffer, result));
}
void payz_tester_command_expectfail(const char *method,
const char *params,
errcode_t expected_code)
{
bool ret;
const char *buffer;
const jsmntok_t *result;
const char *error;
errcode_t actual_code;
ret = payz_tester_command(&buffer, &result, method, params);
if (ret)
errx(1, "payz_tester_command_expectfail(%s, %s, "
"%"PRIerrcode"): Command succeeded? %.*s",
method, params, expected_code,
json_tok_full_len(result),
json_tok_full(buffer, result));
error = json_scan(tmpctx, buffer, result,
"{code:%}",
JSON_SCAN(json_to_errcode, &actual_code));
if (error)
errx(1, "payz_tester_command_expectfail(%s, %s, "
"%"PRIerrcode"): Failed to parse error: %s",
method, params, expected_code,
error);
if (actual_code != expected_code)
errx(1, "payz_tester_command_expectfail(%s, %s, "
"%"PRIerrcode"): Expected error code %"PRIerrcode", "
"got %"PRIerrcode"",
method, params, expected_code,
expected_code, actual_code);
}
void payz_tester_command_ok(const char *method,
const char *params)
{
bool ret;
const char *buffer;
const jsmntok_t *result;
ret = payz_tester_command(&buffer, &result, method, params);
if (!ret)
errx(1, "payz_tester_command_ok(%s, %s): "
"Command failed! %.*s",
method, params,
json_tok_full_len(result),
json_tok_full(buffer, result));
}
/*-----------------------------------------------------------------------------
Component Waiting
-----------------------------------------------------------------------------*/
static void
payz_tester_wait_component_generic(const char *api_name,
bool expected_found,
const char **buffer,
const jsmntok_t **component,
u32 entity,
const char *component_name)
{
struct timemono start = time_mono();
const jsmntok_t *result;
bool found = false;
bool ret;
do {
const char *params;
if (time_greater(timemono_since(start), TESTER_TIMEOUT)) {
const char *rbuf;
const jsmntok_t *result;
char *systrace;
char *listentities;
(void) payz_tester_command(&rbuf, &result,
"payecs_systrace",
tal_fmt(tmpctx,
"[%"PRIu32"]",
entity));
systrace = tal_strndup(NULL,
json_tok_full(rbuf, result),
json_tok_full_len(result));
(void) payz_tester_command(&rbuf, &result,
"payecs_listentities",
"[]");
listentities = tal_strndup(systrace,
json_tok_full(rbuf, result),
json_tok_full_len(result));
tal_steal(tmpctx, systrace);
errx(1,
"%s(%"PRIu32", %s): "
"Timed out!\n"
"\nsystrace: %s\n"
"\nlistentities: %s\n",
api_name,
entity, component_name,
systrace, listentities);
}
/* Since we use tmpctx and payz_tester_command clears that,
* we have to regen the params at each loop iteration.
*/
params = tal_fmt(tmpctx, "[%"PRIu32", [\"%s\"]]",
entity, component_name);
ret = payz_tester_command(buffer, &result,
"payecs_getcomponents", params);
if (!ret)
errx(1,
"%s(%"PRIu32", %s): "
"payecs_getcomponents failed! %.*s",
api_name,
entity, component_name,
json_tok_full_len(result),
json_tok_full(*buffer, result));
*component = json_get_member(*buffer, result, component_name);
if (!(*component))
errx(1,
"%s(%"PRIu32", %s): "
"payecs_getcomponents did not return "
"component??? %.*s",
api_name,
entity, component_name,
json_tok_full_len(result),
json_tok_full(*buffer, result));
found = !json_tok_is_null(*buffer, *component);
} while (found != expected_found);
}
void payz_tester_wait_component(const char **buffer,
const jsmntok_t **component,
u32 entity,
const char *component_name)
{
/* Wait for "found" to be true. */
payz_tester_wait_component_generic("payz_tester_wait_component",
true,
buffer, component,
entity, component_name);
}
void payz_tester_wait_detach_component(u32 entity,
const char *component_name)
{
/* Dummy variables. */
const char *buffer;
const jsmntok_t *component;
/* Wait for "found" to be false. */
payz_tester_wait_component_generic("payz_tester_wait_detach_component",
false,
&buffer, &component,
entity, component_name);
}
| 26.948889 | 79 | 0.628927 | [
"object"
] |
d6d316a4ec0b083f71523a79f955529fbd54f83a | 838 | h | C | cases/spherical_surfers/param/post/objects/surfer__us_1o0__surftimeconst_9o0__reorientationtime_1o5/pz/group/_member/passive/choice.h | C0PEP0D/sheld0n | 497d4ee8b6b1815cd5fa1b378d1b947ee259f4bc | [
"MIT"
] | null | null | null | cases/spherical_surfers/param/post/objects/surfer__us_1o0__surftimeconst_9o0__reorientationtime_1o5/pz/group/_member/passive/choice.h | C0PEP0D/sheld0n | 497d4ee8b6b1815cd5fa1b378d1b947ee259f4bc | [
"MIT"
] | null | null | null | cases/spherical_surfers/param/post/objects/surfer__us_1o0__surftimeconst_9o0__reorientationtime_1o5/pz/group/_member/passive/choice.h | C0PEP0D/sheld0n | 497d4ee8b6b1815cd5fa1b378d1b947ee259f4bc | [
"MIT"
] | null | null | null | #ifndef C0P_PARAM_POST_OBJECTS_SURFER__US_1O0__SURFTIMECONST_9O0__REORIENTATIONTIME_1O5_PZ_GROUP_MEMBER_PASSIVE_CHOICE_H
#define C0P_PARAM_POST_OBJECTS_SURFER__US_1O0__SURFTIMECONST_9O0__REORIENTATIONTIME_1O5_PZ_GROUP_MEMBER_PASSIVE_CHOICE_H
#pragma once
// choose your post
#include "core/post/objects/object/post/passive/position/core.h"
#include "param/post/objects/surfer__us_1o0__surftimeconst_9o0__reorientationtime_1o5/pz/group/_member/passive/position/parameters.h"
namespace c0p {
template<typename TypeSurferUs1O0Surftimeconst9O0Reorientationtime1O5Step>
using PostSurferUs1O0Surftimeconst9O0Reorientationtime1O5PzGroupMemberPassive = PostPostPassivePosition<PostSurferUs1O0Surftimeconst9O0Reorientationtime1O5PzGroupMemberPassivePositionParameters, TypeSurferUs1O0Surftimeconst9O0Reorientationtime1O5Step>;
}
#endif
| 55.866667 | 256 | 0.909308 | [
"object"
] |
d6d57b1ba0320bf98d51c0e72cd0169ffdaf979e | 28,132 | h | C | google/cloud/datamigration/data_migration_client.h | joezqren/google-cloud-cpp | 325d312b0a21569f3c57515aec7d91f3540d3b48 | [
"Apache-2.0"
] | null | null | null | google/cloud/datamigration/data_migration_client.h | joezqren/google-cloud-cpp | 325d312b0a21569f3c57515aec7d91f3540d3b48 | [
"Apache-2.0"
] | null | null | null | google/cloud/datamigration/data_migration_client.h | joezqren/google-cloud-cpp | 325d312b0a21569f3c57515aec7d91f3540d3b48 | [
"Apache-2.0"
] | null | null | null | // Copyright 2022 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
//
// 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.
// Generated by the Codegen C++ plugin.
// If you make any local changes, they will be lost.
// source: google/cloud/clouddms/v1/clouddms.proto
#ifndef GOOGLE_CLOUD_CPP_GOOGLE_CLOUD_DATAMIGRATION_DATA_MIGRATION_CLIENT_H
#define GOOGLE_CLOUD_CPP_GOOGLE_CLOUD_DATAMIGRATION_DATA_MIGRATION_CLIENT_H
#include "google/cloud/datamigration/data_migration_connection.h"
#include "google/cloud/future.h"
#include "google/cloud/options.h"
#include "google/cloud/polling_policy.h"
#include "google/cloud/status_or.h"
#include "google/cloud/version.h"
#include <google/longrunning/operations.grpc.pb.h>
#include <map>
#include <memory>
namespace google {
namespace cloud {
namespace datamigration {
GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN
///
/// Database Migration service
///
/// @par Equality
///
/// Instances of this class created via copy-construction or copy-assignment
/// always compare equal. Instances created with equal
/// `std::shared_ptr<*Connection>` objects compare equal. Objects that compare
/// equal share the same underlying resources.
///
/// @par Performance
///
/// Creating a new instance of this class is a relatively expensive operation,
/// new objects establish new connections to the service. In contrast,
/// copy-construction, move-construction, and the corresponding assignment
/// operations are relatively efficient as the copies share all underlying
/// resources.
///
/// @par Thread Safety
///
/// Concurrent access to different instances of this class, even if they compare
/// equal, is guaranteed to work. Two or more threads operating on the same
/// instance of this class is not guaranteed to work. Since copy-construction
/// and move-construction is a relatively efficient operation, consider using
/// such a copy when using this class from multiple threads.
///
class DataMigrationServiceClient {
public:
explicit DataMigrationServiceClient(
std::shared_ptr<DataMigrationServiceConnection> connection,
Options options = {});
~DataMigrationServiceClient();
//@{
// @name Copy and move support
DataMigrationServiceClient(DataMigrationServiceClient const&) = default;
DataMigrationServiceClient& operator=(DataMigrationServiceClient const&) =
default;
DataMigrationServiceClient(DataMigrationServiceClient&&) = default;
DataMigrationServiceClient& operator=(DataMigrationServiceClient&&) = default;
//@}
//@{
// @name Equality
friend bool operator==(DataMigrationServiceClient const& a,
DataMigrationServiceClient const& b) {
return a.connection_ == b.connection_;
}
friend bool operator!=(DataMigrationServiceClient const& a,
DataMigrationServiceClient const& b) {
return !(a == b);
}
//@}
///
/// Lists migration jobs in a given project and location.
///
/// @param parent Required. The parent, which owns this collection of
/// migrationJobs.
/// @param options Optional. Operation options.
/// @return
/// @googleapis_link{google::cloud::clouddms::v1::MigrationJob,google/cloud/clouddms/v1/clouddms_resources.proto#L373}
///
/// [google.cloud.clouddms.v1.ListMigrationJobsRequest]:
/// @googleapis_reference_link{google/cloud/clouddms/v1/clouddms.proto#L239}
/// [google.cloud.clouddms.v1.MigrationJob]:
/// @googleapis_reference_link{google/cloud/clouddms/v1/clouddms_resources.proto#L373}
///
StreamRange<google::cloud::clouddms::v1::MigrationJob> ListMigrationJobs(
std::string const& parent, Options options = {});
///
/// Lists migration jobs in a given project and location.
///
/// @param request
/// @googleapis_link{google::cloud::clouddms::v1::ListMigrationJobsRequest,google/cloud/clouddms/v1/clouddms.proto#L239}
/// @param options Optional. Operation options.
/// @return
/// @googleapis_link{google::cloud::clouddms::v1::MigrationJob,google/cloud/clouddms/v1/clouddms_resources.proto#L373}
///
/// [google.cloud.clouddms.v1.ListMigrationJobsRequest]:
/// @googleapis_reference_link{google/cloud/clouddms/v1/clouddms.proto#L239}
/// [google.cloud.clouddms.v1.MigrationJob]:
/// @googleapis_reference_link{google/cloud/clouddms/v1/clouddms_resources.proto#L373}
///
StreamRange<google::cloud::clouddms::v1::MigrationJob> ListMigrationJobs(
google::cloud::clouddms::v1::ListMigrationJobsRequest request,
Options options = {});
///
/// Gets details of a single migration job.
///
/// @param name Required. Name of the migration job resource to get.
/// @param options Optional. Operation options.
/// @return
/// @googleapis_link{google::cloud::clouddms::v1::MigrationJob,google/cloud/clouddms/v1/clouddms_resources.proto#L373}
///
/// [google.cloud.clouddms.v1.GetMigrationJobRequest]:
/// @googleapis_reference_link{google/cloud/clouddms/v1/clouddms.proto#L291}
/// [google.cloud.clouddms.v1.MigrationJob]:
/// @googleapis_reference_link{google/cloud/clouddms/v1/clouddms_resources.proto#L373}
///
StatusOr<google::cloud::clouddms::v1::MigrationJob> GetMigrationJob(
std::string const& name, Options options = {});
///
/// Gets details of a single migration job.
///
/// @param request
/// @googleapis_link{google::cloud::clouddms::v1::GetMigrationJobRequest,google/cloud/clouddms/v1/clouddms.proto#L291}
/// @param options Optional. Operation options.
/// @return
/// @googleapis_link{google::cloud::clouddms::v1::MigrationJob,google/cloud/clouddms/v1/clouddms_resources.proto#L373}
///
/// [google.cloud.clouddms.v1.GetMigrationJobRequest]:
/// @googleapis_reference_link{google/cloud/clouddms/v1/clouddms.proto#L291}
/// [google.cloud.clouddms.v1.MigrationJob]:
/// @googleapis_reference_link{google/cloud/clouddms/v1/clouddms_resources.proto#L373}
///
StatusOr<google::cloud::clouddms::v1::MigrationJob> GetMigrationJob(
google::cloud::clouddms::v1::GetMigrationJobRequest const& request,
Options options = {});
///
/// Creates a new migration job in a given project and location.
///
/// @param parent Required. The parent, which owns this collection of
/// migration jobs.
/// @param migration_job Required. Represents a [migration
/// job](https://cloud.google.com/database-migration/docs/reference/rest/v1/projects.locations.migrationJobs)
/// object.
/// @param migration_job_id Required. The ID of the instance to create.
/// @param options Optional. Operation options.
/// @return
/// @googleapis_link{google::cloud::clouddms::v1::MigrationJob,google/cloud/clouddms/v1/clouddms_resources.proto#L373}
///
/// [google.cloud.clouddms.v1.CreateMigrationJobRequest]:
/// @googleapis_reference_link{google/cloud/clouddms/v1/clouddms.proto#L303}
/// [google.cloud.clouddms.v1.MigrationJob]:
/// @googleapis_reference_link{google/cloud/clouddms/v1/clouddms_resources.proto#L373}
///
future<StatusOr<google::cloud::clouddms::v1::MigrationJob>>
CreateMigrationJob(
std::string const& parent,
google::cloud::clouddms::v1::MigrationJob const& migration_job,
std::string const& migration_job_id, Options options = {});
///
/// Creates a new migration job in a given project and location.
///
/// @param request
/// @googleapis_link{google::cloud::clouddms::v1::CreateMigrationJobRequest,google/cloud/clouddms/v1/clouddms.proto#L303}
/// @param options Optional. Operation options.
/// @return
/// @googleapis_link{google::cloud::clouddms::v1::MigrationJob,google/cloud/clouddms/v1/clouddms_resources.proto#L373}
///
/// [google.cloud.clouddms.v1.CreateMigrationJobRequest]:
/// @googleapis_reference_link{google/cloud/clouddms/v1/clouddms.proto#L303}
/// [google.cloud.clouddms.v1.MigrationJob]:
/// @googleapis_reference_link{google/cloud/clouddms/v1/clouddms_resources.proto#L373}
///
future<StatusOr<google::cloud::clouddms::v1::MigrationJob>>
CreateMigrationJob(
google::cloud::clouddms::v1::CreateMigrationJobRequest const& request,
Options options = {});
///
/// Updates the parameters of a single migration job.
///
/// @param migration_job Required. The migration job parameters to update.
/// @param update_mask Required. Field mask is used to specify the fields to
/// be overwritten in the
/// migration job resource by the update.
/// @param options Optional. Operation options.
/// @return
/// @googleapis_link{google::cloud::clouddms::v1::MigrationJob,google/cloud/clouddms/v1/clouddms_resources.proto#L373}
///
/// [google.cloud.clouddms.v1.UpdateMigrationJobRequest]:
/// @googleapis_reference_link{google/cloud/clouddms/v1/clouddms.proto#L331}
/// [google.cloud.clouddms.v1.MigrationJob]:
/// @googleapis_reference_link{google/cloud/clouddms/v1/clouddms_resources.proto#L373}
///
future<StatusOr<google::cloud::clouddms::v1::MigrationJob>>
UpdateMigrationJob(
google::cloud::clouddms::v1::MigrationJob const& migration_job,
google::protobuf::FieldMask const& update_mask, Options options = {});
///
/// Updates the parameters of a single migration job.
///
/// @param request
/// @googleapis_link{google::cloud::clouddms::v1::UpdateMigrationJobRequest,google/cloud/clouddms/v1/clouddms.proto#L331}
/// @param options Optional. Operation options.
/// @return
/// @googleapis_link{google::cloud::clouddms::v1::MigrationJob,google/cloud/clouddms/v1/clouddms_resources.proto#L373}
///
/// [google.cloud.clouddms.v1.UpdateMigrationJobRequest]:
/// @googleapis_reference_link{google/cloud/clouddms/v1/clouddms.proto#L331}
/// [google.cloud.clouddms.v1.MigrationJob]:
/// @googleapis_reference_link{google/cloud/clouddms/v1/clouddms_resources.proto#L373}
///
future<StatusOr<google::cloud::clouddms::v1::MigrationJob>>
UpdateMigrationJob(
google::cloud::clouddms::v1::UpdateMigrationJobRequest const& request,
Options options = {});
///
/// Deletes a single migration job.
///
/// @param name Required. Name of the migration job resource to delete.
/// @param options Optional. Operation options.
/// @return
/// @googleapis_link{google::cloud::clouddms::v1::OperationMetadata,google/cloud/clouddms/v1/clouddms.proto#L601}
///
/// [google.cloud.clouddms.v1.DeleteMigrationJobRequest]:
/// @googleapis_reference_link{google/cloud/clouddms/v1/clouddms.proto#L350}
/// [google.cloud.clouddms.v1.OperationMetadata]:
/// @googleapis_reference_link{google/cloud/clouddms/v1/clouddms.proto#L601}
///
future<StatusOr<google::cloud::clouddms::v1::OperationMetadata>>
DeleteMigrationJob(std::string const& name, Options options = {});
///
/// Deletes a single migration job.
///
/// @param request
/// @googleapis_link{google::cloud::clouddms::v1::DeleteMigrationJobRequest,google/cloud/clouddms/v1/clouddms.proto#L350}
/// @param options Optional. Operation options.
/// @return
/// @googleapis_link{google::cloud::clouddms::v1::OperationMetadata,google/cloud/clouddms/v1/clouddms.proto#L601}
///
/// [google.cloud.clouddms.v1.DeleteMigrationJobRequest]:
/// @googleapis_reference_link{google/cloud/clouddms/v1/clouddms.proto#L350}
/// [google.cloud.clouddms.v1.OperationMetadata]:
/// @googleapis_reference_link{google/cloud/clouddms/v1/clouddms.proto#L601}
///
future<StatusOr<google::cloud::clouddms::v1::OperationMetadata>>
DeleteMigrationJob(
google::cloud::clouddms::v1::DeleteMigrationJobRequest const& request,
Options options = {});
///
/// Start an already created migration job.
///
/// @param request
/// @googleapis_link{google::cloud::clouddms::v1::StartMigrationJobRequest,google/cloud/clouddms/v1/clouddms.proto#L375}
/// @param options Optional. Operation options.
/// @return
/// @googleapis_link{google::cloud::clouddms::v1::MigrationJob,google/cloud/clouddms/v1/clouddms_resources.proto#L373}
///
/// [google.cloud.clouddms.v1.StartMigrationJobRequest]:
/// @googleapis_reference_link{google/cloud/clouddms/v1/clouddms.proto#L375}
/// [google.cloud.clouddms.v1.MigrationJob]:
/// @googleapis_reference_link{google/cloud/clouddms/v1/clouddms_resources.proto#L373}
///
future<StatusOr<google::cloud::clouddms::v1::MigrationJob>> StartMigrationJob(
google::cloud::clouddms::v1::StartMigrationJobRequest const& request,
Options options = {});
///
/// Stops a running migration job.
///
/// @param request
/// @googleapis_link{google::cloud::clouddms::v1::StopMigrationJobRequest,google/cloud/clouddms/v1/clouddms.proto#L383}
/// @param options Optional. Operation options.
/// @return
/// @googleapis_link{google::cloud::clouddms::v1::MigrationJob,google/cloud/clouddms/v1/clouddms_resources.proto#L373}
///
/// [google.cloud.clouddms.v1.StopMigrationJobRequest]:
/// @googleapis_reference_link{google/cloud/clouddms/v1/clouddms.proto#L383}
/// [google.cloud.clouddms.v1.MigrationJob]:
/// @googleapis_reference_link{google/cloud/clouddms/v1/clouddms_resources.proto#L373}
///
future<StatusOr<google::cloud::clouddms::v1::MigrationJob>> StopMigrationJob(
google::cloud::clouddms::v1::StopMigrationJobRequest const& request,
Options options = {});
///
/// Resume a migration job that is currently stopped and is resumable (was
/// stopped during CDC phase).
///
/// @param request
/// @googleapis_link{google::cloud::clouddms::v1::ResumeMigrationJobRequest,google/cloud/clouddms/v1/clouddms.proto#L391}
/// @param options Optional. Operation options.
/// @return
/// @googleapis_link{google::cloud::clouddms::v1::MigrationJob,google/cloud/clouddms/v1/clouddms_resources.proto#L373}
///
/// [google.cloud.clouddms.v1.ResumeMigrationJobRequest]:
/// @googleapis_reference_link{google/cloud/clouddms/v1/clouddms.proto#L391}
/// [google.cloud.clouddms.v1.MigrationJob]:
/// @googleapis_reference_link{google/cloud/clouddms/v1/clouddms_resources.proto#L373}
///
future<StatusOr<google::cloud::clouddms::v1::MigrationJob>>
ResumeMigrationJob(
google::cloud::clouddms::v1::ResumeMigrationJobRequest const& request,
Options options = {});
///
/// Promote a migration job, stopping replication to the destination and
/// promoting the destination to be a standalone database.
///
/// @param request
/// @googleapis_link{google::cloud::clouddms::v1::PromoteMigrationJobRequest,google/cloud/clouddms/v1/clouddms.proto#L399}
/// @param options Optional. Operation options.
/// @return
/// @googleapis_link{google::cloud::clouddms::v1::MigrationJob,google/cloud/clouddms/v1/clouddms_resources.proto#L373}
///
/// [google.cloud.clouddms.v1.PromoteMigrationJobRequest]:
/// @googleapis_reference_link{google/cloud/clouddms/v1/clouddms.proto#L399}
/// [google.cloud.clouddms.v1.MigrationJob]:
/// @googleapis_reference_link{google/cloud/clouddms/v1/clouddms_resources.proto#L373}
///
future<StatusOr<google::cloud::clouddms::v1::MigrationJob>>
PromoteMigrationJob(
google::cloud::clouddms::v1::PromoteMigrationJobRequest const& request,
Options options = {});
///
/// Verify a migration job, making sure the destination can reach the source
/// and that all configuration and prerequisites are met.
///
/// @param request
/// @googleapis_link{google::cloud::clouddms::v1::VerifyMigrationJobRequest,google/cloud/clouddms/v1/clouddms.proto#L407}
/// @param options Optional. Operation options.
/// @return
/// @googleapis_link{google::cloud::clouddms::v1::MigrationJob,google/cloud/clouddms/v1/clouddms_resources.proto#L373}
///
/// [google.cloud.clouddms.v1.VerifyMigrationJobRequest]:
/// @googleapis_reference_link{google/cloud/clouddms/v1/clouddms.proto#L407}
/// [google.cloud.clouddms.v1.MigrationJob]:
/// @googleapis_reference_link{google/cloud/clouddms/v1/clouddms_resources.proto#L373}
///
future<StatusOr<google::cloud::clouddms::v1::MigrationJob>>
VerifyMigrationJob(
google::cloud::clouddms::v1::VerifyMigrationJobRequest const& request,
Options options = {});
///
/// Restart a stopped or failed migration job, resetting the destination
/// instance to its original state and starting the migration process from
/// scratch.
///
/// @param request
/// @googleapis_link{google::cloud::clouddms::v1::RestartMigrationJobRequest,google/cloud/clouddms/v1/clouddms.proto#L415}
/// @param options Optional. Operation options.
/// @return
/// @googleapis_link{google::cloud::clouddms::v1::MigrationJob,google/cloud/clouddms/v1/clouddms_resources.proto#L373}
///
/// [google.cloud.clouddms.v1.RestartMigrationJobRequest]:
/// @googleapis_reference_link{google/cloud/clouddms/v1/clouddms.proto#L415}
/// [google.cloud.clouddms.v1.MigrationJob]:
/// @googleapis_reference_link{google/cloud/clouddms/v1/clouddms_resources.proto#L373}
///
future<StatusOr<google::cloud::clouddms::v1::MigrationJob>>
RestartMigrationJob(
google::cloud::clouddms::v1::RestartMigrationJobRequest const& request,
Options options = {});
///
/// Generate a SSH configuration script to configure the reverse SSH
/// connectivity.
///
/// @param request
/// @googleapis_link{google::cloud::clouddms::v1::GenerateSshScriptRequest,google/cloud/clouddms/v1/clouddms.proto#L423}
/// @param options Optional. Operation options.
/// @return
/// @googleapis_link{google::cloud::clouddms::v1::SshScript,google/cloud/clouddms/v1/clouddms.proto#L464}
///
/// [google.cloud.clouddms.v1.GenerateSshScriptRequest]:
/// @googleapis_reference_link{google/cloud/clouddms/v1/clouddms.proto#L423}
/// [google.cloud.clouddms.v1.SshScript]:
/// @googleapis_reference_link{google/cloud/clouddms/v1/clouddms.proto#L464}
///
StatusOr<google::cloud::clouddms::v1::SshScript> GenerateSshScript(
google::cloud::clouddms::v1::GenerateSshScriptRequest const& request,
Options options = {});
///
/// Retrieve a list of all connection profiles in a given project and
/// location.
///
/// @param parent Required. The parent, which owns this collection of
/// connection profiles.
/// @param options Optional. Operation options.
/// @return
/// @googleapis_link{google::cloud::clouddms::v1::ConnectionProfile,google/cloud/clouddms/v1/clouddms_resources.proto#L537}
///
/// [google.cloud.clouddms.v1.ListConnectionProfilesRequest]:
/// @googleapis_reference_link{google/cloud/clouddms/v1/clouddms.proto#L470}
/// [google.cloud.clouddms.v1.ConnectionProfile]:
/// @googleapis_reference_link{google/cloud/clouddms/v1/clouddms_resources.proto#L537}
///
StreamRange<google::cloud::clouddms::v1::ConnectionProfile>
ListConnectionProfiles(std::string const& parent, Options options = {});
///
/// Retrieve a list of all connection profiles in a given project and
/// location.
///
/// @param request
/// @googleapis_link{google::cloud::clouddms::v1::ListConnectionProfilesRequest,google/cloud/clouddms/v1/clouddms.proto#L470}
/// @param options Optional. Operation options.
/// @return
/// @googleapis_link{google::cloud::clouddms::v1::ConnectionProfile,google/cloud/clouddms/v1/clouddms_resources.proto#L537}
///
/// [google.cloud.clouddms.v1.ListConnectionProfilesRequest]:
/// @googleapis_reference_link{google/cloud/clouddms/v1/clouddms.proto#L470}
/// [google.cloud.clouddms.v1.ConnectionProfile]:
/// @googleapis_reference_link{google/cloud/clouddms/v1/clouddms_resources.proto#L537}
///
StreamRange<google::cloud::clouddms::v1::ConnectionProfile>
ListConnectionProfiles(
google::cloud::clouddms::v1::ListConnectionProfilesRequest request,
Options options = {});
///
/// Gets details of a single connection profile.
///
/// @param name Required. Name of the connection profile resource to get.
/// @param options Optional. Operation options.
/// @return
/// @googleapis_link{google::cloud::clouddms::v1::ConnectionProfile,google/cloud/clouddms/v1/clouddms_resources.proto#L537}
///
/// [google.cloud.clouddms.v1.GetConnectionProfileRequest]:
/// @googleapis_reference_link{google/cloud/clouddms/v1/clouddms.proto#L521}
/// [google.cloud.clouddms.v1.ConnectionProfile]:
/// @googleapis_reference_link{google/cloud/clouddms/v1/clouddms_resources.proto#L537}
///
StatusOr<google::cloud::clouddms::v1::ConnectionProfile> GetConnectionProfile(
std::string const& name, Options options = {});
///
/// Gets details of a single connection profile.
///
/// @param request
/// @googleapis_link{google::cloud::clouddms::v1::GetConnectionProfileRequest,google/cloud/clouddms/v1/clouddms.proto#L521}
/// @param options Optional. Operation options.
/// @return
/// @googleapis_link{google::cloud::clouddms::v1::ConnectionProfile,google/cloud/clouddms/v1/clouddms_resources.proto#L537}
///
/// [google.cloud.clouddms.v1.GetConnectionProfileRequest]:
/// @googleapis_reference_link{google/cloud/clouddms/v1/clouddms.proto#L521}
/// [google.cloud.clouddms.v1.ConnectionProfile]:
/// @googleapis_reference_link{google/cloud/clouddms/v1/clouddms_resources.proto#L537}
///
StatusOr<google::cloud::clouddms::v1::ConnectionProfile> GetConnectionProfile(
google::cloud::clouddms::v1::GetConnectionProfileRequest const& request,
Options options = {});
///
/// Creates a new connection profile in a given project and location.
///
/// @param parent Required. The parent, which owns this collection of
/// connection profiles.
/// @param connection_profile Required. The create request body including the
/// connection profile data
/// @param connection_profile_id Required. The connection profile identifier.
/// @param options Optional. Operation options.
/// @return
/// @googleapis_link{google::cloud::clouddms::v1::ConnectionProfile,google/cloud/clouddms/v1/clouddms_resources.proto#L537}
///
/// [google.cloud.clouddms.v1.CreateConnectionProfileRequest]:
/// @googleapis_reference_link{google/cloud/clouddms/v1/clouddms.proto#L532}
/// [google.cloud.clouddms.v1.ConnectionProfile]:
/// @googleapis_reference_link{google/cloud/clouddms/v1/clouddms_resources.proto#L537}
///
future<StatusOr<google::cloud::clouddms::v1::ConnectionProfile>>
CreateConnectionProfile(
std::string const& parent,
google::cloud::clouddms::v1::ConnectionProfile const& connection_profile,
std::string const& connection_profile_id, Options options = {});
///
/// Creates a new connection profile in a given project and location.
///
/// @param request
/// @googleapis_link{google::cloud::clouddms::v1::CreateConnectionProfileRequest,google/cloud/clouddms/v1/clouddms.proto#L532}
/// @param options Optional. Operation options.
/// @return
/// @googleapis_link{google::cloud::clouddms::v1::ConnectionProfile,google/cloud/clouddms/v1/clouddms_resources.proto#L537}
///
/// [google.cloud.clouddms.v1.CreateConnectionProfileRequest]:
/// @googleapis_reference_link{google/cloud/clouddms/v1/clouddms.proto#L532}
/// [google.cloud.clouddms.v1.ConnectionProfile]:
/// @googleapis_reference_link{google/cloud/clouddms/v1/clouddms_resources.proto#L537}
///
future<StatusOr<google::cloud::clouddms::v1::ConnectionProfile>>
CreateConnectionProfile(
google::cloud::clouddms::v1::CreateConnectionProfileRequest const&
request,
Options options = {});
///
/// Update the configuration of a single connection profile.
///
/// @param connection_profile Required. The connection profile parameters to
/// update.
/// @param update_mask Required. Field mask is used to specify the fields to
/// be overwritten in the
/// connection profile resource by the update.
/// @param options Optional. Operation options.
/// @return
/// @googleapis_link{google::cloud::clouddms::v1::ConnectionProfile,google/cloud/clouddms/v1/clouddms_resources.proto#L537}
///
/// [google.cloud.clouddms.v1.UpdateConnectionProfileRequest]:
/// @googleapis_reference_link{google/cloud/clouddms/v1/clouddms.proto#L558}
/// [google.cloud.clouddms.v1.ConnectionProfile]:
/// @googleapis_reference_link{google/cloud/clouddms/v1/clouddms_resources.proto#L537}
///
future<StatusOr<google::cloud::clouddms::v1::ConnectionProfile>>
UpdateConnectionProfile(
google::cloud::clouddms::v1::ConnectionProfile const& connection_profile,
google::protobuf::FieldMask const& update_mask, Options options = {});
///
/// Update the configuration of a single connection profile.
///
/// @param request
/// @googleapis_link{google::cloud::clouddms::v1::UpdateConnectionProfileRequest,google/cloud/clouddms/v1/clouddms.proto#L558}
/// @param options Optional. Operation options.
/// @return
/// @googleapis_link{google::cloud::clouddms::v1::ConnectionProfile,google/cloud/clouddms/v1/clouddms_resources.proto#L537}
///
/// [google.cloud.clouddms.v1.UpdateConnectionProfileRequest]:
/// @googleapis_reference_link{google/cloud/clouddms/v1/clouddms.proto#L558}
/// [google.cloud.clouddms.v1.ConnectionProfile]:
/// @googleapis_reference_link{google/cloud/clouddms/v1/clouddms_resources.proto#L537}
///
future<StatusOr<google::cloud::clouddms::v1::ConnectionProfile>>
UpdateConnectionProfile(
google::cloud::clouddms::v1::UpdateConnectionProfileRequest const&
request,
Options options = {});
///
/// Deletes a single Database Migration Service connection profile.
/// A connection profile can only be deleted if it is not in use by any
/// active migration jobs.
///
/// @param name Required. Name of the connection profile resource to delete.
/// @param options Optional. Operation options.
/// @return
/// @googleapis_link{google::cloud::clouddms::v1::OperationMetadata,google/cloud/clouddms/v1/clouddms.proto#L601}
///
/// [google.cloud.clouddms.v1.DeleteConnectionProfileRequest]:
/// @googleapis_reference_link{google/cloud/clouddms/v1/clouddms.proto#L577}
/// [google.cloud.clouddms.v1.OperationMetadata]:
/// @googleapis_reference_link{google/cloud/clouddms/v1/clouddms.proto#L601}
///
future<StatusOr<google::cloud::clouddms::v1::OperationMetadata>>
DeleteConnectionProfile(std::string const& name, Options options = {});
///
/// Deletes a single Database Migration Service connection profile.
/// A connection profile can only be deleted if it is not in use by any
/// active migration jobs.
///
/// @param request
/// @googleapis_link{google::cloud::clouddms::v1::DeleteConnectionProfileRequest,google/cloud/clouddms/v1/clouddms.proto#L577}
/// @param options Optional. Operation options.
/// @return
/// @googleapis_link{google::cloud::clouddms::v1::OperationMetadata,google/cloud/clouddms/v1/clouddms.proto#L601}
///
/// [google.cloud.clouddms.v1.DeleteConnectionProfileRequest]:
/// @googleapis_reference_link{google/cloud/clouddms/v1/clouddms.proto#L577}
/// [google.cloud.clouddms.v1.OperationMetadata]:
/// @googleapis_reference_link{google/cloud/clouddms/v1/clouddms.proto#L601}
///
future<StatusOr<google::cloud::clouddms::v1::OperationMetadata>>
DeleteConnectionProfile(
google::cloud::clouddms::v1::DeleteConnectionProfileRequest const&
request,
Options options = {});
private:
std::shared_ptr<DataMigrationServiceConnection> connection_;
Options options_;
};
GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END
} // namespace datamigration
} // namespace cloud
} // namespace google
#endif // GOOGLE_CLOUD_CPP_GOOGLE_CLOUD_DATAMIGRATION_DATA_MIGRATION_CLIENT_H
| 45.228296 | 128 | 0.734928 | [
"object"
] |
d6dd716ee12c5e7ff66802c1192153e1c3b519aa | 3,732 | h | C | components/password_manager/core/browser/http_password_store_migrator.h | mghgroup/Glide-Browser | 6a4c1eaa6632ec55014fee87781c6bbbb92a2af5 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | components/password_manager/core/browser/http_password_store_migrator.h | mghgroup/Glide-Browser | 6a4c1eaa6632ec55014fee87781c6bbbb92a2af5 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | components/password_manager/core/browser/http_password_store_migrator.h | mghgroup/Glide-Browser | 6a4c1eaa6632ec55014fee87781c6bbbb92a2af5 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 2 | 2021-01-05T23:43:46.000Z | 2021-01-07T23:36:34.000Z | // Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef COMPONENTS_PASSWORD_MANAGER_CORE_BROWSER_HTTP_PASSWORD_STORE_MIGRATOR_H_
#define COMPONENTS_PASSWORD_MANAGER_CORE_BROWSER_HTTP_PASSWORD_STORE_MIGRATOR_H_
#include <memory>
#include <vector>
#include "base/macros.h"
#include "base/sequence_checker.h"
#include "components/password_manager/core/browser/hsts_query.h"
#include "components/password_manager/core/browser/password_store_consumer.h"
#include "url/origin.h"
namespace autofill {
struct PasswordForm;
}
namespace password_manager {
// These values are persisted to logs. Entries should not be renumbered and
// numeric values should never be reused.
//
// Needs to stay in sync with HttpPasswordMigrationMode in enums.xml.
enum class HttpPasswordMigrationMode {
// HTTP credentials are deleted after migration to HTTPS.
kMove = 0,
// HTTP credentials are kept after migration to HTTPS.
kCopy = 1,
kMaxValue = kCopy,
};
// The class is responsible for migrating the passwords saved on HTTP to HTTPS
// origin. It automatically determines whether HTTP passwords should be moved or
// copied depending on the site's HSTS status. If a site has HSTS enabled, the
// HTTP password is considered obsolete and will be replaced by an HTTPS
// version. If HSTS is not enabled, some parts of the site might still be served
// via HTTP, which is why the password is copied in this case.
// Furthermore, if a site has migrated to HTTPS and HSTS is enabled, the
// corresponding HTTP site statistics are cleared as well, since they are
// obsolete.
class HttpPasswordStoreMigrator : public PasswordStoreConsumer {
public:
// API to be implemented by an embedder of HttpPasswordStoreMigrator.
class Consumer {
public:
virtual ~Consumer() = default;
// Notify the embedder that |forms| were migrated to HTTPS. |forms| contain
// the updated HTTPS scheme.
virtual void ProcessMigratedForms(
std::vector<std::unique_ptr<autofill::PasswordForm>> forms) = 0;
};
// |https_origin| should specify a valid HTTPS URL.
HttpPasswordStoreMigrator(const url::Origin& https_origin,
PasswordStore* store,
network::mojom::NetworkContext* network_context,
Consumer* consumer);
~HttpPasswordStoreMigrator() override;
// Creates HTTPS version of |http_form|.
static autofill::PasswordForm MigrateHttpFormToHttps(
const autofill::PasswordForm& http_form);
// PasswordStoreConsumer:
void OnGetPasswordStoreResults(
std::vector<std::unique_ptr<autofill::PasswordForm>> results) override;
// Callback for PostHSTSQueryForHostAndNetworkContext.
void OnHSTSQueryResult(HSTSResult is_hsts);
private:
void ProcessPasswordStoreResults();
PasswordStore* const store_;
Consumer* consumer_;
// |ProcessPasswordStoreResults| requires that both |OnHSTSQueryResult| and
// |OnGetPasswordStoreResults| have returned. Since this can happen in an
// arbitrary order, boolean flags are introduced to indicate completion. Only
// if both are set to true |ProcessPasswordStoreResults| gets called.
bool got_hsts_query_result_ = false;
bool got_password_store_results_ = false;
HttpPasswordMigrationMode mode_ = HttpPasswordMigrationMode::kMove;
std::vector<std::unique_ptr<autofill::PasswordForm>> results_;
url::Origin http_origin_domain_;
SEQUENCE_CHECKER(sequence_checker_);
DISALLOW_COPY_AND_ASSIGN(HttpPasswordStoreMigrator);
};
} // namespace password_manager
#endif // COMPONENTS_PASSWORD_MANAGER_CORE_BROWSER_HTTP_PASSWORD_STORE_MIGRATOR_H_
| 38.081633 | 83 | 0.764737 | [
"vector"
] |
d6e36cb0fb5d25243ac21ffa7517725673b6204c | 57,016 | c | C | src/libav/libavcodec/options.c | fillest/rtmp_load | 12845c868d144195688f7158eb4126c582cfdce3 | [
"MIT"
] | 10 | 2015-05-19T08:08:02.000Z | 2020-09-26T00:58:57.000Z | src/libav/libavcodec/options.c | fillest/rtmp_load | 12845c868d144195688f7158eb4126c582cfdce3 | [
"MIT"
] | null | null | null | src/libav/libavcodec/options.c | fillest/rtmp_load | 12845c868d144195688f7158eb4126c582cfdce3 | [
"MIT"
] | 3 | 2016-07-05T12:35:52.000Z | 2022-03-31T09:13:02.000Z | /*
* Copyright (c) 2001 Fabrice Bellard
* Copyright (c) 2002-2004 Michael Niedermayer <michaelni@gmx.at>
*
* This file is part of Libav.
*
* Libav is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* Libav is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with Libav; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
/**
* @file
* Options definition for AVCodecContext.
*/
#include "avcodec.h"
#include "internal.h"
#include "libavutil/avassert.h"
#include "libavutil/opt.h"
#include <float.h> /* FLT_MIN, FLT_MAX */
static const char* context_to_name(void* ptr) {
AVCodecContext *avc= ptr;
if(avc && avc->codec && avc->codec->name)
return avc->codec->name;
else
return "NULL";
}
static void *codec_child_next(void *obj, void *prev)
{
AVCodecContext *s = obj;
if (!prev && s->codec && s->codec->priv_class && s->priv_data)
return s->priv_data;
return NULL;
}
static const AVClass *codec_child_class_next(const AVClass *prev)
{
AVCodec *c = NULL;
/* find the codec that corresponds to prev */
while (prev && (c = av_codec_next(c)))
if (c->priv_class == prev)
break;
/* find next codec with priv options */
while (c = av_codec_next(c))
if (c->priv_class)
return c->priv_class;
return NULL;
}
#define OFFSET(x) offsetof(AVCodecContext,x)
#define DEFAULT 0 //should be NAN but it does not work as it is not a constant in glibc as required by ANSI/ISO C
//these names are too long to be readable
#define V AV_OPT_FLAG_VIDEO_PARAM
#define A AV_OPT_FLAG_AUDIO_PARAM
#define S AV_OPT_FLAG_SUBTITLE_PARAM
#define E AV_OPT_FLAG_ENCODING_PARAM
#define D AV_OPT_FLAG_DECODING_PARAM
#define AV_CODEC_DEFAULT_BITRATE 200*1000
static const AVOption options[]={
{"b", "set bitrate (in bits/s)", OFFSET(bit_rate), AV_OPT_TYPE_INT, {.dbl = AV_CODEC_DEFAULT_BITRATE }, INT_MIN, INT_MAX, V|A|E},
{"ab", "this option is deprecated, use b", OFFSET(bit_rate), AV_OPT_TYPE_INT, {.dbl = AV_CODEC_DEFAULT_BITRATE }, INT_MIN, INT_MAX, A|E},
{"bt", "set video bitrate tolerance (in bits/s)", OFFSET(bit_rate_tolerance), AV_OPT_TYPE_INT, {.dbl = AV_CODEC_DEFAULT_BITRATE*20 }, 1, INT_MAX, V|E},
{"flags", NULL, OFFSET(flags), AV_OPT_TYPE_FLAGS, {.dbl = DEFAULT }, 0, UINT_MAX, V|A|E|D, "flags"},
{"mv4", "use four motion vector by macroblock (mpeg4)", 0, AV_OPT_TYPE_CONST, {.dbl = CODEC_FLAG_4MV }, INT_MIN, INT_MAX, V|E, "flags"},
#if FF_API_MPEGVIDEO_GLOBAL_OPTS
{"obmc", "use overlapped block motion compensation (h263+)", 0, AV_OPT_TYPE_CONST, {.dbl = CODEC_FLAG_OBMC }, INT_MIN, INT_MAX, V|E, "flags"},
#endif
{"qpel", "use 1/4 pel motion compensation", 0, AV_OPT_TYPE_CONST, {.dbl = CODEC_FLAG_QPEL }, INT_MIN, INT_MAX, V|E, "flags"},
{"loop", "use loop filter", 0, AV_OPT_TYPE_CONST, {.dbl = CODEC_FLAG_LOOP_FILTER }, INT_MIN, INT_MAX, V|E, "flags"},
{"qscale", "use fixed qscale", 0, AV_OPT_TYPE_CONST, {.dbl = CODEC_FLAG_QSCALE }, INT_MIN, INT_MAX, 0, "flags"},
{"gmc", "use gmc", 0, AV_OPT_TYPE_CONST, {.dbl = CODEC_FLAG_GMC }, INT_MIN, INT_MAX, V|E, "flags"},
{"mv0", "always try a mb with mv=<0,0>", 0, AV_OPT_TYPE_CONST, {.dbl = CODEC_FLAG_MV0 }, INT_MIN, INT_MAX, V|E, "flags"},
#if FF_API_MPEGVIDEO_GLOBAL_OPTS
{"part", "use data partitioning", 0, AV_OPT_TYPE_CONST, {.dbl = CODEC_FLAG_PART }, INT_MIN, INT_MAX, V|E, "flags"},
#endif
{"input_preserved", NULL, 0, AV_OPT_TYPE_CONST, {.dbl = CODEC_FLAG_INPUT_PRESERVED }, INT_MIN, INT_MAX, 0, "flags"},
{"pass1", "use internal 2pass ratecontrol in first pass mode", 0, AV_OPT_TYPE_CONST, {.dbl = CODEC_FLAG_PASS1 }, INT_MIN, INT_MAX, 0, "flags"},
{"pass2", "use internal 2pass ratecontrol in second pass mode", 0, AV_OPT_TYPE_CONST, {.dbl = CODEC_FLAG_PASS2 }, INT_MIN, INT_MAX, 0, "flags"},
#if FF_API_MJPEG_GLOBAL_OPTS
{"extern_huff", "use external huffman table (for mjpeg)", 0, AV_OPT_TYPE_CONST, {.dbl = CODEC_FLAG_EXTERN_HUFF }, INT_MIN, INT_MAX, 0, "flags"},
#endif
{"gray", "only decode/encode grayscale", 0, AV_OPT_TYPE_CONST, {.dbl = CODEC_FLAG_GRAY }, INT_MIN, INT_MAX, V|E|D, "flags"},
{"emu_edge", "don't draw edges", 0, AV_OPT_TYPE_CONST, {.dbl = CODEC_FLAG_EMU_EDGE }, INT_MIN, INT_MAX, 0, "flags"},
{"psnr", "error[?] variables will be set during encoding", 0, AV_OPT_TYPE_CONST, {.dbl = CODEC_FLAG_PSNR }, INT_MIN, INT_MAX, V|E, "flags"},
{"truncated", NULL, 0, AV_OPT_TYPE_CONST, {.dbl = CODEC_FLAG_TRUNCATED }, INT_MIN, INT_MAX, 0, "flags"},
{"naq", "normalize adaptive quantization", 0, AV_OPT_TYPE_CONST, {.dbl = CODEC_FLAG_NORMALIZE_AQP }, INT_MIN, INT_MAX, V|E, "flags"},
{"ildct", "use interlaced dct", 0, AV_OPT_TYPE_CONST, {.dbl = CODEC_FLAG_INTERLACED_DCT }, INT_MIN, INT_MAX, V|E, "flags"},
{"low_delay", "force low delay", 0, AV_OPT_TYPE_CONST, {.dbl = CODEC_FLAG_LOW_DELAY }, INT_MIN, INT_MAX, V|D|E, "flags"},
#if FF_API_MPEGVIDEO_GLOBAL_OPTS
{"alt", "enable alternate scantable (mpeg2/mpeg4)", 0, AV_OPT_TYPE_CONST, {.dbl = CODEC_FLAG_ALT_SCAN }, INT_MIN, INT_MAX, V|E, "flags"},
#endif
{"global_header", "place global headers in extradata instead of every keyframe", 0, AV_OPT_TYPE_CONST, {.dbl = CODEC_FLAG_GLOBAL_HEADER }, INT_MIN, INT_MAX, V|A|E, "flags"},
{"bitexact", "use only bitexact stuff (except (i)dct)", 0, AV_OPT_TYPE_CONST, {.dbl = CODEC_FLAG_BITEXACT }, INT_MIN, INT_MAX, A|V|S|D|E, "flags"},
{"aic", "h263 advanced intra coding / mpeg4 ac prediction", 0, AV_OPT_TYPE_CONST, {.dbl = CODEC_FLAG_AC_PRED }, INT_MIN, INT_MAX, V|E, "flags"},
#if FF_API_MPEGVIDEO_GLOBAL_OPTS
{"umv", "use unlimited motion vectors", 0, AV_OPT_TYPE_CONST, {.dbl = CODEC_FLAG_H263P_UMV }, INT_MIN, INT_MAX, V|E, "flags"},
#endif
{"cbp", "use rate distortion optimization for cbp", 0, AV_OPT_TYPE_CONST, {.dbl = CODEC_FLAG_CBP_RD }, INT_MIN, INT_MAX, V|E, "flags"},
{"qprd", "use rate distortion optimization for qp selection", 0, AV_OPT_TYPE_CONST, {.dbl = CODEC_FLAG_QP_RD }, INT_MIN, INT_MAX, V|E, "flags"},
#if FF_API_MPEGVIDEO_GLOBAL_OPTS
{"aiv", "h263 alternative inter vlc", 0, AV_OPT_TYPE_CONST, {.dbl = CODEC_FLAG_H263P_AIV }, INT_MIN, INT_MAX, V|E, "flags"},
{"slice", NULL, 0, AV_OPT_TYPE_CONST, {.dbl = CODEC_FLAG_H263P_SLICE_STRUCT }, INT_MIN, INT_MAX, V|E, "flags"},
#endif
{"ilme", "interlaced motion estimation", 0, AV_OPT_TYPE_CONST, {.dbl = CODEC_FLAG_INTERLACED_ME }, INT_MIN, INT_MAX, V|E, "flags"},
#if FF_API_MPEGVIDEO_GLOBAL_OPTS
{"scan_offset", "will reserve space for svcd scan offset user data", 0, AV_OPT_TYPE_CONST, {.dbl = CODEC_FLAG_SVCD_SCAN_OFFSET }, INT_MIN, INT_MAX, V|E, "flags"},
#endif
{"cgop", "closed gop", 0, AV_OPT_TYPE_CONST, {.dbl = CODEC_FLAG_CLOSED_GOP }, INT_MIN, INT_MAX, V|E, "flags"},
{"fast", "allow non spec compliant speedup tricks", 0, AV_OPT_TYPE_CONST, {.dbl = CODEC_FLAG2_FAST }, INT_MIN, INT_MAX, V|E, "flags2"},
{"sgop", "strictly enforce gop size", 0, AV_OPT_TYPE_CONST, {.dbl = CODEC_FLAG2_STRICT_GOP }, INT_MIN, INT_MAX, V|E, "flags2"},
{"noout", "skip bitstream encoding", 0, AV_OPT_TYPE_CONST, {.dbl = CODEC_FLAG2_NO_OUTPUT }, INT_MIN, INT_MAX, V|E, "flags2"},
{"local_header", "place global headers at every keyframe instead of in extradata", 0, AV_OPT_TYPE_CONST, {.dbl = CODEC_FLAG2_LOCAL_HEADER }, INT_MIN, INT_MAX, V|E, "flags2"},
{"sub_id", NULL, OFFSET(sub_id), AV_OPT_TYPE_INT, {.dbl = DEFAULT }, INT_MIN, INT_MAX},
{"me_method", "set motion estimation method", OFFSET(me_method), AV_OPT_TYPE_INT, {.dbl = ME_EPZS }, INT_MIN, INT_MAX, V|E, "me_method"},
{"zero", "zero motion estimation (fastest)", 0, AV_OPT_TYPE_CONST, {.dbl = ME_ZERO }, INT_MIN, INT_MAX, V|E, "me_method" },
{"full", "full motion estimation (slowest)", 0, AV_OPT_TYPE_CONST, {.dbl = ME_FULL }, INT_MIN, INT_MAX, V|E, "me_method" },
{"epzs", "EPZS motion estimation (default)", 0, AV_OPT_TYPE_CONST, {.dbl = ME_EPZS }, INT_MIN, INT_MAX, V|E, "me_method" },
{"esa", "esa motion estimation (alias for full)", 0, AV_OPT_TYPE_CONST, {.dbl = ME_FULL }, INT_MIN, INT_MAX, V|E, "me_method" },
{"tesa", "tesa motion estimation", 0, AV_OPT_TYPE_CONST, {.dbl = ME_TESA }, INT_MIN, INT_MAX, V|E, "me_method" },
{"dia", "dia motion estimation (alias for epzs)", 0, AV_OPT_TYPE_CONST, {.dbl = ME_EPZS }, INT_MIN, INT_MAX, V|E, "me_method" },
{"log", "log motion estimation", 0, AV_OPT_TYPE_CONST, {.dbl = ME_LOG }, INT_MIN, INT_MAX, V|E, "me_method" },
{"phods", "phods motion estimation", 0, AV_OPT_TYPE_CONST, {.dbl = ME_PHODS }, INT_MIN, INT_MAX, V|E, "me_method" },
{"x1", "X1 motion estimation", 0, AV_OPT_TYPE_CONST, {.dbl = ME_X1 }, INT_MIN, INT_MAX, V|E, "me_method" },
{"hex", "hex motion estimation", 0, AV_OPT_TYPE_CONST, {.dbl = ME_HEX }, INT_MIN, INT_MAX, V|E, "me_method" },
{"umh", "umh motion estimation", 0, AV_OPT_TYPE_CONST, {.dbl = ME_UMH }, INT_MIN, INT_MAX, V|E, "me_method" },
{"iter", "iter motion estimation", 0, AV_OPT_TYPE_CONST, {.dbl = ME_ITER }, INT_MIN, INT_MAX, V|E, "me_method" },
{"extradata_size", NULL, OFFSET(extradata_size), AV_OPT_TYPE_INT, {.dbl = DEFAULT }, INT_MIN, INT_MAX},
{"time_base", NULL, OFFSET(time_base), AV_OPT_TYPE_RATIONAL, {.dbl = 0}, INT_MIN, INT_MAX},
{"g", "set the group of picture size", OFFSET(gop_size), AV_OPT_TYPE_INT, {.dbl = 12 }, INT_MIN, INT_MAX, V|E},
{"ar", "set audio sampling rate (in Hz)", OFFSET(sample_rate), AV_OPT_TYPE_INT, {.dbl = DEFAULT }, INT_MIN, INT_MAX, A|D|E},
{"ac", "set number of audio channels", OFFSET(channels), AV_OPT_TYPE_INT, {.dbl = DEFAULT }, INT_MIN, INT_MAX, A|D|E},
{"cutoff", "set cutoff bandwidth", OFFSET(cutoff), AV_OPT_TYPE_INT, {.dbl = DEFAULT }, INT_MIN, INT_MAX, A|E},
{"frame_size", NULL, OFFSET(frame_size), AV_OPT_TYPE_INT, {.dbl = DEFAULT }, INT_MIN, INT_MAX, A|E},
{"frame_number", NULL, OFFSET(frame_number), AV_OPT_TYPE_INT, {.dbl = DEFAULT }, INT_MIN, INT_MAX},
{"delay", NULL, OFFSET(delay), AV_OPT_TYPE_INT, {.dbl = DEFAULT }, INT_MIN, INT_MAX},
{"qcomp", "video quantizer scale compression (VBR)", OFFSET(qcompress), AV_OPT_TYPE_FLOAT, {.dbl = 0.5 }, -FLT_MAX, FLT_MAX, V|E},
{"qblur", "video quantizer scale blur (VBR)", OFFSET(qblur), AV_OPT_TYPE_FLOAT, {.dbl = 0.5 }, -1, FLT_MAX, V|E},
{"qmin", "min video quantizer scale (VBR)", OFFSET(qmin), AV_OPT_TYPE_INT, {.dbl = 2 }, -1, 69, V|E},
{"qmax", "max video quantizer scale (VBR)", OFFSET(qmax), AV_OPT_TYPE_INT, {.dbl = 31 }, -1, 69, V|E},
{"qdiff", "max difference between the quantizer scale (VBR)", OFFSET(max_qdiff), AV_OPT_TYPE_INT, {.dbl = 3 }, INT_MIN, INT_MAX, V|E},
{"bf", "use 'frames' B frames", OFFSET(max_b_frames), AV_OPT_TYPE_INT, {.dbl = DEFAULT }, -1, FF_MAX_B_FRAMES, V|E},
{"b_qfactor", "qp factor between p and b frames", OFFSET(b_quant_factor), AV_OPT_TYPE_FLOAT, {.dbl = 1.25 }, -FLT_MAX, FLT_MAX, V|E},
{"rc_strategy", "ratecontrol method", OFFSET(rc_strategy), AV_OPT_TYPE_INT, {.dbl = DEFAULT }, INT_MIN, INT_MAX, V|E},
{"b_strategy", "strategy to choose between I/P/B-frames", OFFSET(b_frame_strategy), AV_OPT_TYPE_INT, {.dbl = 0 }, INT_MIN, INT_MAX, V|E},
#if FF_API_X264_GLOBAL_OPTS
{"wpredp", "weighted prediction analysis method", OFFSET(weighted_p_pred), AV_OPT_TYPE_INT, {.dbl = -1 }, INT_MIN, INT_MAX, V|E},
#endif
{"ps", "rtp payload size in bytes", OFFSET(rtp_payload_size), AV_OPT_TYPE_INT, {.dbl = DEFAULT }, INT_MIN, INT_MAX, V|E},
{"mv_bits", NULL, OFFSET(mv_bits), AV_OPT_TYPE_INT, {.dbl = DEFAULT }, INT_MIN, INT_MAX},
{"header_bits", NULL, OFFSET(header_bits), AV_OPT_TYPE_INT, {.dbl = DEFAULT }, INT_MIN, INT_MAX},
{"i_tex_bits", NULL, OFFSET(i_tex_bits), AV_OPT_TYPE_INT, {.dbl = DEFAULT }, INT_MIN, INT_MAX},
{"p_tex_bits", NULL, OFFSET(p_tex_bits), AV_OPT_TYPE_INT, {.dbl = DEFAULT }, INT_MIN, INT_MAX},
{"i_count", NULL, OFFSET(i_count), AV_OPT_TYPE_INT, {.dbl = DEFAULT }, INT_MIN, INT_MAX},
{"p_count", NULL, OFFSET(p_count), AV_OPT_TYPE_INT, {.dbl = DEFAULT }, INT_MIN, INT_MAX},
{"skip_count", NULL, OFFSET(skip_count), AV_OPT_TYPE_INT, {.dbl = DEFAULT }, INT_MIN, INT_MAX},
{"misc_bits", NULL, OFFSET(misc_bits), AV_OPT_TYPE_INT, {.dbl = DEFAULT }, INT_MIN, INT_MAX},
{"frame_bits", NULL, OFFSET(frame_bits), AV_OPT_TYPE_INT, {.dbl = DEFAULT }, INT_MIN, INT_MAX},
{"codec_tag", NULL, OFFSET(codec_tag), AV_OPT_TYPE_INT, {.dbl = DEFAULT }, INT_MIN, INT_MAX},
{"bug", "workaround not auto detected encoder bugs", OFFSET(workaround_bugs), AV_OPT_TYPE_FLAGS, {.dbl = FF_BUG_AUTODETECT }, INT_MIN, INT_MAX, V|D, "bug"},
{"autodetect", NULL, 0, AV_OPT_TYPE_CONST, {.dbl = FF_BUG_AUTODETECT }, INT_MIN, INT_MAX, V|D, "bug"},
{"old_msmpeg4", "some old lavc generated msmpeg4v3 files (no autodetection)", 0, AV_OPT_TYPE_CONST, {.dbl = FF_BUG_OLD_MSMPEG4 }, INT_MIN, INT_MAX, V|D, "bug"},
{"xvid_ilace", "Xvid interlacing bug (autodetected if fourcc==XVIX)", 0, AV_OPT_TYPE_CONST, {.dbl = FF_BUG_XVID_ILACE }, INT_MIN, INT_MAX, V|D, "bug"},
{"ump4", "(autodetected if fourcc==UMP4)", 0, AV_OPT_TYPE_CONST, {.dbl = FF_BUG_UMP4 }, INT_MIN, INT_MAX, V|D, "bug"},
{"no_padding", "padding bug (autodetected)", 0, AV_OPT_TYPE_CONST, {.dbl = FF_BUG_NO_PADDING }, INT_MIN, INT_MAX, V|D, "bug"},
{"amv", NULL, 0, AV_OPT_TYPE_CONST, {.dbl = FF_BUG_AMV }, INT_MIN, INT_MAX, V|D, "bug"},
{"ac_vlc", "illegal vlc bug (autodetected per fourcc)", 0, AV_OPT_TYPE_CONST, {.dbl = FF_BUG_AC_VLC }, INT_MIN, INT_MAX, V|D, "bug"},
{"qpel_chroma", NULL, 0, AV_OPT_TYPE_CONST, {.dbl = FF_BUG_QPEL_CHROMA }, INT_MIN, INT_MAX, V|D, "bug"},
{"std_qpel", "old standard qpel (autodetected per fourcc/version)", 0, AV_OPT_TYPE_CONST, {.dbl = FF_BUG_STD_QPEL }, INT_MIN, INT_MAX, V|D, "bug"},
{"qpel_chroma2", NULL, 0, AV_OPT_TYPE_CONST, {.dbl = FF_BUG_QPEL_CHROMA2 }, INT_MIN, INT_MAX, V|D, "bug"},
{"direct_blocksize", "direct-qpel-blocksize bug (autodetected per fourcc/version)", 0, AV_OPT_TYPE_CONST, {.dbl = FF_BUG_DIRECT_BLOCKSIZE }, INT_MIN, INT_MAX, V|D, "bug"},
{"edge", "edge padding bug (autodetected per fourcc/version)", 0, AV_OPT_TYPE_CONST, {.dbl = FF_BUG_EDGE }, INT_MIN, INT_MAX, V|D, "bug"},
{"hpel_chroma", NULL, 0, AV_OPT_TYPE_CONST, {.dbl = FF_BUG_HPEL_CHROMA }, INT_MIN, INT_MAX, V|D, "bug"},
{"dc_clip", NULL, 0, AV_OPT_TYPE_CONST, {.dbl = FF_BUG_DC_CLIP }, INT_MIN, INT_MAX, V|D, "bug"},
{"ms", "workaround various bugs in microsofts broken decoders", 0, AV_OPT_TYPE_CONST, {.dbl = FF_BUG_MS }, INT_MIN, INT_MAX, V|D, "bug"},
{"trunc", "trancated frames", 0, AV_OPT_TYPE_CONST, {.dbl = FF_BUG_TRUNCATED}, INT_MIN, INT_MAX, V|D, "bug"},
{"lelim", "single coefficient elimination threshold for luminance (negative values also consider dc coefficient)", OFFSET(luma_elim_threshold), AV_OPT_TYPE_INT, {.dbl = DEFAULT }, INT_MIN, INT_MAX, V|E},
{"celim", "single coefficient elimination threshold for chrominance (negative values also consider dc coefficient)", OFFSET(chroma_elim_threshold), AV_OPT_TYPE_INT, {.dbl = DEFAULT }, INT_MIN, INT_MAX, V|E},
{"strict", "how strictly to follow the standards", OFFSET(strict_std_compliance), AV_OPT_TYPE_INT, {.dbl = DEFAULT }, INT_MIN, INT_MAX, A|V|D|E, "strict"},
{"very", "strictly conform to a older more strict version of the spec or reference software", 0, AV_OPT_TYPE_CONST, {.dbl = FF_COMPLIANCE_VERY_STRICT }, INT_MIN, INT_MAX, V|D|E, "strict"},
{"strict", "strictly conform to all the things in the spec no matter what consequences", 0, AV_OPT_TYPE_CONST, {.dbl = FF_COMPLIANCE_STRICT }, INT_MIN, INT_MAX, V|D|E, "strict"},
{"normal", NULL, 0, AV_OPT_TYPE_CONST, {.dbl = FF_COMPLIANCE_NORMAL }, INT_MIN, INT_MAX, V|D|E, "strict"},
{"unofficial", "allow unofficial extensions", 0, AV_OPT_TYPE_CONST, {.dbl = FF_COMPLIANCE_UNOFFICIAL }, INT_MIN, INT_MAX, V|D|E, "strict"},
{"experimental", "allow non standardized experimental things", 0, AV_OPT_TYPE_CONST, {.dbl = FF_COMPLIANCE_EXPERIMENTAL }, INT_MIN, INT_MAX, V|D|E, "strict"},
{"b_qoffset", "qp offset between P and B frames", OFFSET(b_quant_offset), AV_OPT_TYPE_FLOAT, {.dbl = 1.25 }, -FLT_MAX, FLT_MAX, V|E},
#if FF_API_ER
{"er", "set error detection aggressivity", OFFSET(error_recognition), AV_OPT_TYPE_INT, {.dbl = FF_ER_CAREFUL }, INT_MIN, INT_MAX, A|V|D, "er"},
{"careful", NULL, 0, AV_OPT_TYPE_CONST, {.dbl = FF_ER_CAREFUL }, INT_MIN, INT_MAX, V|D, "er"},
{"compliant", NULL, 0, AV_OPT_TYPE_CONST, {.dbl = FF_ER_COMPLIANT }, INT_MIN, INT_MAX, V|D, "er"},
{"aggressive", NULL, 0, AV_OPT_TYPE_CONST, {.dbl = FF_ER_AGGRESSIVE }, INT_MIN, INT_MAX, V|D, "er"},
{"very_aggressive", NULL, 0, AV_OPT_TYPE_CONST, {.dbl = FF_ER_VERY_AGGRESSIVE }, INT_MIN, INT_MAX, V|D, "er"},
{"explode", "abort decoding on error recognition", 0, AV_OPT_TYPE_CONST, {.dbl = FF_ER_EXPLODE }, INT_MIN, INT_MAX, V|D, "er"},
#endif /* FF_API_ER */
{"err_detect", "set error detection flags", OFFSET(err_recognition), AV_OPT_TYPE_FLAGS, {.dbl = AV_EF_CRCCHECK }, INT_MIN, INT_MAX, A|V|D, "err_detect"},
{"crccheck", "verify embedded CRCs", 0, AV_OPT_TYPE_CONST, {.dbl = AV_EF_CRCCHECK }, INT_MIN, INT_MAX, V|D, "err_detect"},
{"bitstream", "detect bitstream specification deviations", 0, AV_OPT_TYPE_CONST, {.dbl = AV_EF_BITSTREAM }, INT_MIN, INT_MAX, V|D, "err_detect"},
{"buffer", "detect improper bitstream length", 0, AV_OPT_TYPE_CONST, {.dbl = AV_EF_BUFFER }, INT_MIN, INT_MAX, V|D, "err_detect"},
{"explode", "abort decoding on minor error detection", 0, AV_OPT_TYPE_CONST, {.dbl = AV_EF_EXPLODE }, INT_MIN, INT_MAX, V|D, "err_detect"},
{"has_b_frames", NULL, OFFSET(has_b_frames), AV_OPT_TYPE_INT, {.dbl = DEFAULT }, INT_MIN, INT_MAX},
{"block_align", NULL, OFFSET(block_align), AV_OPT_TYPE_INT, {.dbl = DEFAULT }, INT_MIN, INT_MAX},
#if FF_API_PARSE_FRAME
{"parse_only", NULL, OFFSET(parse_only), AV_OPT_TYPE_INT, {.dbl = DEFAULT }, INT_MIN, INT_MAX},
#endif
{"mpeg_quant", "use MPEG quantizers instead of H.263", OFFSET(mpeg_quant), AV_OPT_TYPE_INT, {.dbl = DEFAULT }, INT_MIN, INT_MAX, V|E},
{"qsquish", "how to keep quantizer between qmin and qmax (0 = clip, 1 = use differentiable function)", OFFSET(rc_qsquish), AV_OPT_TYPE_FLOAT, {.dbl = DEFAULT }, 0, 99, V|E},
{"rc_qmod_amp", "experimental quantizer modulation", OFFSET(rc_qmod_amp), AV_OPT_TYPE_FLOAT, {.dbl = DEFAULT }, -FLT_MAX, FLT_MAX, V|E},
{"rc_qmod_freq", "experimental quantizer modulation", OFFSET(rc_qmod_freq), AV_OPT_TYPE_INT, {.dbl = DEFAULT }, INT_MIN, INT_MAX, V|E},
{"rc_override_count", NULL, OFFSET(rc_override_count), AV_OPT_TYPE_INT, {.dbl = DEFAULT }, INT_MIN, INT_MAX},
{"rc_eq", "set rate control equation", OFFSET(rc_eq), AV_OPT_TYPE_STRING, {.str = NULL}, CHAR_MIN, CHAR_MAX, V|E},
{"maxrate", "set max bitrate tolerance (in bits/s)", OFFSET(rc_max_rate), AV_OPT_TYPE_INT, {.dbl = DEFAULT }, INT_MIN, INT_MAX, V|A|E},
{"minrate", "set min bitrate tolerance (in bits/s)", OFFSET(rc_min_rate), AV_OPT_TYPE_INT, {.dbl = DEFAULT }, INT_MIN, INT_MAX, V|A|E},
{"bufsize", "set ratecontrol buffer size (in bits)", OFFSET(rc_buffer_size), AV_OPT_TYPE_INT, {.dbl = DEFAULT }, INT_MIN, INT_MAX, A|V|E},
{"rc_buf_aggressivity", "currently useless", OFFSET(rc_buffer_aggressivity), AV_OPT_TYPE_FLOAT, {.dbl = 1.0 }, -FLT_MAX, FLT_MAX, V|E},
{"i_qfactor", "qp factor between P and I frames", OFFSET(i_quant_factor), AV_OPT_TYPE_FLOAT, {.dbl = -0.8 }, -FLT_MAX, FLT_MAX, V|E},
{"i_qoffset", "qp offset between P and I frames", OFFSET(i_quant_offset), AV_OPT_TYPE_FLOAT, {.dbl = 0.0 }, -FLT_MAX, FLT_MAX, V|E},
{"rc_init_cplx", "initial complexity for 1-pass encoding", OFFSET(rc_initial_cplx), AV_OPT_TYPE_FLOAT, {.dbl = DEFAULT }, -FLT_MAX, FLT_MAX, V|E},
{"dct", "DCT algorithm", OFFSET(dct_algo), AV_OPT_TYPE_INT, {.dbl = DEFAULT }, 0, INT_MAX, V|E, "dct"},
{"auto", "autoselect a good one (default)", 0, AV_OPT_TYPE_CONST, {.dbl = FF_DCT_AUTO }, INT_MIN, INT_MAX, V|E, "dct"},
{"fastint", "fast integer", 0, AV_OPT_TYPE_CONST, {.dbl = FF_DCT_FASTINT }, INT_MIN, INT_MAX, V|E, "dct"},
{"int", "accurate integer", 0, AV_OPT_TYPE_CONST, {.dbl = FF_DCT_INT }, INT_MIN, INT_MAX, V|E, "dct"},
{"mmx", NULL, 0, AV_OPT_TYPE_CONST, {.dbl = FF_DCT_MMX }, INT_MIN, INT_MAX, V|E, "dct"},
{"mlib", NULL, 0, AV_OPT_TYPE_CONST, {.dbl = FF_DCT_MLIB }, INT_MIN, INT_MAX, V|E, "dct"},
{"altivec", NULL, 0, AV_OPT_TYPE_CONST, {.dbl = FF_DCT_ALTIVEC }, INT_MIN, INT_MAX, V|E, "dct"},
{"faan", "floating point AAN DCT", 0, AV_OPT_TYPE_CONST, {.dbl = FF_DCT_FAAN }, INT_MIN, INT_MAX, V|E, "dct"},
{"lumi_mask", "compresses bright areas stronger than medium ones", OFFSET(lumi_masking), AV_OPT_TYPE_FLOAT, {.dbl = 0 }, -FLT_MAX, FLT_MAX, V|E},
{"tcplx_mask", "temporal complexity masking", OFFSET(temporal_cplx_masking), AV_OPT_TYPE_FLOAT, {.dbl = 0 }, -FLT_MAX, FLT_MAX, V|E},
{"scplx_mask", "spatial complexity masking", OFFSET(spatial_cplx_masking), AV_OPT_TYPE_FLOAT, {.dbl = 0 }, -FLT_MAX, FLT_MAX, V|E},
{"p_mask", "inter masking", OFFSET(p_masking), AV_OPT_TYPE_FLOAT, {.dbl = 0 }, -FLT_MAX, FLT_MAX, V|E},
{"dark_mask", "compresses dark areas stronger than medium ones", OFFSET(dark_masking), AV_OPT_TYPE_FLOAT, {.dbl = 0 }, -FLT_MAX, FLT_MAX, V|E},
{"idct", "select IDCT implementation", OFFSET(idct_algo), AV_OPT_TYPE_INT, {.dbl = DEFAULT }, 0, INT_MAX, V|E|D, "idct"},
{"auto", NULL, 0, AV_OPT_TYPE_CONST, {.dbl = FF_IDCT_AUTO }, INT_MIN, INT_MAX, V|E|D, "idct"},
{"int", NULL, 0, AV_OPT_TYPE_CONST, {.dbl = FF_IDCT_INT }, INT_MIN, INT_MAX, V|E|D, "idct"},
{"simple", NULL, 0, AV_OPT_TYPE_CONST, {.dbl = FF_IDCT_SIMPLE }, INT_MIN, INT_MAX, V|E|D, "idct"},
{"simplemmx", NULL, 0, AV_OPT_TYPE_CONST, {.dbl = FF_IDCT_SIMPLEMMX }, INT_MIN, INT_MAX, V|E|D, "idct"},
{"libmpeg2mmx", NULL, 0, AV_OPT_TYPE_CONST, {.dbl = FF_IDCT_LIBMPEG2MMX }, INT_MIN, INT_MAX, V|E|D, "idct"},
{"ps2", NULL, 0, AV_OPT_TYPE_CONST, {.dbl = FF_IDCT_PS2 }, INT_MIN, INT_MAX, V|E|D, "idct"},
{"mlib", NULL, 0, AV_OPT_TYPE_CONST, {.dbl = FF_IDCT_MLIB }, INT_MIN, INT_MAX, V|E|D, "idct"},
{"arm", NULL, 0, AV_OPT_TYPE_CONST, {.dbl = FF_IDCT_ARM }, INT_MIN, INT_MAX, V|E|D, "idct"},
{"altivec", NULL, 0, AV_OPT_TYPE_CONST, {.dbl = FF_IDCT_ALTIVEC }, INT_MIN, INT_MAX, V|E|D, "idct"},
{"sh4", NULL, 0, AV_OPT_TYPE_CONST, {.dbl = FF_IDCT_SH4 }, INT_MIN, INT_MAX, V|E|D, "idct"},
{"simplearm", NULL, 0, AV_OPT_TYPE_CONST, {.dbl = FF_IDCT_SIMPLEARM }, INT_MIN, INT_MAX, V|E|D, "idct"},
{"simplearmv5te", NULL, 0, AV_OPT_TYPE_CONST, {.dbl = FF_IDCT_SIMPLEARMV5TE }, INT_MIN, INT_MAX, V|E|D, "idct"},
{"simplearmv6", NULL, 0, AV_OPT_TYPE_CONST, {.dbl = FF_IDCT_SIMPLEARMV6 }, INT_MIN, INT_MAX, V|E|D, "idct"},
{"simpleneon", NULL, 0, AV_OPT_TYPE_CONST, {.dbl = FF_IDCT_SIMPLENEON }, INT_MIN, INT_MAX, V|E|D, "idct"},
{"simplealpha", NULL, 0, AV_OPT_TYPE_CONST, {.dbl = FF_IDCT_SIMPLEALPHA }, INT_MIN, INT_MAX, V|E|D, "idct"},
{"h264", NULL, 0, AV_OPT_TYPE_CONST, {.dbl = FF_IDCT_H264 }, INT_MIN, INT_MAX, V|E|D, "idct"},
{"vp3", NULL, 0, AV_OPT_TYPE_CONST, {.dbl = FF_IDCT_VP3 }, INT_MIN, INT_MAX, V|E|D, "idct"},
{"ipp", NULL, 0, AV_OPT_TYPE_CONST, {.dbl = FF_IDCT_IPP }, INT_MIN, INT_MAX, V|E|D, "idct"},
{"xvidmmx", NULL, 0, AV_OPT_TYPE_CONST, {.dbl = FF_IDCT_XVIDMMX }, INT_MIN, INT_MAX, V|E|D, "idct"},
{"faani", "floating point AAN IDCT", 0, AV_OPT_TYPE_CONST, {.dbl = FF_IDCT_FAAN }, INT_MIN, INT_MAX, V|D|E, "idct"},
{"slice_count", NULL, OFFSET(slice_count), AV_OPT_TYPE_INT, {.dbl = DEFAULT }, INT_MIN, INT_MAX},
{"ec", "set error concealment strategy", OFFSET(error_concealment), AV_OPT_TYPE_FLAGS, {.dbl = 3 }, INT_MIN, INT_MAX, V|D, "ec"},
{"guess_mvs", "iterative motion vector (MV) search (slow)", 0, AV_OPT_TYPE_CONST, {.dbl = FF_EC_GUESS_MVS }, INT_MIN, INT_MAX, V|D, "ec"},
{"deblock", "use strong deblock filter for damaged MBs", 0, AV_OPT_TYPE_CONST, {.dbl = FF_EC_DEBLOCK }, INT_MIN, INT_MAX, V|D, "ec"},
{"bits_per_coded_sample", NULL, OFFSET(bits_per_coded_sample), AV_OPT_TYPE_INT, {.dbl = DEFAULT }, INT_MIN, INT_MAX},
{"pred", "prediction method", OFFSET(prediction_method), AV_OPT_TYPE_INT, {.dbl = DEFAULT }, INT_MIN, INT_MAX, V|E, "pred"},
{"left", NULL, 0, AV_OPT_TYPE_CONST, {.dbl = FF_PRED_LEFT }, INT_MIN, INT_MAX, V|E, "pred"},
{"plane", NULL, 0, AV_OPT_TYPE_CONST, {.dbl = FF_PRED_PLANE }, INT_MIN, INT_MAX, V|E, "pred"},
{"median", NULL, 0, AV_OPT_TYPE_CONST, {.dbl = FF_PRED_MEDIAN }, INT_MIN, INT_MAX, V|E, "pred"},
{"aspect", "sample aspect ratio", OFFSET(sample_aspect_ratio), AV_OPT_TYPE_RATIONAL, {.dbl = 0}, 0, 10, V|E},
{"debug", "print specific debug info", OFFSET(debug), AV_OPT_TYPE_FLAGS, {.dbl = DEFAULT }, 0, INT_MAX, V|A|S|E|D, "debug"},
{"pict", "picture info", 0, AV_OPT_TYPE_CONST, {.dbl = FF_DEBUG_PICT_INFO }, INT_MIN, INT_MAX, V|D, "debug"},
{"rc", "rate control", 0, AV_OPT_TYPE_CONST, {.dbl = FF_DEBUG_RC }, INT_MIN, INT_MAX, V|E, "debug"},
{"bitstream", NULL, 0, AV_OPT_TYPE_CONST, {.dbl = FF_DEBUG_BITSTREAM }, INT_MIN, INT_MAX, V|D, "debug"},
{"mb_type", "macroblock (MB) type", 0, AV_OPT_TYPE_CONST, {.dbl = FF_DEBUG_MB_TYPE }, INT_MIN, INT_MAX, V|D, "debug"},
{"qp", "per-block quantization parameter (QP)", 0, AV_OPT_TYPE_CONST, {.dbl = FF_DEBUG_QP }, INT_MIN, INT_MAX, V|D, "debug"},
{"mv", "motion vector", 0, AV_OPT_TYPE_CONST, {.dbl = FF_DEBUG_MV }, INT_MIN, INT_MAX, V|D, "debug"},
{"dct_coeff", NULL, 0, AV_OPT_TYPE_CONST, {.dbl = FF_DEBUG_DCT_COEFF }, INT_MIN, INT_MAX, V|D, "debug"},
{"skip", NULL, 0, AV_OPT_TYPE_CONST, {.dbl = FF_DEBUG_SKIP }, INT_MIN, INT_MAX, V|D, "debug"},
{"startcode", NULL, 0, AV_OPT_TYPE_CONST, {.dbl = FF_DEBUG_STARTCODE }, INT_MIN, INT_MAX, V|D, "debug"},
{"pts", NULL, 0, AV_OPT_TYPE_CONST, {.dbl = FF_DEBUG_PTS }, INT_MIN, INT_MAX, V|D, "debug"},
{"er", "error recognition", 0, AV_OPT_TYPE_CONST, {.dbl = FF_DEBUG_ER }, INT_MIN, INT_MAX, V|D, "debug"},
{"mmco", "memory management control operations (H.264)", 0, AV_OPT_TYPE_CONST, {.dbl = FF_DEBUG_MMCO }, INT_MIN, INT_MAX, V|D, "debug"},
{"bugs", NULL, 0, AV_OPT_TYPE_CONST, {.dbl = FF_DEBUG_BUGS }, INT_MIN, INT_MAX, V|D, "debug"},
{"vis_qp", "visualize quantization parameter (QP), lower QP are tinted greener", 0, AV_OPT_TYPE_CONST, {.dbl = FF_DEBUG_VIS_QP }, INT_MIN, INT_MAX, V|D, "debug"},
{"vis_mb_type", "visualize block types", 0, AV_OPT_TYPE_CONST, {.dbl = FF_DEBUG_VIS_MB_TYPE }, INT_MIN, INT_MAX, V|D, "debug"},
{"buffers", "picture buffer allocations", 0, AV_OPT_TYPE_CONST, {.dbl = FF_DEBUG_BUFFERS }, INT_MIN, INT_MAX, V|D, "debug"},
{"thread_ops", "threading operations", 0, AV_OPT_TYPE_CONST, {.dbl = FF_DEBUG_THREADS }, INT_MIN, INT_MAX, V|D, "debug"},
{"vismv", "visualize motion vectors (MVs)", OFFSET(debug_mv), AV_OPT_TYPE_INT, {.dbl = DEFAULT }, 0, INT_MAX, V|D, "debug_mv"},
{"pf", "forward predicted MVs of P-frames", 0, AV_OPT_TYPE_CONST, {.dbl = FF_DEBUG_VIS_MV_P_FOR }, INT_MIN, INT_MAX, V|D, "debug_mv"},
{"bf", "forward predicted MVs of B-frames", 0, AV_OPT_TYPE_CONST, {.dbl = FF_DEBUG_VIS_MV_B_FOR }, INT_MIN, INT_MAX, V|D, "debug_mv"},
{"bb", "backward predicted MVs of B-frames", 0, AV_OPT_TYPE_CONST, {.dbl = FF_DEBUG_VIS_MV_B_BACK }, INT_MIN, INT_MAX, V|D, "debug_mv"},
{"cmp", "full pel me compare function", OFFSET(me_cmp), AV_OPT_TYPE_INT, {.dbl = DEFAULT }, INT_MIN, INT_MAX, V|E, "cmp_func"},
{"subcmp", "sub pel me compare function", OFFSET(me_sub_cmp), AV_OPT_TYPE_INT, {.dbl = DEFAULT }, INT_MIN, INT_MAX, V|E, "cmp_func"},
{"mbcmp", "macroblock compare function", OFFSET(mb_cmp), AV_OPT_TYPE_INT, {.dbl = DEFAULT }, INT_MIN, INT_MAX, V|E, "cmp_func"},
{"ildctcmp", "interlaced dct compare function", OFFSET(ildct_cmp), AV_OPT_TYPE_INT, {.dbl = FF_CMP_VSAD }, INT_MIN, INT_MAX, V|E, "cmp_func"},
{"dia_size", "diamond type & size for motion estimation", OFFSET(dia_size), AV_OPT_TYPE_INT, {.dbl = DEFAULT }, INT_MIN, INT_MAX, V|E},
{"last_pred", "amount of motion predictors from the previous frame", OFFSET(last_predictor_count), AV_OPT_TYPE_INT, {.dbl = DEFAULT }, INT_MIN, INT_MAX, V|E},
{"preme", "pre motion estimation", OFFSET(pre_me), AV_OPT_TYPE_INT, {.dbl = DEFAULT }, INT_MIN, INT_MAX, V|E},
{"precmp", "pre motion estimation compare function", OFFSET(me_pre_cmp), AV_OPT_TYPE_INT, {.dbl = DEFAULT }, INT_MIN, INT_MAX, V|E, "cmp_func"},
{"sad", "sum of absolute differences, fast (default)", 0, AV_OPT_TYPE_CONST, {.dbl = FF_CMP_SAD }, INT_MIN, INT_MAX, V|E, "cmp_func"},
{"sse", "sum of squared errors", 0, AV_OPT_TYPE_CONST, {.dbl = FF_CMP_SSE }, INT_MIN, INT_MAX, V|E, "cmp_func"},
{"satd", "sum of absolute Hadamard transformed differences", 0, AV_OPT_TYPE_CONST, {.dbl = FF_CMP_SATD }, INT_MIN, INT_MAX, V|E, "cmp_func"},
{"dct", "sum of absolute DCT transformed differences", 0, AV_OPT_TYPE_CONST, {.dbl = FF_CMP_DCT }, INT_MIN, INT_MAX, V|E, "cmp_func"},
{"psnr", "sum of squared quantization errors (avoid, low quality)", 0, AV_OPT_TYPE_CONST, {.dbl = FF_CMP_PSNR }, INT_MIN, INT_MAX, V|E, "cmp_func"},
{"bit", "number of bits needed for the block", 0, AV_OPT_TYPE_CONST, {.dbl = FF_CMP_BIT }, INT_MIN, INT_MAX, V|E, "cmp_func"},
{"rd", "rate distortion optimal, slow", 0, AV_OPT_TYPE_CONST, {.dbl = FF_CMP_RD }, INT_MIN, INT_MAX, V|E, "cmp_func"},
{"zero", "0", 0, AV_OPT_TYPE_CONST, {.dbl = FF_CMP_ZERO }, INT_MIN, INT_MAX, V|E, "cmp_func"},
{"vsad", "sum of absolute vertical differences", 0, AV_OPT_TYPE_CONST, {.dbl = FF_CMP_VSAD }, INT_MIN, INT_MAX, V|E, "cmp_func"},
{"vsse", "sum of squared vertical differences", 0, AV_OPT_TYPE_CONST, {.dbl = FF_CMP_VSSE }, INT_MIN, INT_MAX, V|E, "cmp_func"},
{"nsse", "noise preserving sum of squared differences", 0, AV_OPT_TYPE_CONST, {.dbl = FF_CMP_NSSE }, INT_MIN, INT_MAX, V|E, "cmp_func"},
#if CONFIG_SNOW_ENCODER
{"w53", "5/3 wavelet, only used in snow", 0, AV_OPT_TYPE_CONST, {.dbl = FF_CMP_W53 }, INT_MIN, INT_MAX, V|E, "cmp_func"},
{"w97", "9/7 wavelet, only used in snow", 0, AV_OPT_TYPE_CONST, {.dbl = FF_CMP_W97 }, INT_MIN, INT_MAX, V|E, "cmp_func"},
#endif
{"dctmax", NULL, 0, AV_OPT_TYPE_CONST, {.dbl = FF_CMP_DCTMAX }, INT_MIN, INT_MAX, V|E, "cmp_func"},
{"chroma", NULL, 0, AV_OPT_TYPE_CONST, {.dbl = FF_CMP_CHROMA }, INT_MIN, INT_MAX, V|E, "cmp_func"},
{"pre_dia_size", "diamond type & size for motion estimation pre-pass", OFFSET(pre_dia_size), AV_OPT_TYPE_INT, {.dbl = DEFAULT }, INT_MIN, INT_MAX, V|E},
{"subq", "sub pel motion estimation quality", OFFSET(me_subpel_quality), AV_OPT_TYPE_INT, {.dbl = 8 }, INT_MIN, INT_MAX, V|E},
{"dtg_active_format", NULL, OFFSET(dtg_active_format), AV_OPT_TYPE_INT, {.dbl = DEFAULT }, INT_MIN, INT_MAX},
{"me_range", "limit motion vectors range (1023 for DivX player)", OFFSET(me_range), AV_OPT_TYPE_INT, {.dbl = DEFAULT }, INT_MIN, INT_MAX, V|E},
{"ibias", "intra quant bias", OFFSET(intra_quant_bias), AV_OPT_TYPE_INT, {.dbl = FF_DEFAULT_QUANT_BIAS }, INT_MIN, INT_MAX, V|E},
{"pbias", "inter quant bias", OFFSET(inter_quant_bias), AV_OPT_TYPE_INT, {.dbl = FF_DEFAULT_QUANT_BIAS }, INT_MIN, INT_MAX, V|E},
{"color_table_id", NULL, OFFSET(color_table_id), AV_OPT_TYPE_INT, {.dbl = DEFAULT }, INT_MIN, INT_MAX},
{"global_quality", NULL, OFFSET(global_quality), AV_OPT_TYPE_INT, {.dbl = DEFAULT }, INT_MIN, INT_MAX, V|A|E},
{"coder", NULL, OFFSET(coder_type), AV_OPT_TYPE_INT, {.dbl = DEFAULT }, INT_MIN, INT_MAX, V|E, "coder"},
{"vlc", "variable length coder / huffman coder", 0, AV_OPT_TYPE_CONST, {.dbl = FF_CODER_TYPE_VLC }, INT_MIN, INT_MAX, V|E, "coder"},
{"ac", "arithmetic coder", 0, AV_OPT_TYPE_CONST, {.dbl = FF_CODER_TYPE_AC }, INT_MIN, INT_MAX, V|E, "coder"},
{"raw", "raw (no encoding)", 0, AV_OPT_TYPE_CONST, {.dbl = FF_CODER_TYPE_RAW }, INT_MIN, INT_MAX, V|E, "coder"},
{"rle", "run-length coder", 0, AV_OPT_TYPE_CONST, {.dbl = FF_CODER_TYPE_RLE }, INT_MIN, INT_MAX, V|E, "coder"},
{"deflate", "deflate-based coder", 0, AV_OPT_TYPE_CONST, {.dbl = FF_CODER_TYPE_DEFLATE }, INT_MIN, INT_MAX, V|E, "coder"},
{"context", "context model", OFFSET(context_model), AV_OPT_TYPE_INT, {.dbl = DEFAULT }, INT_MIN, INT_MAX, V|E},
{"slice_flags", NULL, OFFSET(slice_flags), AV_OPT_TYPE_INT, {.dbl = DEFAULT }, INT_MIN, INT_MAX},
{"xvmc_acceleration", NULL, OFFSET(xvmc_acceleration), AV_OPT_TYPE_INT, {.dbl = DEFAULT }, INT_MIN, INT_MAX},
{"mbd", "macroblock decision algorithm (high quality mode)", OFFSET(mb_decision), AV_OPT_TYPE_INT, {.dbl = DEFAULT }, INT_MIN, INT_MAX, V|E, "mbd"},
{"simple", "use mbcmp (default)", 0, AV_OPT_TYPE_CONST, {.dbl = FF_MB_DECISION_SIMPLE }, INT_MIN, INT_MAX, V|E, "mbd"},
{"bits", "use fewest bits", 0, AV_OPT_TYPE_CONST, {.dbl = FF_MB_DECISION_BITS }, INT_MIN, INT_MAX, V|E, "mbd"},
{"rd", "use best rate distortion", 0, AV_OPT_TYPE_CONST, {.dbl = FF_MB_DECISION_RD }, INT_MIN, INT_MAX, V|E, "mbd"},
{"stream_codec_tag", NULL, OFFSET(stream_codec_tag), AV_OPT_TYPE_INT, {.dbl = DEFAULT }, INT_MIN, INT_MAX},
{"sc_threshold", "scene change threshold", OFFSET(scenechange_threshold), AV_OPT_TYPE_INT, {.dbl = DEFAULT }, INT_MIN, INT_MAX, V|E},
{"lmin", "min lagrange factor (VBR)", OFFSET(lmin), AV_OPT_TYPE_INT, {.dbl = 2*FF_QP2LAMBDA }, 0, INT_MAX, V|E},
{"lmax", "max lagrange factor (VBR)", OFFSET(lmax), AV_OPT_TYPE_INT, {.dbl = 31*FF_QP2LAMBDA }, 0, INT_MAX, V|E},
{"nr", "noise reduction", OFFSET(noise_reduction), AV_OPT_TYPE_INT, {.dbl = DEFAULT }, INT_MIN, INT_MAX, V|E},
{"rc_init_occupancy", "number of bits which should be loaded into the rc buffer before decoding starts", OFFSET(rc_initial_buffer_occupancy), AV_OPT_TYPE_INT, {.dbl = DEFAULT }, INT_MIN, INT_MAX, V|E},
{"inter_threshold", NULL, OFFSET(inter_threshold), AV_OPT_TYPE_INT, {.dbl = DEFAULT }, INT_MIN, INT_MAX, V|E},
#if FF_API_X264_GLOBAL_OPTS
#define X264_DEFAULTS CODEC_FLAG2_FASTPSKIP|CODEC_FLAG2_PSY|CODEC_FLAG2_MBTREE
#else
#define X264_DEFAULTS 0
#endif
#if FF_API_LAME_GLOBAL_OPTS
#define LAME_DEFAULTS CODEC_FLAG2_BIT_RESERVOIR
#else
#define LAME_DEFAULTS 0
#endif
{"flags2", NULL, OFFSET(flags2), AV_OPT_TYPE_FLAGS, {.dbl = X264_DEFAULTS|LAME_DEFAULTS }, 0, UINT_MAX, V|A|E|D, "flags2"},
{"error", NULL, OFFSET(error_rate), AV_OPT_TYPE_INT, {.dbl = DEFAULT }, INT_MIN, INT_MAX, V|E},
#if FF_API_ANTIALIAS_ALGO
{"antialias", "MP3 antialias algorithm", OFFSET(antialias_algo), AV_OPT_TYPE_INT, {.dbl = DEFAULT }, INT_MIN, INT_MAX, V|D, "aa"},
{"auto", NULL, 0, AV_OPT_TYPE_CONST, {.dbl = FF_AA_AUTO }, INT_MIN, INT_MAX, V|D, "aa"},
{"fastint", NULL, 0, AV_OPT_TYPE_CONST, {.dbl = FF_AA_FASTINT }, INT_MIN, INT_MAX, V|D, "aa"},
{"int", NULL, 0, AV_OPT_TYPE_CONST, {.dbl = FF_AA_INT }, INT_MIN, INT_MAX, V|D, "aa"},
{"float", NULL, 0, AV_OPT_TYPE_CONST, {.dbl = FF_AA_FLOAT }, INT_MIN, INT_MAX, V|D, "aa"},
#endif
{"qns", "quantizer noise shaping", OFFSET(quantizer_noise_shaping), AV_OPT_TYPE_INT, {.dbl = DEFAULT }, INT_MIN, INT_MAX, V|E},
{"threads", NULL, OFFSET(thread_count), AV_OPT_TYPE_INT, {.dbl = 1 }, 0, INT_MAX, V|E|D, "threads"},
{"auto", "detect a good number of threads", 0, AV_OPT_TYPE_CONST, {.dbl = 0 }, INT_MIN, INT_MAX, V|E|D, "threads"},
{"me_threshold", "motion estimaton threshold", OFFSET(me_threshold), AV_OPT_TYPE_INT, {.dbl = DEFAULT }, INT_MIN, INT_MAX, V|E},
{"mb_threshold", "macroblock threshold", OFFSET(mb_threshold), AV_OPT_TYPE_INT, {.dbl = DEFAULT }, INT_MIN, INT_MAX, V|E},
{"dc", "intra_dc_precision", OFFSET(intra_dc_precision), AV_OPT_TYPE_INT, {.dbl = 0 }, INT_MIN, INT_MAX, V|E},
{"nssew", "nsse weight", OFFSET(nsse_weight), AV_OPT_TYPE_INT, {.dbl = 8 }, INT_MIN, INT_MAX, V|E},
{"skip_top", "number of macroblock rows at the top which are skipped", OFFSET(skip_top), AV_OPT_TYPE_INT, {.dbl = DEFAULT }, INT_MIN, INT_MAX, V|D},
{"skip_bottom", "number of macroblock rows at the bottom which are skipped", OFFSET(skip_bottom), AV_OPT_TYPE_INT, {.dbl = DEFAULT }, INT_MIN, INT_MAX, V|D},
{"profile", NULL, OFFSET(profile), AV_OPT_TYPE_INT, {.dbl = FF_PROFILE_UNKNOWN }, INT_MIN, INT_MAX, V|A|E, "profile"},
{"unknown", NULL, 0, AV_OPT_TYPE_CONST, {.dbl = FF_PROFILE_UNKNOWN }, INT_MIN, INT_MAX, V|A|E, "profile"},
{"aac_main", NULL, 0, AV_OPT_TYPE_CONST, {.dbl = FF_PROFILE_AAC_MAIN }, INT_MIN, INT_MAX, A|E, "profile"},
{"aac_low", NULL, 0, AV_OPT_TYPE_CONST, {.dbl = FF_PROFILE_AAC_LOW }, INT_MIN, INT_MAX, A|E, "profile"},
{"aac_ssr", NULL, 0, AV_OPT_TYPE_CONST, {.dbl = FF_PROFILE_AAC_SSR }, INT_MIN, INT_MAX, A|E, "profile"},
{"aac_ltp", NULL, 0, AV_OPT_TYPE_CONST, {.dbl = FF_PROFILE_AAC_LTP }, INT_MIN, INT_MAX, A|E, "profile"},
{"dts", NULL, 0, AV_OPT_TYPE_CONST, {.dbl = FF_PROFILE_DTS }, INT_MIN, INT_MAX, A|E, "profile"},
{"dts_es", NULL, 0, AV_OPT_TYPE_CONST, {.dbl = FF_PROFILE_DTS_ES }, INT_MIN, INT_MAX, A|E, "profile"},
{"dts_96_24", NULL, 0, AV_OPT_TYPE_CONST, {.dbl = FF_PROFILE_DTS_96_24 }, INT_MIN, INT_MAX, A|E, "profile"},
{"dts_hd_hra", NULL, 0, AV_OPT_TYPE_CONST, {.dbl = FF_PROFILE_DTS_HD_HRA }, INT_MIN, INT_MAX, A|E, "profile"},
{"dts_hd_ma", NULL, 0, AV_OPT_TYPE_CONST, {.dbl = FF_PROFILE_DTS_HD_MA }, INT_MIN, INT_MAX, A|E, "profile"},
{"level", NULL, OFFSET(level), AV_OPT_TYPE_INT, {.dbl = FF_LEVEL_UNKNOWN }, INT_MIN, INT_MAX, V|A|E, "level"},
{"unknown", NULL, 0, AV_OPT_TYPE_CONST, {.dbl = FF_LEVEL_UNKNOWN }, INT_MIN, INT_MAX, V|A|E, "level"},
{"lowres", "decode at 1= 1/2, 2=1/4, 3=1/8 resolutions", OFFSET(lowres), AV_OPT_TYPE_INT, {.dbl = 0 }, 0, INT_MAX, V|A|D},
{"skip_threshold", "frame skip threshold", OFFSET(frame_skip_threshold), AV_OPT_TYPE_INT, {.dbl = DEFAULT }, INT_MIN, INT_MAX, V|E},
{"skip_factor", "frame skip factor", OFFSET(frame_skip_factor), AV_OPT_TYPE_INT, {.dbl = DEFAULT }, INT_MIN, INT_MAX, V|E},
{"skip_exp", "frame skip exponent", OFFSET(frame_skip_exp), AV_OPT_TYPE_INT, {.dbl = DEFAULT }, INT_MIN, INT_MAX, V|E},
{"skipcmp", "frame skip compare function", OFFSET(frame_skip_cmp), AV_OPT_TYPE_INT, {.dbl = FF_CMP_DCTMAX }, INT_MIN, INT_MAX, V|E, "cmp_func"},
{"border_mask", "increases the quantizer for macroblocks close to borders", OFFSET(border_masking), AV_OPT_TYPE_FLOAT, {.dbl = DEFAULT }, -FLT_MAX, FLT_MAX, V|E},
{"mblmin", "min macroblock lagrange factor (VBR)", OFFSET(mb_lmin), AV_OPT_TYPE_INT, {.dbl = FF_QP2LAMBDA * 2 }, 1, FF_LAMBDA_MAX, V|E},
{"mblmax", "max macroblock lagrange factor (VBR)", OFFSET(mb_lmax), AV_OPT_TYPE_INT, {.dbl = FF_QP2LAMBDA * 31 }, 1, FF_LAMBDA_MAX, V|E},
{"mepc", "motion estimation bitrate penalty compensation (1.0 = 256)", OFFSET(me_penalty_compensation), AV_OPT_TYPE_INT, {.dbl = 256 }, INT_MIN, INT_MAX, V|E},
{"skip_loop_filter", NULL, OFFSET(skip_loop_filter), AV_OPT_TYPE_INT, {.dbl = AVDISCARD_DEFAULT }, INT_MIN, INT_MAX, V|D, "avdiscard"},
{"skip_idct" , NULL, OFFSET(skip_idct) , AV_OPT_TYPE_INT, {.dbl = AVDISCARD_DEFAULT }, INT_MIN, INT_MAX, V|D, "avdiscard"},
{"skip_frame" , NULL, OFFSET(skip_frame) , AV_OPT_TYPE_INT, {.dbl = AVDISCARD_DEFAULT }, INT_MIN, INT_MAX, V|D, "avdiscard"},
{"none" , NULL, 0, AV_OPT_TYPE_CONST, {.dbl = AVDISCARD_NONE }, INT_MIN, INT_MAX, V|D, "avdiscard"},
{"default" , NULL, 0, AV_OPT_TYPE_CONST, {.dbl = AVDISCARD_DEFAULT }, INT_MIN, INT_MAX, V|D, "avdiscard"},
{"noref" , NULL, 0, AV_OPT_TYPE_CONST, {.dbl = AVDISCARD_NONREF }, INT_MIN, INT_MAX, V|D, "avdiscard"},
{"bidir" , NULL, 0, AV_OPT_TYPE_CONST, {.dbl = AVDISCARD_BIDIR }, INT_MIN, INT_MAX, V|D, "avdiscard"},
{"nokey" , NULL, 0, AV_OPT_TYPE_CONST, {.dbl = AVDISCARD_NONKEY }, INT_MIN, INT_MAX, V|D, "avdiscard"},
{"all" , NULL, 0, AV_OPT_TYPE_CONST, {.dbl = AVDISCARD_ALL }, INT_MIN, INT_MAX, V|D, "avdiscard"},
{"bidir_refine", "refine the two motion vectors used in bidirectional macroblocks", OFFSET(bidir_refine), AV_OPT_TYPE_INT, {.dbl = 1 }, 0, 4, V|E},
{"brd_scale", "downscales frames for dynamic B-frame decision", OFFSET(brd_scale), AV_OPT_TYPE_INT, {.dbl = DEFAULT }, 0, 10, V|E},
#if FF_API_X264_GLOBAL_OPTS
{"crf", "enables constant quality mode, and selects the quality (x264)", OFFSET(crf), AV_OPT_TYPE_FLOAT, {.dbl = DEFAULT }, 0, 51, V|E},
{"cqp", "constant quantization parameter rate control method", OFFSET(cqp), AV_OPT_TYPE_INT, {.dbl = -1 }, INT_MIN, INT_MAX, V|E},
#endif
{"keyint_min", "minimum interval between IDR-frames (x264)", OFFSET(keyint_min), AV_OPT_TYPE_INT, {.dbl = 25 }, INT_MIN, INT_MAX, V|E},
{"refs", "reference frames to consider for motion compensation (Snow)", OFFSET(refs), AV_OPT_TYPE_INT, {.dbl = 1 }, INT_MIN, INT_MAX, V|E},
{"chromaoffset", "chroma qp offset from luma", OFFSET(chromaoffset), AV_OPT_TYPE_INT, {.dbl = DEFAULT }, INT_MIN, INT_MAX, V|E},
#if FF_API_X264_GLOBAL_OPTS
{"bframebias", "influences how often B-frames are used", OFFSET(bframebias), AV_OPT_TYPE_INT, {.dbl = DEFAULT }, INT_MIN, INT_MAX, V|E},
#endif
{"trellis", "rate-distortion optimal quantization", OFFSET(trellis), AV_OPT_TYPE_INT, {.dbl = DEFAULT }, INT_MIN, INT_MAX, V|A|E},
#if FF_API_X264_GLOBAL_OPTS
{"directpred", "direct mv prediction mode - 0 (none), 1 (spatial), 2 (temporal), 3 (auto)", OFFSET(directpred), AV_OPT_TYPE_INT, {.dbl = -1 }, INT_MIN, INT_MAX, V|E},
{"bpyramid", "allows B-frames to be used as references for predicting", 0, AV_OPT_TYPE_CONST, {.dbl = CODEC_FLAG2_BPYRAMID }, INT_MIN, INT_MAX, V|E, "flags2"},
{"wpred", "weighted biprediction for b-frames (H.264)", 0, AV_OPT_TYPE_CONST, {.dbl = CODEC_FLAG2_WPRED }, INT_MIN, INT_MAX, V|E, "flags2"},
{"mixed_refs", "one reference per partition, as opposed to one reference per macroblock", 0, AV_OPT_TYPE_CONST, {.dbl = CODEC_FLAG2_MIXED_REFS }, INT_MIN, INT_MAX, V|E, "flags2"},
{"dct8x8", "high profile 8x8 transform (H.264)", 0, AV_OPT_TYPE_CONST, {.dbl = CODEC_FLAG2_8X8DCT }, INT_MIN, INT_MAX, V|E, "flags2"},
{"fastpskip", "fast pskip (H.264)", 0, AV_OPT_TYPE_CONST, {.dbl = CODEC_FLAG2_FASTPSKIP }, INT_MIN, INT_MAX, V|E, "flags2"},
{"aud", "access unit delimiters (H.264)", 0, AV_OPT_TYPE_CONST, {.dbl = CODEC_FLAG2_AUD }, INT_MIN, INT_MAX, V|E, "flags2"},
#endif
{"skiprd", "RD optimal MB level residual skipping", 0, AV_OPT_TYPE_CONST, {.dbl = CODEC_FLAG2_SKIP_RD }, INT_MIN, INT_MAX, V|E, "flags2"},
#if FF_API_X264_GLOBAL_OPTS
{"complexityblur", "reduce fluctuations in qp (before curve compression)", OFFSET(complexityblur), AV_OPT_TYPE_FLOAT, {.dbl = -1 }, -1, FLT_MAX, V|E},
{"deblockalpha", "in-loop deblocking filter alphac0 parameter", OFFSET(deblockalpha), AV_OPT_TYPE_INT, {.dbl = DEFAULT }, -6, 6, V|E},
{"deblockbeta", "in-loop deblocking filter beta parameter", OFFSET(deblockbeta), AV_OPT_TYPE_INT, {.dbl = DEFAULT }, -6, 6, V|E},
{"partitions", "macroblock subpartition sizes to consider", OFFSET(partitions), AV_OPT_TYPE_FLAGS, {.dbl = DEFAULT }, INT_MIN, INT_MAX, V|E, "partitions"},
{"parti4x4", NULL, 0, AV_OPT_TYPE_CONST, {.dbl = X264_PART_I4X4 }, INT_MIN, INT_MAX, V|E, "partitions"},
{"parti8x8", NULL, 0, AV_OPT_TYPE_CONST, {.dbl = X264_PART_I8X8 }, INT_MIN, INT_MAX, V|E, "partitions"},
{"partp4x4", NULL, 0, AV_OPT_TYPE_CONST, {.dbl = X264_PART_P4X4 }, INT_MIN, INT_MAX, V|E, "partitions"},
{"partp8x8", NULL, 0, AV_OPT_TYPE_CONST, {.dbl = X264_PART_P8X8 }, INT_MIN, INT_MAX, V|E, "partitions"},
{"partb8x8", NULL, 0, AV_OPT_TYPE_CONST, {.dbl = X264_PART_B8X8 }, INT_MIN, INT_MAX, V|E, "partitions"},
#endif
{"sc_factor", "multiplied by qscale for each frame and added to scene_change_score", OFFSET(scenechange_factor), AV_OPT_TYPE_INT, {.dbl = 6 }, 0, INT_MAX, V|E},
{"mv0_threshold", NULL, OFFSET(mv0_threshold), AV_OPT_TYPE_INT, {.dbl = 256 }, 0, INT_MAX, V|E},
#if FF_API_MPEGVIDEO_GLOBAL_OPTS
{"ivlc", "intra vlc table", 0, AV_OPT_TYPE_CONST, {.dbl = CODEC_FLAG2_INTRA_VLC }, INT_MIN, INT_MAX, V|E, "flags2"},
#endif
{"b_sensitivity", "adjusts sensitivity of b_frame_strategy 1", OFFSET(b_sensitivity), AV_OPT_TYPE_INT, {.dbl = 40 }, 1, INT_MAX, V|E},
{"compression_level", NULL, OFFSET(compression_level), AV_OPT_TYPE_INT, {.dbl = FF_COMPRESSION_DEFAULT }, INT_MIN, INT_MAX, V|A|E},
{"min_prediction_order", NULL, OFFSET(min_prediction_order), AV_OPT_TYPE_INT, {.dbl = -1 }, INT_MIN, INT_MAX, A|E},
{"max_prediction_order", NULL, OFFSET(max_prediction_order), AV_OPT_TYPE_INT, {.dbl = -1 }, INT_MIN, INT_MAX, A|E},
#if FF_API_FLAC_GLOBAL_OPTS
{"lpc_coeff_precision", "deprecated, use flac-specific options", OFFSET(lpc_coeff_precision), AV_OPT_TYPE_INT, {.dbl = DEFAULT }, 0, INT_MAX, A|E},
{"prediction_order_method", "deprecated, use flac-specific options", OFFSET(prediction_order_method), AV_OPT_TYPE_INT, {.dbl = -1 }, INT_MIN, INT_MAX, A|E},
{"min_partition_order", "deprecated, use flac-specific options", OFFSET(min_partition_order), AV_OPT_TYPE_INT, {.dbl = -1 }, INT_MIN, INT_MAX, A|E},
{"max_partition_order", "deprecated, use flac-specific options", OFFSET(max_partition_order), AV_OPT_TYPE_INT, {.dbl = -1 }, INT_MIN, INT_MAX, A|E},
#endif
{"timecode_frame_start", "GOP timecode frame start number, in non drop frame format", OFFSET(timecode_frame_start), AV_OPT_TYPE_INT64, {.dbl = 0 }, 0, INT64_MAX, V|E},
#if FF_API_MPEGVIDEO_GLOBAL_OPTS
{"drop_frame_timecode", NULL, 0, AV_OPT_TYPE_CONST, {.dbl = CODEC_FLAG2_DROP_FRAME_TIMECODE }, INT_MIN, INT_MAX, V|E, "flags2"},
{"non_linear_q", "use non linear quantizer", 0, AV_OPT_TYPE_CONST, {.dbl = CODEC_FLAG2_NON_LINEAR_QUANT }, INT_MIN, INT_MAX, V|E, "flags2"},
#endif
#if FF_API_REQUEST_CHANNELS
{"request_channels", "set desired number of audio channels", OFFSET(request_channels), AV_OPT_TYPE_INT, {.dbl = DEFAULT }, 0, INT_MAX, A|D},
#endif
#if FF_API_DRC_SCALE
{"drc_scale", "percentage of dynamic range compression to apply", OFFSET(drc_scale), AV_OPT_TYPE_FLOAT, {.dbl = 0.0 }, 0.0, 1.0, A|D},
#endif
#if FF_API_LAME_GLOBAL_OPTS
{"reservoir", "use bit reservoir", 0, AV_OPT_TYPE_CONST, {.dbl = CODEC_FLAG2_BIT_RESERVOIR }, INT_MIN, INT_MAX, A|E, "flags2"},
#endif
#if FF_API_X264_GLOBAL_OPTS
{"mbtree", "use macroblock tree ratecontrol (x264 only)", 0, AV_OPT_TYPE_CONST, {.dbl = CODEC_FLAG2_MBTREE }, INT_MIN, INT_MAX, V|E, "flags2"},
#endif
{"bits_per_raw_sample", NULL, OFFSET(bits_per_raw_sample), AV_OPT_TYPE_INT, {.dbl = DEFAULT }, INT_MIN, INT_MAX},
{"channel_layout", NULL, OFFSET(channel_layout), AV_OPT_TYPE_INT64, {.dbl = DEFAULT }, 0, INT64_MAX, A|E|D, "channel_layout"},
{"request_channel_layout", NULL, OFFSET(request_channel_layout), AV_OPT_TYPE_INT64, {.dbl = DEFAULT }, 0, INT64_MAX, A|D, "request_channel_layout"},
{"rc_max_vbv_use", NULL, OFFSET(rc_max_available_vbv_use), AV_OPT_TYPE_FLOAT, {.dbl = 1.0/3 }, 0.0, FLT_MAX, V|E},
{"rc_min_vbv_use", NULL, OFFSET(rc_min_vbv_overflow_use), AV_OPT_TYPE_FLOAT, {.dbl = 3 }, 0.0, FLT_MAX, V|E},
{"ticks_per_frame", NULL, OFFSET(ticks_per_frame), AV_OPT_TYPE_INT, {.dbl = 1 }, 1, INT_MAX, A|V|E|D},
{"color_primaries", NULL, OFFSET(color_primaries), AV_OPT_TYPE_INT, {.dbl = AVCOL_PRI_UNSPECIFIED }, 1, AVCOL_PRI_NB-1, V|E|D},
{"color_trc", NULL, OFFSET(color_trc), AV_OPT_TYPE_INT, {.dbl = AVCOL_TRC_UNSPECIFIED }, 1, AVCOL_TRC_NB-1, V|E|D},
{"colorspace", NULL, OFFSET(colorspace), AV_OPT_TYPE_INT, {.dbl = AVCOL_SPC_UNSPECIFIED }, 1, AVCOL_SPC_NB-1, V|E|D},
{"color_range", NULL, OFFSET(color_range), AV_OPT_TYPE_INT, {.dbl = AVCOL_RANGE_UNSPECIFIED }, 0, AVCOL_RANGE_NB-1, V|E|D},
{"chroma_sample_location", NULL, OFFSET(chroma_sample_location), AV_OPT_TYPE_INT, {.dbl = AVCHROMA_LOC_UNSPECIFIED }, 0, AVCHROMA_LOC_NB-1, V|E|D},
#if FF_API_X264_GLOBAL_OPTS
{"psy", "use psycho visual optimization", 0, AV_OPT_TYPE_CONST, {.dbl = CODEC_FLAG2_PSY }, INT_MIN, INT_MAX, V|E, "flags2"},
{"psy_rd", "specify psycho visual strength", OFFSET(psy_rd), AV_OPT_TYPE_FLOAT, {.dbl = -1.0 }, -1, FLT_MAX, V|E},
{"psy_trellis", "specify psycho visual trellis", OFFSET(psy_trellis), AV_OPT_TYPE_FLOAT, {.dbl = -1 }, -1, FLT_MAX, V|E},
{"aq_mode", "specify aq method", OFFSET(aq_mode), AV_OPT_TYPE_INT, {.dbl = -1 }, -1, INT_MAX, V|E},
{"aq_strength", "specify aq strength", OFFSET(aq_strength), AV_OPT_TYPE_FLOAT, {.dbl = -1.0 }, -1, FLT_MAX, V|E},
{"rc_lookahead", "specify number of frames to look ahead for frametype", OFFSET(rc_lookahead), AV_OPT_TYPE_INT, {.dbl = -1 }, -1, INT_MAX, V|E},
{"ssim", "ssim will be calculated during encoding", 0, AV_OPT_TYPE_CONST, {.dbl = CODEC_FLAG2_SSIM }, INT_MIN, INT_MAX, V|E, "flags2"},
{"intra_refresh", "use periodic insertion of intra blocks instead of keyframes", 0, AV_OPT_TYPE_CONST, {.dbl = CODEC_FLAG2_INTRA_REFRESH }, INT_MIN, INT_MAX, V|E, "flags2"},
{"crf_max", "in crf mode, prevents vbv from lowering quality beyond this point", OFFSET(crf_max), AV_OPT_TYPE_FLOAT, {.dbl = DEFAULT }, 0, 51, V|E},
#endif
{"log_level_offset", "set the log level offset", OFFSET(log_level_offset), AV_OPT_TYPE_INT, {.dbl = 0 }, INT_MIN, INT_MAX },
#if FF_API_FLAC_GLOBAL_OPTS
{"lpc_type", "deprecated, use flac-specific options", OFFSET(lpc_type), AV_OPT_TYPE_INT, {.dbl = AV_LPC_TYPE_DEFAULT }, AV_LPC_TYPE_DEFAULT, AV_LPC_TYPE_NB-1, A|E},
{"none", NULL, 0, AV_OPT_TYPE_CONST, {.dbl = AV_LPC_TYPE_NONE }, INT_MIN, INT_MAX, A|E, "lpc_type"},
{"fixed", NULL, 0, AV_OPT_TYPE_CONST, {.dbl = AV_LPC_TYPE_FIXED }, INT_MIN, INT_MAX, A|E, "lpc_type"},
{"levinson", NULL, 0, AV_OPT_TYPE_CONST, {.dbl = AV_LPC_TYPE_LEVINSON }, INT_MIN, INT_MAX, A|E, "lpc_type"},
{"cholesky", NULL, 0, AV_OPT_TYPE_CONST, {.dbl = AV_LPC_TYPE_CHOLESKY }, INT_MIN, INT_MAX, A|E, "lpc_type"},
{"lpc_passes", "deprecated, use flac-specific options", OFFSET(lpc_passes), AV_OPT_TYPE_INT, {.dbl = -1 }, INT_MIN, INT_MAX, A|E},
#endif
{"slices", "number of slices, used in parallelized encoding", OFFSET(slices), AV_OPT_TYPE_INT, {.dbl = 0 }, 0, INT_MAX, V|E},
{"thread_type", "select multithreading type", OFFSET(thread_type), AV_OPT_TYPE_FLAGS, {.dbl = FF_THREAD_SLICE|FF_THREAD_FRAME }, 0, INT_MAX, V|E|D, "thread_type"},
{"slice", NULL, 0, AV_OPT_TYPE_CONST, {.dbl = FF_THREAD_SLICE }, INT_MIN, INT_MAX, V|E|D, "thread_type"},
{"frame", NULL, 0, AV_OPT_TYPE_CONST, {.dbl = FF_THREAD_FRAME }, INT_MIN, INT_MAX, V|E|D, "thread_type"},
{"audio_service_type", "audio service type", OFFSET(audio_service_type), AV_OPT_TYPE_INT, {.dbl = AV_AUDIO_SERVICE_TYPE_MAIN }, 0, AV_AUDIO_SERVICE_TYPE_NB-1, A|E, "audio_service_type"},
{"ma", "Main Audio Service", 0, AV_OPT_TYPE_CONST, {.dbl = AV_AUDIO_SERVICE_TYPE_MAIN }, INT_MIN, INT_MAX, A|E, "audio_service_type"},
{"ef", "Effects", 0, AV_OPT_TYPE_CONST, {.dbl = AV_AUDIO_SERVICE_TYPE_EFFECTS }, INT_MIN, INT_MAX, A|E, "audio_service_type"},
{"vi", "Visually Impaired", 0, AV_OPT_TYPE_CONST, {.dbl = AV_AUDIO_SERVICE_TYPE_VISUALLY_IMPAIRED }, INT_MIN, INT_MAX, A|E, "audio_service_type"},
{"hi", "Hearing Impaired", 0, AV_OPT_TYPE_CONST, {.dbl = AV_AUDIO_SERVICE_TYPE_HEARING_IMPAIRED }, INT_MIN, INT_MAX, A|E, "audio_service_type"},
{"di", "Dialogue", 0, AV_OPT_TYPE_CONST, {.dbl = AV_AUDIO_SERVICE_TYPE_DIALOGUE }, INT_MIN, INT_MAX, A|E, "audio_service_type"},
{"co", "Commentary", 0, AV_OPT_TYPE_CONST, {.dbl = AV_AUDIO_SERVICE_TYPE_COMMENTARY }, INT_MIN, INT_MAX, A|E, "audio_service_type"},
{"em", "Emergency", 0, AV_OPT_TYPE_CONST, {.dbl = AV_AUDIO_SERVICE_TYPE_EMERGENCY }, INT_MIN, INT_MAX, A|E, "audio_service_type"},
{"vo", "Voice Over", 0, AV_OPT_TYPE_CONST, {.dbl = AV_AUDIO_SERVICE_TYPE_VOICE_OVER }, INT_MIN, INT_MAX, A|E, "audio_service_type"},
{"ka", "Karaoke", 0, AV_OPT_TYPE_CONST, {.dbl = AV_AUDIO_SERVICE_TYPE_KARAOKE }, INT_MIN, INT_MAX, A|E, "audio_service_type"},
{"request_sample_fmt", NULL, OFFSET(request_sample_fmt), AV_OPT_TYPE_INT, {.dbl = AV_SAMPLE_FMT_NONE }, AV_SAMPLE_FMT_NONE, AV_SAMPLE_FMT_NB-1, A|D, "request_sample_fmt"},
{"u8" , "8-bit unsigned integer", 0, AV_OPT_TYPE_CONST, {.dbl = AV_SAMPLE_FMT_U8 }, INT_MIN, INT_MAX, A|D, "request_sample_fmt"},
{"s16", "16-bit signed integer", 0, AV_OPT_TYPE_CONST, {.dbl = AV_SAMPLE_FMT_S16 }, INT_MIN, INT_MAX, A|D, "request_sample_fmt"},
{"s32", "32-bit signed integer", 0, AV_OPT_TYPE_CONST, {.dbl = AV_SAMPLE_FMT_S32 }, INT_MIN, INT_MAX, A|D, "request_sample_fmt"},
{"flt", "32-bit float", 0, AV_OPT_TYPE_CONST, {.dbl = AV_SAMPLE_FMT_FLT }, INT_MIN, INT_MAX, A|D, "request_sample_fmt"},
{"dbl", "64-bit double", 0, AV_OPT_TYPE_CONST, {.dbl = AV_SAMPLE_FMT_DBL }, INT_MIN, INT_MAX, A|D, "request_sample_fmt"},
{NULL},
};
#undef A
#undef V
#undef S
#undef E
#undef D
#undef DEFAULT
static const AVClass av_codec_context_class = {
.class_name = "AVCodecContext",
.item_name = context_to_name,
.option = options,
.version = LIBAVUTIL_VERSION_INT,
.log_level_offset_offset = OFFSET(log_level_offset),
.child_next = codec_child_next,
.child_class_next = codec_child_class_next,
};
#if FF_API_ALLOC_CONTEXT
void avcodec_get_context_defaults2(AVCodecContext *s, enum AVMediaType codec_type){
avcodec_get_context_defaults3(s, NULL);
s->codec_type = codec_type;
}
#endif
int avcodec_get_context_defaults3(AVCodecContext *s, AVCodec *codec){
memset(s, 0, sizeof(AVCodecContext));
s->av_class = &av_codec_context_class;
s->codec_type = codec ? codec->type : AVMEDIA_TYPE_UNKNOWN;
s->codec = codec;
av_opt_set_defaults(s);
s->time_base = (AVRational){0,1};
s->get_buffer = avcodec_default_get_buffer;
s->release_buffer = avcodec_default_release_buffer;
s->get_format = avcodec_default_get_format;
s->execute = avcodec_default_execute;
s->execute2 = avcodec_default_execute2;
s->sample_aspect_ratio = (AVRational){0,1};
s->pix_fmt = PIX_FMT_NONE;
s->sample_fmt = AV_SAMPLE_FMT_NONE;
s->reget_buffer = avcodec_default_reget_buffer;
s->reordered_opaque = AV_NOPTS_VALUE;
if(codec && codec->priv_data_size){
if(!s->priv_data){
s->priv_data= av_mallocz(codec->priv_data_size);
if (!s->priv_data) {
return AVERROR(ENOMEM);
}
}
if(codec->priv_class){
*(const AVClass**)s->priv_data = codec->priv_class;
av_opt_set_defaults(s->priv_data);
}
}
if (codec && codec->defaults) {
int ret;
const AVCodecDefault *d = codec->defaults;
while (d->key) {
ret = av_opt_set(s, d->key, d->value, 0);
av_assert0(ret >= 0);
d++;
}
}
return 0;
}
AVCodecContext *avcodec_alloc_context3(AVCodec *codec){
AVCodecContext *avctx= av_malloc(sizeof(AVCodecContext));
if(avctx==NULL) return NULL;
if(avcodec_get_context_defaults3(avctx, codec) < 0){
av_free(avctx);
return NULL;
}
return avctx;
}
#if FF_API_ALLOC_CONTEXT
AVCodecContext *avcodec_alloc_context2(enum AVMediaType codec_type){
AVCodecContext *avctx= av_malloc(sizeof(AVCodecContext));
if(avctx==NULL) return NULL;
avcodec_get_context_defaults2(avctx, codec_type);
return avctx;
}
void avcodec_get_context_defaults(AVCodecContext *s){
avcodec_get_context_defaults2(s, AVMEDIA_TYPE_UNKNOWN);
}
AVCodecContext *avcodec_alloc_context(void){
return avcodec_alloc_context2(AVMEDIA_TYPE_UNKNOWN);
}
#endif
int avcodec_copy_context(AVCodecContext *dest, const AVCodecContext *src)
{
if (avcodec_is_open(dest)) { // check that the dest context is uninitialized
av_log(dest, AV_LOG_ERROR,
"Tried to copy AVCodecContext %p into already-initialized %p\n",
src, dest);
return AVERROR(EINVAL);
}
memcpy(dest, src, sizeof(*dest));
/* set values specific to opened codecs back to their default state */
dest->priv_data = NULL;
dest->codec = NULL;
dest->slice_offset = NULL;
dest->hwaccel = NULL;
dest->thread_opaque = NULL;
dest->internal = NULL;
/* reallocate values that should be allocated separately */
dest->rc_eq = NULL;
dest->extradata = NULL;
dest->intra_matrix = NULL;
dest->inter_matrix = NULL;
dest->rc_override = NULL;
if (src->rc_eq) {
dest->rc_eq = av_strdup(src->rc_eq);
if (!dest->rc_eq)
return AVERROR(ENOMEM);
}
#define alloc_and_copy_or_fail(obj, size, pad) \
if (src->obj && size > 0) { \
dest->obj = av_malloc(size + pad); \
if (!dest->obj) \
goto fail; \
memcpy(dest->obj, src->obj, size); \
if (pad) \
memset(((uint8_t *) dest->obj) + size, 0, pad); \
}
alloc_and_copy_or_fail(extradata, src->extradata_size,
FF_INPUT_BUFFER_PADDING_SIZE);
alloc_and_copy_or_fail(intra_matrix, 64 * sizeof(int16_t), 0);
alloc_and_copy_or_fail(inter_matrix, 64 * sizeof(int16_t), 0);
alloc_and_copy_or_fail(rc_override, src->rc_override_count * sizeof(*src->rc_override), 0);
#undef alloc_and_copy_or_fail
return 0;
fail:
av_freep(&dest->rc_override);
av_freep(&dest->intra_matrix);
av_freep(&dest->inter_matrix);
av_freep(&dest->extradata);
av_freep(&dest->rc_eq);
return AVERROR(ENOMEM);
}
const AVClass *avcodec_get_class(void)
{
return &av_codec_context_class;
}
| 82.03741 | 207 | 0.700067 | [
"vector",
"model",
"transform"
] |
d6f00677d52a1fcd96b96b34959ab7be7feb6208 | 5,080 | h | C | 11sem/template.h | canorbal/2_year_in_MIPT | 76a7e9ba31cc8975225304c05182fb9909aa9d45 | [
"Xnet",
"X11"
] | null | null | null | 11sem/template.h | canorbal/2_year_in_MIPT | 76a7e9ba31cc8975225304c05182fb9909aa9d45 | [
"Xnet",
"X11"
] | null | null | null | 11sem/template.h | canorbal/2_year_in_MIPT | 76a7e9ba31cc8975225304c05182fb9909aa9d45 | [
"Xnet",
"X11"
] | null | null | null | #ifndef TEMPLATE_H_
#define TEMPLATE_H_
#include <iostream>
#include "frac.h"
using namespace std;
template <typename Type, int n>
class Vector
{
private:
Type elements[n];
public:
Vector<Type, n>(Type* array)
{
for(int i = 0; i<n; i++)
{
elements[i] = array[i];
}
}
Type operator[](int n_element)
{
if (n_element >= n)
{
std::cout << "index is out of range\n";
return -1;
}
return elements[n_element];
}
Vector<Type, n> plus(Vector<Type, n> A)
{
Type p[n];
for(int i=0; i<n; i++)
{
p[i] = A[i] + elements[i];
}
return Vector<Type, n>(p);
}
friend Vector<Type, n> operator + (Vector<Type, n> A, Vector<Type, n> B)
{
return A.plus(B);
}
friend Vector<Type, n> operator * (Type k, Vector<Type, n> A)
{
Type p[n];
for(int i=0; i<n; i++)
{
p[i] = k * A[i];
}
return Vector<Type, n>(p);
}
friend Vector<Type, n> operator - (Vector A, Vector B)
{
return A + (-1)*B;
}
friend Vector<Type, n> operator * (Vector<Type, n> A, Type k)
{
return k*A;
}
friend Type operator * (Vector<Type, n> A, Vector<Type, n> B)
{
Type sum = 0;
for(int i=0; i<n; i++)
{
sum += (A[i] * B[i]);
}
return sum;
}
friend std::ostream & operator << (std::ostream & os, Vector<Type, n> A)
{
os << "( ";
for(int i=0; i<n; i++)
{
os << A[i] << " ";
}
os << ") \n";
return os;
}
};
template <typename Type, int n, int m>
class Matrix
{
private:
Type elements[n][m];
public:
Matrix(Type** p)
{
for(int i=0; i<n; i++)
{
for(int j=0; j<m; j++)
{
this->elements[i][j] = p[i][j];
}
}
}
Vector<Type, m> operator[](int n_row)
{
Type* p = new Type[m];
for(int i=0; i<m; i++)
{
p[i] = elements[n_row][i];
}
return Vector<Type, m>(p);
}
friend Matrix<Type, n, m> operator + (Matrix<Type, n, m> A, Matrix<Type, n, m> B)
{
Type** p = new Type*[n];
for(int i=0; i<n; i++)
{
p[i] = new Type[m];
for(int j=0; j<m; j++)
{
p[i][j] = A[i][j] + B[i][j];
}
}
return Matrix<Type, n, m>(p);
}
friend Matrix<Type, n, m> operator * (Type k, Matrix<Type, n, m> A)
{
Type** p = new Type*[n];
for(int i=0; i<n; i++)
{
p[i] = new Type[m];
for(int j=0; j<m; j++)
{
p[i][j] = k * A[i][j];
}
}
return Matrix<Type, n, m>(p);
}
friend Matrix<Type, n, m> operator - (Matrix<Type, n, m> A, Matrix<Type, n, m> B)
{
return A+(-1)*B;
}
template<typename Type1, int n1, int m1, int l1, int k1> friend Matrix<Type, n1, k1> operator * (Matrix<Type, n1, m1> A, Matrix<Type, l1, k1> B);
friend Vector<Type, n> operator * (Matrix<Type, n, m> A, Vector<Type, m> B)
{
Type p[n];
for(int i=0; i<n; i++)
{
for(int j=0; j<m; j++)
{
p[i] = p[i] + A[i][j]*B[j];
}
}
return Vector<Type, n>(p);
}
friend std::ostream & operator << (std::ostream & os, Matrix<Type, n, m> A)
{
for(int i=0; i<n; i++)
{
for(int j=0; j<m; j++)
{
os << A[i][j] << " ";
}
os << "\n";
}
return os;
};
};
template<typename Type, int n1, int m1, int l1, int k1> Matrix<Type, n1, k1> operator * (Matrix<Type, n1, m1> A, Matrix<Type, l1, k1> B)
{
try
{
Type** p = new Type*[n1];
if (m1 != l1)
throw 1;
for (int i=0; i<n1; i++)
{
p[i] = new Type[k1];
for(int j=0; j<k1; j++)
{
for (int ind = 0; ind < m1; ind++)
{
p[i][j] = p[i][j] + A[i][ind] * B[ind][j];
}
}
}
return Matrix<Type, n1, k1>(p);
}
catch(...)
{
std::cout << "ndim are different\n";
}
}
#endif
| 23.738318 | 153 | 0.350984 | [
"vector"
] |
d6f9b590bd762d33b048402b82c33f63c27617d7 | 1,798 | h | C | programl/ir/llvm/llvm.h | NaderAlAwar/ProGraML | e4acad3819e477d3000d175b4166b75e1d770141 | [
"Apache-2.0"
] | 169 | 2019-12-20T05:21:03.000Z | 2022-03-28T07:45:08.000Z | programl/ir/llvm/llvm.h | NaderAlAwar/ProGraML | e4acad3819e477d3000d175b4166b75e1d770141 | [
"Apache-2.0"
] | 119 | 2019-12-20T01:30:18.000Z | 2022-03-09T15:10:11.000Z | programl/ir/llvm/llvm.h | NaderAlAwar/ProGraML | e4acad3819e477d3000d175b4166b75e1d770141 | [
"Apache-2.0"
] | 41 | 2019-12-23T10:40:54.000Z | 2022-03-16T02:00:10.000Z | // This file defines the APIs for constructing program graphs from LLVM-IR.
//
// Copyright 2019-2020 the ProGraML authors.
//
// Contact Chris Cummins <chrisc.101@gmail.com>.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#pragma once
#include <utility>
#include <vector>
#include "labm8/cpp/status.h"
#include "llvm/IR/Module.h"
#include "llvm/Support/MemoryBuffer.h"
#include "programl/proto/program_graph.pb.h"
#include "programl/proto/util.pb.h"
namespace programl {
namespace ir {
namespace llvm {
const static ProgramGraphOptions defaultOptions;
// Construct a program graph from the given module.
labm8::Status BuildProgramGraph(::llvm::Module& module, ProgramGraph* graph,
const ProgramGraphOptions& options = defaultOptions);
// Construct a program graph from a buffer for a module.
labm8::Status BuildProgramGraph(const ::llvm::MemoryBuffer& irBuffer, ProgramGraph* graph,
const ProgramGraphOptions& options = defaultOptions);
// Construct a program graph from a string of IR.
labm8::Status BuildProgramGraph(const string& irString, ProgramGraph* graph,
const ProgramGraphOptions& options = defaultOptions);
} // namespace llvm
} // namespace ir
} // namespace programl
| 35.96 | 90 | 0.723026 | [
"vector"
] |
d6fc67047c1e413e0891a8ae04eee33a4a2184b2 | 510 | h | C | Engine/Core/GameObject.h | Archlisk/FrozenCore | 2fad5e0ffbb74644cb63afaa29a93738342ab534 | [
"MIT"
] | null | null | null | Engine/Core/GameObject.h | Archlisk/FrozenCore | 2fad5e0ffbb74644cb63afaa29a93738342ab534 | [
"MIT"
] | null | null | null | Engine/Core/GameObject.h | Archlisk/FrozenCore | 2fad5e0ffbb74644cb63afaa29a93738342ab534 | [
"MIT"
] | null | null | null | #pragma once
#include <Engine.h>
#include <Core/Transform.h>
class GameObject {
public:
GameObject(const Vec3 position = Vec3(0), const Vec3 rotation = Vec3(0), const Vec3 scale = Vec3(1))
: transform(position, rotation, scale){}
virtual ~GameObject() {}
virtual void Render3D() {}
virtual void Render2D() {}
virtual void Update(double) {}
template<typename T>
static inline T& Create(const String& name, T* ptr) {
return Engine::Get().CreateObject(name, ptr);
}
Transform transform;
};
| 20.4 | 102 | 0.694118 | [
"transform"
] |
d6fec08ce1ce528897a8eca048eed89e03a4e0e3 | 1,735 | h | C | aws-cpp-sdk-proton/include/aws/proton/model/UpdateServicePipelineResult.h | perfectrecall/aws-sdk-cpp | fb8cbebf2fd62720b65aeff841ad2950e73d8ebd | [
"Apache-2.0"
] | 1 | 2022-02-10T08:06:54.000Z | 2022-02-10T08:06:54.000Z | aws-cpp-sdk-proton/include/aws/proton/model/UpdateServicePipelineResult.h | perfectrecall/aws-sdk-cpp | fb8cbebf2fd62720b65aeff841ad2950e73d8ebd | [
"Apache-2.0"
] | 1 | 2022-01-03T23:59:37.000Z | 2022-01-03T23:59:37.000Z | aws-cpp-sdk-proton/include/aws/proton/model/UpdateServicePipelineResult.h | ravindra-wagh/aws-sdk-cpp | 7d5ff01b3c3b872f31ca98fb4ce868cd01e97696 | [
"Apache-2.0"
] | 1 | 2021-12-30T04:25:33.000Z | 2021-12-30T04:25:33.000Z | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#pragma once
#include <aws/proton/Proton_EXPORTS.h>
#include <aws/proton/model/ServicePipeline.h>
#include <utility>
namespace Aws
{
template<typename RESULT_TYPE>
class AmazonWebServiceResult;
namespace Utils
{
namespace Json
{
class JsonValue;
} // namespace Json
} // namespace Utils
namespace Proton
{
namespace Model
{
class AWS_PROTON_API UpdateServicePipelineResult
{
public:
UpdateServicePipelineResult();
UpdateServicePipelineResult(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);
UpdateServicePipelineResult& operator=(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);
/**
* <p>The pipeline details returned by Proton.</p>
*/
inline const ServicePipeline& GetPipeline() const{ return m_pipeline; }
/**
* <p>The pipeline details returned by Proton.</p>
*/
inline void SetPipeline(const ServicePipeline& value) { m_pipeline = value; }
/**
* <p>The pipeline details returned by Proton.</p>
*/
inline void SetPipeline(ServicePipeline&& value) { m_pipeline = std::move(value); }
/**
* <p>The pipeline details returned by Proton.</p>
*/
inline UpdateServicePipelineResult& WithPipeline(const ServicePipeline& value) { SetPipeline(value); return *this;}
/**
* <p>The pipeline details returned by Proton.</p>
*/
inline UpdateServicePipelineResult& WithPipeline(ServicePipeline&& value) { SetPipeline(std::move(value)); return *this;}
private:
ServicePipeline m_pipeline;
};
} // namespace Model
} // namespace Proton
} // namespace Aws
| 25.514706 | 125 | 0.703746 | [
"model"
] |
d6ff64bbcd67b3db5c84d401d8992fba21b98597 | 5,576 | h | C | include/bluetooth/mesh/gen_dtt_cli.h | odwraca/nrf9160-dk-aws-fota-secure | ca56782313b6a91e795d614be40b071b33936737 | [
"MIT-0",
"MIT"
] | 1 | 2021-07-24T14:58:23.000Z | 2021-07-24T14:58:23.000Z | include/bluetooth/mesh/gen_dtt_cli.h | odwraca/nrf9160-dk-aws-fota-secure | ca56782313b6a91e795d614be40b071b33936737 | [
"MIT-0",
"MIT"
] | 1 | 2020-04-07T16:59:58.000Z | 2020-04-07T16:59:58.000Z | include/bluetooth/mesh/gen_dtt_cli.h | odwraca/nrf9160-dk-aws-fota-secure | ca56782313b6a91e795d614be40b071b33936737 | [
"MIT-0",
"MIT"
] | 1 | 2020-05-12T13:33:52.000Z | 2020-05-12T13:33:52.000Z | /*
* Copyright (c) 2019 Nordic Semiconductor ASA
*
* SPDX-License-Identifier: LicenseRef-BSD-5-Clause-Nordic
*/
/**
*
* @file
* @defgroup bt_mesh_dtt_cli Generic Default Transition Time Client API
* @{
* @brief API for the Generic Default Transition Time (DTT) Client.
*/
#ifndef BT_MESH_GEN_DTT_CLI_H__
#define BT_MESH_GEN_DTT_CLI_H__
#include <bluetooth/mesh/gen_dtt.h>
#include <bluetooth/mesh/model_types.h>
#ifdef __cplusplus
extern "C" {
#endif
struct bt_mesh_dtt_cli;
/** @def BT_MESH_DTT_CLI_INIT
*
* @brief Initialization parameters for the @ref bt_mesh_dtt_cli.
*
* @param[in] _status_handler Optional status message handler.
* @sa bt_mesh_dtt_cli::status_handler
*/
#define BT_MESH_DTT_CLI_INIT(_status_handler) \
{ \
.pub = { .msg = NET_BUF_SIMPLE(BT_MESH_MODEL_BUF_LEN( \
BT_MESH_DTT_OP_SET, \
BT_MESH_DTT_MSG_LEN_SET)) }, \
.status_handler = _status_handler, \
}
/** @def BT_MESH_MODEL_DTT_CLI
*
* @brief Generic DTT Client model composition data entry.
*
* @param[in] _cli Pointer to a @ref bt_mesh_dtt_cli instance.
*/
#define BT_MESH_MODEL_DTT_CLI(_cli) \
BT_MESH_MODEL_CB(BT_MESH_MODEL_ID_GEN_DEF_TRANS_TIME_CLI, \
_bt_mesh_dtt_cli_op, &(_cli)->pub, \
BT_MESH_MODEL_USER_DATA(struct bt_mesh_dtt_cli, \
_cli), \
&_bt_mesh_dtt_cli_cb)
/**
* Generic DTT client structure.
*
* Should be initialized using the @ref BT_MESH_DTT_CLI_INIT macro.
*/
struct bt_mesh_dtt_cli {
/** @brief Default Transition Time status message handler.
*
* @param[in] cli Client that received the message.
* @param[in] ctx Message context.
* @param[in] transition_time Transition time presented in the message.
*/
void (*const status_handler)(struct bt_mesh_dtt_cli *cli,
struct bt_mesh_msg_ctx *ctx,
s32_t transition_time);
/** Response context for tracking acknowledged messages. */
struct bt_mesh_model_ack_ctx ack_ctx;
/** Model publish parameters. */
struct bt_mesh_model_pub pub;
/** Composition data model entry pointer. */
struct bt_mesh_model *model;
};
/** @brief Get the Default Transition Time of the server.
*
* This call is blocking if the @p rsp_transition_time buffer is non-NULL.
* Otherwise, this function will return, and the response will be passed to the
* @ref bt_mesh_dtt_cli::status_handler callback.
*
* @param[in] cli Client making the request.
* @param[in] ctx Message context to use for sending, or NULL to publish with
* the configured parameters.
* @param[out] rsp_transition_time Pointer to a response buffer, or NULL to keep
* from blocking. Note that the response is a signed value, that can be
* K_FOREVER if the current state is unknown or too large to represent.
*
* @retval 0 Successfully retrieved the status of the bound srv.
* @retval -EALREADY A blocking operation is already in progress in this model.
* @retval -EAGAIN The request timed out.
*/
int bt_mesh_dtt_get(struct bt_mesh_dtt_cli *cli, struct bt_mesh_msg_ctx *ctx,
s32_t *rsp_transition_time);
/** @brief Set the Default Transition Time of the server.
*
* This call is blocking if the @p rsp_transition_time buffer is non-NULL.
* Otherwise, this function will return, and the response will be passed to the
* @ref bt_mesh_dtt_cli::status_handler callback.
*
* @param[in] cli Client model to send on.
* @param[in] ctx Message context to use for sending, or NULL to publish with
* the configured parameters.
* @param[in] transition_time Transition time to set (in milliseconds). Must be
* less than @ref BT_MESH_MODEL_TRANSITION_TIME_MAX_MS.
* @param[out] rsp_transition_time Response buffer, or NULL to keep from
* blocking. Note that the response is a signed value, that can be K_FOREVER if
* the current state is unknown or too large to represent.
*
* @retval 0 Successfully sent the message and populated the
* @p rsp_transition_time buffer.
* @retval -EINVAL The given transition time is invalid.
* @retval -EALREADY A blocking operation is already in progress in this model.
* @retval -EAGAIN The request timed out.
*/
int bt_mesh_dtt_set(struct bt_mesh_dtt_cli *cli, struct bt_mesh_msg_ctx *ctx,
u32_t transition_time, s32_t *rsp_transition_time);
/** @brief Set the Default Transition Time of the server without requesting a
* response.
*
* @param[in] cli Client model to send on.
* @param[in] ctx Message context to use for sending, or NULL to publish with
* the configured parameters.
* @param[in] transition_time Transition time to set (in milliseconds). Must be
* less than @ref BT_MESH_MODEL_TRANSITION_TIME_MAX_MS.
*
* @retval 0 Successfully sent the message.
* @retval -EINVAL The given transition time is invalid.
* @retval -ENOTSUP A message context was not provided and publishing is not
* supported.
* @retval -EADDRNOTAVAIL A message context was not provided and publishing is
* not configured.
* @retval -EAGAIN The device has not been provisioned.
*/
int bt_mesh_dtt_set_unack(struct bt_mesh_dtt_cli *cli,
struct bt_mesh_msg_ctx *ctx, u32_t transition_time);
/** @cond INTERNAL_HIDDEN */
extern const struct bt_mesh_model_op _bt_mesh_dtt_cli_op[];
extern const struct bt_mesh_model_cb _bt_mesh_dtt_cli_cb;
/** @endcond */
#ifdef __cplusplus
}
#endif
#endif /* BT_MESH_GEN_DTT_CLI_H__ */
/** @} */
| 35.974194 | 80 | 0.709469 | [
"mesh",
"model"
] |
d902c234989c79e488d64fc2d02608d9f4705e68 | 1,762 | h | C | include/snake.h | RanieriSantos/snaze | 0689d8f138764e0ba3dc5bb6acd3572a61c0e139 | [
"MIT"
] | null | null | null | include/snake.h | RanieriSantos/snaze | 0689d8f138764e0ba3dc5bb6acd3572a61c0e139 | [
"MIT"
] | null | null | null | include/snake.h | RanieriSantos/snaze | 0689d8f138764e0ba3dc5bb6acd3572a61c0e139 | [
"MIT"
] | null | null | null | #ifndef SNAKE_H
#define SNAKE_H
#include <vector>
#include "../include/basicStructures.h" // position, Direction
class Snake {
private:
int lifes = 5; // number of snake lifes. Initating with 5
std::vector<position> snake; // snake head + body. Index 0 = snake head
Directions direc; // snake direction
// pointe to current level
public:
//! |brief Snake constructor
//! \param init - initial position of snake
//! \param dir - initial direction of snake
Snake() {
// default
}
Snake(position init, Directions dir) {
position pos;
pos.index_row = init.index_row;
pos.index_column = init.index_column;
snake.push_back(pos);
direc = dir;
};
//! \brief Snake loses a life
//! \param respawn position of current map
void lost_life(position respawn);
//>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> GETS
//! \brief Return how many lifes the snake still has
int get_lifes();
//! \brief Returns snake vector
std::vector<position>* get_snake();
//! \brief Return snake direction
Directions get_diretion();
//>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> SETS
//! \brief add a position to snake body
//! \param row - row index of the position
//! \param col - column index of the position
void set_snake(int row, int col);
//! \brief add direction of snake
void set_diretion(Directions direction);
void move(Directions way);
};
#endif | 29.366667 | 80 | 0.510783 | [
"vector"
] |
d9064852988771895b89e86ad8ba035ba94404c7 | 1,841 | h | C | Base/Poll/eventloop.h | Nefertarii/CPP_Server | a1f04dac2cdd6b9959e81ab36584b9a0e38cb7b9 | [
"MIT"
] | null | null | null | Base/Poll/eventloop.h | Nefertarii/CPP_Server | a1f04dac2cdd6b9959e81ab36584b9a0e38cb7b9 | [
"MIT"
] | null | null | null | Base/Poll/eventloop.h | Nefertarii/CPP_Server | a1f04dac2cdd6b9959e81ab36584b9a0e38cb7b9 | [
"MIT"
] | null | null | null | #ifndef POLL_EVENTLOOP_H_
#define POLL_EVENTLOOP_H_
#include <Base/Timer/timestamp.h>
#include <Base/noncopyable.h>
#include <functional>
#include <memory>
#include <mutex>
#include <thread>
#include <unistd.h>
#include <vector>
namespace Wasi {
namespace Time {
class TimerId;
} // namespace Time
namespace Sockets {
class Channel;
} // namespace Sockets
namespace Poll {
class Poller;
class TimerQueue;
using ChannelList = std::vector<Sockets::Channel*>;
using Functors = std::function<void()>;
class EventLoop : Noncopyable {
private:
int wake_up_fd;
bool looping;
bool event_handling;
bool quit;
bool calling_pending_functors;
const pid_t thread_id;
Time::TimeStamp poll_return_time;
Sockets::Channel* current_active_channel;
std::unique_ptr<Poller> poller;
std::unique_ptr<TimerQueue> timer_queue;
ChannelList active_channels;
std::mutex mtx;
std::vector<Functors> pending_functors;
std::unique_ptr<Sockets::Channel> wakeup_channel;
void Abort_not_in_loop_thread();
void Do_pending_functors();
void Handle_read();
public:
EventLoop();
void Loop();
void Quit();
Time::TimeStamp Poll_return_time() const;
Time::TimerId Run_at(const Time::TimeStamp& time, Functors callback);
Time::TimerId Run_after(double delay, Functors callback);
Time::TimerId Run_every(double interval, Functors callback);
void Update_channel(Sockets::Channel* channel);
void Remove_channel(Sockets::Channel* channel);
void Assert_in_loop_thread();
bool Is_in_loop_thread() const;
void Queue_in_loop(Functors callback);
void Run_in_loop(Functors callback);
void Wake_up();
~EventLoop();
};
} // namespace Poll
} // namespace Wasi
#endif // !POLL_EVENTLOOP_H_ | 26.3 | 74 | 0.698533 | [
"vector"
] |
d906937dfe3248fe51281512b28e67efcde10687 | 99,947 | c | C | src/firmware/lib/STM32_CPAL_Driver/src/cpal_i2c.c | BHFaction/Tribot | 38d8caaa73775654125db3091b8de2aadb3dba99 | [
"MIT"
] | 3 | 2017-04-04T04:03:28.000Z | 2021-05-29T08:08:48.000Z | src/firmware/lib/STM32_CPAL_Driver/src/cpal_i2c.c | BHFaction/Tribot | 38d8caaa73775654125db3091b8de2aadb3dba99 | [
"MIT"
] | null | null | null | src/firmware/lib/STM32_CPAL_Driver/src/cpal_i2c.c | BHFaction/Tribot | 38d8caaa73775654125db3091b8de2aadb3dba99 | [
"MIT"
] | 2 | 2018-02-28T14:16:11.000Z | 2019-05-07T18:02:16.000Z | /**
******************************************************************************
* @file STM32_CPAL_Driver/src/cpal_i2c.c
* @author MCD Application Team
* @version V1.2.0
* @date 21-December-2012
* @brief This file provides all the CPAL firmware functions for I2C peripheral.
******************************************************************************
* @attention
*
* <h2><center>© COPYRIGHT 2012 STMicroelectronics</center></h2>
*
* Licensed under MCD-ST Liberty SW License Agreement V2, (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.st.com/software_license_agreement_liberty_v2
*
* 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.
*
******************************************************************************
*/
/* Includes ------------------------------------------------------------------*/
#include "cpal_i2c.h"
/* Private typedef -----------------------------------------------------------*/
/* Private defines -----------------------------------------------------------*/
/* Private macro -------------------------------------------------------------*/
/* This macro allows to test on a flag status and to start Timeout procedure if the
waiting time exceeds the allowed timeout period.
@note This macro has not been implemented as a function because the entered parameter
'cmd' itself can be a macro (if it was implemented as a function, the check on the
flag would be done only once, while the required behavior is to check the flag
continuously). */
#define __CPAL_I2C_TIMEOUT_DETECT ((pDevInitStruct->wCPAL_Timeout == CPAL_I2C_TIMEOUT_MIN) ||\
(pDevInitStruct->wCPAL_Timeout == CPAL_I2C_TIMEOUT_DEFAULT))
#define __CPAL_I2C_TIMEOUT(cmd, timeout) pDevInitStruct->wCPAL_Timeout = CPAL_I2C_TIMEOUT_MIN + (timeout);\
while (((cmd) == 0) && (!__CPAL_I2C_TIMEOUT_DETECT));\
if (__CPAL_I2C_TIMEOUT_DETECT)\
{\
return CPAL_I2C_Timeout (pDevInitStruct); \
}\
pDevInitStruct->wCPAL_Timeout = CPAL_I2C_TIMEOUT_DEFAULT
#define __CPAL_I2C_TIMEOUT_SPINLOOP(cmd, timeout){\
volatile uint32_t cntdown = 5000 * timeout;\
while (((cmd) == 0) && (cntdown--));\
if (cntdown == 0)\
{\
return CPAL_I2C_Timeout (pDevInitStruct);\
}\
}\
/* Private variables ---------------------------------------------------------*/
/*========= Table Exported from HAL =========*/
extern I2C_TypeDef* CPAL_I2C_DEVICE[];
#ifdef CPAL_I2C_DMA_PROGMODEL
extern DMA_TypeDef* CPAL_I2C_DMA[];
#if defined (STM32F2XX) || defined (STM32F4XX)
extern DMA_Stream_TypeDef* CPAL_I2C_DMA_TX_Stream[];
extern DMA_Stream_TypeDef* CPAL_I2C_DMA_RX_Stream[];
#else
extern DMA_Channel_TypeDef* CPAL_I2C_DMA_TX_Channel[];
extern DMA_Channel_TypeDef* CPAL_I2C_DMA_RX_Channel[];
#endif
extern const uint32_t CPAL_I2C_DMA_TX_TC_FLAG[];
extern const uint32_t CPAL_I2C_DMA_RX_TC_FLAG[];
extern const uint32_t CPAL_I2C_DMA_TX_HT_FLAG[];
extern const uint32_t CPAL_I2C_DMA_RX_HT_FLAG[];
extern const uint32_t CPAL_I2C_DMA_TX_TE_FLAG[];
extern const uint32_t CPAL_I2C_DMA_RX_TE_FLAG[];
#endif /* CPAL_I2C_DMA_PROGMODEL */
/*========= Local structures used in CPAL_I2C_StructInit() function =========*/
I2C_InitTypeDef I2C_InitStructure;
/* Private function prototypes -----------------------------------------------*/
/*========= Local Master events handlers =========*/
#ifdef CPAL_I2C_MASTER_MODE
static uint32_t I2C_MASTER_START_Handle(CPAL_InitTypeDef* pDevInitStruct); /* Handle Master SB Interrupt event */
static uint32_t I2C_MASTER_ADDR_Handle(CPAL_InitTypeDef* pDevInitStruct); /* Handle Master ADDR Interrupt event */
#ifdef CPAL_I2C_10BIT_ADDR_MODE
static uint32_t I2C_MASTER_ADD10_Handle(CPAL_InitTypeDef* pDevInitStruct); /* Handle Master ADD10 Interrupt event */
#endif /* CPAL_I2C_10BIT_ADDR_MODE */
#ifdef CPAL_I2C_IT_PROGMODEL
static uint32_t I2C_MASTER_TXE_Handle(CPAL_InitTypeDef* pDevInitStruct); /* Handle Master TXE Interrupt event */
#endif /* CPAL_I2C_IT_PROGMODEL */
#if defined (CPAL_I2C_IT_PROGMODEL) || defined (CPAL_I2C_DMA_1BYTE_CASE)
static uint32_t I2C_MASTER_RXNE_Handle(CPAL_InitTypeDef* pDevInitStruct); /* Handle Master RXNE Interrupt event */
#endif /* CPAL_I2C_IT_PROGMODEL || CPAL_I2C_DMA_1BYTE_CASE */
#endif /* CPAL_I2C_MASTER_MODE */
/*========= Local Slave events handlers =========*/
#ifdef CPAL_I2C_SLAVE_MODE
static uint32_t I2C_SLAVE_ADDR_Handle(CPAL_InitTypeDef* pDevInitStruct); /* Handle Slave ADDR Interrupt event */
static uint32_t I2C_SLAVE_STOP_Handle(CPAL_InitTypeDef* pDevInitStruct); /* Handle Slave STOPF Interrupt event */
#ifdef CPAL_I2C_IT_PROGMODEL
static uint32_t I2C_SLAVE_TXE_Handle(CPAL_InitTypeDef* pDevInitStruct); /* Handle Slave TXE Interrupt event */
static uint32_t I2C_SLAVE_RXNE_Handle(CPAL_InitTypeDef* pDevInitStruct); /* Handle Slave RXNE Interrupt event */
#endif /* CPAL_I2C_IT_PROGMODEL */
#endif /* CPAL_I2C_SLAVE_MODE */
/*========= CPAL Timeout handler =========*/
static uint32_t CPAL_I2C_Timeout (CPAL_InitTypeDef* pDevInitStruct);
/* Private functions ---------------------------------------------------------*/
/*================== USER CPAL Functions ==================*/
/**
* @brief Initialize the peripheral and all related clocks, GPIOs, DMA and
* Interrupts according to the specified parameters in the
* CPAL_InitTypeDef structure.
* @param pDevInitStruct : Pointer to the peripheral configuration structure.
* @retval CPAL_PASS or CPAL_FAIL
*/
uint32_t CPAL_I2C_Init(CPAL_InitTypeDef* pDevInitStruct)
{
CPAL_LOG("\n\r\n\rLOG <CPAL_I2C_Init> : I2C Device Init");
/* If CPAL_State is not BUSY */
if ((pDevInitStruct->CPAL_State == CPAL_STATE_READY)
|| (pDevInitStruct->CPAL_State == CPAL_STATE_ERROR)
|| (pDevInitStruct->CPAL_State == CPAL_STATE_DISABLED))
{
/*
- If CPAL_State is CPAL_STATE_ERROR (an Error occurred in transaction):
Perform the initialization routines (device will be deinitialized during initialization).
- If CPAL_State is CPAL_STATE_READY:
Perform the initialization routines
- If CPAL_State is CPAL_STATE_DISABLED:
Perform the Initialization routines */
#ifndef CPAL_I2C_DMA_PROGMODEL
if (pDevInitStruct->CPAL_ProgModel == CPAL_PROGMODEL_DMA)
{
/* update State */
pDevInitStruct->CPAL_State = CPAL_STATE_ERROR;
/* Exit Init function */
return CPAL_FAIL;
}
#endif /* CPAL_I2C_DMA_PROGMODEL */
#ifndef CPAL_I2C_IT_PROGMODEL
if (pDevInitStruct->CPAL_ProgModel == CPAL_PROGMODEL_INTERRUPT)
{
/* update State */
pDevInitStruct->CPAL_State = CPAL_STATE_ERROR;
/* Exit Init function */
return CPAL_FAIL;
}
#endif /* CPAL_I2C_IT_PROGMODEL */
/* Disable I2Cx Device */
__CPAL_I2C_HAL_DISABLE_DEV(pDevInitStruct->CPAL_Dev);
CPAL_LOG("\n\rLOG : I2C Device Disabled");
/* Deinitialize I2Cx GPIO */
CPAL_I2C_HAL_GPIODeInit(pDevInitStruct->CPAL_Dev);
CPAL_LOG("\n\rLOG : I2C Device IOs Deinit");
/* Deinitialize I2Cx Clock */
CPAL_I2C_HAL_CLKDeInit(pDevInitStruct->CPAL_Dev);
CPAL_LOG("\n\rLOG : I2C Device Clock Deinit");
#ifdef CPAL_I2C_DMA_PROGMODEL
/* Deinitialize DMA Channels */
if (pDevInitStruct->CPAL_ProgModel == CPAL_PROGMODEL_DMA)
{
CPAL_I2C_HAL_DMADeInit(pDevInitStruct->CPAL_Dev, pDevInitStruct->CPAL_Direction);
CPAL_LOG("\n\rLOG : I2C Device DMA Deinit");
}
#endif /* CPAL_I2C_DMA_PROGMODEL */
/*----------------------------------------------------------------------------
Peripheral Clock Initialization
---------------------------------------------------------------------------*/
/* Initialize I2Cx Clock */
CPAL_I2C_HAL_CLKInit(pDevInitStruct->CPAL_Dev);
CPAL_LOG("\n\rLOG : I2C Device Clock Init");
/*----------------------------------------------------------------------------
GPIO pins configuration
---------------------------------------------------------------------------*/
/* Initialize I2Cx GPIO */
CPAL_I2C_HAL_GPIOInit(pDevInitStruct->CPAL_Dev);
CPAL_LOG("\n\rLOG : I2C Device IOs Init");
/*----------------------------------------------------------------------------
Peripheral Initialization
---------------------------------------------------------------------------*/
/* Enable I2Cx Device */
__CPAL_I2C_HAL_ENABLE_DEV(pDevInitStruct->CPAL_Dev);
CPAL_LOG("\n\rLOG : I2C Device Enabled");
/* Initialize I2Cx device with parameters stored in pCPAL_I2C_Struct */
I2C_Init(CPAL_I2C_DEVICE[pDevInitStruct->CPAL_Dev], pDevInitStruct->pCPAL_I2C_Struct);
CPAL_LOG("\n\rLOG : I2C Device Config");
/* If General Call Mode Option Bit Selected */
if ((pDevInitStruct->wCPAL_Options & CPAL_OPT_I2C_GENCALL) != 0)
{
/* Enable GENERAL CALL Address Mode */
__CPAL_I2C_HAL_ENABLE_GENCALL(pDevInitStruct->CPAL_Dev);
CPAL_LOG("\n\rLOG : I2C Device GENCALL Mode Enabled");
}
/* If Dual Address Mode Option Bit Selected */
if ((pDevInitStruct->wCPAL_Options & CPAL_OPT_I2C_DUALADDR) != 0)
{
/* Enable Dual Address Mode */
__CPAL_I2C_HAL_ENABLE_DUALADDR(pDevInitStruct->CPAL_Dev);
/* Configure OAR2 */
__CPAL_I2C_HAL_OAR2_CONF(pDevInitStruct->CPAL_Dev, (uint8_t)(pDevInitStruct->wCPAL_Options & 0x000000FE));
CPAL_LOG("\n\rLOG : I2C Device DUAL ADDR Mode Enabled");
}
/* If NACK Slave Own Address option bit selected */
if ((pDevInitStruct->wCPAL_Options & CPAL_OPT_I2C_NACK_ADD) != 0)
{
/* Disable Acknowledgement of own Address */
__CPAL_I2C_HAL_DISABLE_ACK(pDevInitStruct->CPAL_Dev);
CPAL_LOG("\n\rLOG : I2C Device NACK Own Address Mode Enabled");
}
#ifdef CPAL_I2C_DMA_PROGMODEL
/*----------------------------------------------------------------------------
DMA Initialization :
---------------------------------------------------------------------------*/
/* If DMA Programming model is selected*/
if (pDevInitStruct->CPAL_ProgModel == CPAL_PROGMODEL_DMA)
{
/* Initialize I2Cx DMA Channels */
CPAL_I2C_HAL_DMAInit(pDevInitStruct->CPAL_Dev, pDevInitStruct->CPAL_Direction, pDevInitStruct->wCPAL_Options);
CPAL_LOG("\n\rLOG : I2C Device DMA Init");
}
#endif /* CPAL_I2C_DMA_PROGMODEL */
/*----------------------------------------------------------------------------
Peripheral and DMA interrupts Initialization
---------------------------------------------------------------------------*/
/* Initialize I2Cx Interrupts */
CPAL_I2C_HAL_ITInit(pDevInitStruct->CPAL_Dev, pDevInitStruct->wCPAL_Options, pDevInitStruct->CPAL_Direction, pDevInitStruct->CPAL_ProgModel);
CPAL_LOG("\n\rLOG : I2C Device IT Init");
/* Update CPAL_State to CPAL_STATE_READY */
pDevInitStruct->CPAL_State = CPAL_STATE_READY;
CPAL_LOG("\n\rLOG : I2C Device Ready");
/* Initialize Timeout Procedure */
_CPAL_TIMEOUT_INIT();
return CPAL_PASS;
}
/* If CPAL_State is BUSY (a transaction is still on going) Exit Init function */
else
{
CPAL_LOG("\n\rERROR : I2C Device Busy");
return CPAL_FAIL;
}
}
/**
* @brief Deinitialize the peripheral and all related clocks, GPIOs, DMA and NVIC
* to their reset values.
* @param pDevInitStruct: Pointer to the peripheral configuration structure.
* @retval CPAL_PASS or CPAL_FAIL
* @note The Peripheral clock is disabled but the GPIO Ports clocks remains
* enabled after this deinitialization.
*/
uint32_t CPAL_I2C_DeInit(CPAL_InitTypeDef* pDevInitStruct)
{
CPAL_LOG("\n\r\n\rLOG <CPAL_I2C_DeInit> : I2C Device Deinit");
/* If CPAL_State is not BUSY */
if ((pDevInitStruct->CPAL_State == CPAL_STATE_READY)
|| (pDevInitStruct->CPAL_State == CPAL_STATE_ERROR)
|| (pDevInitStruct->CPAL_State == CPAL_STATE_DISABLED))
{
/*
- If CPAL_State is CPAL_STATE_ERROR (an Error occurred in transaction):
Perform the deinitialization routines
- If CPAL_State is CPAL_STATE_READY:
Perform the deinitialization routines
- If CPAL_State is CPAL_STATE_DISABLED:
Perform the deinitialization routines */
/*----------------------------------------------------------------------------
GPIO pins Deinitialization
Note: The GPIO clock remains enabled after this deinitialization
---------------------------------------------------------------------------*/
/* Deinitialize I2Cx GPIO */
CPAL_I2C_HAL_GPIODeInit(pDevInitStruct->CPAL_Dev);
CPAL_LOG("\n\rLOG : I2C Device IOs Deinit");
/*----------------------------------------------------------------------------
Peripheral Deinitialization
---------------------------------------------------------------------------*/
/* Disable I2Cx Device */
__CPAL_I2C_HAL_DISABLE_DEV(pDevInitStruct->CPAL_Dev);
CPAL_LOG("\n\rLOG : I2C Device Disabled");
/*----------------------------------------------------------------------------
Peripheral Clock Deinitialization
---------------------------------------------------------------------------*/
/* Deinitialize I2Cx Clock */
CPAL_I2C_HAL_CLKDeInit(pDevInitStruct->CPAL_Dev);
CPAL_LOG("\n\rLOG : I2C Device Clock Deinit");
#ifdef CPAL_I2C_DMA_PROGMODEL
/*----------------------------------------------------------------------------
DMA Deinitialization : if DMA Programming model is selected
---------------------------------------------------------------------------*/
if (pDevInitStruct->CPAL_ProgModel == CPAL_PROGMODEL_DMA)
{
CPAL_I2C_HAL_DMADeInit(pDevInitStruct->CPAL_Dev, pDevInitStruct->CPAL_Direction);
CPAL_LOG("\n\rLOG : I2C Device DMA Deinit");
}
#endif /* CPAL_I2C_DMA_PROGMODEL */
/*----------------------------------------------------------------------------
Interrupts Deinitialization
---------------------------------------------------------------------------*/
CPAL_I2C_HAL_ITDeInit(pDevInitStruct->CPAL_Dev, pDevInitStruct->wCPAL_Options, pDevInitStruct->CPAL_Direction, pDevInitStruct->CPAL_ProgModel);
CPAL_LOG("\n\rLOG : I2C Device IT Deinit");
/*----------------------------------------------------------------------------
Structure fields initialization
-----------------------------------------------------------------------------*/
/* Initialize pDevInitStruct state parameters to their default values */
pDevInitStruct-> CPAL_State = CPAL_STATE_DISABLED; /* Device Disabled */
pDevInitStruct-> wCPAL_DevError = CPAL_I2C_ERR_NONE; /* No Device Error */
pDevInitStruct-> wCPAL_Timeout = ((uint32_t)CPAL_I2C_TIMEOUT_DEFAULT); /* Set timeout value to CPAL_I2C_TIMEOUT_DEFAULT */
CPAL_LOG("\n\rLOG :Set State fields to default");
/*----------------------------------------------------------------------------
Deinitialize Timeout Procedure
-----------------------------------------------------------------------------*/
_CPAL_TIMEOUT_DEINIT();
return CPAL_PASS;
}
/* If CPAL_State is BUSY (a transaction is still on going) Exit Init function */
else
{
CPAL_LOG("\n\rERROR : I2C Device Busy");
return CPAL_FAIL;
}
}
/**
* @brief Initialize the peripheral structure with default values according
* to the specified parameters in the CPAL_I2CDevTypeDef structure.
* @param pDevInitStruct: Pointer to the peripheral configuration structure.
* @retval CPAL_PASS or CPAL_FAIL.
*/
uint32_t CPAL_I2C_StructInit(CPAL_InitTypeDef* pDevInitStruct)
{
/* Initialize I2C_InitStructure to their default values */
I2C_InitStructure.I2C_ClockSpeed = 100000; /* Initialize the I2C_ClockSpeed member */
I2C_InitStructure.I2C_Mode = I2C_Mode_I2C; /* Initialize the I2C_Mode member */
I2C_InitStructure.I2C_DutyCycle = I2C_DutyCycle_2; /* Initialize the I2C_DutyCycle member */
I2C_InitStructure.I2C_OwnAddress1 = 0; /* Initialize the I2C_OwnAddress1 member */
I2C_InitStructure.I2C_Ack = I2C_Ack_Enable; /* Initialize the I2C_Ack member */
I2C_InitStructure.I2C_AcknowledgedAddress = I2C_AcknowledgedAddress_7bit; /* Initialize the I2C_AcknowledgedAddress member */
/* Initialize pDevInitStruct parameter to their default values */
pDevInitStruct-> CPAL_Direction = CPAL_DIRECTION_TXRX; /* Transmitter and Receiver direction selected */
pDevInitStruct-> CPAL_Mode = CPAL_MODE_MASTER; /* Mode Master selected */
pDevInitStruct-> CPAL_ProgModel = CPAL_PROGMODEL_DMA; /* DMA Programming Model selected */
pDevInitStruct-> pCPAL_TransferTx = pNULL; /* Point pCPAL_TransferTx to a Null pointer */
pDevInitStruct-> pCPAL_TransferRx = pNULL; /* Point pCPAL_TransferRx to a Null pointer */
pDevInitStruct-> CPAL_State = CPAL_STATE_DISABLED; /* Device Disabled */
pDevInitStruct-> wCPAL_DevError = CPAL_I2C_ERR_NONE; /* No Device Error */
pDevInitStruct-> wCPAL_Options = ((uint32_t)0x00000000); /* No Options selected */
pDevInitStruct-> wCPAL_Timeout = ((uint32_t)CPAL_I2C_TIMEOUT_DEFAULT); /* Set timeout value to CPAL_I2C_TIMEOUT_DEFAULT */
pDevInitStruct-> pCPAL_I2C_Struct = &I2C_InitStructure; /* Point to I2C_InitStructure (with default values) */
CPAL_LOG("\n\r\n\rLOG <CPAL_I2C_StructInit> : I2C Device Structure set to Default Value");
return CPAL_PASS;
}
#if defined (CPAL_I2C_MASTER_MODE) || ! defined (CPAL_I2C_LISTEN_MODE)
/**
* @brief Allows to send a data or a buffer of data through the peripheral to
* a selected device in a selected location address.
* @param pDevInitStruct: Pointer to the peripheral configuration structure.
* @retval CPAL_PASS or CPAL_FAIL.
*/
uint32_t CPAL_I2C_Write(CPAL_InitTypeDef* pDevInitStruct)
{
/* Check I2C State:
- If busy --> exit Write operation
- If disabled --> exit Write operation
- If error --> exit Write operation
- If ready -->
- If Master Mode selected with No memory Address Mode OR Slave Mode Selected.
- Test the value of programming model
- If DMA Programming Model --> enable TX DMA Channel.
- If Interrupt Programming Model --> enable Buffer Interrupt.
- Update CPAL_STATE to CPAL_STATE_READY_TX.
- If Master mode selected --> generate start condition
- Enable Event Interrupt */
CPAL_LOG("\n\r\n\rLOG <CPAL_I2C_Write> : I2C Device Write OP");
/* If Device is Busy (a transaction is still on going) Exit Write function */
if (((pDevInitStruct->CPAL_State & CPAL_STATE_BUSY) != 0)
|| (pDevInitStruct->CPAL_State == CPAL_STATE_READY_TX)
|| (pDevInitStruct->CPAL_State == CPAL_STATE_READY_RX))
{
CPAL_LOG("\n\rERROR : I2C Device Busy");
return CPAL_FAIL;
}
/* If CPAL_State is CPAL_STATE_DISABLED (device is not initialized) Exit Write function */
else if (pDevInitStruct->CPAL_State == CPAL_STATE_DISABLED)
{
CPAL_LOG("\n\rERROR : I2C Device Not Initialized");
return CPAL_FAIL;
}
/* If CPAL_State is CPAL_STATE_ERROR (Error occurred ) */
else if (pDevInitStruct->CPAL_State == CPAL_STATE_ERROR)
{
CPAL_LOG("\n\rERROR : I2C Device Error");
return CPAL_FAIL;
}
/* If CPAL_State is CPAL_STATE_READY ( Start Communication )*/
else
{
/* Update CPAL_State to CPAL_STATE_BUSY */
pDevInitStruct->CPAL_State = CPAL_STATE_BUSY;
/* No Stop Condition Generation option Mode bit not selected */
if ((pDevInitStruct->wCPAL_Options & CPAL_OPT_I2C_NOSTOP_MODE) == 0)
{
/* Wait until Busy flag is reset */
__CPAL_I2C_TIMEOUT(!(__CPAL_I2C_HAL_GET_BUSY(pDevInitStruct->CPAL_Dev)), CPAL_I2C_TIMEOUT_BUSY);
}
/* If Master Mode selected */
if (pDevInitStruct->CPAL_Mode == CPAL_MODE_MASTER)
{
#ifdef CPAL_I2C_MASTER_MODE
CPAL_LOG("\n\rLOG : I2C Device Master");
/* Generate Start */
__CPAL_I2C_HAL_START(pDevInitStruct->CPAL_Dev);
/* If No memory Address Option Bit is Selected */
if ((pDevInitStruct->wCPAL_Options & CPAL_OPT_NO_MEM_ADDR) != 0)
{
/* Switch Programing Mode Enable DMA or IT Buffer */
CPAL_I2C_Enable_DMA_IT(pDevInitStruct, CPAL_DIRECTION_TX);
}
/* Update CPAL_State to CPAL_STATE_READY_TX */
pDevInitStruct->CPAL_State = CPAL_STATE_READY_TX;
CPAL_LOG("\n\rLOG : I2C Device Ready TX");
CPAL_LOG("\n\rLOG : I2C Device Generates Start");
/* Initialize timeout value */
pDevInitStruct->wCPAL_Timeout = CPAL_I2C_TIMEOUT_MIN + CPAL_I2C_TIMEOUT_SB;
#endif /* CPAL_I2C_MASTER_MODE */
}
/* If Slave Mode selected */
else
{
#ifdef CPAL_I2C_SLAVE_MODE
/* If NACK Slave Own Address option bit selected */
if ((pDevInitStruct->wCPAL_Options & CPAL_OPT_I2C_NACK_ADD) != 0)
{
/* Enable Acknowledgement of Own address */
__CPAL_I2C_HAL_ENABLE_ACK(pDevInitStruct->CPAL_Dev);
}
/* Switch Programing Mode Enable DMA or IT Buffer */
CPAL_I2C_Enable_DMA_IT(pDevInitStruct, CPAL_DIRECTION_TX);
/* Update CPAL_State to CPAL_STATE_READY_TX */
pDevInitStruct->CPAL_State = CPAL_STATE_READY_TX;
CPAL_LOG("\n\rLOG : I2C Device Ready TX");
CPAL_LOG("\n\rLOG : I2C Device Slave");
#endif /* CPAL_I2C_SLAVE_MODE */
}
/* Enable EVENT Interrupts*/
CPAL_LOG("\n\rLOG : I2C Device EVT IT Enabled");
__CPAL_I2C_HAL_ENABLE_EVTIT(pDevInitStruct->CPAL_Dev);
}
return CPAL_PASS;
}
/**
* @brief Allows to receive a data or a buffer of data through the peripheral
* from a selected device in a selected location address.
* @param pDevInitStruct: Pointer to the peripheral configuration structure.
* @retval CPAL_PASS or CPAL_FAIL.
*/
uint32_t CPAL_I2C_Read(CPAL_InitTypeDef* pDevInitStruct)
{
/* Check I2C State:
- If busy --> exit Read operation
- If disabled --> exit Read operation
- If error --> exit Read operation
- If ready -->
- If Master Mode with Memory Address Mode.
- Generate start
- Send Slave Address
- Send Memory Address
- Else Test the value of programming model
- If DMA Programming Model --> enable RX DMA Channel
- If Interrupt Programming Model --> enable Buffer Interrupt
- Update CPAL_STATE to CPAL_STATE_READY_RX.
- If Master mode selected --> generate start condition
- Enable Event Interrupt */
CPAL_LOG("\n\r\n\rLOG <CPAL_I2C_Read> : I2C Device Perform Read OP");
/* If Device is Busy (a transaction is still on going) Exit Read function */
if (((pDevInitStruct->CPAL_State & CPAL_STATE_BUSY) != 0)
|| (pDevInitStruct->CPAL_State == CPAL_STATE_READY_TX)
|| (pDevInitStruct->CPAL_State == CPAL_STATE_READY_RX))
{
CPAL_LOG("\n\rERROR : I2C Device Busy");
return CPAL_FAIL;
}
/* If CPAL_State is CPAL_STATE_DISABLED (device is not initialized) Exit Read function */
else if (pDevInitStruct->CPAL_State == CPAL_STATE_DISABLED)
{
CPAL_LOG("\n\rERROR : I2C Device Not Initialized");
return CPAL_FAIL;
}
/* If CPAL_State is CPAL_STATE_ERROR (Error occurred ) */
else if (pDevInitStruct->CPAL_State == CPAL_STATE_ERROR)
{
CPAL_LOG("\n\rERROR : I2C Device Error");
return CPAL_FAIL;
}
/* If CPAL_State is CPAL_STATE_READY */
else
{
/* Update CPAL_State to CPAL_STATE_BUSY */
pDevInitStruct->CPAL_State = CPAL_STATE_BUSY;
/* No Stop Condition Generation Mode option bit not selected */
if ((pDevInitStruct->wCPAL_Options & CPAL_OPT_I2C_NOSTOP_MODE) == 0)
{
/* Wait until Busy flag is reset */
__CPAL_I2C_TIMEOUT(!(__CPAL_I2C_HAL_GET_BUSY(pDevInitStruct->CPAL_Dev)), CPAL_I2C_TIMEOUT_BUSY);
}
#ifdef CPAL_I2C_DMA_1BYTE_CASE
/* If One byte transfer with DMA programming model */
if ((pDevInitStruct->CPAL_ProgModel == CPAL_PROGMODEL_DMA)
&& (pDevInitStruct->pCPAL_TransferRx->wNumData == 1))
{
/* Affect 1Byte DMA option to wCPAL_Options */
pDevInitStruct->wCPAL_Options |= CPAL_DMA_1BYTE_CASE;
/* Change ProgModel to Interrupt */
pDevInitStruct->CPAL_ProgModel = CPAL_PROGMODEL_INTERRUPT;
}
#endif /* CPAL_I2C_DMA_1BYTE_CASE */
#ifdef CPAL_I2C_MASTER_MODE
/* If "No Memory Address" Option Bit is not selected and Master Mode selected */
if (((pDevInitStruct->wCPAL_Options & CPAL_OPT_NO_MEM_ADDR) == 0)
&& (pDevInitStruct->CPAL_Mode == CPAL_MODE_MASTER ))
{
CPAL_LOG("\n\rLOG : I2C Device Master No Addr Mem Mode");
/* Generate Start */
__CPAL_I2C_HAL_START(pDevInitStruct->CPAL_Dev);
/* Wait until SB flag is set */
__CPAL_I2C_TIMEOUT(__CPAL_I2C_HAL_GET_SB(pDevInitStruct->CPAL_Dev), CPAL_I2C_TIMEOUT_SB);
/* Send Device Address */
/* If 7 Bit Addressing Mode */
if (pDevInitStruct->pCPAL_I2C_Struct->I2C_AcknowledgedAddress == I2C_AcknowledgedAddress_7bit)
{
/* Send Slave address with bit0 reset for write */
__CPAL_I2C_HAL_SEND((pDevInitStruct->CPAL_Dev), (uint8_t)((pDevInitStruct->pCPAL_TransferRx->wAddr1) & (uint8_t)(~I2C_OAR1_ADD0)));
/* Wait until ADDR flag is reset */
__CPAL_I2C_TIMEOUT(__CPAL_I2C_HAL_GET_ADDR(pDevInitStruct->CPAL_Dev), CPAL_I2C_TIMEOUT_ADDR);
}
#ifdef CPAL_I2C_10BIT_ADDR_MODE
/* If 10 Bit Addressing Mode */
else
{
/* Declare local variable that contains Address Header */
uint8_t I2CHeaderAddress = 0x00;
/* Calculate Header Address */
I2CHeaderAddress = (uint8_t)((((pDevInitStruct->pCPAL_TransferRx->wAddr1) & 0xFF00) >>7) | 0xF0);
/* Send Header Address */
__CPAL_I2C_HAL_SEND((pDevInitStruct->CPAL_Dev), I2CHeaderAddress);
/* Wait until ADD10 flag is set */
__CPAL_I2C_TIMEOUT(__CPAL_I2C_HAL_GET_ADD10(pDevInitStruct->CPAL_Dev), CPAL_I2C_TIMEOUT_ADD10);
/* Send Slave address with bit0 reset for write */
__CPAL_I2C_HAL_SEND((pDevInitStruct->CPAL_Dev), (uint8_t)(pDevInitStruct->pCPAL_TransferRx->wAddr1));
/* Wait until ADDR flag is set */
__CPAL_I2C_TIMEOUT(__CPAL_I2C_HAL_GET_ADDR(pDevInitStruct->CPAL_Dev), CPAL_I2C_TIMEOUT_ADDR);
}
#endif /* CPAL_I2C_10BIT_ADDR_MODE */
CPAL_LOG("\n\rLOG : I2C Device Target Address Sent ");
/* Clear ADDR flag: (Read SR1 followed by read of SR2), SR1 read operation is already done */
__CPAL_I2C_HAL_CLEAR_ADDR(pDevInitStruct->CPAL_Dev);
/* Wait until TXE flag is set */
__CPAL_I2C_TIMEOUT(__CPAL_I2C_HAL_GET_TXE(pDevInitStruct->CPAL_Dev), CPAL_I2C_TIMEOUT_TXE);
/* If 8 Bit register mode */
if ((pDevInitStruct->wCPAL_Options & CPAL_OPT_16BIT_REG) == 0)
{
/* Send Register Address */
__CPAL_I2C_HAL_SEND((pDevInitStruct->CPAL_Dev), (uint8_t)(((pDevInitStruct->pCPAL_TransferRx->wAddr2)& 0x00FF)));
/* Wait until TXE flag is set */
__CPAL_I2C_TIMEOUT(__CPAL_I2C_HAL_GET_TXE(pDevInitStruct->CPAL_Dev), CPAL_I2C_TIMEOUT_TXE);
}
#ifdef CPAL_16BIT_REG_OPTION
/* If 16 Bit register mode */
else
{
/* Send MSB Register Address */
__CPAL_I2C_HAL_SEND((pDevInitStruct->CPAL_Dev), (uint8_t)(((pDevInitStruct->pCPAL_TransferRx->wAddr2)& 0xFF00) >>8));
/* Wait until TXE flag is set */
__CPAL_I2C_TIMEOUT(__CPAL_I2C_HAL_GET_TXE(pDevInitStruct->CPAL_Dev), CPAL_I2C_TIMEOUT_TXE);
/* Send LSB Register Address */
__CPAL_I2C_HAL_SEND((pDevInitStruct->CPAL_Dev), (uint8_t)((pDevInitStruct->pCPAL_TransferRx->wAddr2)& 0x00FF));
/* Initialize Timeout value */
pDevInitStruct->wCPAL_Timeout = CPAL_I2C_TIMEOUT_MIN + CPAL_I2C_TIMEOUT_TXE;
/* Wait until TXE flag is set */
__CPAL_I2C_TIMEOUT(__CPAL_I2C_HAL_GET_TXE(pDevInitStruct->CPAL_Dev), CPAL_I2C_TIMEOUT_TXE);
}
#endif /* CPAL_16BIT_REG_OPTION */
CPAL_LOG("\n\rLOG : I2C Device Target Memory Address Sent");
}
else
#endif /* CPAL_I2C_MASTER_MODE */
if (pDevInitStruct->CPAL_ProgModel == CPAL_PROGMODEL_DMA)
{
CPAL_LOG("\n\rLOG : I2C Device Master No Memory Address Mode ");
/* Switch Programing Mode Enable DMA or IT Buffer */
CPAL_I2C_Enable_DMA_IT(pDevInitStruct, CPAL_DIRECTION_RX);
}
/* Update CPAL_State to CPAL_STATE_READY_RX */
pDevInitStruct->CPAL_State = CPAL_STATE_READY_RX;
CPAL_LOG("\n\rLOG : I2C Device Ready RX");
/* If Master Mode selected */
if (pDevInitStruct->CPAL_Mode == CPAL_MODE_MASTER )
{
#ifdef CPAL_I2C_MASTER_MODE
CPAL_LOG("\n\rLOG : I2C Device Master");
/* Generate Start */
__CPAL_I2C_HAL_START(pDevInitStruct->CPAL_Dev);
CPAL_LOG("\n\rLOG : I2C Device Generates Start");
/* Initialize Timeout value */
pDevInitStruct->wCPAL_Timeout = CPAL_I2C_TIMEOUT_MIN + CPAL_I2C_TIMEOUT_SB;
#endif /* CPAL_I2C_MASTER_MODE */
}
/* If Slave Mode selected */
else
{
#ifdef CPAL_I2C_SLAVE_MODE
/* If NACK Slave Own Address option bit selected */
if ((pDevInitStruct->wCPAL_Options & CPAL_OPT_I2C_NACK_ADD) != 0)
{
/* Enable Acknowledgement of Own address */
__CPAL_I2C_HAL_ENABLE_ACK(pDevInitStruct->CPAL_Dev);
}
if (pDevInitStruct->CPAL_ProgModel == CPAL_PROGMODEL_INTERRUPT)
{
/* Enable IT Buffer */
CPAL_I2C_Enable_DMA_IT(pDevInitStruct, CPAL_DIRECTION_RX);
}
CPAL_LOG("\n\rLOG : I2C Device Slave");
#endif /* CPAL_I2C_SLAVE_MODE */
}
CPAL_LOG("\n\rLOG : I2C Device EVT IT Enabled");
/* Enable EVENT Interrupts*/
__CPAL_I2C_HAL_ENABLE_EVTIT(pDevInitStruct->CPAL_Dev);
}
return CPAL_PASS;
}
#endif /* CPAL_I2C_MASTER_MODE || ! CPAL_I2C_LISTEN_MODE */
#if defined (CPAL_I2C_LISTEN_MODE) && defined (CPAL_I2C_SLAVE_MODE)
/**
* @brief Allows slave device to start a communication without knowing in advance
* the nature of the operation (read or write). Slave waits until it receive
* its own address.CPAL_I2C_SLAVE_READ_UserCallback is called for a read request
* and CPAL_I2C_SLAVE_WRITE_UserCallback for a write request in I2C_SLAVE_ADDR_Handle.
* User must implement inorder to configure DMA, interrupts and transfer parameters.
* @param pDevInitStruct: Pointer to the peripheral configuration structure.
* @retval CPAL_PASS or CPAL_FAIL.
*/
uint32_t CPAL_I2C_Listen(CPAL_InitTypeDef* pDevInitStruct)
{
/* Check I2C State:
- If busy --> exit operation
- If disabled --> exit operation
- If error --> exit operation
- If ready -->
- Enable Event Interrupt */
CPAL_LOG("\n\r\n\rLOG <CPAL_I2C_Listen> : I2C Device in listen mode");
/* If Device is Busy (a transaction is still on going) Exit function */
if (((pDevInitStruct->CPAL_State & CPAL_STATE_BUSY) != 0)
|| (pDevInitStruct->CPAL_State == CPAL_STATE_READY_TX)
|| (pDevInitStruct->CPAL_State == CPAL_STATE_READY_RX))
{
CPAL_LOG("\n\rERROR : I2C Device Busy");
return CPAL_FAIL;
}
/* If CPAL_State is CPAL_STATE_DISABLED (device is not initialized) Exit function */
else if (pDevInitStruct->CPAL_State == CPAL_STATE_DISABLED)
{
CPAL_LOG("\n\rERROR : I2C Device Not Initialized");
return CPAL_FAIL;
}
/* If CPAL_State is CPAL_STATE_ERROR (Error occurred ) */
else if (pDevInitStruct->CPAL_State == CPAL_STATE_ERROR)
{
CPAL_LOG("\n\rERROR : I2C Device Error");
return CPAL_FAIL;
}
/* If CPAL_State is CPAL_STATE_READY */
else
{
/* Set device to slave mode */
pDevInitStruct->CPAL_Mode = CPAL_MODE_SLAVE;
/* Update CPAL_State to CPAL_STATE_BUSY */
pDevInitStruct->CPAL_State = CPAL_STATE_BUSY;
#ifdef CPAL_I2C_DMA_1BYTE_CASE
/* If One byte transfer with DMA programming model */
if ((pDevInitStruct->CPAL_ProgModel == CPAL_PROGMODEL_DMA)
&& (pDevInitStruct->pCPAL_TransferRx->wNumData == 1))
{
/* Affect 1Byte DMA option to wCPAL_Options */
pDevInitStruct->wCPAL_Options |= CPAL_DMA_1BYTE_CASE;
/* Change ProgModel to Interrupt */
pDevInitStruct->CPAL_ProgModel = CPAL_PROGMODEL_INTERRUPT;
}
#endif /* CPAL_I2C_DMA_1BYTE_CASE */
/* If NACK Slave Own Address option bit selected */
if ((pDevInitStruct->wCPAL_Options & CPAL_OPT_I2C_NACK_ADD) != 0)
{
/* Enable Acknowledgement of Own address */
__CPAL_I2C_HAL_ENABLE_ACK(pDevInitStruct->CPAL_Dev);
}
CPAL_LOG("\n\rLOG : I2C Device EVT IT Enabled");
/* Enable EVENT Interrupts*/
__CPAL_I2C_HAL_ENABLE_EVTIT(pDevInitStruct->CPAL_Dev);
}
return CPAL_PASS;
}
#endif /* CPAL_I2C_LISTEN_MODE && CPAL_I2C_SLAVE_MODE */
/**
* @brief Wait until target device is ready for communication (This function is
* used with Memory devices).
* @param pDevInitStruct: Pointer to the peripheral configuration structure.
* @retval CPAL_PASS or CPAL_FAIL.
*/
uint32_t CPAL_I2C_IsDeviceReady(CPAL_InitTypeDef* pDevInitStruct)
{
__IO uint32_t Timeout = 0xFFFF;
CPAL_LOG("\n\r\n\rLOG <CPAL_I2C_DeviceIsReady> : Wait until I2C Device is Ready");
/* Set CPAL state to CPAL_STATE_DISABLED */
pDevInitStruct->CPAL_State = CPAL_STATE_BUSY;
/* Disable ERROR Interrupt */
__CPAL_I2C_HAL_DISABLE_ERRIT(pDevInitStruct->CPAL_Dev);
/* Disable I2Cx Device */
__CPAL_I2C_HAL_DISABLE_DEV(pDevInitStruct->CPAL_Dev);
/* Enable I2Cx Device */
__CPAL_I2C_HAL_ENABLE_DEV(pDevInitStruct->CPAL_Dev);
/* Generate Start */
__CPAL_I2C_HAL_START(pDevInitStruct->CPAL_Dev);
/* Wait until SB flag is set */
__CPAL_I2C_TIMEOUT(__CPAL_I2C_HAL_GET_SB(pDevInitStruct->CPAL_Dev), CPAL_I2C_TIMEOUT_SB);
/* Send Slave address with bit0 reset for write */
__CPAL_I2C_HAL_SEND((pDevInitStruct->CPAL_Dev), (uint8_t)((pDevInitStruct->pCPAL_TransferTx->wAddr1) & (uint8_t)(~I2C_OAR1_ADD0)));
/* wait until timeout elapsed or target device acknowledge its address*/
while ((__CPAL_I2C_HAL_GET_ADDR(pDevInitStruct->CPAL_Dev) == 0) && (Timeout-- != 0));
/* If Timeout occurred */
if (Timeout == 0)
{
return CPAL_FAIL;
}
/* If ADDR flag is set */
else
{
/* Clear AF flag */
__CPAL_I2C_HAL_CLEAR_AF(pDevInitStruct->CPAL_Dev);
/* Generate Stop */
__CPAL_I2C_HAL_STOP(pDevInitStruct->CPAL_Dev);
/* wait until Busy flag is reset */
while(__CPAL_I2C_HAL_GET_BUSY(pDevInitStruct->CPAL_Dev));
/* Disable I2Cx Device */
__CPAL_I2C_HAL_DISABLE_DEV(pDevInitStruct->CPAL_Dev);
CPAL_LOG("\n\rLOG : I2C Device Disabled");
/* Enable I2Cx Device */
__CPAL_I2C_HAL_ENABLE_DEV(pDevInitStruct->CPAL_Dev);
CPAL_LOG("\n\rLOG : I2C Device Enabled");
/* Enable ACK */
__CPAL_I2C_HAL_ENABLE_ACK(pDevInitStruct->CPAL_Dev);
/* Enable ERROR Interrupt */
__CPAL_I2C_HAL_ENABLE_ERRIT(pDevInitStruct->CPAL_Dev);
/* Set CPAL state to ready */
pDevInitStruct->CPAL_State = CPAL_STATE_READY;
CPAL_LOG("\n\rLOG : I2C Target device Ready");
return CPAL_PASS;
}
}
/*================== CPAL_I2C_Interrupt_Handler ==================*/
/**
* @brief This function handles I2C interrupt request for preparing communication
* and for transfer phase in case of using Interrupt Programming Model.
* @param pDevInitStruct: Pointer to the peripheral configuration structure.
* @retval CPAL_PASS.
*/
uint32_t CPAL_I2C_EV_IRQHandler( CPAL_InitTypeDef* pDevInitStruct)
{
__IO uint16_t I2CFlagStatus = 0x0000;
/* Read I2C1 Status Registers 1 and 2 */
I2CFlagStatus = __CPAL_I2C_HAL_GET_EVENT(pDevInitStruct->CPAL_Dev);
#ifdef CPAL_I2C_MASTER_MODE
/*----------------------------------------------------------------------------------------------*/
/*---------------------------------- If Master Mode selected ----------------------------------*/
if (pDevInitStruct->CPAL_Mode == CPAL_MODE_MASTER)
{
/*----------------------------------------*/
/*------------- If SB event --------------*/
if ((I2CFlagStatus & (uint16_t)CPAL_I2C_EVT_SB ) != 0)
{
return I2C_MASTER_START_Handle(pDevInitStruct);
}
/*----------------------------------------*/
/*------------- If ADDR event ------------*/
if((I2CFlagStatus & (uint16_t)CPAL_I2C_EVT_ADDR ) != 0)
{
return I2C_MASTER_ADDR_Handle(pDevInitStruct);
}
#ifdef CPAL_I2C_10BIT_ADDR_MODE
/*----------------------------------------*/
/*------------- If ADD10 event *----------*/
if ((I2CFlagStatus & (uint16_t)CPAL_I2C_EVT_ADD10) != 0)
{
return I2C_MASTER_ADD10_Handle(pDevInitStruct);
}
#endif /* CPAL_I2C_10BIT_ADDR_MODE */
#ifdef CPAL_I2C_IT_PROGMODEL
/*----------------------------------------*/
/*------------- If TXE event -------------*/
if (((I2CFlagStatus & (uint16_t)CPAL_I2C_EVT_TXE) != 0) && (pDevInitStruct->CPAL_State == CPAL_STATE_BUSY_TX))
{
return I2C_MASTER_TXE_Handle(pDevInitStruct);
}
#endif /* CPAL_I2C_IT_PROGMODEL */
#if defined (CPAL_I2C_IT_PROGMODEL) || defined (CPAL_I2C_DMA_1BYTE_CASE)
/*----------------------------------------*/
/*------------- If RXNE event ------------*/
if (((I2CFlagStatus & (uint16_t)CPAL_I2C_EVT_RXNE) != 0) && (pDevInitStruct->CPAL_State == CPAL_STATE_BUSY_RX))
{
return I2C_MASTER_RXNE_Handle(pDevInitStruct);
}
#endif /* CPAL_I2C_IT_PROGMODEL || CPAL_I2C_DMA_1BYTE_CASE */
}
#endif /* CPAL_I2C_MASTER_MODE */
#ifdef CPAL_I2C_SLAVE_MODE
/*----------------------------------------------------------------------------------------------*/
/*---------------------------------- If Slave Mode selected ------------------------------------*/
if (pDevInitStruct->CPAL_Mode == CPAL_MODE_SLAVE)
{
/*----------------------------------------*/
/*------------- If ADDR event ------------*/
if ((I2CFlagStatus & (uint16_t)CPAL_I2C_EVT_ADDR ) != 0)
{
return I2C_SLAVE_ADDR_Handle(pDevInitStruct);
}
#ifdef CPAL_I2C_IT_PROGMODEL
/*----------------------------------------*/
/*------------- If TXE event -------------*/
if ((I2CFlagStatus & (uint16_t)CPAL_I2C_EVT_TXE) != 0)
{
return I2C_SLAVE_TXE_Handle(pDevInitStruct);
}
/*----------------------------------------*/
/*------------- If RXNE event ------------*/
if ((I2CFlagStatus & (uint16_t)CPAL_I2C_EVT_RXNE) != 0)
{
return I2C_SLAVE_RXNE_Handle(pDevInitStruct);
}
#endif /* CPAL_I2C_IT_PROGMODEL */
/*----------------------------------------*/
/*------------- If STOPF event ------------*/
if ((I2CFlagStatus & (uint16_t)CPAL_I2C_EVT_STOPF) != 0)
{
return I2C_SLAVE_STOP_Handle(pDevInitStruct);
}
}
#endif /* CPAL_I2C_SLAVE_MODE */
return CPAL_PASS;
}
/**
* @brief Allows to handle errors occurred during initialization or communication
* in order to recover the correct communication status or call specific
* user functions.
* @param pDevInitStruct: Pointer to the peripheral configuration structure.
* @retval CPAL_PASS.
*/
uint32_t CPAL_I2C_ER_IRQHandler(CPAL_InitTypeDef* pDevInitStruct)
{
/* If AF detected in Slave mode transmitter */
if ((pDevInitStruct->CPAL_Mode == CPAL_MODE_SLAVE) && (pDevInitStruct->pCPAL_TransferTx->wNumData == 0) &&
((pDevInitStruct->CPAL_State == CPAL_STATE_READY) || (pDevInitStruct->CPAL_State == CPAL_STATE_BUSY_TX)))
{
/* Clear error flags that can be cleared by writing to SR register */
__CPAL_I2C_HAL_CLEAR_ERROR((pDevInitStruct->CPAL_Dev));
/* If Interrupt Programming Model */
if (pDevInitStruct->CPAL_ProgModel == CPAL_PROGMODEL_INTERRUPT)
{
#ifdef CPAL_I2C_IT_PROGMODEL
/* Disable EVENT Interrupt */
__CPAL_I2C_HAL_DISABLE_EVTIT(pDevInitStruct->CPAL_Dev);
CPAL_LOG("\n\rLOG : I2C Device EVT IT Disabled");
/* Disable Buffer interrupt */
__CPAL_I2C_HAL_DISABLE_BUFIT(pDevInitStruct->CPAL_Dev);
CPAL_LOG("\n\rLOG : I2C Device BUFF IT Disabled");
/* Wait until Busy flag is reset */
__CPAL_I2C_TIMEOUT_SPINLOOP(!(__CPAL_I2C_HAL_GET_BUSY(pDevInitStruct->CPAL_Dev)), CPAL_I2C_TIMEOUT_BUSY);
/* Update CPAL_State to CPAL_STATE_READY */
pDevInitStruct->CPAL_State = CPAL_STATE_READY;
/* Call TX TC UserCallback */
CPAL_I2C_TXTC_UserCallback(pDevInitStruct);
#endif /* CPAL_I2C_IT_PROGMODEL */
}
}
else
{
/* Read Error Register and affect to wCPAL_DevError */
pDevInitStruct->wCPAL_DevError = __CPAL_I2C_HAL_GET_ERROR(pDevInitStruct->CPAL_Dev);
/* Set Device state to CPAL_STATE_ERROR */
pDevInitStruct->CPAL_State = CPAL_STATE_ERROR;
CPAL_LOG("\n\r\n\rERROR <CPAL_I2C_ErrorHandler> : I2C Device Error");
/* Clear error flags that can be cleared by writing to SR register */
__CPAL_I2C_HAL_CLEAR_ERROR((pDevInitStruct->CPAL_Dev));
/* If Bus error occurred ---------------------------------------------------*/
if ((pDevInitStruct->wCPAL_DevError & CPAL_I2C_ERR_BERR) != 0)
{
CPAL_LOG("\n\rERROR : I2C Device BERR");
/* Generate I2C software reset in order to release SDA and SCL lines */
__CPAL_I2C_HAL_SWRST(pDevInitStruct->CPAL_Dev);
CPAL_LOG("\n\r I2C Device Software reset");
#ifdef USE_MULTIPLE_ERROR_CALLBACK
/* Call Bus Error UserCallback */
CPAL_I2C_BERR_UserCallback(pDevInitStruct->CPAL_Dev);
#endif /* USE_MULTIPLE_ERROR_CALLBACK */
}
/* If Arbitration Loss error occurred --------------------------------------*/
if ((pDevInitStruct->wCPAL_DevError & CPAL_I2C_ERR_ARLO) != 0)
{
CPAL_LOG("\n\rERROR : I2C Device ARLO");
/* Generate I2C software reset in order to release SDA and SCL lines */
__CPAL_I2C_HAL_SWRST(pDevInitStruct->CPAL_Dev);
CPAL_LOG("\n\r I2C Device Software reset");
#ifdef USE_MULTIPLE_ERROR_CALLBACK
/* Call Arbitration Lost UserCallback */
CPAL_I2C_ARLO_UserCallback(pDevInitStruct->CPAL_Dev);
#endif /* USE_MULTIPLE_ERROR_CALLBACK */
}
/* If Overrun error occurred -----------------------------------------------*/
if ((pDevInitStruct->wCPAL_DevError & CPAL_I2C_ERR_OVR) != 0)
{
CPAL_LOG("\n\rERROR : I2C Device OVR");
/* No I2C software reset is performed here in order to allow user to get back
the last data received correctly */
#ifdef USE_MULTIPLE_ERROR_CALLBACK
/* Call Overrun error UserCallback */
CPAL_I2C_OVR_UserCallback(pDevInitStruct->CPAL_Dev);
#endif /* USE_MULTIPLE_ERROR_CALLBACK */
}
/* If Acknowledge Failure error occurred -----------------------------------*/
if ((pDevInitStruct->wCPAL_DevError & CPAL_I2C_ERR_AF) != 0)
{
CPAL_LOG("\n\rERROR : I2C Device AF");
/* No I2C software reset is performed here in order to allow user to recover
communication */
#ifdef USE_MULTIPLE_ERROR_CALLBACK
/* Call Acknowledge Failure UserCallback */
CPAL_I2C_AF_UserCallback(pDevInitStruct->CPAL_Dev);
#endif /* USE_MULTIPLE_ERROR_CALLBACK */
}
/* USE_SINGLE_ERROR_CALLBACK is defined in cpal_conf.h file */
#if defined(USE_SINGLE_ERROR_CALLBACK)
/* Call Error UserCallback */
CPAL_I2C_ERR_UserCallback(pDevInitStruct->CPAL_Dev, pDevInitStruct->wCPAL_DevError);
#endif /* USE_SINGLE_ERROR_CALLBACK */
}
return CPAL_PASS;
}
#ifdef CPAL_I2C_DMA_PROGMODEL
/**
* @brief Handle I2C DMA TX interrupt request when DMA programming Model is
* used for data transmission.
* @param pDevInitStruct: Pointer to the peripheral configuration structure.
* @retval CPAL_PASS.
*/
uint32_t CPAL_I2C_DMA_TX_IRQHandler(CPAL_InitTypeDef* pDevInitStruct)
{
/* Reinitialize Timeout Value to default (no timeout initiated) */
pDevInitStruct->wCPAL_Timeout = CPAL_I2C_TIMEOUT_DEFAULT;
CPAL_LOG("\n\r\n\rLOG <CPAL_I2C_DMA_TX_IRQHandler> : I2C Device TX DMA ");
/*------------- If TC interrupt ------------*/
if((__CPAL_I2C_HAL_GET_DMATX_TCIT(pDevInitStruct->CPAL_Dev)) != 0)
{
CPAL_LOG("\n\rLOG : I2C Device TX Complete");
/* Update remaining number of data */
pDevInitStruct->pCPAL_TransferTx->wNumData = 0;
/* Call DMA TX TC UserCallback */
CPAL_I2C_DMATXTC_UserCallback(pDevInitStruct);
/* If DMA Normal mode */
if ((pDevInitStruct->wCPAL_Options & CPAL_OPT_DMATX_CIRCULAR) == 0)
{
/* If Master Mode selected */
if (pDevInitStruct->CPAL_Mode == CPAL_MODE_MASTER)
{
#ifdef CPAL_I2C_MASTER_MODE
/* Disable DMA Request */
__CPAL_I2C_HAL_DISABLE_DMAREQ(pDevInitStruct->CPAL_Dev);
/* Wait until BTF flag is set */
__CPAL_I2C_TIMEOUT_SPINLOOP(__CPAL_I2C_HAL_GET_BTF(pDevInitStruct->CPAL_Dev), CPAL_I2C_TIMEOUT_BTF);
/* No Stop Condition Generation option bit not selected */
if ((pDevInitStruct->wCPAL_Options & CPAL_OPT_I2C_NOSTOP) == 0)
{
/* Generate Stop Condition */
__CPAL_I2C_HAL_STOP(pDevInitStruct->CPAL_Dev);
/* Wait until Busy flag is reset */
__CPAL_I2C_TIMEOUT_SPINLOOP(!(__CPAL_I2C_HAL_GET_BUSY(pDevInitStruct->CPAL_Dev)), CPAL_I2C_TIMEOUT_BUSY);
}
/* Disable DMA Channel */
__CPAL_I2C_HAL_DISABLE_DMATX(pDevInitStruct->CPAL_Dev);
/* Disable EVENT Interrupt */
__CPAL_I2C_HAL_DISABLE_EVTIT(pDevInitStruct->CPAL_Dev);
CPAL_LOG("\n\rLOG : I2C Device Master TX DMA Disabled");
/* Update CPAL_State to CPAL_STATE_READY */
pDevInitStruct->CPAL_State = CPAL_STATE_READY;
}
#endif /* CPAL_I2C_MASTER_MODE */
else
{
#ifdef CPAL_I2C_SLAVE_MODE
/* Disable DMA Request and Channel */
__CPAL_I2C_HAL_DISABLE_DMAREQ(pDevInitStruct->CPAL_Dev);
__CPAL_I2C_HAL_DISABLE_DMATX(pDevInitStruct->CPAL_Dev);
/* Disable EVENT Interrupt */
__CPAL_I2C_HAL_DISABLE_EVTIT(pDevInitStruct->CPAL_Dev);
/* Wait until Busy flag is reset */
__CPAL_I2C_TIMEOUT_SPINLOOP(!(__CPAL_I2C_HAL_GET_BUSY(pDevInitStruct->CPAL_Dev)), CPAL_I2C_TIMEOUT_BUSY);
CPAL_LOG("\n\rLOG : I2C Device Slave TX DMA Disabled");
/* Update CPAL_State to CPAL_STATE_READY */
pDevInitStruct->CPAL_State = CPAL_STATE_READY;
#endif /* CPAL_I2C_SLAVE_MODE */
}
}
/* Call TX TC UserCallback */
CPAL_I2C_TXTC_UserCallback(pDevInitStruct);
}
/*------------- If HT interrupt ------------*/
else if ((__CPAL_I2C_HAL_GET_DMATX_HTIT(pDevInitStruct->CPAL_Dev)) != 0)
{
CPAL_LOG("\n\rLOG : I2C Device TX DMA Half Transfer ");
/* Call DMA TX HT UserCallback */
CPAL_I2C_DMATXHT_UserCallback(pDevInitStruct);
}
/*------------- If TE interrupt ------------*/
else if ((__CPAL_I2C_HAL_GET_DMATX_TEIT(pDevInitStruct->CPAL_Dev)) != 0)
{
CPAL_LOG("\n\rERROR : I2C Device TX DMA Transfer Error ");
/* Update CPAL_State to CPAL_STATE_ERROR */
pDevInitStruct->CPAL_State = CPAL_STATE_ERROR;
/* Update remaining number of data */
pDevInitStruct->pCPAL_TransferTx->wNumData = __CPAL_I2C_HAL_DMATX_GET_CNDT(pDevInitStruct->CPAL_Dev);
/* Call DMA TX TE UserCallback */
CPAL_I2C_DMATXTE_UserCallback(pDevInitStruct);
}
/* Clear DMA Interrupt Flag */
__CPAL_I2C_HAL_CLEAR_DMATX_IT(pDevInitStruct->CPAL_Dev);
return CPAL_PASS;
}
/**
* @brief Handle I2C DMA RX interrupt request when DMA programming Model is
* used for data reception.
* @param pDevInitStruct: Pointer to the peripheral configuration structure.
* @retval CPAL_PASS.
*/
uint32_t CPAL_I2C_DMA_RX_IRQHandler(CPAL_InitTypeDef* pDevInitStruct)
{
/* Reinitialize Timeout Value to default (no timeout initiated) */
pDevInitStruct->wCPAL_Timeout = CPAL_I2C_TIMEOUT_DEFAULT;
CPAL_LOG("\n\r\n\rLOG <CPAL_I2C_DMA_RX_IRQHandler> : I2C Device RX DMA ");
/*------------- If TC interrupt ------------*/
if ((__CPAL_I2C_HAL_GET_DMARX_TCIT(pDevInitStruct->CPAL_Dev)) != 0)
{
CPAL_LOG("\n\rLOG : I2C Device RX Complete");
/* Update remaining number of data */
pDevInitStruct->pCPAL_TransferRx->wNumData = 0;
/* Call DMA RX TC UserCallback */
CPAL_I2C_DMARXTC_UserCallback(pDevInitStruct);
/* If DMA Normal model */
if ((pDevInitStruct->wCPAL_Options & CPAL_OPT_DMARX_CIRCULAR) == 0)
{
/* If Master Mode selected */
if ((pDevInitStruct->CPAL_Mode == CPAL_MODE_MASTER))
{
#ifdef CPAL_I2C_MASTER_MODE
/* Generate Stop Condition */
__CPAL_I2C_HAL_STOP(pDevInitStruct->CPAL_Dev);
/* Disable DMA Request and Channel */
__CPAL_I2C_HAL_DISABLE_DMAREQ(pDevInitStruct->CPAL_Dev);
/* Wait until Busy flag is reset */
__CPAL_I2C_TIMEOUT_SPINLOOP(!(__CPAL_I2C_HAL_GET_BUSY(pDevInitStruct->CPAL_Dev)), CPAL_I2C_TIMEOUT_BUSY);
/* Disable DMA Channel */
__CPAL_I2C_HAL_DISABLE_DMARX(pDevInitStruct->CPAL_Dev);
/* Disable EVENT Interrupt */
__CPAL_I2C_HAL_DISABLE_EVTIT(pDevInitStruct->CPAL_Dev);
/* Disable DMA automatic NACK generation */
__CPAL_I2C_HAL_DISABLE_LAST(pDevInitStruct->CPAL_Dev);
CPAL_LOG("\n\rLOG : I2C Device Master RX DMA Disabled");
/* Update CPAL_State to CPAL_STATE_READY */
pDevInitStruct->CPAL_State = CPAL_STATE_READY;
/* Call RX TC UserCallback */
CPAL_I2C_RXTC_UserCallback(pDevInitStruct);
#endif /* CPAL_I2C_MASTER_MODE */
}
else if ((pDevInitStruct->CPAL_Mode == CPAL_MODE_SLAVE) && ((pDevInitStruct->wCPAL_Options & CPAL_OPT_I2C_NOSTOP) != 0))
{
#ifdef CPAL_I2C_SLAVE_MODE
/* Disable DMA Request */
__CPAL_I2C_HAL_DISABLE_DMAREQ(pDevInitStruct->CPAL_Dev);
/* Disable DMA Channel */
__CPAL_I2C_HAL_DISABLE_DMARX(pDevInitStruct->CPAL_Dev);
/* Disable EVENT Interrupt */
__CPAL_I2C_HAL_DISABLE_EVTIT(pDevInitStruct->CPAL_Dev);
CPAL_LOG("\n\rLOG : I2C Device Slave RX DMA Disabled");
/* Update CPAL_State to CPAL_STATE_READY */
pDevInitStruct->CPAL_State = CPAL_STATE_READY;
/* Call RX TC UserCallback */
CPAL_I2C_RXTC_UserCallback(pDevInitStruct);
#endif /* CPAL_I2C_SLAVE_MODE */
}
}
else
{
/* Call RX TC UserCallback */
CPAL_I2C_RXTC_UserCallback(pDevInitStruct);
}
}
/*------------- If HT interrupt ------------*/
else if ((__CPAL_I2C_HAL_GET_DMARX_HTIT(pDevInitStruct->CPAL_Dev)) != 0)
{
CPAL_LOG("\n\rLOG : I2C Device RX DMA Half Transfer");
/* Call DMA RX HT UserCallback */
CPAL_I2C_DMARXHT_UserCallback(pDevInitStruct);
}
/*------------- If TE interrupt ------------*/
else if ((__CPAL_I2C_HAL_GET_DMARX_TEIT(pDevInitStruct->CPAL_Dev)) != 0)
{
CPAL_LOG("\n\rERROR : I2C Device RX DMA Transfer Error ");
/* Update CPAL_State to CPAL_STATE_ERROR */
pDevInitStruct->CPAL_State = CPAL_STATE_ERROR;
/* Update remaining number of data */
pDevInitStruct->pCPAL_TransferRx->wNumData = __CPAL_I2C_HAL_DMARX_GET_CNDT(pDevInitStruct->CPAL_Dev);
/* Call DMA RX TE UserCallback */
CPAL_I2C_DMARXTE_UserCallback(pDevInitStruct);
}
/* Clear DMA Interrupt Flag */
__CPAL_I2C_HAL_CLEAR_DMARX_IT(pDevInitStruct->CPAL_Dev);
return CPAL_PASS;
}
#endif /* CPAL_I2C_DMA_PROGMODEL */
/*================== CPAL_I2C_Timeout_Function ==================*/
/**
* @brief This function Manages I2C Timeouts when waiting for specific events.
* @param None
* @retval CPAL_PASS or CPAL_FAIL.
*/
void CPAL_I2C_TIMEOUT_Manager(void)
{
uint32_t index = 0;
/* Manage I2C timeouts conditions */
for (index = 0; index < CPAL_I2C_DEV_NUM; index ++)
{
if (I2C_DevStructures[index] != pNULL)
{
/* If Timeout occurred */
if (I2C_DevStructures[index]->wCPAL_Timeout == CPAL_I2C_TIMEOUT_DETECTED)
{
/* Reinitialize Timeout Value */
I2C_DevStructures[index]->wCPAL_Timeout = CPAL_I2C_TIMEOUT_DEFAULT;
/* update CPAL_State to CPAL_STATE_ERROR */
I2C_DevStructures[index]->CPAL_State = CPAL_STATE_ERROR;
/* In case of Device Error Timeout_Callback should not be called */
if (I2C_DevStructures[index]->wCPAL_DevError == CPAL_I2C_ERR_NONE)
{
/* update wCPAL_DevError to CPAL_I2C_ERR_TIMEOUT */
I2C_DevStructures[index]->wCPAL_DevError = CPAL_I2C_ERR_TIMEOUT;
CPAL_LOG("\n\r\n\rLOG <CPAL_I2C_TIMEOUT_Manager> : I2C Device Timeout Error");
/* Call CPAL_TIMEOUT_UserCallback */
CPAL_TIMEOUT_UserCallback(I2C_DevStructures[index]);
}
}
/* If Timeout is triggered (wCPAL_Timeout != CPAL_I2C_TIMEOUT_DEFAULT)*/
else if (I2C_DevStructures[index]->wCPAL_Timeout != CPAL_I2C_TIMEOUT_DEFAULT)
{
/* Decrement the timeout value */
I2C_DevStructures[index]->wCPAL_Timeout--;
}
}
}
}
/**
* @brief This function Manages I2C Timeouts when Timeout occurred.
* @param pDevInitStruct: Pointer to the peripheral configuration structure.
* @retval CPAL_PASS or CPAL_FAIL.
*/
uint32_t CPAL_I2C_Timeout (CPAL_InitTypeDef* pDevInitStruct)
{
/* Reinitialize Timeout Value */
pDevInitStruct->wCPAL_Timeout = CPAL_I2C_TIMEOUT_DEFAULT;
/* update CPAL_State to CPAL_STATE_ERROR */
pDevInitStruct->CPAL_State = CPAL_STATE_ERROR;
/* update wCPAL_DevError to CPAL_I2C_ERR_TIMEOUT */
pDevInitStruct->wCPAL_DevError = CPAL_I2C_ERR_TIMEOUT;
/* Call Timeout Callback and quit current function */
return (CPAL_TIMEOUT_UserCallback(pDevInitStruct));
}
/*================== CPAL_I2C_Event_Handler ==================*/
#ifdef CPAL_I2C_MASTER_MODE
/**
* @brief Handles Master Start condition (SB) interrupt event.
* @param pDevInitStruct: Pointer to the peripheral configuration structure.
* @retval CPAL_PASS or CPAL_FAIL.
*/
static uint32_t I2C_MASTER_START_Handle(CPAL_InitTypeDef* pDevInitStruct)
{
#ifdef CPAL_I2C_10BIT_ADDR_MODE
/* Declare local variable that contains Address Header */
uint8_t I2CHeaderAddress = 0x00;
#endif /* CPAL_I2C_10BIT_ADDR_MODE */
/* Reinitialize Timeout Value */
pDevInitStruct->wCPAL_Timeout = CPAL_I2C_TIMEOUT_DEFAULT;
CPAL_LOG("\n\r\n\rLOG <I2C_EV_IRQHandler> : I2C Device Master IT");
CPAL_LOG("\n\rLOG : I2C Device Start Acknowledged");
/* If 7 bit Addressing Mode selected */
if (pDevInitStruct->pCPAL_I2C_Struct->I2C_AcknowledgedAddress == I2C_AcknowledgedAddress_7bit)
{
CPAL_LOG("\n\rLOG : I2C Device 7bit Address");
/* Send Address */
/* If Master run as receiver */
if (pDevInitStruct->CPAL_State == CPAL_STATE_READY_RX)
{
/* Send Slave address with bit0 set for read */
__CPAL_I2C_HAL_SEND((pDevInitStruct->CPAL_Dev), (uint8_t)((pDevInitStruct->pCPAL_TransferRx->wAddr1) | I2C_OAR1_ADD0));
/* Update CPAL_State to CPAL_STATE_BUSY */
pDevInitStruct->CPAL_State = CPAL_STATE_BUSY_RX;
CPAL_LOG("\n\rLOG : I2C Device Busy RX");
}
/* If Master run as Transmitter */
else
{
/* Send Slave address with bit0 reset for write */
__CPAL_I2C_HAL_SEND((pDevInitStruct->CPAL_Dev), (uint8_t)((pDevInitStruct->pCPAL_TransferTx->wAddr1) & (~I2C_OAR1_ADD0)));
/* Update CPAL_State to CPAL_STATE_BUSY */
pDevInitStruct->CPAL_State = CPAL_STATE_BUSY_TX;
CPAL_LOG("\n\rLOG : I2C Device Busy TX");
}
CPAL_LOG("\n\rLOG : I2C Device Target Address Sent");
/* Initialize Timeout value */
pDevInitStruct->wCPAL_Timeout = CPAL_I2C_TIMEOUT_MIN + CPAL_I2C_TIMEOUT_ADDR;
}
#ifdef CPAL_I2C_10BIT_ADDR_MODE
/* If 10 bit Addressing Mode selected */
else
{
CPAL_LOG("\n\rLOG : I2C Device 10bit Address");
/* If Master run as receiver */
if (pDevInitStruct->CPAL_State == CPAL_STATE_READY_RX)
{
/* Calculate RX Header Address */
I2CHeaderAddress = ((((pDevInitStruct->pCPAL_TransferRx->wAddr1) & 0xFF00) >>7) | 0xF0);
}
/* If Master run as Transmitter */
else if (pDevInitStruct->CPAL_State == CPAL_STATE_READY_TX)
{
/* Calculate TX Header Address */
I2CHeaderAddress = ((((pDevInitStruct->pCPAL_TransferTx->wAddr1) & 0xFF00) >>7) | 0xF0);
}
/* If Master run as Receiver */
else if (pDevInitStruct->CPAL_State == CPAL_STATE_BUSY_RX)
{
/* Calculate RX Header Address */
I2CHeaderAddress = ((((pDevInitStruct->pCPAL_TransferRx->wAddr1) & 0xFF00) >>7) | 0xF1);
}
/* Send Header */
__CPAL_I2C_HAL_SEND((pDevInitStruct->CPAL_Dev), I2CHeaderAddress);
CPAL_LOG("\n\rLOG : I2C Device Target Header Sent ");
/* Initialize Timeout value */
pDevInitStruct->wCPAL_Timeout = CPAL_I2C_TIMEOUT_MIN + CPAL_I2C_TIMEOUT_ADD10;
}
#endif /* CPAL_I2C_10BIT_ADDR_MODE */
#if defined (STM32F10X_LD) || defined (STM32F10X_LD_VL) || defined (STM32F10X_MD) || defined (STM32F10X_MD_VL)\
|| defined (STM32F10X_HD) || defined (STM32F10X_HD_VL) || defined (STM32F10X_XL) || defined (STM32F10X_CL)
#ifdef CPAL_I2C_CLOSECOM_METHOD2
if ((pDevInitStruct->CPAL_ProgModel == CPAL_PROGMODEL_INTERRUPT) &&(pDevInitStruct->CPAL_State == CPAL_STATE_BUSY_RX)
&& (pDevInitStruct->pCPAL_TransferRx->wNumData == 2))
{
/* Activate POS bit */
__CPAL_I2C_HAL_ENABLE_POS(pDevInitStruct->CPAL_Dev);
}
#endif /* CPAL_I2C_CLOSECOM_METHOD2 */
#endif
return CPAL_PASS;
}
/**
* @brief Handles Master address matched (ADDR) interrupt event.
* @param pDevInitStruct: Pointer to the peripheral configuration structure.
* @retval CPAL_PASS or CPAL_FAIL.
*/
static uint32_t I2C_MASTER_ADDR_Handle(CPAL_InitTypeDef* pDevInitStruct)
{
/* Initialize Timeout value (1 ms for each data to be sent/received) */
if (pDevInitStruct->CPAL_ProgModel != CPAL_PROGMODEL_DMA)
{
/* Reinitialize Timeout Value to default (no timeout initiated) */
pDevInitStruct->wCPAL_Timeout = CPAL_I2C_TIMEOUT_DEFAULT;
}
else if (pDevInitStruct->CPAL_State == CPAL_STATE_BUSY_TX)
{
/* Set 1ms timeout for each data transfer in case of DMA Tx mode */
pDevInitStruct->wCPAL_Timeout = CPAL_I2C_TIMEOUT_MIN + pDevInitStruct->pCPAL_TransferTx->wNumData;
}
else if (pDevInitStruct->CPAL_State == CPAL_STATE_BUSY_RX)
{
/* Set 1ms timeout for each data transfer in case of DMA Rx mode */
pDevInitStruct->wCPAL_Timeout = CPAL_I2C_TIMEOUT_MIN + pDevInitStruct->pCPAL_TransferRx->wNumData;
}
else
{
/* Reinitialize Timeout Value to default (no timeout initiated) */
pDevInitStruct->wCPAL_Timeout = CPAL_I2C_TIMEOUT_DEFAULT;
}
if ((pDevInitStruct->CPAL_State == CPAL_STATE_BUSY_RX) && (pDevInitStruct->CPAL_ProgModel == CPAL_PROGMODEL_INTERRUPT) && (pDevInitStruct->pCPAL_TransferRx->wNumData == 0))
{
/* Program STOP bit then clear ADDR flag */
__CPAL_I2C_HAL_STOP(pDevInitStruct->CPAL_Dev);
__CPAL_I2C_HAL_CLEAR_ADDR(pDevInitStruct->CPAL_Dev);
/* Update CPAL_State to CPAL_STATE_READY */
pDevInitStruct->CPAL_State = CPAL_STATE_READY;
}
else
{
if ((pDevInitStruct->CPAL_State == CPAL_STATE_BUSY_RX) && (pDevInitStruct->CPAL_ProgModel == CPAL_PROGMODEL_INTERRUPT))
{
/* Switch Programing Mode Enable DMA or IT Buffer */
CPAL_I2C_Enable_DMA_IT(pDevInitStruct, CPAL_DIRECTION_RX);
}
#if defined (STM32L1XX_MD) || defined (STM32L1XX_HD) || defined (STM32F2XX) || defined (STM32F4XX)
/* If CPAL_State is CPAL_STATE_BUSY_RX and receiving one byte */
if ((pDevInitStruct->CPAL_State == CPAL_STATE_BUSY_RX) && (pDevInitStruct->pCPAL_TransferRx->wNumData == 1))
{
/* Disable Acknowledge */
__CPAL_I2C_HAL_DISABLE_ACK(pDevInitStruct->CPAL_Dev);
/* Clear ADDR Flag by reading SR1 then SR2 */
__CPAL_I2C_HAL_CLEAR_ADDR(pDevInitStruct->CPAL_Dev);
/* Program Generation of Stop Condition */
__CPAL_I2C_HAL_STOP(pDevInitStruct->CPAL_Dev);
}
else if ((pDevInitStruct->CPAL_ProgModel == CPAL_PROGMODEL_INTERRUPT) &&(pDevInitStruct->CPAL_State == CPAL_STATE_BUSY_RX) && (pDevInitStruct->pCPAL_TransferRx->wNumData == 2))
{
/* Disable Acknowledge */
__CPAL_I2C_HAL_DISABLE_ACK(pDevInitStruct->CPAL_Dev);
/* Enable Pos */
__CPAL_I2C_HAL_ENABLE_POS(pDevInitStruct->CPAL_Dev);
/* Clear ADDR Flag by reading SR1 then SR2 */
__CPAL_I2C_HAL_CLEAR_ADDR(pDevInitStruct->CPAL_Dev);
}
else
{
/* Clear ADDR Flag by reading SR1 then SR2 */
__CPAL_I2C_HAL_CLEAR_ADDR(pDevInitStruct->CPAL_Dev);
}
#else
#ifdef CPAL_I2C_CLOSECOM_METHOD1
__CPAL_I2C_HAL_CLEAR_ADDR(pDevInitStruct->CPAL_Dev);
#endif /* CPAL_I2C_CLOSECOM_METHOD1 */
/* If CPAL_State is CPAL_STATE_BUSY_RX and receiving one byte */
if ((pDevInitStruct->CPAL_State == CPAL_STATE_BUSY_RX) && (pDevInitStruct->pCPAL_TransferRx->wNumData == 1))
{
/* Disable Acknowledge */
__CPAL_I2C_HAL_DISABLE_ACK(pDevInitStruct->CPAL_Dev);
#ifdef CPAL_I2C_CLOSECOM_METHOD2
#ifdef USE_CPAL_CRITICAL_CALLBACK
/* Call Critical section Callback */
CPAL_EnterCriticalSection_UserCallback();
#endif /* USE_CPAL_CRITICAL_CALLBACK */
/* Clear ADDR Flag by reading SR1 then SR2 */
__CPAL_I2C_HAL_CLEAR_ADDR(pDevInitStruct->CPAL_Dev);
/* Program Generation of Stop Condition */
__CPAL_I2C_HAL_STOP(pDevInitStruct->CPAL_Dev);
#ifdef USE_CPAL_CRITICAL_CALLBACK
/* Call Critical section Callback */
CPAL_ExitCriticalSection_UserCallback();
#endif /* USE_CPAL_CRITICAL_CALLBACK */
#else
/* Program Generation of Stop Condition */
__CPAL_I2C_HAL_STOP(pDevInitStruct->CPAL_Dev);
#endif /* CPAL_I2C_CLOSECOM_METHOD2 */
}
#ifdef CPAL_I2C_CLOSECOM_METHOD2
else if ((pDevInitStruct->CPAL_ProgModel == CPAL_PROGMODEL_INTERRUPT) &&(pDevInitStruct->CPAL_State == CPAL_STATE_BUSY_RX)
&& (pDevInitStruct->pCPAL_TransferRx->wNumData == 2))
{
/* Clear ADDR Flag by reading SR1 then SR2 */
__CPAL_I2C_HAL_CLEAR_ADDR(pDevInitStruct->CPAL_Dev);
/* Disable Acknowledge */
__CPAL_I2C_HAL_DISABLE_ACK(pDevInitStruct->CPAL_Dev);
}
else
{
/* Clear ADDR Flag by reading SR1 then SR2 */
__CPAL_I2C_HAL_CLEAR_ADDR(pDevInitStruct->CPAL_Dev);
}
#endif /* CPAL_I2C_CLOSECOM_METHOD2 */
#endif /* STM32L1XX_MD || STM32L1XX_HD || STM32F2XX || STM32F4XX */
#ifdef CPAL_I2C_10BIT_ADDR_MODE
/* If CPAL_State is not CPAL_STATE_BUSY */
if (((pDevInitStruct->CPAL_State & (CPAL_STATE_READY_TX | CPAL_STATE_READY_RX)) != 0)
&& (pDevInitStruct->pCPAL_I2C_Struct->I2C_AcknowledgedAddress == I2C_AcknowledgedAddress_10bit))
{
/* If Master run as receiver */
if (pDevInitStruct->CPAL_State == CPAL_STATE_READY_RX)
{
/* Update CPAL_State to CPAL_STATE_BUSY_RX */
pDevInitStruct->CPAL_State = CPAL_STATE_BUSY_RX;
CPAL_LOG("\n\rLOG : I2C Device Busy RX");
/* Generate Repeated start bit */
__CPAL_I2C_HAL_START(pDevInitStruct->CPAL_Dev);
/* Initialize Timeout value */
pDevInitStruct->wCPAL_Timeout = CPAL_I2C_TIMEOUT_MIN + CPAL_I2C_TIMEOUT_SB;
}
/* If Master run as Transmitter */
if (pDevInitStruct->CPAL_State == CPAL_STATE_READY_TX)
{
/* Update CPAL_State to CPAL_STATE_BUSY_TX */
pDevInitStruct->CPAL_State = CPAL_STATE_BUSY_TX;
CPAL_LOG("\n\rLOG : I2C Device Busy TX");
}
}
else if ((pDevInitStruct->wCPAL_Options & CPAL_OPT_NO_MEM_ADDR) == 0)
#endif /* CPAL_I2C_10BIT_ADDR_MODE */
#ifndef CPAL_I2C_10BIT_ADDR_MODE
/* If CPAL_OPT_NO_MEM_ADDR is not enabled */
if ((pDevInitStruct->wCPAL_Options & CPAL_OPT_NO_MEM_ADDR) == 0)
#endif /* CPAL_I2C_10BIT_ADDR_MODE */
{
/* If CPAL_State is CPAL_STATE_BUSY_TX */
if (pDevInitStruct->CPAL_State == CPAL_STATE_BUSY_TX)
{
/* If 8 Bit register mode */
if ((pDevInitStruct->wCPAL_Options & CPAL_OPT_16BIT_REG) == 0)
{
/* Send Register Address */
__CPAL_I2C_HAL_SEND((pDevInitStruct->CPAL_Dev), (uint8_t)((pDevInitStruct->pCPAL_TransferTx->wAddr2)& 0x00FF));
/* Wait until TXE flag is set */
__CPAL_I2C_TIMEOUT_SPINLOOP(__CPAL_I2C_HAL_GET_TXE(pDevInitStruct->CPAL_Dev), CPAL_I2C_TIMEOUT_TXE);
}
#ifdef CPAL_16BIT_REG_OPTION
/* If 16 Bit register mode */
else
{
/* Send MSB Register Address */
__CPAL_I2C_HAL_SEND((pDevInitStruct->CPAL_Dev), (uint8_t)(((pDevInitStruct->pCPAL_TransferTx->wAddr2)& 0xFF00) >>8));
/* Wait until TXE flag is set */
__CPAL_I2C_TIMEOUT_SPINLOOP(__CPAL_I2C_HAL_GET_TXE(pDevInitStruct->CPAL_Dev), CPAL_I2C_TIMEOUT_TXE);
/* Send LSB Register Address */
__CPAL_I2C_HAL_SEND((pDevInitStruct->CPAL_Dev), (uint8_t)((pDevInitStruct->pCPAL_TransferTx->wAddr2)& 0x00FF));
/* Wait until TXE flag is set */
__CPAL_I2C_TIMEOUT_SPINLOOP(__CPAL_I2C_HAL_GET_TXE(pDevInitStruct->CPAL_Dev), CPAL_I2C_TIMEOUT_TXE);
}
#endif /* CPAL_16BIT_REG_OPTION */
}
/* Switch Programing Mode Enable DMA or IT Buffer */
CPAL_I2C_Enable_DMA_IT(pDevInitStruct, CPAL_DIRECTION_TXRX);
}
}
return CPAL_PASS;
}
#ifdef CPAL_I2C_10BIT_ADDR_MODE
/**
* @brief Handles Master 10bit address matched (ADD10) interrupt event.
* @param pDevInitStruct: Pointer to the peripheral configuration structure.
* @retval CPAL_PASS or CPAL_FAIL.
*/
static uint32_t I2C_MASTER_ADD10_Handle(CPAL_InitTypeDef* pDevInitStruct)
{
/* Reinitialize Timeout Value */
pDevInitStruct->wCPAL_Timeout = CPAL_I2C_TIMEOUT_DEFAULT;
CPAL_LOG("\n\r\n\rLOG <I2C_EV_IRQHandler> : I2C Device Master IT");
CPAL_LOG("\n\rLOG : I2C Device Header Address Acknowledged");
/* Send Address */
/* If Master run as receiver */
if (pDevInitStruct->CPAL_State == CPAL_STATE_READY_RX)
{
/* Send Slave Address */
__CPAL_I2C_HAL_SEND((pDevInitStruct->CPAL_Dev), (uint8_t)(pDevInitStruct->pCPAL_TransferRx->wAddr1));
}
/* If Master run as Transmitter */
else if (pDevInitStruct->CPAL_State == CPAL_STATE_READY_TX)
{
/* Send Slave Address */
__CPAL_I2C_HAL_SEND((pDevInitStruct->CPAL_Dev), (uint8_t)(pDevInitStruct->pCPAL_TransferTx->wAddr1));
}
CPAL_LOG("\n\rLOG : I2C Device Target Address Sent");
/* Initialize Timeout value */
pDevInitStruct->wCPAL_Timeout = CPAL_I2C_TIMEOUT_MIN + CPAL_I2C_TIMEOUT_ADDR;
return CPAL_PASS;
}
#endif /* CPAL_I2C_10BIT_ADDR_MODE */
#ifdef CPAL_I2C_IT_PROGMODEL
/**
* @brief Handles Master transmission (TXE) interrupt event.
* @param pDevInitStruct: Pointer to the peripheral configuration structure.
* @retval CPAL_PASS or CPAL_FAIL.
*/
static uint32_t I2C_MASTER_TXE_Handle(CPAL_InitTypeDef* pDevInitStruct)
{
/* If Interrupt Programming Model selected */
if (pDevInitStruct->CPAL_ProgModel == CPAL_PROGMODEL_INTERRUPT)
{
/* If Buffer end */
if (pDevInitStruct->pCPAL_TransferTx->wNumData != 0)
{
/* Call TX UserCallback */
CPAL_I2C_TX_UserCallback(pDevInitStruct);
/* Write Byte */
__CPAL_I2C_HAL_SEND((pDevInitStruct->CPAL_Dev), (*(pDevInitStruct->pCPAL_TransferTx->pbBuffer)));
/* Decrement remaining number of data */
pDevInitStruct->pCPAL_TransferTx->wNumData--;
/* If Buffer end */
if (pDevInitStruct->pCPAL_TransferTx->wNumData != 0)
{
/* Point to next data */
pDevInitStruct->pCPAL_TransferTx->pbBuffer++;
}
}
else
{
/* No Stop Condition Generation option bit not selected */
if ((pDevInitStruct->wCPAL_Options & CPAL_OPT_I2C_NOSTOP) == 0)
{
/* Generate Stop Condition */
__CPAL_I2C_HAL_STOP(pDevInitStruct->CPAL_Dev);
CPAL_LOG("\n\r\n\rLOG <I2C_EV_IRQHandler> : I2C Device Master IT");
CPAL_LOG("\n\rLOG : I2C Device Generates Stop");
}
CPAL_LOG("\n\rLOG : I2C Device TX Complete");
/* Disable EVENT Interrupt */
__CPAL_I2C_HAL_DISABLE_EVTIT(pDevInitStruct->CPAL_Dev);
CPAL_LOG("\n\rLOG : I2C Device TX EVT IT Disabled");
/* Disable Buffer interrupt */
__CPAL_I2C_HAL_DISABLE_BUFIT(pDevInitStruct->CPAL_Dev);
CPAL_LOG("\n\rLOG : I2C Device TX BUFF IT Disabled");
/* No Stop Condition Generation option bit not selected */
if ((pDevInitStruct->wCPAL_Options & CPAL_OPT_I2C_NOSTOP) == 0)
{
/* Wait until BTF and TXE flags are reset */
__CPAL_I2C_TIMEOUT_SPINLOOP(!(__CPAL_I2C_HAL_GET_EVENT(pDevInitStruct->CPAL_Dev) & (I2C_SR1_BTF | I2C_SR1_TXE )), CPAL_I2C_TIMEOUT_BUSY);
}
else
{
/* Wait until BTF flags is reset */
__CPAL_I2C_TIMEOUT_SPINLOOP(!(__CPAL_I2C_HAL_GET_EVENT(pDevInitStruct->CPAL_Dev) & I2C_SR1_TXE ), CPAL_I2C_TIMEOUT_BUSY);
}
/* Update CPAL_State to CPAL_STATE_READY */
pDevInitStruct->CPAL_State = CPAL_STATE_READY;
/* Call TX Transfer complete Callback */
CPAL_I2C_TXTC_UserCallback(pDevInitStruct);
}
}
return CPAL_PASS;
}
#endif /* CPAL_I2C_IT_PROGMODEL */
#if defined (CPAL_I2C_IT_PROGMODEL) || defined (CPAL_I2C_DMA_1BYTE_CASE)
/**
* @brief Handles Master reception (RXNE flag) interrupt event.
* @param pDevInitStruct: Pointer to the peripheral configuration structure.
* @retval CPAL_PASS or CPAL_FAIL.
*/
static uint32_t I2C_MASTER_RXNE_Handle(CPAL_InitTypeDef* pDevInitStruct)
{
/* If Interrupt Programming Model selected */
if (pDevInitStruct->CPAL_ProgModel == CPAL_PROGMODEL_INTERRUPT)
{
#if defined (STM32L1XX_MD) || defined (STM32L1XX_HD) || defined (STM32F2XX) || defined (STM32F4XX)
/* if less than 3 bytes remaining for reception */
if (pDevInitStruct->pCPAL_TransferRx->wNumData <= 3)
{
/* One byte */
if (pDevInitStruct->pCPAL_TransferRx->wNumData == 1)
{
/* Read Byte */
*(pDevInitStruct->pCPAL_TransferRx->pbBuffer) = __CPAL_I2C_HAL_RECEIVE(pDevInitStruct->CPAL_Dev);
/* Point to next data and Decrement remaining number of data */
pDevInitStruct->pCPAL_TransferRx->wNumData--;
CPAL_LOG("\n\r\n\rLOG <I2C_EV_IRQHandler> : I2C Device Master IT");
CPAL_LOG("\n\rLOG : I2C Device RX Nack Programmed");
CPAL_LOG("\n\rLOG : I2C Device RX Stop Programmed");
}
/* Two bytes */
if (pDevInitStruct->pCPAL_TransferRx->wNumData == 2)
{
/* Disable Buffer interrupt */
__CPAL_I2C_HAL_DISABLE_BUFIT(pDevInitStruct->CPAL_Dev);
/* Wait until BTF flag is set */
__CPAL_I2C_TIMEOUT_SPINLOOP(__CPAL_I2C_HAL_GET_BTF(pDevInitStruct->CPAL_Dev), CPAL_I2C_TIMEOUT_BTF);
/* Generate Stop Condition */
__CPAL_I2C_HAL_STOP(pDevInitStruct->CPAL_Dev);
/* Read Byte */
*(pDevInitStruct->pCPAL_TransferRx->pbBuffer) = __CPAL_I2C_HAL_RECEIVE(pDevInitStruct->CPAL_Dev);
/* Point to next data and Decrement remaining number of data */
pDevInitStruct->pCPAL_TransferRx->pbBuffer++;
pDevInitStruct->pCPAL_TransferRx->wNumData--;
/* Read Byte */
*(pDevInitStruct->pCPAL_TransferRx->pbBuffer) = __CPAL_I2C_HAL_RECEIVE(pDevInitStruct->CPAL_Dev);
/*Decrement remaining number of data */
pDevInitStruct->pCPAL_TransferRx->wNumData--;
CPAL_LOG("\n\r\n\rLOG <I2C_EV_IRQHandler> : I2C Device Master IT");
CPAL_LOG("\n\rLOG : I2C Device RX Nack Programmed");
CPAL_LOG("\n\rLOG : I2C Device RX Stop Programmed");
}
/* 3 Last bytes */
if (pDevInitStruct->pCPAL_TransferRx->wNumData == 3)
{
/* Disable Buffer interrupt */
__CPAL_I2C_HAL_DISABLE_BUFIT(pDevInitStruct->CPAL_Dev);
/* Wait until BTF flag is set */
__CPAL_I2C_TIMEOUT_SPINLOOP(__CPAL_I2C_HAL_GET_BTF(pDevInitStruct->CPAL_Dev), CPAL_I2C_TIMEOUT_BTF);
/* Program NACK Generation */
__CPAL_I2C_HAL_DISABLE_ACK(pDevInitStruct->CPAL_Dev);
/* Read Byte */
*(pDevInitStruct->pCPAL_TransferRx->pbBuffer) = __CPAL_I2C_HAL_RECEIVE(pDevInitStruct->CPAL_Dev);
/* Point to next data and Decrement remaining number of data */
pDevInitStruct->pCPAL_TransferRx->pbBuffer++;
pDevInitStruct->pCPAL_TransferRx->wNumData--;
/* Wait until BTF flag is set */
__CPAL_I2C_TIMEOUT_SPINLOOP(__CPAL_I2C_HAL_GET_BTF(pDevInitStruct->CPAL_Dev), CPAL_I2C_TIMEOUT_BTF);
/* Generate Stop Condition */
__CPAL_I2C_HAL_STOP(pDevInitStruct->CPAL_Dev);
/* Read Byte */
*(pDevInitStruct->pCPAL_TransferRx->pbBuffer) = __CPAL_I2C_HAL_RECEIVE(pDevInitStruct->CPAL_Dev);
/* Point to next data and Decrement remaining number of data */
pDevInitStruct->pCPAL_TransferRx->pbBuffer++;
pDevInitStruct->pCPAL_TransferRx->wNumData--;
/* Read Byte */
*(pDevInitStruct->pCPAL_TransferRx->pbBuffer) = __CPAL_I2C_HAL_RECEIVE(pDevInitStruct->CPAL_Dev);
/* Decrement remaining number of data */
pDevInitStruct->pCPAL_TransferRx->wNumData--;
CPAL_LOG("\n\r\n\rLOG <I2C_EV_IRQHandler> : I2C Device Master IT");
CPAL_LOG("\n\rLOG : I2C Device RX Nack Programmed");
CPAL_LOG("\n\rLOG : I2C Device RX Stop Programmed");
}
}
#else
#ifdef CPAL_I2C_CLOSECOM_METHOD1
/* if Two bytes remaining for reception */
if (pDevInitStruct->pCPAL_TransferRx->wNumData == 2)
{
/* Read Byte */
*(pDevInitStruct->pCPAL_TransferRx->pbBuffer) = __CPAL_I2C_HAL_RECEIVE(pDevInitStruct->CPAL_Dev);
/* Disable Acknowledge */
__CPAL_I2C_HAL_DISABLE_ACK(pDevInitStruct->CPAL_Dev);
/* Program Generation of Stop Condition */
__CPAL_I2C_HAL_STOP(pDevInitStruct->CPAL_Dev);
/* Point to next data and Decrement remaining number of data */
pDevInitStruct->pCPAL_TransferRx->wNumData--;
/* Point to next data and Decrement remaining number of data */
pDevInitStruct->pCPAL_TransferRx->pbBuffer++;
}
/* if One byte remaining for reception */
else if (pDevInitStruct->pCPAL_TransferRx->wNumData == 1)
{
/* Read Byte */
*(pDevInitStruct->pCPAL_TransferRx->pbBuffer) = __CPAL_I2C_HAL_RECEIVE(pDevInitStruct->CPAL_Dev);
/* Point to next data and Decrement remaining number of data */
pDevInitStruct->pCPAL_TransferRx->wNumData--;
CPAL_LOG("\n\r\n\rLOG <I2C_EV_IRQHandler> : I2C Device Master IT");
CPAL_LOG("\n\rLOG : I2C Device RX Nack Programmed");
CPAL_LOG("\n\rLOG : I2C Device RX Stop Programmed");
}
#endif /* CPAL_I2C_CLOSECOM_METHOD1 */
#ifdef CPAL_I2C_CLOSECOM_METHOD2
/* if less than 3 bytes remaining for reception */
if (pDevInitStruct->pCPAL_TransferRx->wNumData <= 3)
{
/* One byte */
if (pDevInitStruct->pCPAL_TransferRx->wNumData == 1)
{
/* Read Byte */
*(pDevInitStruct->pCPAL_TransferRx->pbBuffer) = __CPAL_I2C_HAL_RECEIVE(pDevInitStruct->CPAL_Dev);
/* Point to next data and Decrement remaining number of data */
pDevInitStruct->pCPAL_TransferRx->wNumData--;
CPAL_LOG("\n\r\n\rLOG <I2C_EV_IRQHandler> : I2C Device Master IT");
CPAL_LOG("\n\rLOG : I2C Device RX Nack Programmed");
CPAL_LOG("\n\rLOG : I2C Device RX Stop Programmed");
}
/* Two bytes */
if (pDevInitStruct->pCPAL_TransferRx->wNumData == 2)
{
/* Disable Buffer interrupt */
__CPAL_I2C_HAL_DISABLE_BUFIT(pDevInitStruct->CPAL_Dev);
/* Wait until BTF flag is set */
__CPAL_I2C_TIMEOUT_SPINLOOP(__CPAL_I2C_HAL_GET_BTF(pDevInitStruct->CPAL_Dev), CPAL_I2C_TIMEOUT_BTF);
/* Generate Stop Condition */
__CPAL_I2C_HAL_STOP(pDevInitStruct->CPAL_Dev);
/* Read Byte */
*(pDevInitStruct->pCPAL_TransferRx->pbBuffer) = __CPAL_I2C_HAL_RECEIVE(pDevInitStruct->CPAL_Dev);
/* Point to next data and Decrement remaining number of data */
pDevInitStruct->pCPAL_TransferRx->pbBuffer++;
pDevInitStruct->pCPAL_TransferRx->wNumData--;
/* Read Byte */
*(pDevInitStruct->pCPAL_TransferRx->pbBuffer) = __CPAL_I2C_HAL_RECEIVE(pDevInitStruct->CPAL_Dev);
/*Decrement remaining number of data */
pDevInitStruct->pCPAL_TransferRx->wNumData--;
/* Reset POS */
__CPAL_I2C_HAL_DISABLE_POS(pDevInitStruct->CPAL_Dev);
CPAL_LOG("\n\r\n\rLOG <I2C_EV_IRQHandler> : I2C Device Master IT");
CPAL_LOG("\n\rLOG : I2C Device RX Nack Programmed");
CPAL_LOG("\n\rLOG : I2C Device RX Stop Programmed");
}
/* 3 Last bytes */
if (pDevInitStruct->pCPAL_TransferRx->wNumData == 3)
{
/* Disable Buffer interrupt */
__CPAL_I2C_HAL_DISABLE_BUFIT(pDevInitStruct->CPAL_Dev);
/* Wait until BTF flag is set */
__CPAL_I2C_TIMEOUT_SPINLOOP(__CPAL_I2C_HAL_GET_BTF(pDevInitStruct->CPAL_Dev), CPAL_I2C_TIMEOUT_BTF);
/* Program NACK Generation */
__CPAL_I2C_HAL_DISABLE_ACK(pDevInitStruct->CPAL_Dev);
/* Read Byte */
*(pDevInitStruct->pCPAL_TransferRx->pbBuffer) = __CPAL_I2C_HAL_RECEIVE(pDevInitStruct->CPAL_Dev);
/* Point to next data and Decrement remaining number of data */
pDevInitStruct->pCPAL_TransferRx->pbBuffer++;
pDevInitStruct->pCPAL_TransferRx->wNumData--;
/* Generate Stop Condition */
__CPAL_I2C_HAL_STOP(pDevInitStruct->CPAL_Dev);
/* Read Byte */
*(pDevInitStruct->pCPAL_TransferRx->pbBuffer) = __CPAL_I2C_HAL_RECEIVE(pDevInitStruct->CPAL_Dev);
/* Point to next data and Decrement remaining number of data */
pDevInitStruct->pCPAL_TransferRx->pbBuffer++;
pDevInitStruct->pCPAL_TransferRx->wNumData--;
/* Wait until RXNE flag is set */
__CPAL_I2C_TIMEOUT_SPINLOOP(__CPAL_I2C_HAL_GET_RXNE(pDevInitStruct->CPAL_Dev), CPAL_I2C_TIMEOUT_RXNE);
/* Read Byte */
*(pDevInitStruct->pCPAL_TransferRx->pbBuffer) = __CPAL_I2C_HAL_RECEIVE(pDevInitStruct->CPAL_Dev);
/* Decrement remaining number of data */
pDevInitStruct->pCPAL_TransferRx->wNumData--;
CPAL_LOG("\n\r\n\rLOG <I2C_EV_IRQHandler> : I2C Device Master IT");
CPAL_LOG("\n\rLOG : I2C Device RX Nack Programmed");
CPAL_LOG("\n\rLOG : I2C Device RX Stop Programmed");
}
}
#endif /* CPAL_I2C_CLOSECOM_METHOD2 */
#endif /* STM32L1XX_MD || STM32L1XX_HD || STM32F2XX || STM32F4XX */
/* if bytes remaining for reception */
else
{
/* Read Byte */
*(pDevInitStruct->pCPAL_TransferRx->pbBuffer) = __CPAL_I2C_HAL_RECEIVE(pDevInitStruct->CPAL_Dev);
/* Point to next data and Decrement remaining number of data */
pDevInitStruct->pCPAL_TransferRx->pbBuffer++;
pDevInitStruct->pCPAL_TransferRx->wNumData--;
/* Call RX UserCallback */
CPAL_I2C_RX_UserCallback(pDevInitStruct);
}
/* If All data are received */
if (pDevInitStruct->pCPAL_TransferRx->wNumData == 0)
{
CPAL_LOG("\n\rLOG : I2C Device Nack and Stop Generated ");
CPAL_LOG("\n\rLOG : I2C Device RX Complete");
/* Disable EVENT Interrupt */
__CPAL_I2C_HAL_DISABLE_EVTIT(pDevInitStruct->CPAL_Dev);
CPAL_LOG("\n\rLOG : I2C Device RX EVT IT Disabled");
/* Disable Buffer interrupt */
__CPAL_I2C_HAL_DISABLE_BUFIT(pDevInitStruct->CPAL_Dev);
CPAL_LOG("\n\rLOG : I2C Device RX BUFF IT Disabled");
/* Clear BTF Flag */
__CPAL_I2C_HAL_CLEAR_BTF(pDevInitStruct->CPAL_Dev);
/* If 1Byte DMA option is selected */
if ((pDevInitStruct->wCPAL_Options & CPAL_DMA_1BYTE_CASE) != 0)
{
/* Clear 1Byte DMA option from wCPAL_Options */
pDevInitStruct->wCPAL_Options &= ~CPAL_DMA_1BYTE_CASE;
/* Change ProgModel to DMA */
pDevInitStruct->CPAL_ProgModel = CPAL_PROGMODEL_DMA;
}
/* Wait until Busy flag is reset */
__CPAL_I2C_TIMEOUT_SPINLOOP(!(__CPAL_I2C_HAL_GET_BUSY(pDevInitStruct->CPAL_Dev)), CPAL_I2C_TIMEOUT_BUSY);
/* Enable ACK generation and disable POS */
__CPAL_I2C_HAL_ENABLE_ACK(pDevInitStruct->CPAL_Dev);
__CPAL_I2C_HAL_DISABLE_POS(pDevInitStruct->CPAL_Dev);
/* Update CPAL_State to CPAL_STATE_READY */
pDevInitStruct->CPAL_State = CPAL_STATE_READY;
/* Call RX Transfer complete Callback */
CPAL_I2C_RXTC_UserCallback(pDevInitStruct);
}
}
return CPAL_PASS;
}
#endif /* CPAL_I2C_IT_PROGMODEL || CPAL_I2C_DMA_1BYTE_CASE */
#endif /* CPAL_I2C_MASTER_MODE */
#ifdef CPAL_I2C_SLAVE_MODE
/**
* @brief Handles Slave address matched (ADDR) interrupt event.
* @param pDevInitStruct: Pointer to the peripheral configuration structure.
* @retval CPAL_PASS or CPAL_FAIL.
*/
static uint32_t I2C_SLAVE_ADDR_Handle(CPAL_InitTypeDef* pDevInitStruct)
{
CPAL_LOG("\n\r\n\rLOG <I2C_EV_IRQHandler> : I2C Device Slave IT");
CPAL_LOG("\n\rLOG : I2C Device Address Matched");
#ifdef CPAL_I2C_LISTEN_MODE
/* If slave receive request for write */
if (__CPAL_I2C_HAL_GET_TRA(pDevInitStruct->CPAL_Dev) != 0)
{
pDevInitStruct->CPAL_State = CPAL_STATE_BUSY_TX;
/* Call Slave Transmit UserCallback */
CPAL_I2C_SLAVE_WRITE_UserCallback(pDevInitStruct);
}
/* If slave receive request for read */
else
{
pDevInitStruct->CPAL_State = CPAL_STATE_BUSY_RX;
/* Call Slave receive UserCallback */
CPAL_I2C_SLAVE_READ_UserCallback(pDevInitStruct);
}
#else
/* If General Call Addressing Mode selected */
if (__CPAL_I2C_HAL_GET_GENCALL(pDevInitStruct->CPAL_Dev) != 0)
{
CPAL_LOG("\n\rLOG : I2C Device GENCALL Mode");
/* Call GENCALL UserCallback */
CPAL_I2C_GENCALL_UserCallback(pDevInitStruct);
}
/* If DUAL Addressing Mode is not selected */
if (__CPAL_I2C_HAL_GET_DUALF(pDevInitStruct->CPAL_Dev) != 0)
{
CPAL_LOG("\n\rLOG : I2C Device DUAL ADDR Mode Selected");
/* Call DUALF UserCallback */
CPAL_I2C_DUALF_UserCallback(pDevInitStruct);
}
/* If device is ready for transmission */
if (pDevInitStruct->CPAL_State == CPAL_STATE_READY_TX)
{
/* Update CPAL_State to CPAL_STATE_BUSY */
pDevInitStruct->CPAL_State = CPAL_STATE_BUSY_TX;
CPAL_LOG("\n\rLOG : I2C Device Busy TX");
}
/* If device is ready for reception */
else if (pDevInitStruct->CPAL_State == CPAL_STATE_READY_RX)
{
/* Update CPAL_State to CPAL_STATE_BUSY_RX */
pDevInitStruct->CPAL_State = CPAL_STATE_BUSY_RX;
CPAL_LOG("\n\rLOG : I2C Device Busy RX");
}
#endif /* CPAL_I2C_LISTEN_MODE */
return CPAL_PASS;
}
/**
* @brief Handles Slave Stop condiction (STOPF) interrupt event.
* @param pDevInitStruct: Pointer to the peripheral configuration structure.
* @retval CPAL_PASS or CPAL_FAIL.
*/
static uint32_t I2C_SLAVE_STOP_Handle(CPAL_InitTypeDef* pDevInitStruct)
{
/* Clear STOPF */
__CPAL_I2C_HAL_CLEAR_STOPF(pDevInitStruct->CPAL_Dev);
CPAL_LOG("\n\r\n\rLOG <I2C_EV_IRQHandler> : I2C Device Slave IT");
CPAL_LOG("\n\rLOG : I2C Device Stop Detected");
/* If NACK Slave Own Address option bit selected */
if ((pDevInitStruct->wCPAL_Options & CPAL_OPT_I2C_NACK_ADD) != 0)
{
/* Disable Acknowledgement of own Address */
__CPAL_I2C_HAL_DISABLE_ACK(pDevInitStruct->CPAL_Dev);
}
/* If Interrupt Programming Model */
if (pDevInitStruct->CPAL_ProgModel == CPAL_PROGMODEL_INTERRUPT)
{
#ifdef CPAL_I2C_IT_PROGMODEL
/* Disable EVENT Interrupt */
__CPAL_I2C_HAL_DISABLE_EVTIT(pDevInitStruct->CPAL_Dev);
CPAL_LOG("\n\rLOG : I2C Device EVT IT Disabled");
/* Disable Buffer interrupt */
__CPAL_I2C_HAL_DISABLE_BUFIT(pDevInitStruct->CPAL_Dev);
CPAL_LOG("\n\rLOG : I2C Device BUFF IT Disabled");
#endif /* CPAL_I2C_IT_PROGMODEL */
}
/* If DMA Programming model */
else
{
#ifdef CPAL_I2C_DMA_PROGMODEL
/* If Slave run as receiver */
if (pDevInitStruct->CPAL_State == CPAL_STATE_BUSY_RX)
{
/* Disable DMA Request and Channel */
__CPAL_I2C_HAL_DISABLE_DMAREQ(pDevInitStruct->CPAL_Dev);
__CPAL_I2C_HAL_DISABLE_DMARX(pDevInitStruct->CPAL_Dev);
/* Disable EVENT Interrupt */
__CPAL_I2C_HAL_DISABLE_EVTIT(pDevInitStruct->CPAL_Dev);
/* Update remaining number of data */
pDevInitStruct->pCPAL_TransferRx->wNumData = __CPAL_I2C_HAL_DMARX_GET_CNDT(pDevInitStruct->CPAL_Dev);
CPAL_LOG("\n\rLOG : I2C Device RX Complete");
CPAL_LOG("\n\rLOG : I2C Device RX DMA Disabled");
}
#endif /* CPAL_I2C_DMA_PROGMODEL */
}
/* Wait until Busy flag is reset */
__CPAL_I2C_TIMEOUT_SPINLOOP(!(__CPAL_I2C_HAL_GET_BUSY(pDevInitStruct->CPAL_Dev)), CPAL_I2C_TIMEOUT_BUSY);
/* If Slave run as receiver */
if (pDevInitStruct->CPAL_State == CPAL_STATE_BUSY_RX)
{
/* Update CPAL_State to CPAL_STATE_READY */
pDevInitStruct->CPAL_State = CPAL_STATE_READY;
/* Call RX Transfer complete Callback */
CPAL_I2C_RXTC_UserCallback(pDevInitStruct);
}
return CPAL_PASS;
}
#ifdef CPAL_I2C_IT_PROGMODEL
/**
* @brief Handles Slave transmission (TXE) interrupt event.
* @param pDevInitStruct: Pointer to the peripheral configuration structure.
* @retval CPAL_PASS or CPAL_FAIL.
*/
static uint32_t I2C_SLAVE_TXE_Handle(CPAL_InitTypeDef* pDevInitStruct)
{
/* If Interrupt Programming Model selected */
if (pDevInitStruct->CPAL_ProgModel == CPAL_PROGMODEL_INTERRUPT)
{
if (pDevInitStruct->pCPAL_TransferTx->wNumData != 0)
{
/* Call TX UserCallback */
CPAL_I2C_TX_UserCallback(pDevInitStruct);
/* Write Byte */
__CPAL_I2C_HAL_SEND((pDevInitStruct->CPAL_Dev), (*(pDevInitStruct->pCPAL_TransferTx->pbBuffer)));
/* Decrement remaining number of data */
pDevInitStruct->pCPAL_TransferTx->wNumData--;
if (pDevInitStruct->pCPAL_TransferTx->wNumData != 0)
{
/* Point to next data */
pDevInitStruct->pCPAL_TransferTx->pbBuffer++;
}
else
{
CPAL_LOG("\n\r\n\rLOG <I2C_EV_IRQHandler> : I2C Device Slave IT");
CPAL_LOG("\n\rLOG : I2C Device TX Complete");
}
}
}
return CPAL_PASS;
}
/**
* @brief Handles Slave reception (RXNE) interrupt event.
* @param pDevInitStruct: Pointer to the peripheral configuration structure.
* @retval CPAL_PASS or CPAL_FAIL.
*/
static uint32_t I2C_SLAVE_RXNE_Handle(CPAL_InitTypeDef* pDevInitStruct)
{
/* If Interrupt Programming Model selected */
if (pDevInitStruct->CPAL_ProgModel == CPAL_PROGMODEL_INTERRUPT)
{
/* If data remaining for reception */
if (pDevInitStruct->pCPAL_TransferRx->wNumData != 0)
{
/* Read Byte */
*(pDevInitStruct->pCPAL_TransferRx->pbBuffer) = __CPAL_I2C_HAL_RECEIVE(pDevInitStruct->CPAL_Dev);
/* Call RX UserCallback */
CPAL_I2C_RX_UserCallback(pDevInitStruct);
/* Decrement remaining number of data */
pDevInitStruct->pCPAL_TransferRx->wNumData--;
/* If data remaining for reception */
if (pDevInitStruct->pCPAL_TransferRx->wNumData != 0)
{
/* Point to next data */
pDevInitStruct->pCPAL_TransferRx->pbBuffer++;
}
else
{
/* No Stop Condition Generation option bit selected */
if ((pDevInitStruct->wCPAL_Options & CPAL_OPT_I2C_NOSTOP) != 0)
{
/* Disable EVENT Interrupt */
__CPAL_I2C_HAL_DISABLE_EVTIT(pDevInitStruct->CPAL_Dev);
CPAL_LOG("\n\rLOG : I2C Device EVT IT Disabled");
/* Disable Buffer interrupt */
__CPAL_I2C_HAL_DISABLE_BUFIT(pDevInitStruct->CPAL_Dev);
CPAL_LOG("\n\rLOG : I2C Device BUFF IT Disabled");
/* Update CPAL_State to CPAL_STATE_READY */
pDevInitStruct->CPAL_State = CPAL_STATE_READY;
/* Call RX Transfer complete Callback */
CPAL_I2C_RXTC_UserCallback(pDevInitStruct);
}
CPAL_LOG("\n\r\n\rLOG <I2C_EV_IRQHandler> : I2C Device Slave IT");
CPAL_LOG("\n\rLOG : I2C Device RX Complete");
}
}
}
return CPAL_PASS;
}
#endif /* CPAL_I2C_IT_PROGMODEL */
#endif /* CPAL_I2C_SLAVE_MODE */
/*================== Local DMA and IT Manager ==================*/
/**
* @brief This function Configure I2C DMA and Interrupts before starting transfer phase.
* @param pDevInitStruct: Pointer to the peripheral configuration structure.
* @param Direction : Transfer direction.
* @retval CPAL_PASS or CPAL_FAIL.
*/
uint32_t CPAL_I2C_Enable_DMA_IT (CPAL_InitTypeDef* pDevInitStruct, CPAL_DirectionTypeDef Direction)
{
/* Switch the value of CPAL_ProgModel */
switch (pDevInitStruct->CPAL_ProgModel)
{
#if defined (CPAL_I2C_IT_PROGMODEL) || defined (CPAL_I2C_DMA_1BYTE_CASE)
/*----------------------------------------------------------------------------
Interrupt mode : if CPAL_ProgModel = CPAL_PROGMODEL_INTERRUPT
---------------------------------------------------------------------------*/
case CPAL_PROGMODEL_INTERRUPT:
/* Enable BUFFER Interrupt*/
__CPAL_I2C_HAL_ENABLE_BUFIT(pDevInitStruct->CPAL_Dev);
CPAL_LOG("\n\rLOG : I2C Device BUFF IT Enabled");
return CPAL_PASS;
#endif /* CPAL_I2C_IT_PROGMODEL || CPAL_I2C_DMA_1BYTE_CASE */
#ifdef CPAL_I2C_DMA_PROGMODEL
/*----------------------------------------------------------------------------
DMA mode : if CPAL_ProgModel = CPAL_PROGMODEL_DMA
---------------------------------------------------------------------------*/
case CPAL_PROGMODEL_DMA:
/* Disable EVENT Interrupt */
__CPAL_I2C_HAL_DISABLE_EVTIT(pDevInitStruct->CPAL_Dev);
/* Enable DMA request */
__CPAL_I2C_HAL_ENABLE_DMAREQ(pDevInitStruct->CPAL_Dev);
/* If a data transmission will be performed */
if ((pDevInitStruct->CPAL_State == CPAL_STATE_BUSY_TX) || (Direction == CPAL_DIRECTION_TX))
{
/* Configure TX DMA Channels */
CPAL_I2C_HAL_DMATXConfig(pDevInitStruct->CPAL_Dev, pDevInitStruct->pCPAL_TransferTx, pDevInitStruct->wCPAL_Options);
/* Disable DMA automatic NACK generation */
__CPAL_I2C_HAL_DISABLE_LAST(pDevInitStruct->CPAL_Dev);
/* Enable TX DMA Channels */
__CPAL_I2C_HAL_ENABLE_DMATX(pDevInitStruct->CPAL_Dev);
CPAL_LOG("\n\rLOG : I2C Device DMA TX Enabled");
}
/* If a data reception will be performed */
else if ((pDevInitStruct->CPAL_State == CPAL_STATE_BUSY_RX) || (Direction == CPAL_DIRECTION_RX))
{
/* Configure RX DMA Channels */
CPAL_I2C_HAL_DMARXConfig(pDevInitStruct->CPAL_Dev, pDevInitStruct->pCPAL_TransferRx, pDevInitStruct->wCPAL_Options);
/* If Master Mode Selected */
if(pDevInitStruct->CPAL_Mode == CPAL_MODE_MASTER )
{
/* Enable DMA automatic NACK generation */
__CPAL_I2C_HAL_ENABLE_LAST(pDevInitStruct->CPAL_Dev);
}
/* Enable RX DMA Channels */
__CPAL_I2C_HAL_ENABLE_DMARX(pDevInitStruct->CPAL_Dev);
}
return CPAL_PASS;
#endif /* CPAL_I2C_DMA_PROGMODEL */
/*----------------------------------------------------------------------------
Default: return error and exit Write Operation
---------------------------------------------------------------------------*/
default:
/* Update CPAL_State to CPAL_STATE_ERROR */
pDevInitStruct->CPAL_State = CPAL_STATE_ERROR;
CPAL_LOG("\n\rERROR : I2C Device Error");
/* exit function */
return CPAL_FAIL;
}
}
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
| 39.011319 | 181 | 0.608282 | [
"model"
] |
d910a7fc8184b60fd10fd17b0b77599c997eef47 | 5,694 | h | C | isda_cds_model_c_v1.8.2/lib/include/isda/datelist.h | keithalewis/xll_isda_cds | 64ede82ca899d1310bcc87816c4d693804a455cb | [
"MIT"
] | null | null | null | isda_cds_model_c_v1.8.2/lib/include/isda/datelist.h | keithalewis/xll_isda_cds | 64ede82ca899d1310bcc87816c4d693804a455cb | [
"MIT"
] | null | null | null | isda_cds_model_c_v1.8.2/lib/include/isda/datelist.h | keithalewis/xll_isda_cds | 64ede82ca899d1310bcc87816c4d693804a455cb | [
"MIT"
] | null | null | null | /*
* ISDA CDS Standard Model
*
* Copyright (C) 2009 International Swaps and Derivatives Association, Inc.
* Developed and supported in collaboration with Markit
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the ISDA CDS Standard Model Public License.
*/
#ifndef DATELIST_H
#define DATELIST_H
#include "cgeneral.h"
#include "bastypes.h"
#include "dtlist.h"
#ifdef __cplusplus
extern "C"
{
#endif
/*f
***************************************************************************
** Makes an array of dates from startDate, MaturityDate, & interval.
** If (maturityDate-startDate) divided by interval is not an integer,
** there is a stub. If stubAtEnd is set, the stub is placed at the end;
** otherwise, it is placed at the beginning.
** Unlike JpmcdsNewDateListExtended, the startDate and maturityDate are always
** included, and are the first and last dates respectively.
** Assuming there is no stub, dates created are of the form:
** baseDate + idx*Interval, where startIdx <= idx <= Time2Maturity/Interval
** Returns a new DateList on success, and NULL on failure.
***************************************************************************
*/
TDateList* JpmcdsNewDateList(
TDate startDate, /* (I) Start Date */
TDate maturityDate, /* (I) Maturity Date */
TDateInterval *interval, /* (I) Increment */
TBoolean stubAtEnd); /* (I) T=Stub at end; F=Stub at beg. */
/*f
***************************************************************************
** Makes an array of dates using startDate, MaturityDate, & interval.
** If time2Maturity/interval is not an integer, there is a stub. If stubAtEnd
** is set, the stub is placed at the end; otherwise, it is placed at the
** beginning.
** If there is a stub at the END, the MaturityDate is NOT included
** in the list; but the NEXT date is.
** If there is a stub at the BEGINNING, the startDate is NOT included
** in the list; but the PREVIOUS date is.
** This is necessary for Actual/Actual stub calculation.
** Assuming there is no stub, dates created are of the form:
** baseDate + idx*Interval, where startIdx <= idx <= Time2Maturity/Interval
** Returns a new DateList on success, and NULL on failure.
***************************************************************************
*/
TDateList* JpmcdsNewDateListExtended(
TDate startDate, /* (I) Start Date */
TDate maturityDate, /* (I) Maturity Date */
TDateInterval *interval, /* (I) Increment */
TBoolean stubAtEnd); /* (I) T=Stub at end; F=Stub at beg. */
/*f
***************************************************************************
** Makes an array of dates using startDate, MaturityDate, rollDate &
** interval. If rollDate is non-zero and stubAtEnd is False, then the rollDate
** is used to generate cash flow dates. First starting from roll-date we see if
** we can count forward an integral number of intervals to the maturity date.
** If this is so then we can generate our datelist by counting forward from
** the rolldate.
**
** Returns a new DateList on success, and NULL on failure.
***************************************************************************
*/
TDateList * JpmcdsNewDateListExtendedRoll(
TDate startDate, /* (I) Start Date */
TDate maturityDate, /* (I) Maturity Date */
TDate rollDate, /* (I) Date for roll information */
TDateInterval *interval, /* (I) Increment */
TBoolean stubAtEnd); /* (I) T=Stub at end; F=Stub at beg. */
/*f
***************************************************************************
** Allocates a new TDateList and copies supplied dates into it from
** supplied TCurve.
**
** This provides a convenient way to isolate the dates of a TCurve.
***************************************************************************
*/
TDateList* JpmcdsNewDateListFromTCurve
(TCurve *curve); /* (I) Given curve */
/*f
***************************************************************************
** Allocates a new TDateList by calling JpmcdsNewDateList, and then removing
** the startDate.
***************************************************************************
*/
TDateList* JpmcdsNewPayDates
(TDate startDate, /* (I) This date is not included */
TDate matDate, /* (I) */
TDateInterval *payInterval, /* (I) */
TBoolean stubAtEnd); /* (I) */
/*f
***************************************************************************
** Creates a new business-day adjusted dateList from an UN-adjusted
** datelist, using the supplied busisness day adjustment convention.
***************************************************************************
*/
TDateList* JpmcdsNewDateListBusDayAdj
(
TDateList *dateList, /* (I) Unadjusted date list */
long badDayConv, /* (I) See JpmcdsBusinessDay */
char *holidayFile /* (I) Holiday date file */
);
/*f
***************************************************************************
** Adjusts a datelist (in-place) according to the supplied business day
** adjustment convention.
***************************************************************************
*/
int JpmcdsDateListBusDayAdj
(
TDateList *dateList, /* (I/O) Date list to adjust (in-place) */
long badDayConv, /* (I) See JpmcdsBusinessDay */
char *holidayFile /* (I) Holiday date file */
);
#ifdef __cplusplus
}
#endif
#endif /* DATELIST_H */
| 39 | 80 | 0.532842 | [
"model"
] |
d919c68f5661f4c0bbf6c9752c25b031ab678ebc | 2,905 | c | C | 3pxnet-inference/val/fc_reference.c | SRavit1/3pxnet | 1f81a2bdcbb97c42163e914b01dba4e6c73ade60 | [
"MIT"
] | 7 | 2020-12-11T16:06:03.000Z | 2022-02-13T20:56:06.000Z | 3pxnet-inference/val/fc_reference.c | SRavit1/3pxnet | 1f81a2bdcbb97c42163e914b01dba4e6c73ade60 | [
"MIT"
] | 4 | 2021-07-13T10:50:49.000Z | 2021-08-13T16:06:20.000Z | 3pxnet-inference/val/fc_reference.c | SRavit1/3pxnet | 1f81a2bdcbb97c42163e914b01dba4e6c73ade60 | [
"MIT"
] | 1 | 2021-07-06T03:41:55.000Z | 2021-07-06T03:41:55.000Z | /*
* MIT License
*
* Copyright (c) 2019 UCLA NanoCAD Laboratory
*
* 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.
*/
/*!
* \file fc_reference.c
* \brief Reference Fully-Connected Layer for Binarized Implementations
* \author Wojciech Romaszkan
* \author NanoCAD Laboratory, University of California Los Angeles
* \copyright MIT License
*/
#include "fc_reference.h"
/**
* @details Reference Fully Connected Layer
* @param[in] pAct - pointer to the packed activation vector
* @param[in] pWgt - pointer to the packed weight vector
* @param[in] numIn - length of the input vector
* @param[in] numOut - length of the output vector
* @param[out] pOut - pointer to the packed output vector
* @param[in] pMean - pointer to mean vector (if NULL, Batch Norm is skipped)
* @param[in] pVar - pointer to variance vector
* @param[in] pGamma - pointer to gamma vector
* @param[in] pBeta - pointer to beta vector
* @param[in] epsilon - batch norm epsilon value
*/
void refFc(int16_t * pAct, int16_t * pWgt, const uint16_t numIn, const uint16_t numOut, float * pOut,
float * pMean, float * pVar, float * pGamma, float * pBeta, float epsilon) {
// Local pointer to activations
int16_t *pIn = pAct;
// Outer loop - outputs
for (uint16_t out = 0; out < numOut; out++) {
// Reset activation pointer
pIn = pAct;
// Clear output
*pOut = 0;
// Inner loop - inputs
for (uint16_t in = 0; in < numIn; in++) {
// Multiply-Accumulate
*pOut += (*pIn++) * (*pWgt++);
} // in
if (pMean) {
*pOut = ((*pGamma++)*(((float)*pOut - *pMean++)/(*pVar++ )) + *pBeta++);
}
// Optional Batch Norm - skip if pMean is NULL
// Move onto the next output
pOut++;
} // out
}
| 38.223684 | 102 | 0.65852 | [
"vector"
] |
d924d84c93d492daa824d2547755036922249d28 | 4,612 | h | C | mace/core/net_def_adapter.h | dreadlord1984/mace | 3dc71dca6bb1389899f5d2b3137562c0dfbe0321 | [
"Apache-2.0"
] | null | null | null | mace/core/net_def_adapter.h | dreadlord1984/mace | 3dc71dca6bb1389899f5d2b3137562c0dfbe0321 | [
"Apache-2.0"
] | null | null | null | mace/core/net_def_adapter.h | dreadlord1984/mace | 3dc71dca6bb1389899f5d2b3137562c0dfbe0321 | [
"Apache-2.0"
] | null | null | null | // Copyright 2019 The MACE Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef MACE_CORE_NET_DEF_ADAPTER_H_
#define MACE_CORE_NET_DEF_ADAPTER_H_
#include <memory>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <vector>
#include "mace/core/types.h"
#include "mace/proto/mace.pb.h"
#include "mace/port/port.h"
#include "mace/core/operator.h"
#include "mace/core/net_optimizer.h"
namespace mace {
class OpRegistryBase;
class Workspace;
class Device;
///////////////////////////////////////////////////////////////////////////////
/// Conventions
///
/// 1. For the Ops ran with data format(like Conv2D),
/// The inputs and outputs are DataFormat::NCHW if ran on CPU
/// with float data type.
/// while the inputs and outputs are DataFormat::NHWC for
/// other situation(ran on GPU, quantization, DSP)
///
/// 2. Op with DataFormat::AUTO stands for inputs must have
/// fixed format (NHWC or NCHW), determined at runtime.
///
/// 3. if Op with DataFormat::AUTO, the arguments of this op
/// is formatted to NHWC.
///////////////////////////////////////////////////////////////////////////////
class NetDefAdapter {
public:
NetDefAdapter(const OpRegistryBase *op_registry,
const Workspace *ws);
// Adapt original net_def to a better net.
// 1. Adapt device: choose best device for every op in the net.
// 2. Adapt data type: Add data type related transform ops
// for mixing precision.
// 3. Adapt data format: confirm data format of every op
// and add transpose if necessary.
// 4. Adapt memory type: Add BufferTransform if necessary
// for transforming memory type between ops.
MaceStatus AdaptNetDef(
const NetDef *net_def,
Device *target_device,
NetDef *target_net_def);
public:
NetDefAdapter(const NetDefAdapter&) = delete;
NetDefAdapter(const NetDefAdapter&&) = delete;
NetDefAdapter &operator=(const NetDefAdapter &) = delete;
NetDefAdapter &operator=(const NetDefAdapter &&) = delete;
private:
struct InternalOutputInfo {
InternalOutputInfo(const MemoryType mem_type,
const DataType dtype,
const DataFormat data_format,
const std::vector<index_t> &shape,
int op_idx)
: mem_type(mem_type), dtype(dtype), data_format(data_format),
shape(shape), op_idx(op_idx) {}
MemoryType mem_type;
DataType dtype;
DataFormat data_format;
std::vector<index_t> shape; // tensor shape
int op_idx; // operation which generate the tensor
};
typedef std::unordered_map<std::string, InternalOutputInfo> TensorInfoMap;
typedef std::unordered_map<std::string, std::vector<index_t>> TensorShapeMap;
private:
MaceStatus AdaptDevice(OpConditionContext *context,
Device *target_device,
Device *cpu_device,
const TensorInfoMap &output_map,
const NetDef *net_def,
OperatorDef *op);
MaceStatus AdaptDataType(OpConditionContext *context,
OperatorDef *op);
MaceStatus AdaptDataFormat(
OpConditionContext *context,
OperatorDef *op,
bool is_quantized_model,
TensorInfoMap *output_map,
TensorShapeMap *tensor_shape_map,
std::unordered_set<std::string> *transformed_set,
DataFormat *op_output_df,
NetDef *target_net_def);
MaceStatus AdaptMemoryType(
OpConditionContext *context,
OperatorDef *op_def,
TensorInfoMap *output_map,
TensorShapeMap *tensor_shape_map,
std::unordered_set<std::string> *transformed_set,
MemoryType *op_output_mem_types,
NetDef *target_net_def);
std::string DebugString(const NetDef *net_def);
private:
const OpRegistryBase *op_registry_;
const Workspace *ws_;
NetOptimizer net_optimizer_;
};
} // namespace mace
#endif // MACE_CORE_NET_DEF_ADAPTER_H_
| 35.206107 | 79 | 0.652212 | [
"shape",
"vector",
"transform"
] |
d925bd62bfba0b758ce3a7526475a7c7f02dc765 | 6,571 | h | C | include/sick_safetyscanners/cola2/Command.h | Tractonomy/sick_safetyscanners | 25fe3477b8a24c07f79b7750085ba7cf09b49279 | [
"Apache-2.0"
] | null | null | null | include/sick_safetyscanners/cola2/Command.h | Tractonomy/sick_safetyscanners | 25fe3477b8a24c07f79b7750085ba7cf09b49279 | [
"Apache-2.0"
] | 2 | 2020-09-05T14:01:46.000Z | 2020-12-08T08:00:05.000Z | include/sick_safetyscanners/cola2/Command.h | Tractonomy/sick_safetyscanners | 25fe3477b8a24c07f79b7750085ba7cf09b49279 | [
"Apache-2.0"
] | 1 | 2020-09-02T13:38:28.000Z | 2020-09-02T13:38:28.000Z | // this is for emacs file handling -*- mode: c++; indent-tabs-mode: nil -*-
// -- BEGIN LICENSE BLOCK ----------------------------------------------
/*!
* Copyright (C) 2018, SICK AG, Waldkirch
* Copyright (C) 2018, FZI Forschungszentrum Informatik, Karlsruhe, Germany
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// -- END LICENSE BLOCK ------------------------------------------------
//----------------------------------------------------------------------
/*!
* \file Command.h
*
* \author Lennart Puck <puck@fzi.de>
* \date 2018-09-24
*/
//----------------------------------------------------------------------
#ifndef SICK_SAFETYSCANNERS_COLA2_COMMAND_H
#define SICK_SAFETYSCANNERS_COLA2_COMMAND_H
#include <vector>
#include <sick_safetyscanners/datastructure/PacketBuffer.h>
#include <sick_safetyscanners/data_processing/ParseTCPPacket.h>
#include <sick_safetyscanners/data_processing/ReadWriteHelper.hpp>
#include <boost/thread/mutex.hpp>
namespace sick {
namespace cola2 {
/*!
* \brief Forward declaration of the cola2session class.
*/
class Cola2Session;
/*!
* \brief Base class for commands. Defines the base interface and does the common tasks.
*/
class Command
{
public:
/*!
* \brief Constructor of the command. Sets the common variables for a command to the sensor.
*
* \param session The session in which the command will be executed.
* \param command_type Defines what type of command will be executed in the sensor (Read, Write,
* Invoking a method).
* \param command_mode Specifies the mode of the command. If the request is by index or name.
*/
Command(sick::cola2::Cola2Session& session,
const uint16_t& command_type,
const uint16_t& command_mode);
/*!
* \brief We have virtual member functions, so a virtual destructor is needed.
*/
virtual ~Command() {}
/*!
* \brief Locks a mutex to prevent other commands being executed in parallel.
*/
void lockExecutionMutex();
/*!
* \brief Adds the data to the telegram and afterwards the header with the correct length.
*
* \param telegram The telegram, which will be modified with the data and header.
* \returns Completed telegram.
*/
std::vector<uint8_t> constructTelegram(const std::vector<uint8_t>& telegram) const;
/*!
* \brief Parses the da incoming data package and then processes it with the inherited
* processReply. Afterwards the mutex will be unlocked to allow new commands to be send.
*
*
* \param packet The incoming data package which will be processed.
*/
void processReplyBase(const std::vector<uint8_t>& packet);
/*!
* \brief Scooped call to the mutex, which will block until the reply was processed.
*/
void waitForCompletion();
/*!
* \brief Returns the current session ID.
*
* \returns The current session ID.
*/
uint32_t getSessionID() const;
/*!
* \brief Sets the session ID.
*
* \param session_id The new session ID.
*/
void setSessionID(const uint32_t& session_id);
/*!
* \brief Returns if the command was successfully parsed.
*
* \returns If the command was successfully parsed.
*/
bool wasSuccessful() const;
/*!
* \brief Returns the command type.
*
* \returns The command type.
*/
uint8_t getCommandType() const;
/*!
* \brief Sets the command type.
*
* \param command_type The new command type.
*/
void setCommandType(const uint8_t& command_type);
/*!
* \brief Returns the command mode.
*
* \returns The command mode.
*/
uint8_t getCommandMode() const;
/*!
* \brief Sets the command mode.
*
* \param command_mode The new command mode.
*/
void setCommandMode(const uint8_t& command_mode);
/*!
* \brief Returns the request id of the command.
*
* \returns The request id.
*/
uint16_t getRequestID() const;
/*!
* \brief Sets the request ID of the command.
*
* \param request_id The new request id.
*/
void setRequestID(const uint16_t& request_id);
/*!
* \brief Returns the data vector.
*
* \returns The data vector.
*/
std::vector<uint8_t> getDataVector() const;
/*!
* \brief Sets the data vector.
*
* \param data The new data vector.
*/
void setDataVector(const std::vector<uint8_t>& data);
protected:
sick::cola2::Cola2Session& m_session;
std::vector<uint8_t> expandTelegram(const std::vector<uint8_t>& telegram,
size_t additional_bytes) const;
private:
std::shared_ptr<sick::data_processing::ParseTCPPacket> m_tcp_parser_ptr;
boost::mutex m_execution_mutex;
bool m_was_successful;
uint8_t m_command_mode;
uint8_t m_command_type;
uint32_t m_session_id;
uint16_t m_request_id;
std::vector<uint8_t> m_data_vector;
virtual bool processReply() = 0;
virtual std::vector<uint8_t> addTelegramData(const std::vector<uint8_t>& telegram) const = 0;
std::vector<uint8_t> addTelegramHeader(const std::vector<uint8_t>& telegram) const;
std::vector<uint8_t> prepareHeader() const;
void writeCola2StxToDataPtr(std::vector<uint8_t>::iterator data_ptr) const;
void writeLengthToDataPtr(std::vector<uint8_t>::iterator data_ptr,
const std::vector<uint8_t>& telegram) const;
void writeCola2HubCntrToDataPtr(std::vector<uint8_t>::iterator data_ptr) const;
void writeCola2NoCToDataPtr(std::vector<uint8_t>::iterator data_ptr) const;
void writeSessionIdToDataPtr(std::vector<uint8_t>::iterator data_ptr) const;
void writeRequestIdToDataPtr(std::vector<uint8_t>::iterator data_ptr) const;
void writeCommandTypeToDataPtr(std::vector<uint8_t>::iterator data_ptr) const;
void writeCommandModeToDataPtr(std::vector<uint8_t>::iterator data_ptr) const;
void writeDataToDataPtr(std::vector<uint8_t>::iterator data_ptr,
const std::vector<uint8_t>& telegram) const;
};
} // namespace cola2
} // namespace sick
#endif // SICK_SAFETYSCANNERS_COLA2_COMMAND_H
| 28.081197 | 98 | 0.669609 | [
"vector"
] |
d927d1a0c8618e9ffa64eaeda5820961f104b748 | 1,473 | h | C | plugins/robots/common/twoDModel/src/engine/items/regions/boundRegion.h | anastasia143/qreal | 9bd224b41e569c9c50ab88848a5746a010c65ad7 | [
"Apache-2.0"
] | 1 | 2017-04-17T03:11:55.000Z | 2017-04-17T03:11:55.000Z | plugins/robots/common/twoDModel/src/engine/items/regions/boundRegion.h | anastasia143/qreal | 9bd224b41e569c9c50ab88848a5746a010c65ad7 | [
"Apache-2.0"
] | null | null | null | plugins/robots/common/twoDModel/src/engine/items/regions/boundRegion.h | anastasia143/qreal | 9bd224b41e569c9c50ab88848a5746a010c65ad7 | [
"Apache-2.0"
] | null | null | null | /* Copyright 2007-2015 QReal Research Group
*
* 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. */
#pragma once
#include "regionItem.h"
namespace twoDModel {
namespace items {
/// Zone in 2D model that is drawn above some other item, maybe with some expanded bounds.
class BoundRegion : public RegionItem
{
public:
explicit BoundRegion(const QGraphicsObject &boundItem, const QString &boundId, QGraphicsItem *parent = 0);
/// Returns a width of the stripe on which region item wider than item it is bound to.
int stroke() const;
/// Sets a width of the stripe on which region item wider than item it is bound to.
void setStroke(int stroke);
void serialize(QDomElement &element) override;
void deserialize(const QDomElement &element) override;
QRectF boundingRect() const override;
private:
QPainterPath shape() const override;
QString regionType() const override;
const QGraphicsObject &mBoundItem;
const QString mBoundId;
int mStroke;
};
}
}
| 29.46 | 107 | 0.754243 | [
"shape",
"model"
] |
d92833906d750240629ed9ffa95f27474bf43331 | 46,475 | c | C | dpdk-2.2.0/drivers/net/virtio/virtio_ethdev.c | mohankri/network-ddk | 7a6a28a852d8408b9a0f479ce3fbd4ca881cc330 | [
"BSD-3-Clause"
] | 4 | 2016-11-05T00:19:10.000Z | 2021-09-05T14:16:43.000Z | dpdk-2.2.0/drivers/net/virtio/virtio_ethdev.c | mohankri/network-ddk | 7a6a28a852d8408b9a0f479ce3fbd4ca881cc330 | [
"BSD-3-Clause"
] | 1 | 2020-01-22T18:17:55.000Z | 2020-01-22T18:17:55.000Z | dpdk-2.2.0/drivers/net/virtio/virtio_ethdev.c | mohankri/network-ddk | 7a6a28a852d8408b9a0f479ce3fbd4ca881cc330 | [
"BSD-3-Clause"
] | null | null | null | /*-
* BSD LICENSE
*
* Copyright(c) 2010-2015 Intel Corporation. All rights reserved.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Intel Corporation nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <stdint.h>
#include <string.h>
#include <stdio.h>
#include <errno.h>
#include <unistd.h>
#ifdef RTE_EXEC_ENV_LINUXAPP
#include <dirent.h>
#include <fcntl.h>
#endif
#include <rte_ethdev.h>
#include <rte_memcpy.h>
#include <rte_string_fns.h>
#include <rte_memzone.h>
#include <rte_malloc.h>
#include <rte_atomic.h>
#include <rte_branch_prediction.h>
#include <rte_pci.h>
#include <rte_ether.h>
#include <rte_common.h>
#include <rte_errno.h>
#include <rte_memory.h>
#include <rte_eal.h>
#include <rte_dev.h>
#include "virtio_ethdev.h"
#include "virtio_pci.h"
#include "virtio_logs.h"
#include "virtqueue.h"
#include "virtio_rxtx.h"
static int eth_virtio_dev_init(struct rte_eth_dev *eth_dev);
static int eth_virtio_dev_uninit(struct rte_eth_dev *eth_dev);
static int virtio_dev_configure(struct rte_eth_dev *dev);
static int virtio_dev_start(struct rte_eth_dev *dev);
static void virtio_dev_stop(struct rte_eth_dev *dev);
static void virtio_dev_promiscuous_enable(struct rte_eth_dev *dev);
static void virtio_dev_promiscuous_disable(struct rte_eth_dev *dev);
static void virtio_dev_allmulticast_enable(struct rte_eth_dev *dev);
static void virtio_dev_allmulticast_disable(struct rte_eth_dev *dev);
static void virtio_dev_info_get(struct rte_eth_dev *dev,
struct rte_eth_dev_info *dev_info);
static int virtio_dev_link_update(struct rte_eth_dev *dev,
__rte_unused int wait_to_complete);
static void virtio_set_hwaddr(struct virtio_hw *hw);
static void virtio_get_hwaddr(struct virtio_hw *hw);
static void virtio_dev_stats_get(struct rte_eth_dev *dev,
struct rte_eth_stats *stats);
static int virtio_dev_xstats_get(struct rte_eth_dev *dev,
struct rte_eth_xstats *xstats, unsigned n);
static void virtio_dev_stats_reset(struct rte_eth_dev *dev);
static void virtio_dev_free_mbufs(struct rte_eth_dev *dev);
static int virtio_vlan_filter_set(struct rte_eth_dev *dev,
uint16_t vlan_id, int on);
static void virtio_mac_addr_add(struct rte_eth_dev *dev,
struct ether_addr *mac_addr,
uint32_t index, uint32_t vmdq __rte_unused);
static void virtio_mac_addr_remove(struct rte_eth_dev *dev, uint32_t index);
static void virtio_mac_addr_set(struct rte_eth_dev *dev,
struct ether_addr *mac_addr);
static int virtio_dev_queue_stats_mapping_set(
__rte_unused struct rte_eth_dev *eth_dev,
__rte_unused uint16_t queue_id,
__rte_unused uint8_t stat_idx,
__rte_unused uint8_t is_rx);
/*
* The set of PCI devices this driver supports
*/
static const struct rte_pci_id pci_id_virtio_map[] = {
#define RTE_PCI_DEV_ID_DECL_VIRTIO(vend, dev) {RTE_PCI_DEVICE(vend, dev)},
#include "rte_pci_dev_ids.h"
{ .vendor_id = 0, /* sentinel */ },
};
struct rte_virtio_xstats_name_off {
char name[RTE_ETH_XSTATS_NAME_SIZE];
unsigned offset;
};
/* [rt]x_qX_ is prepended to the name string here */
static const struct rte_virtio_xstats_name_off rte_virtio_q_stat_strings[] = {
{"good_packets", offsetof(struct virtqueue, packets)},
{"good_bytes", offsetof(struct virtqueue, bytes)},
{"errors", offsetof(struct virtqueue, errors)},
{"multicast_packets", offsetof(struct virtqueue, multicast)},
{"broadcast_packets", offsetof(struct virtqueue, broadcast)},
{"undersize_packets", offsetof(struct virtqueue, size_bins[0])},
{"size_64_packets", offsetof(struct virtqueue, size_bins[1])},
{"size_65_127_packets", offsetof(struct virtqueue, size_bins[2])},
{"size_128_255_packets", offsetof(struct virtqueue, size_bins[3])},
{"size_256_511_packets", offsetof(struct virtqueue, size_bins[4])},
{"size_512_1023_packets", offsetof(struct virtqueue, size_bins[5])},
{"size_1024_1517_packets", offsetof(struct virtqueue, size_bins[6])},
{"size_1518_max_packets", offsetof(struct virtqueue, size_bins[7])},
};
#define VIRTIO_NB_Q_XSTATS (sizeof(rte_virtio_q_stat_strings) / \
sizeof(rte_virtio_q_stat_strings[0]))
static int
virtio_send_command(struct virtqueue *vq, struct virtio_pmd_ctrl *ctrl,
int *dlen, int pkt_num)
{
uint32_t head, i;
int k, sum = 0;
virtio_net_ctrl_ack status = ~0;
struct virtio_pmd_ctrl result;
ctrl->status = status;
if (!(vq && vq->hw->cvq)) {
PMD_INIT_LOG(ERR,
"%s(): Control queue is not supported.",
__func__);
return -1;
}
head = vq->vq_desc_head_idx;
PMD_INIT_LOG(DEBUG, "vq->vq_desc_head_idx = %d, status = %d, "
"vq->hw->cvq = %p vq = %p",
vq->vq_desc_head_idx, status, vq->hw->cvq, vq);
if ((vq->vq_free_cnt < ((uint32_t)pkt_num + 2)) || (pkt_num < 1))
return -1;
memcpy(vq->virtio_net_hdr_mz->addr, ctrl,
sizeof(struct virtio_pmd_ctrl));
/*
* Format is enforced in qemu code:
* One TX packet for header;
* At least one TX packet per argument;
* One RX packet for ACK.
*/
vq->vq_ring.desc[head].flags = VRING_DESC_F_NEXT;
vq->vq_ring.desc[head].addr = vq->virtio_net_hdr_mz->phys_addr;
vq->vq_ring.desc[head].len = sizeof(struct virtio_net_ctrl_hdr);
vq->vq_free_cnt--;
i = vq->vq_ring.desc[head].next;
for (k = 0; k < pkt_num; k++) {
vq->vq_ring.desc[i].flags = VRING_DESC_F_NEXT;
vq->vq_ring.desc[i].addr = vq->virtio_net_hdr_mz->phys_addr
+ sizeof(struct virtio_net_ctrl_hdr)
+ sizeof(ctrl->status) + sizeof(uint8_t)*sum;
vq->vq_ring.desc[i].len = dlen[k];
sum += dlen[k];
vq->vq_free_cnt--;
i = vq->vq_ring.desc[i].next;
}
vq->vq_ring.desc[i].flags = VRING_DESC_F_WRITE;
vq->vq_ring.desc[i].addr = vq->virtio_net_hdr_mz->phys_addr
+ sizeof(struct virtio_net_ctrl_hdr);
vq->vq_ring.desc[i].len = sizeof(ctrl->status);
vq->vq_free_cnt--;
vq->vq_desc_head_idx = vq->vq_ring.desc[i].next;
vq_update_avail_ring(vq, head);
vq_update_avail_idx(vq);
PMD_INIT_LOG(DEBUG, "vq->vq_queue_index = %d", vq->vq_queue_index);
virtqueue_notify(vq);
rte_rmb();
while (vq->vq_used_cons_idx == vq->vq_ring.used->idx) {
rte_rmb();
usleep(100);
}
while (vq->vq_used_cons_idx != vq->vq_ring.used->idx) {
uint32_t idx, desc_idx, used_idx;
struct vring_used_elem *uep;
used_idx = (uint32_t)(vq->vq_used_cons_idx
& (vq->vq_nentries - 1));
uep = &vq->vq_ring.used->ring[used_idx];
idx = (uint32_t) uep->id;
desc_idx = idx;
while (vq->vq_ring.desc[desc_idx].flags & VRING_DESC_F_NEXT) {
desc_idx = vq->vq_ring.desc[desc_idx].next;
vq->vq_free_cnt++;
}
vq->vq_ring.desc[desc_idx].next = vq->vq_desc_head_idx;
vq->vq_desc_head_idx = idx;
vq->vq_used_cons_idx++;
vq->vq_free_cnt++;
}
PMD_INIT_LOG(DEBUG, "vq->vq_free_cnt=%d\nvq->vq_desc_head_idx=%d",
vq->vq_free_cnt, vq->vq_desc_head_idx);
memcpy(&result, vq->virtio_net_hdr_mz->addr,
sizeof(struct virtio_pmd_ctrl));
return result.status;
}
static int
virtio_set_multiple_queues(struct rte_eth_dev *dev, uint16_t nb_queues)
{
struct virtio_hw *hw = dev->data->dev_private;
struct virtio_pmd_ctrl ctrl;
int dlen[1];
int ret;
ctrl.hdr.class = VIRTIO_NET_CTRL_MQ;
ctrl.hdr.cmd = VIRTIO_NET_CTRL_MQ_VQ_PAIRS_SET;
memcpy(ctrl.data, &nb_queues, sizeof(uint16_t));
dlen[0] = sizeof(uint16_t);
ret = virtio_send_command(hw->cvq, &ctrl, dlen, 1);
if (ret) {
PMD_INIT_LOG(ERR, "Multiqueue configured but send command "
"failed, this is too late now...");
return -EINVAL;
}
return 0;
}
void
virtio_dev_queue_release(struct virtqueue *vq) {
struct virtio_hw *hw;
if (vq) {
hw = vq->hw;
/* Select and deactivate the queue */
VIRTIO_WRITE_REG_2(hw, VIRTIO_PCI_QUEUE_SEL, vq->vq_queue_index);
VIRTIO_WRITE_REG_4(hw, VIRTIO_PCI_QUEUE_PFN, 0);
rte_free(vq->sw_ring);
rte_free(vq);
}
}
int virtio_dev_queue_setup(struct rte_eth_dev *dev,
int queue_type,
uint16_t queue_idx,
uint16_t vtpci_queue_idx,
uint16_t nb_desc,
unsigned int socket_id,
struct virtqueue **pvq)
{
char vq_name[VIRTQUEUE_MAX_NAME_SZ];
const struct rte_memzone *mz;
unsigned int vq_size, size;
struct virtio_hw *hw = dev->data->dev_private;
struct virtqueue *vq = NULL;
/* Write the virtqueue index to the Queue Select Field */
VIRTIO_WRITE_REG_2(hw, VIRTIO_PCI_QUEUE_SEL, vtpci_queue_idx);
PMD_INIT_LOG(DEBUG, "selecting queue: %u", vtpci_queue_idx);
/*
* Read the virtqueue size from the Queue Size field
* Always power of 2 and if 0 virtqueue does not exist
*/
vq_size = VIRTIO_READ_REG_2(hw, VIRTIO_PCI_QUEUE_NUM);
PMD_INIT_LOG(DEBUG, "vq_size: %u nb_desc:%u", vq_size, nb_desc);
if (vq_size == 0) {
PMD_INIT_LOG(ERR, "%s: virtqueue does not exist", __func__);
return -EINVAL;
}
if (!rte_is_power_of_2(vq_size)) {
PMD_INIT_LOG(ERR, "%s: virtqueue size is not powerof 2", __func__);
return -EINVAL;
}
if (queue_type == VTNET_RQ) {
snprintf(vq_name, sizeof(vq_name), "port%d_rvq%d",
dev->data->port_id, queue_idx);
vq = rte_zmalloc(vq_name, sizeof(struct virtqueue) +
vq_size * sizeof(struct vq_desc_extra), RTE_CACHE_LINE_SIZE);
vq->sw_ring = rte_zmalloc_socket("rxq->sw_ring",
(RTE_PMD_VIRTIO_RX_MAX_BURST + vq_size) *
sizeof(vq->sw_ring[0]), RTE_CACHE_LINE_SIZE, socket_id);
} else if (queue_type == VTNET_TQ) {
snprintf(vq_name, sizeof(vq_name), "port%d_tvq%d",
dev->data->port_id, queue_idx);
vq = rte_zmalloc(vq_name, sizeof(struct virtqueue) +
vq_size * sizeof(struct vq_desc_extra), RTE_CACHE_LINE_SIZE);
} else if (queue_type == VTNET_CQ) {
snprintf(vq_name, sizeof(vq_name), "port%d_cvq",
dev->data->port_id);
vq = rte_zmalloc(vq_name, sizeof(struct virtqueue) +
vq_size * sizeof(struct vq_desc_extra),
RTE_CACHE_LINE_SIZE);
}
if (vq == NULL) {
PMD_INIT_LOG(ERR, "%s: Can not allocate virtqueue", __func__);
return (-ENOMEM);
}
if (queue_type == VTNET_RQ && vq->sw_ring == NULL) {
PMD_INIT_LOG(ERR, "%s: Can not allocate RX soft ring",
__func__);
rte_free(vq);
return -ENOMEM;
}
vq->hw = hw;
vq->port_id = dev->data->port_id;
vq->queue_id = queue_idx;
vq->vq_queue_index = vtpci_queue_idx;
vq->vq_nentries = vq_size;
if (nb_desc == 0 || nb_desc > vq_size)
nb_desc = vq_size;
vq->vq_free_cnt = nb_desc;
/*
* Reserve a memzone for vring elements
*/
size = vring_size(vq_size, VIRTIO_PCI_VRING_ALIGN);
vq->vq_ring_size = RTE_ALIGN_CEIL(size, VIRTIO_PCI_VRING_ALIGN);
PMD_INIT_LOG(DEBUG, "vring_size: %d, rounded_vring_size: %d", size, vq->vq_ring_size);
mz = rte_memzone_reserve_aligned(vq_name, vq->vq_ring_size,
socket_id, 0, VIRTIO_PCI_VRING_ALIGN);
if (mz == NULL) {
if (rte_errno == EEXIST)
mz = rte_memzone_lookup(vq_name);
if (mz == NULL) {
rte_free(vq);
return -ENOMEM;
}
}
/*
* Virtio PCI device VIRTIO_PCI_QUEUE_PF register is 32bit,
* and only accepts 32 bit page frame number.
* Check if the allocated physical memory exceeds 16TB.
*/
if ((mz->phys_addr + vq->vq_ring_size - 1) >> (VIRTIO_PCI_QUEUE_ADDR_SHIFT + 32)) {
PMD_INIT_LOG(ERR, "vring address shouldn't be above 16TB!");
rte_free(vq);
return -ENOMEM;
}
memset(mz->addr, 0, sizeof(mz->len));
vq->mz = mz;
vq->vq_ring_mem = mz->phys_addr;
vq->vq_ring_virt_mem = mz->addr;
PMD_INIT_LOG(DEBUG, "vq->vq_ring_mem: 0x%"PRIx64, (uint64_t)mz->phys_addr);
PMD_INIT_LOG(DEBUG, "vq->vq_ring_virt_mem: 0x%"PRIx64, (uint64_t)(uintptr_t)mz->addr);
vq->virtio_net_hdr_mz = NULL;
vq->virtio_net_hdr_mem = 0;
if (queue_type == VTNET_TQ) {
/*
* For each xmit packet, allocate a virtio_net_hdr
*/
snprintf(vq_name, sizeof(vq_name), "port%d_tvq%d_hdrzone",
dev->data->port_id, queue_idx);
vq->virtio_net_hdr_mz = rte_memzone_reserve_aligned(vq_name,
vq_size * hw->vtnet_hdr_size,
socket_id, 0, RTE_CACHE_LINE_SIZE);
if (vq->virtio_net_hdr_mz == NULL) {
if (rte_errno == EEXIST)
vq->virtio_net_hdr_mz =
rte_memzone_lookup(vq_name);
if (vq->virtio_net_hdr_mz == NULL) {
rte_free(vq);
return -ENOMEM;
}
}
vq->virtio_net_hdr_mem =
vq->virtio_net_hdr_mz->phys_addr;
memset(vq->virtio_net_hdr_mz->addr, 0,
vq_size * hw->vtnet_hdr_size);
} else if (queue_type == VTNET_CQ) {
/* Allocate a page for control vq command, data and status */
snprintf(vq_name, sizeof(vq_name), "port%d_cvq_hdrzone",
dev->data->port_id);
vq->virtio_net_hdr_mz = rte_memzone_reserve_aligned(vq_name,
PAGE_SIZE, socket_id, 0, RTE_CACHE_LINE_SIZE);
if (vq->virtio_net_hdr_mz == NULL) {
if (rte_errno == EEXIST)
vq->virtio_net_hdr_mz =
rte_memzone_lookup(vq_name);
if (vq->virtio_net_hdr_mz == NULL) {
rte_free(vq);
return -ENOMEM;
}
}
vq->virtio_net_hdr_mem =
vq->virtio_net_hdr_mz->phys_addr;
memset(vq->virtio_net_hdr_mz->addr, 0, PAGE_SIZE);
}
/*
* Set guest physical address of the virtqueue
* in VIRTIO_PCI_QUEUE_PFN config register of device
*/
VIRTIO_WRITE_REG_4(hw, VIRTIO_PCI_QUEUE_PFN,
mz->phys_addr >> VIRTIO_PCI_QUEUE_ADDR_SHIFT);
*pvq = vq;
return 0;
}
static int
virtio_dev_cq_queue_setup(struct rte_eth_dev *dev, uint16_t vtpci_queue_idx,
uint32_t socket_id)
{
struct virtqueue *vq;
int ret;
struct virtio_hw *hw = dev->data->dev_private;
PMD_INIT_FUNC_TRACE();
ret = virtio_dev_queue_setup(dev, VTNET_CQ, VTNET_SQ_CQ_QUEUE_IDX,
vtpci_queue_idx, 0, socket_id, &vq);
if (ret < 0) {
PMD_INIT_LOG(ERR, "control vq initialization failed");
return ret;
}
hw->cvq = vq;
return 0;
}
static void
virtio_free_queues(struct rte_eth_dev *dev)
{
unsigned int i;
for (i = 0; i < dev->data->nb_rx_queues; i++)
virtio_dev_rx_queue_release(dev->data->rx_queues[i]);
dev->data->nb_rx_queues = 0;
for (i = 0; i < dev->data->nb_tx_queues; i++)
virtio_dev_tx_queue_release(dev->data->tx_queues[i]);
dev->data->nb_tx_queues = 0;
}
static void
virtio_dev_close(struct rte_eth_dev *dev)
{
struct virtio_hw *hw = dev->data->dev_private;
struct rte_pci_device *pci_dev = dev->pci_dev;
PMD_INIT_LOG(DEBUG, "virtio_dev_close");
/* reset the NIC */
if (pci_dev->driver->drv_flags & RTE_PCI_DRV_INTR_LSC)
vtpci_irq_config(hw, VIRTIO_MSI_NO_VECTOR);
vtpci_reset(hw);
hw->started = 0;
virtio_dev_free_mbufs(dev);
virtio_free_queues(dev);
}
static void
virtio_dev_promiscuous_enable(struct rte_eth_dev *dev)
{
struct virtio_hw *hw = dev->data->dev_private;
struct virtio_pmd_ctrl ctrl;
int dlen[1];
int ret;
if (!vtpci_with_feature(hw, VIRTIO_NET_F_CTRL_RX)) {
PMD_INIT_LOG(INFO, "host does not support rx control\n");
return;
}
ctrl.hdr.class = VIRTIO_NET_CTRL_RX;
ctrl.hdr.cmd = VIRTIO_NET_CTRL_RX_PROMISC;
ctrl.data[0] = 1;
dlen[0] = 1;
ret = virtio_send_command(hw->cvq, &ctrl, dlen, 1);
if (ret)
PMD_INIT_LOG(ERR, "Failed to enable promisc");
}
static void
virtio_dev_promiscuous_disable(struct rte_eth_dev *dev)
{
struct virtio_hw *hw = dev->data->dev_private;
struct virtio_pmd_ctrl ctrl;
int dlen[1];
int ret;
if (!vtpci_with_feature(hw, VIRTIO_NET_F_CTRL_RX)) {
PMD_INIT_LOG(INFO, "host does not support rx control\n");
return;
}
ctrl.hdr.class = VIRTIO_NET_CTRL_RX;
ctrl.hdr.cmd = VIRTIO_NET_CTRL_RX_PROMISC;
ctrl.data[0] = 0;
dlen[0] = 1;
ret = virtio_send_command(hw->cvq, &ctrl, dlen, 1);
if (ret)
PMD_INIT_LOG(ERR, "Failed to disable promisc");
}
static void
virtio_dev_allmulticast_enable(struct rte_eth_dev *dev)
{
struct virtio_hw *hw = dev->data->dev_private;
struct virtio_pmd_ctrl ctrl;
int dlen[1];
int ret;
if (!vtpci_with_feature(hw, VIRTIO_NET_F_CTRL_RX)) {
PMD_INIT_LOG(INFO, "host does not support rx control\n");
return;
}
ctrl.hdr.class = VIRTIO_NET_CTRL_RX;
ctrl.hdr.cmd = VIRTIO_NET_CTRL_RX_ALLMULTI;
ctrl.data[0] = 1;
dlen[0] = 1;
ret = virtio_send_command(hw->cvq, &ctrl, dlen, 1);
if (ret)
PMD_INIT_LOG(ERR, "Failed to enable allmulticast");
}
static void
virtio_dev_allmulticast_disable(struct rte_eth_dev *dev)
{
struct virtio_hw *hw = dev->data->dev_private;
struct virtio_pmd_ctrl ctrl;
int dlen[1];
int ret;
if (!vtpci_with_feature(hw, VIRTIO_NET_F_CTRL_RX)) {
PMD_INIT_LOG(INFO, "host does not support rx control\n");
return;
}
ctrl.hdr.class = VIRTIO_NET_CTRL_RX;
ctrl.hdr.cmd = VIRTIO_NET_CTRL_RX_ALLMULTI;
ctrl.data[0] = 0;
dlen[0] = 1;
ret = virtio_send_command(hw->cvq, &ctrl, dlen, 1);
if (ret)
PMD_INIT_LOG(ERR, "Failed to disable allmulticast");
}
/*
* dev_ops for virtio, bare necessities for basic operation
*/
static const struct eth_dev_ops virtio_eth_dev_ops = {
.dev_configure = virtio_dev_configure,
.dev_start = virtio_dev_start,
.dev_stop = virtio_dev_stop,
.dev_close = virtio_dev_close,
.promiscuous_enable = virtio_dev_promiscuous_enable,
.promiscuous_disable = virtio_dev_promiscuous_disable,
.allmulticast_enable = virtio_dev_allmulticast_enable,
.allmulticast_disable = virtio_dev_allmulticast_disable,
.dev_infos_get = virtio_dev_info_get,
.stats_get = virtio_dev_stats_get,
.xstats_get = virtio_dev_xstats_get,
.stats_reset = virtio_dev_stats_reset,
.xstats_reset = virtio_dev_stats_reset,
.link_update = virtio_dev_link_update,
.rx_queue_setup = virtio_dev_rx_queue_setup,
.rx_queue_release = virtio_dev_rx_queue_release,
.tx_queue_setup = virtio_dev_tx_queue_setup,
.tx_queue_release = virtio_dev_tx_queue_release,
/* collect stats per queue */
.queue_stats_mapping_set = virtio_dev_queue_stats_mapping_set,
.vlan_filter_set = virtio_vlan_filter_set,
.mac_addr_add = virtio_mac_addr_add,
.mac_addr_remove = virtio_mac_addr_remove,
.mac_addr_set = virtio_mac_addr_set,
};
static inline int
virtio_dev_atomic_read_link_status(struct rte_eth_dev *dev,
struct rte_eth_link *link)
{
struct rte_eth_link *dst = link;
struct rte_eth_link *src = &(dev->data->dev_link);
if (rte_atomic64_cmpset((uint64_t *)dst, *(uint64_t *)dst,
*(uint64_t *)src) == 0)
return -1;
return 0;
}
/**
* Atomically writes the link status information into global
* structure rte_eth_dev.
*
* @param dev
* - Pointer to the structure rte_eth_dev to read from.
* - Pointer to the buffer to be saved with the link status.
*
* @return
* - On success, zero.
* - On failure, negative value.
*/
static inline int
virtio_dev_atomic_write_link_status(struct rte_eth_dev *dev,
struct rte_eth_link *link)
{
struct rte_eth_link *dst = &(dev->data->dev_link);
struct rte_eth_link *src = link;
if (rte_atomic64_cmpset((uint64_t *)dst, *(uint64_t *)dst,
*(uint64_t *)src) == 0)
return -1;
return 0;
}
static void
virtio_update_stats(struct rte_eth_dev *dev, struct rte_eth_stats *stats)
{
unsigned i;
for (i = 0; i < dev->data->nb_tx_queues; i++) {
const struct virtqueue *txvq = dev->data->tx_queues[i];
if (txvq == NULL)
continue;
stats->opackets += txvq->packets;
stats->obytes += txvq->bytes;
stats->oerrors += txvq->errors;
if (i < RTE_ETHDEV_QUEUE_STAT_CNTRS) {
stats->q_opackets[i] = txvq->packets;
stats->q_obytes[i] = txvq->bytes;
}
}
for (i = 0; i < dev->data->nb_rx_queues; i++) {
const struct virtqueue *rxvq = dev->data->rx_queues[i];
if (rxvq == NULL)
continue;
stats->ipackets += rxvq->packets;
stats->ibytes += rxvq->bytes;
stats->ierrors += rxvq->errors;
if (i < RTE_ETHDEV_QUEUE_STAT_CNTRS) {
stats->q_ipackets[i] = rxvq->packets;
stats->q_ibytes[i] = rxvq->bytes;
}
}
stats->rx_nombuf = dev->data->rx_mbuf_alloc_failed;
}
static int
virtio_dev_xstats_get(struct rte_eth_dev *dev, struct rte_eth_xstats *xstats,
unsigned n)
{
unsigned i;
unsigned count = 0;
unsigned nstats = dev->data->nb_tx_queues * VIRTIO_NB_Q_XSTATS +
dev->data->nb_rx_queues * VIRTIO_NB_Q_XSTATS;
if (n < nstats)
return nstats;
for (i = 0; i < dev->data->nb_rx_queues; i++) {
struct virtqueue *rxvq = dev->data->rx_queues[i];
if (rxvq == NULL)
continue;
unsigned t;
for (t = 0; t < VIRTIO_NB_Q_XSTATS; t++) {
snprintf(xstats[count].name, sizeof(xstats[count].name),
"rx_q%u_%s", i,
rte_virtio_q_stat_strings[t].name);
xstats[count].value = *(uint64_t *)(((char *)rxvq) +
rte_virtio_q_stat_strings[t].offset);
count++;
}
}
for (i = 0; i < dev->data->nb_tx_queues; i++) {
struct virtqueue *txvq = dev->data->tx_queues[i];
if (txvq == NULL)
continue;
unsigned t;
for (t = 0; t < VIRTIO_NB_Q_XSTATS; t++) {
snprintf(xstats[count].name, sizeof(xstats[count].name),
"tx_q%u_%s", i,
rte_virtio_q_stat_strings[t].name);
xstats[count].value = *(uint64_t *)(((char *)txvq) +
rte_virtio_q_stat_strings[t].offset);
count++;
}
}
return count;
}
static void
virtio_dev_stats_get(struct rte_eth_dev *dev, struct rte_eth_stats *stats)
{
virtio_update_stats(dev, stats);
}
static void
virtio_dev_stats_reset(struct rte_eth_dev *dev)
{
unsigned int i;
for (i = 0; i < dev->data->nb_tx_queues; i++) {
struct virtqueue *txvq = dev->data->tx_queues[i];
if (txvq == NULL)
continue;
txvq->packets = 0;
txvq->bytes = 0;
txvq->errors = 0;
txvq->multicast = 0;
txvq->broadcast = 0;
memset(txvq->size_bins, 0, sizeof(txvq->size_bins[0]) * 8);
}
for (i = 0; i < dev->data->nb_rx_queues; i++) {
struct virtqueue *rxvq = dev->data->rx_queues[i];
if (rxvq == NULL)
continue;
rxvq->packets = 0;
rxvq->bytes = 0;
rxvq->errors = 0;
rxvq->multicast = 0;
rxvq->broadcast = 0;
memset(rxvq->size_bins, 0, sizeof(rxvq->size_bins[0]) * 8);
}
}
static void
virtio_set_hwaddr(struct virtio_hw *hw)
{
vtpci_write_dev_config(hw,
offsetof(struct virtio_net_config, mac),
&hw->mac_addr, ETHER_ADDR_LEN);
}
static void
virtio_get_hwaddr(struct virtio_hw *hw)
{
if (vtpci_with_feature(hw, VIRTIO_NET_F_MAC)) {
vtpci_read_dev_config(hw,
offsetof(struct virtio_net_config, mac),
&hw->mac_addr, ETHER_ADDR_LEN);
} else {
eth_random_addr(&hw->mac_addr[0]);
virtio_set_hwaddr(hw);
}
}
static void
virtio_mac_table_set(struct virtio_hw *hw,
const struct virtio_net_ctrl_mac *uc,
const struct virtio_net_ctrl_mac *mc)
{
struct virtio_pmd_ctrl ctrl;
int err, len[2];
if (!vtpci_with_feature(hw, VIRTIO_NET_F_CTRL_MAC_ADDR)) {
PMD_DRV_LOG(INFO, "host does not support mac table\n");
return;
}
ctrl.hdr.class = VIRTIO_NET_CTRL_MAC;
ctrl.hdr.cmd = VIRTIO_NET_CTRL_MAC_TABLE_SET;
len[0] = uc->entries * ETHER_ADDR_LEN + sizeof(uc->entries);
memcpy(ctrl.data, uc, len[0]);
len[1] = mc->entries * ETHER_ADDR_LEN + sizeof(mc->entries);
memcpy(ctrl.data + len[0], mc, len[1]);
err = virtio_send_command(hw->cvq, &ctrl, len, 2);
if (err != 0)
PMD_DRV_LOG(NOTICE, "mac table set failed: %d", err);
}
static void
virtio_mac_addr_add(struct rte_eth_dev *dev, struct ether_addr *mac_addr,
uint32_t index, uint32_t vmdq __rte_unused)
{
struct virtio_hw *hw = dev->data->dev_private;
const struct ether_addr *addrs = dev->data->mac_addrs;
unsigned int i;
struct virtio_net_ctrl_mac *uc, *mc;
if (index >= VIRTIO_MAX_MAC_ADDRS) {
PMD_DRV_LOG(ERR, "mac address index %u out of range", index);
return;
}
uc = alloca(VIRTIO_MAX_MAC_ADDRS * ETHER_ADDR_LEN + sizeof(uc->entries));
uc->entries = 0;
mc = alloca(VIRTIO_MAX_MAC_ADDRS * ETHER_ADDR_LEN + sizeof(mc->entries));
mc->entries = 0;
for (i = 0; i < VIRTIO_MAX_MAC_ADDRS; i++) {
const struct ether_addr *addr
= (i == index) ? mac_addr : addrs + i;
struct virtio_net_ctrl_mac *tbl
= is_multicast_ether_addr(addr) ? mc : uc;
memcpy(&tbl->macs[tbl->entries++], addr, ETHER_ADDR_LEN);
}
virtio_mac_table_set(hw, uc, mc);
}
static void
virtio_mac_addr_remove(struct rte_eth_dev *dev, uint32_t index)
{
struct virtio_hw *hw = dev->data->dev_private;
struct ether_addr *addrs = dev->data->mac_addrs;
struct virtio_net_ctrl_mac *uc, *mc;
unsigned int i;
if (index >= VIRTIO_MAX_MAC_ADDRS) {
PMD_DRV_LOG(ERR, "mac address index %u out of range", index);
return;
}
uc = alloca(VIRTIO_MAX_MAC_ADDRS * ETHER_ADDR_LEN + sizeof(uc->entries));
uc->entries = 0;
mc = alloca(VIRTIO_MAX_MAC_ADDRS * ETHER_ADDR_LEN + sizeof(mc->entries));
mc->entries = 0;
for (i = 0; i < VIRTIO_MAX_MAC_ADDRS; i++) {
struct virtio_net_ctrl_mac *tbl;
if (i == index || is_zero_ether_addr(addrs + i))
continue;
tbl = is_multicast_ether_addr(addrs + i) ? mc : uc;
memcpy(&tbl->macs[tbl->entries++], addrs + i, ETHER_ADDR_LEN);
}
virtio_mac_table_set(hw, uc, mc);
}
static void
virtio_mac_addr_set(struct rte_eth_dev *dev, struct ether_addr *mac_addr)
{
struct virtio_hw *hw = dev->data->dev_private;
memcpy(hw->mac_addr, mac_addr, ETHER_ADDR_LEN);
/* Use atomic update if available */
if (vtpci_with_feature(hw, VIRTIO_NET_F_CTRL_MAC_ADDR)) {
struct virtio_pmd_ctrl ctrl;
int len = ETHER_ADDR_LEN;
ctrl.hdr.class = VIRTIO_NET_CTRL_MAC;
ctrl.hdr.cmd = VIRTIO_NET_CTRL_MAC_ADDR_SET;
memcpy(ctrl.data, mac_addr, ETHER_ADDR_LEN);
virtio_send_command(hw->cvq, &ctrl, &len, 1);
} else if (vtpci_with_feature(hw, VIRTIO_NET_F_MAC))
virtio_set_hwaddr(hw);
}
static int
virtio_vlan_filter_set(struct rte_eth_dev *dev, uint16_t vlan_id, int on)
{
struct virtio_hw *hw = dev->data->dev_private;
struct virtio_pmd_ctrl ctrl;
int len;
if (!vtpci_with_feature(hw, VIRTIO_NET_F_CTRL_VLAN))
return -ENOTSUP;
ctrl.hdr.class = VIRTIO_NET_CTRL_VLAN;
ctrl.hdr.cmd = on ? VIRTIO_NET_CTRL_VLAN_ADD : VIRTIO_NET_CTRL_VLAN_DEL;
memcpy(ctrl.data, &vlan_id, sizeof(vlan_id));
len = sizeof(vlan_id);
return virtio_send_command(hw->cvq, &ctrl, &len, 1);
}
static void
virtio_negotiate_features(struct virtio_hw *hw)
{
uint32_t host_features;
/* Prepare guest_features: feature that driver wants to support */
hw->guest_features = VIRTIO_PMD_GUEST_FEATURES;
PMD_INIT_LOG(DEBUG, "guest_features before negotiate = %x",
hw->guest_features);
/* Read device(host) feature bits */
host_features = VIRTIO_READ_REG_4(hw, VIRTIO_PCI_HOST_FEATURES);
PMD_INIT_LOG(DEBUG, "host_features before negotiate = %x",
host_features);
/*
* Negotiate features: Subset of device feature bits are written back
* guest feature bits.
*/
hw->guest_features = vtpci_negotiate_features(hw, host_features);
PMD_INIT_LOG(DEBUG, "features after negotiate = %x",
hw->guest_features);
}
#ifdef RTE_EXEC_ENV_LINUXAPP
static int
parse_sysfs_value(const char *filename, unsigned long *val)
{
FILE *f;
char buf[BUFSIZ];
char *end = NULL;
f = fopen(filename, "r");
if (f == NULL) {
PMD_INIT_LOG(ERR, "%s(): cannot open sysfs value %s",
__func__, filename);
return -1;
}
if (fgets(buf, sizeof(buf), f) == NULL) {
PMD_INIT_LOG(ERR, "%s(): cannot read sysfs value %s",
__func__, filename);
fclose(f);
return -1;
}
*val = strtoul(buf, &end, 0);
if ((buf[0] == '\0') || (end == NULL) || (*end != '\n')) {
PMD_INIT_LOG(ERR, "%s(): cannot parse sysfs value %s",
__func__, filename);
fclose(f);
return -1;
}
fclose(f);
return 0;
}
static int get_uio_dev(struct rte_pci_addr *loc, char *buf, unsigned int buflen,
unsigned int *uio_num)
{
struct dirent *e;
DIR *dir;
char dirname[PATH_MAX];
/* depending on kernel version, uio can be located in uio/uioX
* or uio:uioX */
snprintf(dirname, sizeof(dirname),
SYSFS_PCI_DEVICES "/" PCI_PRI_FMT "/uio",
loc->domain, loc->bus, loc->devid, loc->function);
dir = opendir(dirname);
if (dir == NULL) {
/* retry with the parent directory */
snprintf(dirname, sizeof(dirname),
SYSFS_PCI_DEVICES "/" PCI_PRI_FMT,
loc->domain, loc->bus, loc->devid, loc->function);
dir = opendir(dirname);
if (dir == NULL) {
PMD_INIT_LOG(ERR, "Cannot opendir %s", dirname);
return -1;
}
}
/* take the first file starting with "uio" */
while ((e = readdir(dir)) != NULL) {
/* format could be uio%d ...*/
int shortprefix_len = sizeof("uio") - 1;
/* ... or uio:uio%d */
int longprefix_len = sizeof("uio:uio") - 1;
char *endptr;
if (strncmp(e->d_name, "uio", 3) != 0)
continue;
/* first try uio%d */
errno = 0;
*uio_num = strtoull(e->d_name + shortprefix_len, &endptr, 10);
if (errno == 0 && endptr != (e->d_name + shortprefix_len)) {
snprintf(buf, buflen, "%s/uio%u", dirname, *uio_num);
break;
}
/* then try uio:uio%d */
errno = 0;
*uio_num = strtoull(e->d_name + longprefix_len, &endptr, 10);
if (errno == 0 && endptr != (e->d_name + longprefix_len)) {
snprintf(buf, buflen, "%s/uio:uio%u", dirname,
*uio_num);
break;
}
}
closedir(dir);
/* No uio resource found */
if (e == NULL) {
PMD_INIT_LOG(ERR, "Could not find uio resource");
return -1;
}
return 0;
}
static int
virtio_has_msix(const struct rte_pci_addr *loc)
{
DIR *d;
char dirname[PATH_MAX];
snprintf(dirname, sizeof(dirname),
SYSFS_PCI_DEVICES "/" PCI_PRI_FMT "/msi_irqs",
loc->domain, loc->bus, loc->devid, loc->function);
d = opendir(dirname);
if (d)
closedir(d);
return (d != NULL);
}
/* Extract I/O port numbers from sysfs */
static int virtio_resource_init_by_uio(struct rte_pci_device *pci_dev)
{
char dirname[PATH_MAX];
char filename[PATH_MAX];
unsigned long start, size;
unsigned int uio_num;
if (get_uio_dev(&pci_dev->addr, dirname, sizeof(dirname), &uio_num) < 0)
return -1;
/* get portio size */
snprintf(filename, sizeof(filename),
"%s/portio/port0/size", dirname);
if (parse_sysfs_value(filename, &size) < 0) {
PMD_INIT_LOG(ERR, "%s(): cannot parse size",
__func__);
return -1;
}
/* get portio start */
snprintf(filename, sizeof(filename),
"%s/portio/port0/start", dirname);
if (parse_sysfs_value(filename, &start) < 0) {
PMD_INIT_LOG(ERR, "%s(): cannot parse portio start",
__func__);
return -1;
}
pci_dev->mem_resource[0].addr = (void *)(uintptr_t)start;
pci_dev->mem_resource[0].len = (uint64_t)size;
PMD_INIT_LOG(DEBUG,
"PCI Port IO found start=0x%lx with size=0x%lx",
start, size);
/* save fd */
memset(dirname, 0, sizeof(dirname));
snprintf(dirname, sizeof(dirname), "/dev/uio%u", uio_num);
pci_dev->intr_handle.fd = open(dirname, O_RDWR);
if (pci_dev->intr_handle.fd < 0) {
PMD_INIT_LOG(ERR, "Cannot open %s: %s\n",
dirname, strerror(errno));
return -1;
}
pci_dev->intr_handle.type = RTE_INTR_HANDLE_UIO;
pci_dev->driver->drv_flags |= RTE_PCI_DRV_INTR_LSC;
return 0;
}
/* Extract port I/O numbers from proc/ioports */
static int virtio_resource_init_by_ioports(struct rte_pci_device *pci_dev)
{
uint16_t start, end;
int size;
FILE *fp;
char *line = NULL;
char pci_id[16];
int found = 0;
size_t linesz;
snprintf(pci_id, sizeof(pci_id), PCI_PRI_FMT,
pci_dev->addr.domain,
pci_dev->addr.bus,
pci_dev->addr.devid,
pci_dev->addr.function);
fp = fopen("/proc/ioports", "r");
if (fp == NULL) {
PMD_INIT_LOG(ERR, "%s(): can't open ioports", __func__);
return -1;
}
while (getdelim(&line, &linesz, '\n', fp) > 0) {
char *ptr = line;
char *left;
int n;
n = strcspn(ptr, ":");
ptr[n] = 0;
left = &ptr[n+1];
while (*left && isspace(*left))
left++;
if (!strncmp(left, pci_id, strlen(pci_id))) {
found = 1;
while (*ptr && isspace(*ptr))
ptr++;
sscanf(ptr, "%04hx-%04hx", &start, &end);
size = end - start + 1;
break;
}
}
free(line);
fclose(fp);
if (!found)
return -1;
pci_dev->mem_resource[0].addr = (void *)(uintptr_t)(uint32_t)start;
pci_dev->mem_resource[0].len = (uint64_t)size;
PMD_INIT_LOG(DEBUG,
"PCI Port IO found start=0x%x with size=0x%x",
start, size);
/* can't support lsc interrupt without uio */
pci_dev->driver->drv_flags &= ~RTE_PCI_DRV_INTR_LSC;
return 0;
}
/* Extract I/O port numbers from sysfs */
static int virtio_resource_init(struct rte_pci_device *pci_dev)
{
if (virtio_resource_init_by_uio(pci_dev) == 0)
return 0;
else
return virtio_resource_init_by_ioports(pci_dev);
}
#else
static int
virtio_has_msix(const struct rte_pci_addr *loc __rte_unused)
{
/* nic_uio does not enable interrupts, return 0 (false). */
return 0;
}
static int virtio_resource_init(struct rte_pci_device *pci_dev __rte_unused)
{
/* no setup required */
return 0;
}
#endif
/*
* Process Virtio Config changed interrupt and call the callback
* if link state changed.
*/
static void
virtio_interrupt_handler(__rte_unused struct rte_intr_handle *handle,
void *param)
{
struct rte_eth_dev *dev = param;
struct virtio_hw *hw = dev->data->dev_private;
uint8_t isr;
/* Read interrupt status which clears interrupt */
isr = vtpci_isr(hw);
PMD_DRV_LOG(INFO, "interrupt status = %#x", isr);
if (rte_intr_enable(&dev->pci_dev->intr_handle) < 0)
PMD_DRV_LOG(ERR, "interrupt enable failed");
if (isr & VIRTIO_PCI_ISR_CONFIG) {
if (virtio_dev_link_update(dev, 0) == 0)
_rte_eth_dev_callback_process(dev,
RTE_ETH_EVENT_INTR_LSC);
}
}
static void
rx_func_get(struct rte_eth_dev *eth_dev)
{
struct virtio_hw *hw = eth_dev->data->dev_private;
if (vtpci_with_feature(hw, VIRTIO_NET_F_MRG_RXBUF))
eth_dev->rx_pkt_burst = &virtio_recv_mergeable_pkts;
else
eth_dev->rx_pkt_burst = &virtio_recv_pkts;
}
/*
* This function is based on probe() function in virtio_pci.c
* It returns 0 on success.
*/
static int
eth_virtio_dev_init(struct rte_eth_dev *eth_dev)
{
struct virtio_hw *hw = eth_dev->data->dev_private;
struct virtio_net_config *config;
struct virtio_net_config local_config;
struct rte_pci_device *pci_dev;
RTE_BUILD_BUG_ON(RTE_PKTMBUF_HEADROOM < sizeof(struct virtio_net_hdr));
eth_dev->dev_ops = &virtio_eth_dev_ops;
eth_dev->tx_pkt_burst = &virtio_xmit_pkts;
if (rte_eal_process_type() == RTE_PROC_SECONDARY) {
rx_func_get(eth_dev);
return 0;
}
/* Allocate memory for storing MAC addresses */
eth_dev->data->mac_addrs = rte_zmalloc("virtio", VIRTIO_MAX_MAC_ADDRS * ETHER_ADDR_LEN, 0);
if (eth_dev->data->mac_addrs == NULL) {
PMD_INIT_LOG(ERR,
"Failed to allocate %d bytes needed to store MAC addresses",
VIRTIO_MAX_MAC_ADDRS * ETHER_ADDR_LEN);
return -ENOMEM;
}
pci_dev = eth_dev->pci_dev;
if (virtio_resource_init(pci_dev) < 0)
return -1;
hw->use_msix = virtio_has_msix(&pci_dev->addr);
hw->io_base = (uint32_t)(uintptr_t)pci_dev->mem_resource[0].addr;
/* Reset the device although not necessary at startup */
vtpci_reset(hw);
/* Tell the host we've noticed this device. */
vtpci_set_status(hw, VIRTIO_CONFIG_STATUS_ACK);
/* Tell the host we've known how to drive the device. */
vtpci_set_status(hw, VIRTIO_CONFIG_STATUS_DRIVER);
virtio_negotiate_features(hw);
/* If host does not support status then disable LSC */
if (!vtpci_with_feature(hw, VIRTIO_NET_F_STATUS))
pci_dev->driver->drv_flags &= ~RTE_PCI_DRV_INTR_LSC;
rte_eth_copy_pci_info(eth_dev, pci_dev);
rx_func_get(eth_dev);
/* Setting up rx_header size for the device */
if (vtpci_with_feature(hw, VIRTIO_NET_F_MRG_RXBUF))
hw->vtnet_hdr_size = sizeof(struct virtio_net_hdr_mrg_rxbuf);
else
hw->vtnet_hdr_size = sizeof(struct virtio_net_hdr);
/* Copy the permanent MAC address to: virtio_hw */
virtio_get_hwaddr(hw);
ether_addr_copy((struct ether_addr *) hw->mac_addr,
ð_dev->data->mac_addrs[0]);
PMD_INIT_LOG(DEBUG,
"PORT MAC: %02X:%02X:%02X:%02X:%02X:%02X",
hw->mac_addr[0], hw->mac_addr[1], hw->mac_addr[2],
hw->mac_addr[3], hw->mac_addr[4], hw->mac_addr[5]);
if (vtpci_with_feature(hw, VIRTIO_NET_F_CTRL_VQ)) {
config = &local_config;
vtpci_read_dev_config(hw,
offsetof(struct virtio_net_config, mac),
&config->mac, sizeof(config->mac));
if (vtpci_with_feature(hw, VIRTIO_NET_F_STATUS)) {
vtpci_read_dev_config(hw,
offsetof(struct virtio_net_config, status),
&config->status, sizeof(config->status));
} else {
PMD_INIT_LOG(DEBUG,
"VIRTIO_NET_F_STATUS is not supported");
config->status = 0;
}
if (vtpci_with_feature(hw, VIRTIO_NET_F_MQ)) {
vtpci_read_dev_config(hw,
offsetof(struct virtio_net_config, max_virtqueue_pairs),
&config->max_virtqueue_pairs,
sizeof(config->max_virtqueue_pairs));
} else {
PMD_INIT_LOG(DEBUG,
"VIRTIO_NET_F_MQ is not supported");
config->max_virtqueue_pairs = 1;
}
hw->max_rx_queues =
(VIRTIO_MAX_RX_QUEUES < config->max_virtqueue_pairs) ?
VIRTIO_MAX_RX_QUEUES : config->max_virtqueue_pairs;
hw->max_tx_queues =
(VIRTIO_MAX_TX_QUEUES < config->max_virtqueue_pairs) ?
VIRTIO_MAX_TX_QUEUES : config->max_virtqueue_pairs;
virtio_dev_cq_queue_setup(eth_dev,
config->max_virtqueue_pairs * 2,
SOCKET_ID_ANY);
PMD_INIT_LOG(DEBUG, "config->max_virtqueue_pairs=%d",
config->max_virtqueue_pairs);
PMD_INIT_LOG(DEBUG, "config->status=%d", config->status);
PMD_INIT_LOG(DEBUG,
"PORT MAC: %02X:%02X:%02X:%02X:%02X:%02X",
config->mac[0], config->mac[1],
config->mac[2], config->mac[3],
config->mac[4], config->mac[5]);
} else {
hw->max_rx_queues = 1;
hw->max_tx_queues = 1;
}
eth_dev->data->nb_rx_queues = hw->max_rx_queues;
eth_dev->data->nb_tx_queues = hw->max_tx_queues;
PMD_INIT_LOG(DEBUG, "hw->max_rx_queues=%d hw->max_tx_queues=%d",
hw->max_rx_queues, hw->max_tx_queues);
PMD_INIT_LOG(DEBUG, "port %d vendorID=0x%x deviceID=0x%x",
eth_dev->data->port_id, pci_dev->id.vendor_id,
pci_dev->id.device_id);
/* Setup interrupt callback */
if (pci_dev->driver->drv_flags & RTE_PCI_DRV_INTR_LSC)
rte_intr_callback_register(&pci_dev->intr_handle,
virtio_interrupt_handler, eth_dev);
virtio_dev_cq_start(eth_dev);
return 0;
}
static int
eth_virtio_dev_uninit(struct rte_eth_dev *eth_dev)
{
struct rte_pci_device *pci_dev;
struct virtio_hw *hw = eth_dev->data->dev_private;
PMD_INIT_FUNC_TRACE();
if (rte_eal_process_type() == RTE_PROC_SECONDARY)
return -EPERM;
if (hw->started == 1) {
virtio_dev_stop(eth_dev);
virtio_dev_close(eth_dev);
}
pci_dev = eth_dev->pci_dev;
eth_dev->dev_ops = NULL;
eth_dev->tx_pkt_burst = NULL;
eth_dev->rx_pkt_burst = NULL;
virtio_dev_queue_release(hw->cvq);
rte_free(eth_dev->data->mac_addrs);
eth_dev->data->mac_addrs = NULL;
/* reset interrupt callback */
if (pci_dev->driver->drv_flags & RTE_PCI_DRV_INTR_LSC)
rte_intr_callback_unregister(&pci_dev->intr_handle,
virtio_interrupt_handler,
eth_dev);
PMD_INIT_LOG(DEBUG, "dev_uninit completed");
return 0;
}
static struct eth_driver rte_virtio_pmd = {
.pci_drv = {
.name = "rte_virtio_pmd",
.id_table = pci_id_virtio_map,
.drv_flags = RTE_PCI_DRV_DETACHABLE,
},
.eth_dev_init = eth_virtio_dev_init,
.eth_dev_uninit = eth_virtio_dev_uninit,
.dev_private_size = sizeof(struct virtio_hw),
};
/*
* Driver initialization routine.
* Invoked once at EAL init time.
* Register itself as the [Poll Mode] Driver of PCI virtio devices.
* Returns 0 on success.
*/
static int
rte_virtio_pmd_init(const char *name __rte_unused,
const char *param __rte_unused)
{
if (rte_eal_iopl_init() != 0) {
PMD_INIT_LOG(ERR, "IOPL call failed - cannot use virtio PMD");
return -1;
}
rte_eth_driver_register(&rte_virtio_pmd);
return 0;
}
/*
* Configure virtio device
* It returns 0 on success.
*/
static int
virtio_dev_configure(struct rte_eth_dev *dev)
{
const struct rte_eth_rxmode *rxmode = &dev->data->dev_conf.rxmode;
struct virtio_hw *hw = dev->data->dev_private;
struct rte_pci_device *pci_dev = dev->pci_dev;
PMD_INIT_LOG(DEBUG, "configure");
if (rxmode->hw_ip_checksum) {
PMD_DRV_LOG(ERR, "HW IP checksum not supported");
return (-EINVAL);
}
hw->vlan_strip = rxmode->hw_vlan_strip;
if (rxmode->hw_vlan_filter
&& !vtpci_with_feature(hw, VIRTIO_NET_F_CTRL_VLAN)) {
PMD_DRV_LOG(NOTICE,
"vlan filtering not available on this host");
return -ENOTSUP;
}
if (pci_dev->driver->drv_flags & RTE_PCI_DRV_INTR_LSC)
if (vtpci_irq_config(hw, 0) == VIRTIO_MSI_NO_VECTOR) {
PMD_DRV_LOG(ERR, "failed to set config vector");
return -EBUSY;
}
return 0;
}
static int
virtio_dev_start(struct rte_eth_dev *dev)
{
uint16_t nb_queues, i;
struct virtio_hw *hw = dev->data->dev_private;
struct rte_pci_device *pci_dev = dev->pci_dev;
/* check if lsc interrupt feature is enabled */
if (dev->data->dev_conf.intr_conf.lsc) {
if (!(pci_dev->driver->drv_flags & RTE_PCI_DRV_INTR_LSC)) {
PMD_DRV_LOG(ERR, "link status not supported by host");
return -ENOTSUP;
}
if (rte_intr_enable(&dev->pci_dev->intr_handle) < 0) {
PMD_DRV_LOG(ERR, "interrupt enable failed");
return -EIO;
}
}
/* Initialize Link state */
virtio_dev_link_update(dev, 0);
/* On restart after stop do not touch queues */
if (hw->started)
return 0;
/* Do final configuration before rx/tx engine starts */
virtio_dev_rxtx_start(dev);
vtpci_reinit_complete(hw);
hw->started = 1;
/*Notify the backend
*Otherwise the tap backend might already stop its queue due to fullness.
*vhost backend will have no chance to be waked up
*/
nb_queues = dev->data->nb_rx_queues;
if (nb_queues > 1) {
if (virtio_set_multiple_queues(dev, nb_queues) != 0)
return -EINVAL;
}
PMD_INIT_LOG(DEBUG, "nb_queues=%d", nb_queues);
for (i = 0; i < nb_queues; i++)
virtqueue_notify(dev->data->rx_queues[i]);
PMD_INIT_LOG(DEBUG, "Notified backend at initialization");
for (i = 0; i < dev->data->nb_rx_queues; i++)
VIRTQUEUE_DUMP((struct virtqueue *)dev->data->rx_queues[i]);
for (i = 0; i < dev->data->nb_tx_queues; i++)
VIRTQUEUE_DUMP((struct virtqueue *)dev->data->tx_queues[i]);
return 0;
}
static void virtio_dev_free_mbufs(struct rte_eth_dev *dev)
{
struct rte_mbuf *buf;
int i, mbuf_num = 0;
for (i = 0; i < dev->data->nb_rx_queues; i++) {
PMD_INIT_LOG(DEBUG,
"Before freeing rxq[%d] used and unused buf", i);
VIRTQUEUE_DUMP((struct virtqueue *)dev->data->rx_queues[i]);
PMD_INIT_LOG(DEBUG, "rx_queues[%d]=%p",
i, dev->data->rx_queues[i]);
while ((buf = (struct rte_mbuf *)virtqueue_detatch_unused(
dev->data->rx_queues[i])) != NULL) {
rte_pktmbuf_free(buf);
mbuf_num++;
}
PMD_INIT_LOG(DEBUG, "free %d mbufs", mbuf_num);
PMD_INIT_LOG(DEBUG,
"After freeing rxq[%d] used and unused buf", i);
VIRTQUEUE_DUMP((struct virtqueue *)dev->data->rx_queues[i]);
}
for (i = 0; i < dev->data->nb_tx_queues; i++) {
PMD_INIT_LOG(DEBUG,
"Before freeing txq[%d] used and unused bufs",
i);
VIRTQUEUE_DUMP((struct virtqueue *)dev->data->tx_queues[i]);
mbuf_num = 0;
while ((buf = (struct rte_mbuf *)virtqueue_detatch_unused(
dev->data->tx_queues[i])) != NULL) {
rte_pktmbuf_free(buf);
mbuf_num++;
}
PMD_INIT_LOG(DEBUG, "free %d mbufs", mbuf_num);
PMD_INIT_LOG(DEBUG,
"After freeing txq[%d] used and unused buf", i);
VIRTQUEUE_DUMP((struct virtqueue *)dev->data->tx_queues[i]);
}
}
/*
* Stop device: disable interrupt and mark link down
*/
static void
virtio_dev_stop(struct rte_eth_dev *dev)
{
struct rte_eth_link link;
PMD_INIT_LOG(DEBUG, "stop");
if (dev->data->dev_conf.intr_conf.lsc)
rte_intr_disable(&dev->pci_dev->intr_handle);
memset(&link, 0, sizeof(link));
virtio_dev_atomic_write_link_status(dev, &link);
}
static int
virtio_dev_link_update(struct rte_eth_dev *dev, __rte_unused int wait_to_complete)
{
struct rte_eth_link link, old;
uint16_t status;
struct virtio_hw *hw = dev->data->dev_private;
memset(&link, 0, sizeof(link));
virtio_dev_atomic_read_link_status(dev, &link);
old = link;
link.link_duplex = FULL_DUPLEX;
link.link_speed = SPEED_10G;
if (vtpci_with_feature(hw, VIRTIO_NET_F_STATUS)) {
PMD_INIT_LOG(DEBUG, "Get link status from hw");
vtpci_read_dev_config(hw,
offsetof(struct virtio_net_config, status),
&status, sizeof(status));
if ((status & VIRTIO_NET_S_LINK_UP) == 0) {
link.link_status = 0;
PMD_INIT_LOG(DEBUG, "Port %d is down",
dev->data->port_id);
} else {
link.link_status = 1;
PMD_INIT_LOG(DEBUG, "Port %d is up",
dev->data->port_id);
}
} else {
link.link_status = 1; /* Link up */
}
virtio_dev_atomic_write_link_status(dev, &link);
return (old.link_status == link.link_status) ? -1 : 0;
}
static void
virtio_dev_info_get(struct rte_eth_dev *dev, struct rte_eth_dev_info *dev_info)
{
struct virtio_hw *hw = dev->data->dev_private;
dev_info->driver_name = dev->driver->pci_drv.name;
dev_info->max_rx_queues = (uint16_t)hw->max_rx_queues;
dev_info->max_tx_queues = (uint16_t)hw->max_tx_queues;
dev_info->min_rx_bufsize = VIRTIO_MIN_RX_BUFSIZE;
dev_info->max_rx_pktlen = VIRTIO_MAX_RX_PKTLEN;
dev_info->max_mac_addrs = VIRTIO_MAX_MAC_ADDRS;
dev_info->default_txconf = (struct rte_eth_txconf) {
.txq_flags = ETH_TXQ_FLAGS_NOOFFLOADS
};
}
/*
* It enables testpmd to collect per queue stats.
*/
static int
virtio_dev_queue_stats_mapping_set(__rte_unused struct rte_eth_dev *eth_dev,
__rte_unused uint16_t queue_id, __rte_unused uint8_t stat_idx,
__rte_unused uint8_t is_rx)
{
return 0;
}
static struct rte_driver rte_virtio_driver = {
.type = PMD_PDEV,
.init = rte_virtio_pmd_init,
};
PMD_REGISTER_DRIVER(rte_virtio_driver);
| 27.467494 | 92 | 0.706165 | [
"vector"
] |
d92bd14efcf2e6a2476f85e927e2eec2d091c988 | 963 | h | C | Code/EditorPlugins/Assets/EnginePluginAssets/EnginePluginAssetsPCH.h | Tekh-ops/ezEngine | d6a5887d8709f267bf8f2943ef15054e29f6d3d5 | [
"MIT"
] | 703 | 2015-03-07T15:30:40.000Z | 2022-03-30T00:12:40.000Z | Code/EditorPlugins/Assets/EnginePluginAssets/EnginePluginAssetsPCH.h | Tekh-ops/ezEngine | d6a5887d8709f267bf8f2943ef15054e29f6d3d5 | [
"MIT"
] | 233 | 2015-01-11T16:54:32.000Z | 2022-03-19T18:00:47.000Z | Code/EditorPlugins/Assets/EnginePluginAssets/EnginePluginAssetsPCH.h | Tekh-ops/ezEngine | d6a5887d8709f267bf8f2943ef15054e29f6d3d5 | [
"MIT"
] | 101 | 2016-10-28T14:05:10.000Z | 2022-03-30T19:00:59.000Z | #pragma once
#include <Foundation/Basics.h>
// <StaticLinkUtil::StartHere>
// all include's before this will be left alone and not replaced by the StaticLinkUtil
// all include's AFTER this will be removed by the StaticLinkUtil and updated by what is actually used throughout the library
#include <EnginePluginAssets/EnginePluginAssetsDLL.h>
#include <Core/Graphics/Geometry.h>
#include <Core/ResourceManager/ResourceManager.h>
#include <Core/World/Component.h>
#include <Core/World/GameObject.h>
#include <EditorEngineProcessFramework/EngineProcess/EngineProcessDocumentContext.h>
#include <Foundation/Containers/DynamicArray.h>
#include <Foundation/IO/FileSystem/FileSystem.h>
#include <Foundation/Logging/Log.h>
#include <Foundation/Strings/StringBuilder.h>
#include <GameEngine/GameApplication/GameApplication.h>
#include <RendererCore/Pipeline/View.h>
#include <RendererCore/RenderContext/RenderContext.h>
#include <SharedPluginAssets/Common/Messages.h>
| 40.125 | 125 | 0.817238 | [
"geometry"
] |
d92e8cbe2756aef6df39ea5835d1453dfe7878f2 | 1,081 | h | C | src/MapsData.h | jicese/Maps | cf8e62d5667799b547c9af1d45f8fefa4f8defc7 | [
"MIT"
] | null | null | null | src/MapsData.h | jicese/Maps | cf8e62d5667799b547c9af1d45f8fefa4f8defc7 | [
"MIT"
] | null | null | null | src/MapsData.h | jicese/Maps | cf8e62d5667799b547c9af1d45f8fefa4f8defc7 | [
"MIT"
] | null | null | null | /*
* Copyright 2016-2017 Raefaldhi Amartya Junior <raefaldhiamartya@gmail.com>
* All rights reserved. Distributed under the terms of the MIT license.
*/
#ifndef MAPSDATA_H
#define MAPSDATA_H
#include <vector>
#include <Handler.h>
#include <UrlRequest.h>
class MapsData_Listener;
enum {
MAPDATA_UPDATE = 'mdud'
};
struct MapsVector {
int width;
int height;
float scale;
float longitude;
float latitude;
float zoom;
float bearing;
float pitch;
};
class MapsData {
protected:
MapsData();
~MapsData();
static BMallocIO* data;
static std::vector<BHandler*> handler;
public:
static void Initialize(int, int);
static void Retrieve();
static void SetLongitude(float);
static void SetLatitude(float);
static void SetZoom(float);
static void SetSize(float, float);
static BMallocIO* Get();
static void AddHandler(BHandler*);
static MapsVector GetVector();
private:
static MapsVector mapsVector;
static thread_id thread;
static BUrlRequest* request;
static MapsData_Listener* listener;
static BString baseUrl;
};
#endif // MAPSDATA_H
| 16.890625 | 76 | 0.736355 | [
"vector"
] |
d947dcda0654b0ad12ddbb54d003c02a35b0b2c8 | 6,135 | h | C | src/CycleOptimization/edge_annotations_gauss.h | anapupa/ReebHanTun | 679ba774b75f4f53c502cb79f69bc9061c009eb8 | [
"Unlicense"
] | null | null | null | src/CycleOptimization/edge_annotations_gauss.h | anapupa/ReebHanTun | 679ba774b75f4f53c502cb79f69bc9061c009eb8 | [
"Unlicense"
] | null | null | null | src/CycleOptimization/edge_annotations_gauss.h | anapupa/ReebHanTun | 679ba774b75f4f53c502cb79f69bc9061c009eb8 | [
"Unlicense"
] | null | null | null | /*
(c) 2012 Fengtao Fan
*/
#ifndef _My_EDGE_ANNOTATION_COMPUTING_GAUSS_
#define _My_EDGE_ANNOTATION_COMPUTING_GAUSS_
#include "SimpleMesh.h"
#include <vector>
#include <set>
#ifndef My_Annotation_Type
#define My_Annotation_Type
typedef std::vector<char> Annotation_Type;
#endif
//
#ifndef myFloatIntPairLessThan_
#define myFloatIntPairLessThan_
struct myFloatIntPairLessThan {
bool operator()(const std::pair<float, int> &lhs, const std::pair<float, int> &rhs) {
bool ret = false;
if (lhs.first < rhs.first)
ret = true;
else if (lhs.first == rhs.first) {
if (lhs.second < rhs.second)
ret = true;
}
return ret;
}
};
#endif
struct Annotation_Type_LessThan {
bool operator()(const Annotation_Type &lhs, const Annotation_Type &rhs) {
bool ret = false;
for (unsigned int i = 0; i < lhs.size(); i++) {
if (lhs[i] < rhs[i]) {
ret = true;
break;
} else {
if (lhs[i] > rhs[i]) {
ret = false;
break;
}
}
}
return ret;
}
};
class edge_annotation_computing {
public:
edge_annotation_computing() {
}
~edge_annotation_computing() {
meshPtr = NULL;
//graphPtr = NULL;
}
//
void SetMeshPtr(_SimpleMesh *inMeshPtr) {
meshPtr = inMeshPtr;
}
void SetEdgeSize(const int n) {
//edge_size = n;
}
//
bool IndependenceCheck(std::vector<Annotation_Type> &bReducedVec,
std::vector<int> &lowestOnePtr,
Annotation_Type &objVector);
//
bool ReduceMatrix(std::vector<Annotation_Type> &annMatrix, std::vector<int> &lowestOnePos);
bool GaussianElimination(std::vector<Annotation_Type> &vec);
//
void ReadEdgeAnnotationsFromFile(const char *file_name);
void AssignEdgeAnnotations(std::vector<Annotation_Type> &existEdgeVec) {
if (!edge_annotations.empty()) {
edge_annotations.clear();
}
edge_annotations = existEdgeVec;
}
//
bool CheckZeroAnnotationsAndReturnAnnotation(std::set<int> &cycle, Annotation_Type &res);
bool CheckZeroAnnotationsAndReturnAnnotation(std::vector<int> &cycle, Annotation_Type &res);
//
bool ComputeShortestCanonicalLoops(std::vector<std::vector<int> > &basis_loops,
std::vector<Annotation_Type> &basis_annotations,
std::vector<std::set<int> > &canonical_loops,
std::vector<int> &non_tree_edges,
std::vector<Annotation_Type> &canonical_loops_annotation,
std::set<std::pair<float, int>, myFloatIntPairLessThan> &sorted_loops,
std::vector<std::set<int> > &short_basis_loops,
std::vector<int> &basis_non_tree_edges);
//
bool ComputeShortestCanonicalLoops(std::vector<std::vector<int> > &basis_loops,
std::vector<Annotation_Type> &basis_annotations,
std::vector<Annotation_Type> &reduced_basis_annotations,
std::vector<int> &basis_LowestOnePos,
std::vector<std::set<int> > &canonical_loops,
std::vector<int> &non_tree_edges,
std::vector<Annotation_Type> &canonical_loops_annotation,
std::set<std::pair<float, int>, myFloatIntPairLessThan> &sorted_loops,
std::vector<std::set<int> > &short_basis_loops,
std::vector<int> &basis_non_tree_edges);
//
bool CheckTwoGroupVectorOrthogonality(std::vector<std::vector<int> > &a_loops, std::vector<Annotation_Type> &a_ann,
std::vector<std::vector<int> > &b_loops, std::vector<Annotation_Type> &b_ann);
bool CheckTwoGroupVectorOrthogonality(std::vector<std::vector<int> > &a_loops, std::vector<Annotation_Type> &a_ann,
std::vector<Annotation_Type> &reduced_a_ann, std::vector<int> &a_lowestOne,
std::vector<std::vector<int> > &b_loops, std::vector<Annotation_Type> &b_ann,
std::vector<Annotation_Type> &reduced_b_ann, std::vector<int> &b_lowestOne);
void Add(const Annotation_Type &lhs, const Annotation_Type &rhs, Annotation_Type &res) {
for (unsigned int i = 0; i < lhs.size(); i++) {
res[i] = lhs[i] ^ rhs[i];
}
}
void Times(const Annotation_Type &lhs, const Annotation_Type &rhs, Annotation_Type &res) {
for (unsigned int i = 0; i < lhs.size(); i++) {
res[i] = lhs[i] & rhs[i];
}
}
bool IsZeroAnnotation(const Annotation_Type &ins) {
int sum = 0;
for (unsigned int i = 0; i < ins.size(); i++)
sum += ins[i];
return !(sum);
}
bool IsEqual(const Annotation_Type &lhs, const Annotation_Type &rhs) {
bool ret = true;
for (unsigned int i = 0; i < lhs.size(); i++) {
if (lhs[i] != rhs[i]) {
ret = false;
break;
}
}
return ret;
}
public:
/*
*/
_SimpleMesh *meshPtr;
//int edge_size;
std::vector<Annotation_Type> edge_annotations;
int vec_size;
//
//std::vector<Annotation_Type> reducedHandleBasis;
//std::vector<int> handleLowestOnePos;
////
//std::vector<Annotation_Type> reducedTunnelBasis;
//std::vector<int> tunnelLowestOnePos;
};
#endif //GAUSS_
| 35.057143 | 121 | 0.531214 | [
"vector"
] |
d94ccfb27c32f370cbc1b79926f217256f7b14ae | 3,365 | h | C | Sources/Elastos/LibCore/inc/elastos/text/FormatBase.h | jingcao80/Elastos | d0f39852356bdaf3a1234743b86364493a0441bc | [
"Apache-2.0"
] | 7 | 2017-07-13T10:34:54.000Z | 2021-04-16T05:40:35.000Z | Sources/Elastos/LibCore/inc/elastos/text/FormatBase.h | jingcao80/Elastos | d0f39852356bdaf3a1234743b86364493a0441bc | [
"Apache-2.0"
] | null | null | null | Sources/Elastos/LibCore/inc/elastos/text/FormatBase.h | jingcao80/Elastos | d0f39852356bdaf3a1234743b86364493a0441bc | [
"Apache-2.0"
] | 9 | 2017-07-13T12:33:20.000Z | 2021-06-19T02:46:48.000Z | //=========================================================================
// Copyright (C) 2012 The Elastos Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//=========================================================================
#ifndef __ELASTOS_TEXT_FORMATBASE_H_
#define __ELASTOS_TEXT_FORMATBASE_H_
#include "elastos/core/Object.h"
#include "elastos/core/StringBuffer.h"
#include "AttributedCharacterIteratorAttribute.h"
using Elastos::Core::EIID_ICloneable;
using Elastos::Text::IAttributedCharacterIterator;;
using Elastos::Text::IFieldPosition;
using Elastos::Text::IParsePosition;
using Elastos::Core::StringBuffer;
using Elastos::Core::IStringBuffer;
using Elastos::Core::ICloneable;
namespace Elastos {
namespace Text {
class FormatBase
: public Object
, public IFormat
, public ISerializable
, public ICloneable
{
public:
class Field
: public AttributedCharacterIteratorAttribute
{
protected:
CARAPI constructor(
/* [in] */ const String& fieldName)
{
return AttributedCharacterIteratorAttribute::constructor(fieldName);
}
CARAPI GetClassID(
/* [out] */ ClassID* clsid)
{
assert(0 && "TODO");
return NOERROR;
// return _Field::GetClassID(clsid);
}
};
public:
CAR_INTERFACE_DECL()
virtual CARAPI Clone(
/* [out] */ IInterface** outobj) = 0;
CARAPI CloneImpl(
/* [in] */ IFormat* format);
virtual ~FormatBase();
virtual CARAPI Format(
/* [in] */ IInterface* object,
/* [out] */ String* value);
virtual CARAPI Format(
/* [in] */ IInterface* object,
/* [in] */ IStringBuffer * buffer,
/* [in] */ IFieldPosition* field) = 0;
virtual CARAPI FormatToCharacterIterator(
/* [in] */ IInterface* object,
/* [out] */ IAttributedCharacterIterator** characterIterator);
virtual CARAPI ParseObject(
/* [in] */ const String& string,
/* [out] */ IInterface** object);
virtual CARAPI ParseObject(
/* [in] */ const String& string,
/* [in] */ IParsePosition* position,
/* [out] */ IInterface** object) = 0;
protected:
FormatBase();
static CARAPI UpTo(
/* [in] */ const String& string,
/* [in] */ IParsePosition* position,
/* [in] */ StringBuffer& buffer,
/* [in] */ Char32 stop,
/* [out] */ Boolean* succeeded);
static CARAPI UpToWithQuotes(
/* [in] */ const String& string,
/* [in] */ IParsePosition* position,
/* [in] */ StringBuffer& buffer,
/* [in] */ Char32 stop,
/* [in] */ Char32 start,
/* [out] */ Boolean* succeeded);
};
} // namespace Text
} // namespace Elastos
#endif //__ELASTOS_TEXT_FORMATBASE_H_
| 28.760684 | 80 | 0.598514 | [
"object"
] |
d9502b1c77c4c77e13c10c06e6c485d452db6422 | 25,462 | c | C | src/ltr/gt_ltrdigest.c | satta/genometools | 3955d63c95e142c2475e1436206fddf0eb29185d | [
"BSD-2-Clause"
] | 202 | 2015-01-08T10:09:57.000Z | 2022-03-31T09:45:44.000Z | src/ltr/gt_ltrdigest.c | satta/genometools | 3955d63c95e142c2475e1436206fddf0eb29185d | [
"BSD-2-Clause"
] | 286 | 2015-01-05T16:29:27.000Z | 2022-03-30T21:19:03.000Z | src/ltr/gt_ltrdigest.c | satta/genometools | 3955d63c95e142c2475e1436206fddf0eb29185d | [
"BSD-2-Clause"
] | 56 | 2015-01-19T11:33:22.000Z | 2022-03-21T21:47:05.000Z | /*
Copyright (c) 2008-2013 Sascha Steinbiss <steinbiss@zbh.uni-hamburg.de>
Copyright (c) 2008-2013 Center for Bioinformatics, University of Hamburg
Permission to use, copy, modify, and distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, 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.
*/
#include <ctype.h>
#include <string.h>
#include "core/bioseq_api.h"
#include "core/encseq.h"
#include "core/fileutils_api.h"
#include "core/log.h"
#include "core/logger.h"
#include "core/ma_api.h"
#include "core/option_api.h"
#include "core/output_file_api.h"
#include "core/range_api.h"
#include "core/safearith_api.h"
#include "core/unused_api.h"
#include "core/warning_api.h"
#include "extended/gff3_in_stream.h"
#include "extended/gff3_out_stream_api.h"
#include "extended/region_mapping.h"
#include "extended/seqid2file_api.h"
#include "extended/visitor_stream.h"
#include "ltr/gt_ltrdigest.h"
#include "ltr/ltr_input_check_visitor.h"
#include "ltr/ltrdigest_def.h"
#include "ltr/ltrdigest_file_out_stream.h"
#include "ltr/ltrdigest_pbs_visitor.h"
#include "ltr/ltrdigest_pdom_visitor.h"
#include "ltr/ltrdigest_ppt_visitor.h"
#include "ltr/ltrdigest_strand_assign_visitor.h"
#include "ltr/pdom_model_set.h"
typedef struct GtLTRdigestOptions {
GtStr *trna_lib, *prefix, *cutoffs;
bool verbose,
write_alignments,
write_aaseqs,
output_all_chains,
print_metadata,
force_recreate;
GtOutputFileInfo *ofi;
GtFile *outfp;
GtStrArray *hmm_files;
GtSeqid2FileInfo *s2fi;
GtPdomCutoff cutoff;
double evalue_cutoff;
GtUword nthreads;
unsigned int chain_max_gap_length,
seqnamelen;
GtRange ppt_len, ubox_len;
double ppt_pyrimidine_prob,
ppt_purine_prob,
bkg_a_prob,
bkg_g_prob,
bkg_t_prob,
bkg_c_prob,
ubox_u_prob;
unsigned int ppt_radius,
max_ubox_dist;
unsigned int pbs_radius,
max_edist;
GtRange alilen,
offsetlen,
trnaoffsetlen;
int ali_score_match,
ali_score_mismatch,
ali_score_insertion,
ali_score_deletion;
GtBioseq *trna_lib_bs;
} GtLTRdigestOptions;
static void* gt_ltrdigest_arguments_new(void)
{
GtLTRdigestOptions *arguments = gt_calloc((size_t) 1, sizeof *arguments);
memset(arguments, 0, sizeof *arguments);
arguments->trna_lib = gt_str_new();
arguments->prefix = gt_str_new();
arguments->cutoffs = gt_str_new();
arguments->ofi = gt_output_file_info_new();
arguments->hmm_files = gt_str_array_new();
arguments->s2fi = gt_seqid2file_info_new();
return arguments;
}
static void gt_ltrdigest_arguments_delete(void *tool_arguments)
{
GtLTRdigestOptions *arguments = tool_arguments;
if (!arguments) return;
gt_str_delete(arguments->trna_lib);
gt_str_delete(arguments->prefix);
gt_str_delete(arguments->cutoffs);
gt_str_array_delete(arguments->hmm_files);
gt_file_delete(arguments->outfp);
gt_output_file_info_delete(arguments->ofi);
gt_seqid2file_info_delete(arguments->s2fi);
gt_free(arguments);
}
static GtOptionParser* gt_ltrdigest_option_parser_new(void *tool_arguments)
{
GtLTRdigestOptions *arguments = tool_arguments;
GtOptionParser *op;
GtOption *o, *ot, *oto;
GtOption *oh, *oc, *oeval;
static const char *cutoffs[] = {"NONE", "GA", "TC", NULL};
static GtRange pptlen_defaults = { 8UL, 30UL},
uboxlen_defaults = { 3UL, 30UL},
pbsalilen_defaults = {11UL, 30UL},
pbsoffsetlen_defaults = { 0UL, 5UL},
pbstrnaoffsetlen_defaults = { 0UL, 5UL};
gt_assert(arguments);
/* init */
op = gt_option_parser_new("[option ...] gff3_file",
"Identifies and annotates sequence features in LTR "
"retrotransposon candidates.");
/* Output files */
oto = gt_option_new_string("outfileprefix",
"prefix for output files (e.g. 'foo' will create "
"files called 'foo_*.csv' and 'foo_*.fas')\n"
"Omit this option for GFF3 output only.",
arguments->prefix,
NULL);
gt_option_parser_add_option(op, oto);
gt_option_hide_default(oto);
o = gt_option_new_bool("metadata",
"output metadata (run conditions) to separate file",
&arguments->print_metadata,
true);
gt_option_parser_add_option(op, o);
gt_option_imply(o, oto);
o = gt_option_new_uint("seqnamelen",
"set maximal length of sequence names in FASTA headers"
" (e.g. for clustalw or similar tools)",
&arguments->seqnamelen,
20U);
gt_option_parser_add_option(op, o);
/* PPT search options */
o = gt_option_new_range("pptlen",
"required PPT length range",
&arguments->ppt_len,
&pptlen_defaults);
gt_option_parser_add_option(op, o);
o = gt_option_new_range("uboxlen",
"required U-box length range",
&arguments->ubox_len,
&uboxlen_defaults);
gt_option_parser_add_option(op, o);
o = gt_option_new_uint("uboxdist",
"allowed U-box distance range from PPT",
&arguments->max_ubox_dist, 0);
gt_option_parser_add_option(op, o);
o = gt_option_new_uint("pptradius",
"radius around beginning of 3' LTR "
"to search for PPT",
&arguments->ppt_radius,
30U);
gt_option_parser_add_option(op, o);
o = gt_option_new_probability("pptrprob",
"purine emission probability inside PPT",
&arguments->ppt_purine_prob,
PPT_PURINE_PROB);
gt_option_parser_add_option(op, o);
gt_option_is_extended_option(o);
o = gt_option_new_probability("pptyprob",
"pyrimidine emission probability inside PPT",
&arguments->ppt_pyrimidine_prob,
PPT_PYRIMIDINE_PROB);
gt_option_parser_add_option(op, o);
gt_option_is_extended_option(o);
o = gt_option_new_probability("pptgprob",
"background G emission probability outside PPT",
&arguments->bkg_g_prob,
BKG_G_PROB);
gt_option_parser_add_option(op, o);
gt_option_is_extended_option(o);
o = gt_option_new_probability("pptcprob",
"background C emission probability outside PPT",
&arguments->bkg_c_prob,
BKG_C_PROB);
gt_option_parser_add_option(op, o);
gt_option_is_extended_option(o);
o = gt_option_new_probability("pptaprob",
"background A emission probability outside PPT",
&arguments->bkg_a_prob,
BKG_A_PROB);
gt_option_parser_add_option(op, o);
gt_option_is_extended_option(o);
o = gt_option_new_probability("ppttprob",
"background T emission probability outside PPT",
&arguments->bkg_t_prob,
BKG_T_PROB);
gt_option_parser_add_option(op, o);
gt_option_is_extended_option(o);
o = gt_option_new_probability("pptuprob",
"U/T emission probability inside U-box",
&arguments->ubox_u_prob,
UBOX_U_PROB);
gt_option_parser_add_option(op, o);
gt_option_is_extended_option(o);
/* PBS search options */
ot = gt_option_new_filename("trnas",
"tRNA library in multiple FASTA format for PBS "
"detection\n"
"Omit this option to disable PBS search.",
arguments->trna_lib);
gt_option_parser_add_option(op, ot);
gt_option_hide_default(ot);
o = gt_option_new_range("pbsalilen",
"required PBS/tRNA alignment length range",
&arguments->alilen,
&pbsalilen_defaults);
gt_option_parser_add_option(op, o);
gt_option_imply(o, ot);
o = gt_option_new_range("pbsoffset",
"allowed PBS offset from LTR boundary range",
&arguments->offsetlen,
&pbsoffsetlen_defaults);
gt_option_parser_add_option(op, o);
gt_option_imply(o, ot);
o = gt_option_new_range("pbstrnaoffset",
"allowed PBS/tRNA 3' end alignment offset range",
&arguments->trnaoffsetlen,
&pbstrnaoffsetlen_defaults);
gt_option_parser_add_option(op, o);
gt_option_imply(o, ot);
o = gt_option_new_uint("pbsmaxedist",
"maximal allowed PBS/tRNA alignment unit "
"edit distance",
&arguments->max_edist,
1U);
gt_option_parser_add_option(op, o);
gt_option_imply(o, ot);
o = gt_option_new_uint("pbsradius",
"radius around end of 5' LTR "
"to search for PBS",
&arguments->pbs_radius,
30U);
gt_option_parser_add_option(op, o);
gt_option_imply(o, ot);
/* Protein domain search options */
oh = gt_option_new_filename_array("hmms",
"profile HMM models for domain detection "
"(separate by spaces, finish with --) in "
"HMMER3 format\n"
"Omit this option to disable pHMM search.",
arguments->hmm_files);
gt_option_parser_add_option(op, oh);
oeval = gt_option_new_probability("pdomevalcutoff",
"global E-value cutoff for pHMM search\n"
"default 1E-6",
&arguments->evalue_cutoff,
0.000001);
gt_option_parser_add_option(op, oeval);
gt_option_is_extended_option(oeval);
gt_option_hide_default(oeval);
gt_option_imply(oeval, oh);
oc = gt_option_new_choice("pdomcutoff", "model-specific score cutoff\n"
"choose from TC (trusted cutoff) | "
"GA (gathering cutoff) | "
"NONE (no cutoffs)",
arguments->cutoffs, cutoffs[0], cutoffs);
gt_option_parser_add_option(op, oc);
gt_option_is_extended_option(oeval);
gt_option_imply(oeval, oh);
o = gt_option_new_bool("aliout",
"output pHMM to amino acid sequence alignments",
&arguments->write_alignments,
false);
gt_option_parser_add_option(op, o);
gt_option_imply(o, oh);
gt_option_imply(o, oto);
o = gt_option_new_bool("aaout",
"output amino acid sequences for protein domain "
"hits",
&arguments->write_aaseqs,
false);
gt_option_parser_add_option(op, o);
gt_option_imply(o, oh);
gt_option_imply(o, oto);
o = gt_option_new_bool("allchains",
"output features from all chains and unchained "
"features, labeled with chain numbers",
&arguments->output_all_chains,
false);
gt_option_parser_add_option(op, o);
gt_option_imply(o, oh);
o = gt_option_new_uint("maxgaplen",
"maximal allowed gap size between fragments (in amino "
"acids) when chaining pHMM hits for a protein domain",
&arguments->chain_max_gap_length,
50U);
gt_option_parser_add_option(op, o);
gt_option_is_extended_option(o);
gt_option_imply(o, oh);
o = gt_option_new_uword("threads",
"DEPRECATED, only included for compatibility reasons!"
" Use the -j parameter of the 'gt' call instead.",
&arguments->nthreads,
0);
gt_option_parser_add_option(op, o);
gt_option_is_development_option(o);
o = gt_option_new_bool("force_recreate",
"force recreation of hmmpressed profiles",
&arguments->force_recreate,
false);
gt_option_parser_add_option(op, o);
/* Extended PBS options */
o = gt_option_new_int("pbsmatchscore",
"match score for PBS/tRNA alignments",
&arguments->ali_score_match,
5);
gt_option_parser_add_option(op, o);
gt_option_is_extended_option(o);
gt_option_imply(o, ot);
o = gt_option_new_int("pbsmismatchscore",
"mismatch score for PBS/tRNA alignments",
&arguments->ali_score_mismatch,
-10);
gt_option_parser_add_option(op, o);
gt_option_is_extended_option(o);
gt_option_imply(o, ot);
o = gt_option_new_int("pbsinsertionscore",
"insertion score for PBS/tRNA alignments",
&arguments->ali_score_insertion,
-20);
gt_option_parser_add_option(op, o);
gt_option_is_extended_option(o);
gt_option_imply(o, ot);
o = gt_option_new_int("pbsdeletionscore",
"deletion score for PBS/tRNA alignments",
&arguments->ali_score_deletion,
-20);
gt_option_parser_add_option(op, o);
gt_option_is_extended_option(o);
gt_option_imply(o, ot);
/* verbosity */
o = gt_option_new_verbose(&arguments->verbose);
gt_option_parser_add_option(op, o);
/* output file options */
gt_output_file_info_register_options(arguments->ofi, op, &arguments->outfp);
/* region mapping and sequence source options */
gt_seqid2file_register_options_ext(op, arguments->s2fi, false, false);
return op;
}
int gt_ltrdigest_arguments_check(GT_UNUSED int rest_argc, void *tool_arguments,
GtError* err)
{
GtLTRdigestOptions *arguments = tool_arguments;
int had_err = 0;
if (arguments->nthreads > 0) {
gt_warning("The '-threads' option is deprecated. Please use the '-j'"
"option of the 'gt' call instead, e.g.:\n"
" gt -j "GT_WU" ltrdigest ...", arguments->nthreads);
}
/* -trnas */
if (!had_err && arguments->trna_lib && gt_str_length(arguments->trna_lib) > 0)
{
if (!gt_file_exists(gt_str_get(arguments->trna_lib)))
{
gt_error_set(err, "File '%s' does not exist!",
gt_str_get(arguments->trna_lib));
had_err = -1;
}
}
return had_err;
}
static int gt_ltrdigest_runner(GT_UNUSED int argc, const char **argv,
int parsed_args, void *tool_arguments,
GtError *err)
{
GtLTRdigestOptions *arguments = tool_arguments;
GtNodeStream *gff3_in_stream = NULL,
*check_stream = NULL,
*gff3_out_stream = NULL,
*pdom_stream = NULL,
*ppt_stream = NULL,
*pbs_stream = NULL,
*tab_out_stream = NULL,
*sa_stream = NULL,
*last_stream = NULL;
int had_err = 0,
tests_to_run = 0,
arg = parsed_args;
GtRegionMapping *rmap = NULL;
GtPdomModelSet *ms = NULL;
gt_error_check(err);
gt_assert(arguments);
/* determine and open sequence source */
if (gt_seqid2file_option_used(arguments->s2fi)) {
/* create region mapping */
rmap = gt_seqid2file_region_mapping_new(arguments->s2fi, err);
if (!rmap)
had_err = -1;
} else {
GtEncseqLoader *el;
GtEncseq *encseq;
/* no new-style sequence source option given, fall back to legacy syntax */
if (argc < 3) {
gt_error_set(err, "missing mandatory argument(s)");
had_err = -1;
}
if (!had_err) {
el = gt_encseq_loader_new();
gt_encseq_loader_disable_autosupport(el);
gt_encseq_loader_require_md5_support(el);
gt_encseq_loader_require_description_support(el);
encseq = gt_encseq_loader_load(el, argv[argc-1], err);
/* XXX: clip off terminal argument */
gt_free((char*) argv[argc-1]);
argv[argc-1] = NULL;
argc--;
gt_encseq_loader_delete(el);
if (!encseq)
had_err = -1;
else {
rmap = gt_region_mapping_new_encseq_seqno(encseq);
gt_encseq_delete(encseq);
}
}
}
gt_assert(had_err || rmap);
/* Always search for PPT. */
tests_to_run |= GT_LTRDIGEST_RUN_PPT;
/* Open tRNA library if given. */
if (!had_err && arguments->trna_lib
&& gt_str_length(arguments->trna_lib) > 0)
{
tests_to_run |= GT_LTRDIGEST_RUN_PBS;
arguments->trna_lib_bs = gt_bioseq_new(gt_str_get(arguments->trna_lib),
err);
if (gt_error_is_set(err))
had_err = -1;
}
/* Set HMMER cutoffs. */
if (!had_err && gt_str_array_size(arguments->hmm_files) > 0)
{
tests_to_run |= GT_LTRDIGEST_RUN_PDOM;
if (!strcmp(gt_str_get(arguments->cutoffs), "GA")) {
arguments->cutoff = GT_PHMM_CUTOFF_GA;
} else if (!strcmp(gt_str_get(arguments->cutoffs), "TC")) {
arguments->cutoff = GT_PHMM_CUTOFF_TC;
} else if (!strcmp(gt_str_get(arguments->cutoffs), "NONE")) {
arguments->cutoff = GT_PHMM_CUTOFF_NONE;
} else {
gt_error_set(err, "invalid cutoff setting!");
had_err = -1;
}
}
if (!had_err) {
last_stream = gff3_in_stream = gt_gff3_in_stream_new_sorted(argv[arg]);
}
if (!had_err) {
GtNodeVisitor *check_v;
check_v = gt_ltr_input_check_visitor_new();
last_stream = check_stream = gt_visitor_stream_new(last_stream, check_v);
}
if (!had_err && gt_str_array_size(arguments->hmm_files) > 0) {
GtNodeVisitor *pdom_v;
ms = gt_pdom_model_set_new(arguments->hmm_files, arguments->force_recreate,
err);
if (ms != NULL) {
pdom_v = gt_ltrdigest_pdom_visitor_new(ms, arguments->evalue_cutoff,
arguments->chain_max_gap_length,
arguments->cutoff, rmap, err);
if (pdom_v == NULL)
had_err = -1;
if (!had_err) {
gt_ltrdigest_pdom_visitor_set_source_tag((GtLTRdigestPdomVisitor*)
pdom_v,
GT_LTRDIGEST_TAG);
if (arguments->output_all_chains)
gt_ltrdigest_pdom_visitor_output_all_chains((GtLTRdigestPdomVisitor*)
pdom_v);
last_stream = pdom_stream = gt_visitor_stream_new(last_stream, pdom_v);
}
} else had_err = -1;
}
if (!had_err && arguments->trna_lib_bs) {
GtNodeVisitor *pbs_v;
pbs_v = gt_ltrdigest_pbs_visitor_new(rmap, arguments->pbs_radius,
arguments->max_edist,
arguments->alilen,
arguments->offsetlen,
arguments->trnaoffsetlen,
arguments->ali_score_match,
arguments->ali_score_mismatch,
arguments->ali_score_insertion,
arguments->ali_score_deletion,
arguments->trna_lib_bs, err);
if (pbs_v != NULL)
last_stream = pbs_stream = gt_visitor_stream_new(last_stream, pbs_v);
else
had_err = -1;
}
if (!had_err) {
GtNodeVisitor *ppt_v;
ppt_v = gt_ltrdigest_ppt_visitor_new(rmap, arguments->ppt_len,
arguments->ubox_len,
arguments->ppt_pyrimidine_prob,
arguments->ppt_purine_prob,
arguments->bkg_a_prob,
arguments->bkg_g_prob,
arguments->bkg_t_prob,
arguments->bkg_c_prob,
arguments->ubox_u_prob,
arguments->ppt_radius,
arguments->max_ubox_dist, err);
if (ppt_v != NULL)
last_stream = ppt_stream = gt_visitor_stream_new(last_stream, ppt_v);
else
had_err = -1;
}
if (!had_err) {
GtNodeVisitor *sa_v;
sa_v = gt_ltrdigest_strand_assign_visitor_new();
gt_assert(sa_v);
last_stream = sa_stream = gt_visitor_stream_new(last_stream, sa_v);
}
if (!had_err)
{
/* attach tabular output stream, if requested */
if (gt_str_length(arguments->prefix) > 0)
{
last_stream = tab_out_stream = gt_ltrdigest_file_out_stream_new(
last_stream,
tests_to_run,
rmap,
gt_str_get(arguments->prefix),
arguments->seqnamelen,
err);
if (!tab_out_stream)
had_err = -1;
if (!had_err && arguments->print_metadata)
{
had_err = gt_ltrdigest_file_out_stream_write_metadata(
(GtLTRdigestFileOutStream*)
tab_out_stream,
tests_to_run,
gt_str_get(arguments->trna_lib),
argv[arg],
arguments->ppt_len,
arguments->ubox_len,
arguments->ppt_radius,
arguments->alilen,
arguments->max_edist,
arguments->offsetlen,
arguments->trnaoffsetlen,
arguments->pbs_radius,
arguments->hmm_files,
arguments->chain_max_gap_length,
arguments->evalue_cutoff,
err);
}
if (!had_err)
{
if (arguments->write_alignments)
gt_ltrdigest_file_out_stream_enable_pdom_alignment_output(
tab_out_stream);
if (arguments->write_aaseqs)
gt_ltrdigest_file_out_stream_enable_aa_sequence_output(
tab_out_stream);
}
}
if (!had_err) {
last_stream = gff3_out_stream = gt_gff3_out_stream_new(last_stream,
arguments->outfp);
gt_assert(last_stream);
/* pull the features through the stream and free them afterwards */
had_err = gt_node_stream_pull(last_stream, err);
}
}
gt_pdom_model_set_delete(ms);
gt_node_stream_delete(gff3_out_stream);
gt_node_stream_delete(ppt_stream);
gt_node_stream_delete(pbs_stream);
gt_node_stream_delete(sa_stream);
gt_node_stream_delete(pdom_stream);
gt_node_stream_delete(tab_out_stream);
gt_node_stream_delete(check_stream);
gt_node_stream_delete(gff3_in_stream);
gt_bioseq_delete(arguments->trna_lib_bs);
gt_region_mapping_delete(rmap);
return had_err;
}
GtTool* gt_ltrdigest(void)
{
return gt_tool_new(gt_ltrdigest_arguments_new,
gt_ltrdigest_arguments_delete,
gt_ltrdigest_option_parser_new,
gt_ltrdigest_arguments_check,
gt_ltrdigest_runner);
}
| 37.777448 | 80 | 0.559147 | [
"model"
] |
d9557d8c767b752d62abb58936dbb17f3fb990fc | 102,411 | h | C | mysql-dst/mysql-cluster/sql/sys_vars.h | SJTU-IPADS/dst | 897b929a692642cbf295c105d9d6e64090abb673 | [
"Apache-2.0"
] | 9 | 2020-12-17T01:59:13.000Z | 2022-03-30T16:25:08.000Z | mysql-dst/mysql-cluster/sql/sys_vars.h | SJTU-IPADS/dst | 897b929a692642cbf295c105d9d6e64090abb673 | [
"Apache-2.0"
] | 1 | 2021-07-30T12:06:33.000Z | 2021-07-31T10:16:09.000Z | mysql-dst/mysql-cluster/sql/sys_vars.h | SJTU-IPADS/dst | 897b929a692642cbf295c105d9d6e64090abb673 | [
"Apache-2.0"
] | 1 | 2021-08-01T13:47:07.000Z | 2021-08-01T13:47:07.000Z | #ifndef SYS_VARS_H_INCLUDED
#define SYS_VARS_H_INCLUDED
/* Copyright (c) 2002, 2018, Oracle and/or its affiliates. All rights reserved.
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; version 2 of the License.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
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 */
/**
@file
"private" interface to sys_var - server configuration variables.
This header is included only by the file that contains declarations
of sys_var variables (sys_vars.cc).
*/
#include "my_global.h"
#include "keycaches.h" // dflt_key_cache
#include "my_bit.h" // my_count_bits
#include "my_getopt.h" // get_opt_arg_type
#include "mysql/plugin.h" // enum_mysql_show_type
#include "item.h" // Item
#include "log.h" // sql_print_information
#include "set_var.h" // sys_var
#include "sql_class.h" // THD
#include "sql_plugin.h" // my_plugin_lock_by_name
#include "strfunc.h" // find_type
#include "sys_vars_shared.h" // throw_bounds_warning
#include "tztime.h" // Time_zone
#include "binlog.h" // mysql_bin_log
#include "rpl_rli.h" // sql_slave_skip_counter
#include "rpl_msr.h" // channel_map
#include "rpl_group_replication.h"// is_group_replication_running
/*
a set of mostly trivial (as in f(X)=X) defines below to make system variable
declarations more readable
*/
#define VALID_RANGE(X,Y) X,Y
#define DEFAULT(X) X
#define BLOCK_SIZE(X) X
#define GLOBAL_VAR(X) sys_var::GLOBAL, (((char*)&(X))-(char*)&global_system_variables), sizeof(X)
#define SESSION_VAR(X) sys_var::SESSION, offsetof(SV, X), sizeof(((SV *)0)->X)
#define SESSION_ONLY(X) sys_var::ONLY_SESSION, offsetof(SV, X), sizeof(((SV *)0)->X)
#define NO_CMD_LINE CMD_LINE(NO_ARG, -1)
/*
the define below means that there's no *second* mutex guard,
LOCK_global_system_variables always guards all system variables
*/
#define NO_MUTEX_GUARD ((PolyLock*)0)
#define IN_BINLOG sys_var::SESSION_VARIABLE_IN_BINLOG
#define NOT_IN_BINLOG sys_var::VARIABLE_NOT_IN_BINLOG
#define ON_READ(X) X
#define ON_CHECK(X) X
#define ON_UPDATE(X) X
#define READ_ONLY sys_var::READONLY+
#define NOT_VISIBLE sys_var::INVISIBLE+
#define UNTRACKED_DEFAULT sys_var::TRI_LEVEL+
// this means that Sys_var_charptr initial value was malloc()ed
#define PREALLOCATED sys_var::ALLOCATED+
/*
Sys_var_bit meaning is reversed, like in
@@foreign_key_checks <-> OPTION_NO_FOREIGN_KEY_CHECKS
*/
#define REVERSE(X) ~(X)
#define DEPRECATED(X) X
#define session_var(THD, TYPE) (*(TYPE*)session_var_ptr(THD))
#define global_var(TYPE) (*(TYPE*)global_var_ptr())
#if SIZEOF_OFF_T > 4
#define GET_HA_ROWS GET_ULL
#else
#define GET_HA_ROWS GET_ULONG
#endif
extern sys_var_chain all_sys_vars;
enum charset_enum {IN_SYSTEM_CHARSET, IN_FS_CHARSET};
static const char *bool_values[3]= {"OFF", "ON", 0};
/**
A small wrapper class to pass getopt arguments as a pair
to the Sys_var_* constructors. It improves type safety and helps
to catch errors in the argument order.
*/
struct CMD_LINE
{
int id;
enum get_opt_arg_type arg_type;
CMD_LINE(enum get_opt_arg_type getopt_arg_type, int getopt_id=0)
: id(getopt_id), arg_type(getopt_arg_type) {}
};
/**
Sys_var_integer template is used to generate Sys_var_* classes
for variables that represent the value as a signed or unsigned integer.
They are Sys_var_uint, Sys_var_ulong, Sys_var_harows, Sys_var_ulonglong,
and Sys_var_long.
An integer variable has a minimal and maximal values, and a "block_size"
(any valid value of the variable must be divisible by the block_size).
Class specific constructor arguments: min, max, block_size
Backing store: uint, ulong, ha_rows, ulonglong, long, depending on the
Sys_var_*
*/
template
<typename T, ulong ARGT, enum enum_mysql_show_type SHOWT, bool SIGNED>
class Sys_var_integer: public sys_var
{
public:
Sys_var_integer(const char *name_arg,
const char *comment, int flag_args, ptrdiff_t off, size_t size,
CMD_LINE getopt,
T min_val, T max_val, T def_val, uint block_size, PolyLock *lock=0,
enum binlog_status_enum binlog_status_arg=VARIABLE_NOT_IN_BINLOG,
on_check_function on_check_func=0,
on_update_function on_update_func=0,
const char *substitute=0,
int parse_flag= PARSE_NORMAL)
: sys_var(&all_sys_vars, name_arg, comment, flag_args, off, getopt.id,
getopt.arg_type, SHOWT, def_val, lock, binlog_status_arg,
on_check_func, on_update_func,
substitute, parse_flag)
{
option.var_type= ARGT;
option.min_value= min_val;
option.max_value= max_val;
option.block_size= block_size;
option.u_max_value= (uchar**)max_var_ptr();
if (max_var_ptr())
*max_var_ptr()= max_val;
// Do not set global_var for Sys_var_keycache objects
if (offset >= 0)
global_var(T)= def_val;
DBUG_ASSERT(size == sizeof(T));
DBUG_ASSERT(min_val < max_val);
DBUG_ASSERT(min_val <= def_val);
DBUG_ASSERT(max_val >= def_val);
DBUG_ASSERT(block_size > 0);
DBUG_ASSERT(def_val % block_size == 0);
}
bool do_check(THD *thd, set_var *var)
{
my_bool fixed= FALSE;
longlong v;
ulonglong uv;
v= var->value->val_int();
if (SIGNED) /* target variable has signed type */
{
if (var->value->unsigned_flag)
{
/*
Input value is such a large positive number that MySQL used an
unsigned item to hold it. When cast to a signed longlong, if the
result is negative there is "cycling" and this is incorrect (large
positive input value should not end up as a large negative value in
the session signed variable to be set); instead, we need to pick the
allowed number closest to the positive input value, i.e. pick the
biggest allowed positive integer.
*/
if (v < 0)
uv= max_of_int_range(ARGT);
else /* no cycling, longlong can hold true value */
uv= (ulonglong) v;
}
else
uv= v;
/* This will further restrict with VALID_RANGE, BLOCK_SIZE */
var->save_result.ulonglong_value=
getopt_ll_limit_value(uv, &option, &fixed);
}
else
{
if (var->value->unsigned_flag)
{
/* Guaranteed positive input value, ulonglong can hold it */
uv= (ulonglong) v;
}
else
{
/*
Maybe negative input value; in this case, cast to ulonglong makes it
positive, which is wrong. Pick the closest allowed value i.e. 0.
*/
uv= (ulonglong) (v < 0 ? 0 : v);
}
var->save_result.ulonglong_value=
getopt_ull_limit_value(uv, &option, &fixed);
}
if (max_var_ptr())
{
/* check constraint set with --maximum-...=X */
if (SIGNED)
{
longlong max_val= *max_var_ptr();
if (((longlong)(var->save_result.ulonglong_value)) > max_val)
var->save_result.ulonglong_value= max_val;
/*
Signed variable probably has some kind of symmetry. Then it's good
to limit negative values just as we limit positive values.
*/
max_val= -max_val;
if (((longlong)(var->save_result.ulonglong_value)) < max_val)
var->save_result.ulonglong_value= max_val;
}
else
{
ulonglong max_val= *max_var_ptr();
if (var->save_result.ulonglong_value > max_val)
var->save_result.ulonglong_value= max_val;
}
}
return throw_bounds_warning(thd, name.str,
var->save_result.ulonglong_value !=
(ulonglong)v,
var->value->unsigned_flag, v);
}
bool session_update(THD *thd, set_var *var)
{
session_var(thd, T)= static_cast<T>(var->save_result.ulonglong_value);
return false;
}
bool global_update(THD *thd, set_var *var)
{
global_var(T)= static_cast<T>(var->save_result.ulonglong_value);
return false;
}
bool check_update_type(Item_result type)
{ return type != INT_RESULT; }
void session_save_default(THD *thd, set_var *var)
{
var->save_result.ulonglong_value=
static_cast<ulonglong>(*(T*)global_value_ptr(thd, 0));
}
void global_save_default(THD *thd, set_var *var)
{ var->save_result.ulonglong_value= option.def_value; }
private:
T *max_var_ptr()
{
return scope() == SESSION ? (T*)(((uchar*)&max_system_variables) + offset)
: 0;
}
};
typedef Sys_var_integer<int32, GET_UINT, SHOW_INT, FALSE> Sys_var_int32;
typedef Sys_var_integer<uint, GET_UINT, SHOW_INT, FALSE> Sys_var_uint;
typedef Sys_var_integer<ulong, GET_ULONG, SHOW_LONG, FALSE> Sys_var_ulong;
typedef Sys_var_integer<ha_rows, GET_HA_ROWS, SHOW_HA_ROWS, FALSE>
Sys_var_harows;
typedef Sys_var_integer<ulonglong, GET_ULL, SHOW_LONGLONG, FALSE>
Sys_var_ulonglong;
typedef Sys_var_integer<long, GET_LONG, SHOW_SIGNED_LONG, TRUE> Sys_var_long;
/**
Helper class for variables that take values from a TYPELIB
*/
class Sys_var_typelib: public sys_var
{
protected:
TYPELIB typelib;
public:
Sys_var_typelib(const char *name_arg,
const char *comment, int flag_args, ptrdiff_t off,
CMD_LINE getopt,
SHOW_TYPE show_val_type_arg, const char *values[],
ulonglong def_val, PolyLock *lock,
enum binlog_status_enum binlog_status_arg,
on_check_function on_check_func, on_update_function on_update_func,
const char *substitute, int parse_flag= PARSE_NORMAL)
: sys_var(&all_sys_vars, name_arg, comment, flag_args, off, getopt.id,
getopt.arg_type, show_val_type_arg, def_val, lock,
binlog_status_arg, on_check_func,
on_update_func, substitute, parse_flag)
{
for (typelib.count= 0; values[typelib.count]; typelib.count++) /*no-op */;
typelib.name="";
typelib.type_names= values;
typelib.type_lengths= 0; // only used by Fields_enum and Field_set
option.typelib= &typelib;
}
bool do_check(THD *thd, set_var *var) // works for enums and my_bool
{
char buff[STRING_BUFFER_USUAL_SIZE];
String str(buff, sizeof(buff), system_charset_info), *res;
if (var->value->result_type() == STRING_RESULT)
{
if (!(res=var->value->val_str(&str)))
return true;
else
if (!(var->save_result.ulonglong_value=
find_type(&typelib, res->ptr(), res->length(), false)))
return true;
else
var->save_result.ulonglong_value--;
}
else
{
longlong tmp=var->value->val_int();
if (tmp < 0 || tmp >= typelib.count)
return true;
else
var->save_result.ulonglong_value= tmp;
}
return false;
}
bool check_update_type(Item_result type)
{ return type != INT_RESULT && type != STRING_RESULT; }
};
/**
The class for ENUM variables - variables that take one value from a fixed
list of values.
Class specific constructor arguments:
char* values[] - 0-terminated list of strings of valid values
Backing store: uint
@note
Do *not* use "enum FOO" variables as a backing store, there is no
guarantee that sizeof(enum FOO) == sizeof(uint), there is no guarantee
even that sizeof(enum FOO) == sizeof(enum BAR)
*/
class Sys_var_enum: public Sys_var_typelib
{
public:
Sys_var_enum(const char *name_arg,
const char *comment, int flag_args, ptrdiff_t off, size_t size,
CMD_LINE getopt,
const char *values[], uint def_val, PolyLock *lock=0,
enum binlog_status_enum binlog_status_arg=VARIABLE_NOT_IN_BINLOG,
on_check_function on_check_func=0,
on_update_function on_update_func=0,
const char *substitute=0)
: Sys_var_typelib(name_arg, comment, flag_args, off, getopt,
SHOW_CHAR, values, def_val, lock,
binlog_status_arg, on_check_func, on_update_func,
substitute)
{
option.var_type= GET_ENUM;
global_var(ulong)= def_val;
DBUG_ASSERT(def_val < typelib.count);
DBUG_ASSERT(size == sizeof(ulong));
}
bool session_update(THD *thd, set_var *var)
{
session_var(thd, ulong)=
static_cast<ulong>(var->save_result.ulonglong_value);
return false;
}
bool global_update(THD *thd, set_var *var)
{
global_var(ulong)=
static_cast<ulong>(var->save_result.ulonglong_value);
return false;
}
void session_save_default(THD *thd, set_var *var)
{ var->save_result.ulonglong_value= global_var(ulong); }
void global_save_default(THD *thd, set_var *var)
{ var->save_result.ulonglong_value= option.def_value; }
uchar *session_value_ptr(THD *running_thd, THD *target_thd, LEX_STRING *base)
{ return (uchar*)typelib.type_names[session_var(target_thd, ulong)]; }
uchar *global_value_ptr(THD *thd, LEX_STRING *base)
{ return (uchar*)typelib.type_names[global_var(ulong)]; }
};
/**
The class for boolean variables - a variant of ENUM variables
with the fixed list of values of { OFF , ON }
Backing store: my_bool
*/
class Sys_var_mybool: public Sys_var_typelib
{
public:
Sys_var_mybool(const char *name_arg,
const char *comment, int flag_args, ptrdiff_t off, size_t size,
CMD_LINE getopt,
my_bool def_val, PolyLock *lock=0,
enum binlog_status_enum binlog_status_arg=VARIABLE_NOT_IN_BINLOG,
on_check_function on_check_func=0,
on_update_function on_update_func=0,
const char *substitute=0,
int parse_flag= PARSE_NORMAL)
: Sys_var_typelib(name_arg, comment, flag_args, off, getopt,
SHOW_MY_BOOL, bool_values, def_val, lock,
binlog_status_arg, on_check_func, on_update_func,
substitute, parse_flag)
{
option.var_type= GET_BOOL;
global_var(my_bool)= def_val;
DBUG_ASSERT(def_val < 2);
DBUG_ASSERT(getopt.arg_type == OPT_ARG || getopt.id == -1);
DBUG_ASSERT(size == sizeof(my_bool));
}
bool session_update(THD *thd, set_var *var)
{
session_var(thd, my_bool)=
static_cast<my_bool>(var->save_result.ulonglong_value);
return false;
}
bool global_update(THD *thd, set_var *var)
{
global_var(my_bool)=
static_cast<my_bool>(var->save_result.ulonglong_value);
return false;
}
void session_save_default(THD *thd, set_var *var)
{
var->save_result.ulonglong_value=
static_cast<ulonglong>(*(my_bool *)global_value_ptr(thd, 0));
}
void global_save_default(THD *thd, set_var *var)
{ var->save_result.ulonglong_value= option.def_value; }
};
/**
A variant of enum where:
- Each value may have multiple enum-like aliases.
- Instances of the class can specify different default values for
the cases:
- User specifies the command-line option without a value (i.e.,
--option, not --option=value).
- User does not specify a command-line option at all.
This exists mainly to allow extending a variable that once was
boolean in a GA version, into an enumeration type. Booleans accept
multiple aliases (0=off=false, 1=on=true), but Sys_var_enum does
not, so we could not use Sys_var_enum without breaking backward
compatibility. Moreover, booleans default to false if option is not
given, and true if option is given without value.
This is *incompatible* with boolean in the following sense:
'SELECT @@variable' returns 0 or 1 for a boolean, whereas this class
(similar to enum) returns the textual form. (Note that both boolean,
enum, and this class return the textual form in SHOW VARIABLES and
SELECT * FROM information_schema.variables).
See enforce_gtid_consistency for an example of how this can be used.
*/
class Sys_var_multi_enum : public sys_var
{
public:
struct ALIAS
{
const char *alias;
uint number;
};
/**
Class specific parameters:
@param aliases_arg Array of ALIASes, indicating which textual
values map to which number. Should be terminated with an ALIAS
having member variable alias set to NULL. The first
`value_count_arg' elements must map to 0, 1, etc; these will be
used when the value is displayed. Remaining elements may appear
in arbitrary order.
@param value_count_arg The number of allowed integer values.
@param def_val The default value if no command line option is
given. This must be a valid index into the aliases_arg array, but
it does not have to be less than value_count. The corresponding
alias will be used in mysqld --help to show the default value.
@param command_line_no_value The default value if a command line
option is given without a value ('--command-line-option' without
'=VALUE'). This must be less than value_count_arg.
*/
Sys_var_multi_enum(const char *name_arg,
const char *comment, int flag_args, ptrdiff_t off, size_t size,
CMD_LINE getopt,
const ALIAS aliases_arg[], uint value_count_arg,
uint def_val, uint command_line_no_value_arg, PolyLock *lock=0,
enum binlog_status_enum binlog_status_arg=VARIABLE_NOT_IN_BINLOG,
on_check_function on_check_func=0,
on_update_function on_update_func=0,
const char *substitute=0,
int parse_flag= PARSE_NORMAL)
: sys_var(&all_sys_vars, name_arg, comment, flag_args, off, getopt.id,
getopt.arg_type, SHOW_CHAR, def_val, lock,
binlog_status_arg, on_check_func,
on_update_func, substitute, parse_flag),
value_count(value_count_arg),
aliases(aliases_arg),
command_line_no_value(command_line_no_value_arg)
{
for (alias_count= 0; aliases[alias_count].alias; alias_count++)
DBUG_ASSERT(aliases[alias_count].number < value_count);
DBUG_ASSERT(def_val < alias_count);
option.var_type= GET_STR;
option.value= &command_line_value;
option.def_value= (intptr)aliases[def_val].alias;
global_var(ulong)= aliases[def_val].number;
DBUG_ASSERT(getopt.arg_type == OPT_ARG || getopt.id == -1);
DBUG_ASSERT(size == sizeof(ulong));
}
/**
Return the numeric value for a given alias string, or -1 if the
string is not a valid alias.
*/
int find_value(const char *text)
{
for (uint i= 0; aliases[i].alias != NULL; i++)
if (my_strcasecmp(system_charset_info, aliases[i].alias, text) == 0)
return aliases[i].number;
return -1;
}
/**
Because of limitations in the command-line parsing library, the
value given on the command-line cannot be automatically copied to
the global value. Instead, inheritants of this class should call
this function from mysqld.cc:mysqld_get_one_option.
@param value_str Pointer to the value specified on the command
line (as in --option=VALUE).
@retval NULL Success.
@retval non-NULL Pointer to the invalid string that was used as
argument.
*/
const char *fixup_command_line(const char *value_str)
{
DBUG_ENTER("Sys_var_multi_enum::fixup_command_line");
char *end= NULL;
long value;
// User passed --option (not --option=value).
if (value_str == NULL)
{
value= command_line_no_value;
goto end;
}
// Get textual value.
value= find_value(value_str);
if (value != -1)
goto end;
// Get numeric value.
value= strtol(value_str, &end, 10);
// found a number and nothing else?
if (end > value_str && *end == '\0')
// value is in range?
if (value >= 0 && (longlong)value < (longlong)value_count)
goto end;
// Not a valid value.
DBUG_RETURN(value_str);
end:
global_var(ulong)= value;
DBUG_RETURN(NULL);
}
bool do_check(THD *thd, set_var *var)
{
DBUG_ENTER("Sys_var_multi_enum::do_check");
char buff[STRING_BUFFER_USUAL_SIZE];
String str(buff, sizeof(buff), system_charset_info), *res;
if (var->value->result_type() == STRING_RESULT)
{
res= var->value->val_str(&str);
if (!res)
DBUG_RETURN(true);
int value= find_value(res->ptr());
if (value == -1)
DBUG_RETURN(true);
var->save_result.ulonglong_value= (uint)value;
}
else
{
longlong value= var->value->val_int();
if (value < 0 || value >= (longlong)value_count)
DBUG_RETURN(true);
else
var->save_result.ulonglong_value= value;
}
DBUG_RETURN(false);
}
bool check_update_type(Item_result type)
{ return type != INT_RESULT && type != STRING_RESULT; }
bool session_update(THD *thd, set_var *var)
{
DBUG_ENTER("Sys_var_multi_enum::session_update");
DBUG_ASSERT(0);
/*
Currently not used: uncomment if this class is used as a base for
a session variable.
session_var(thd, ulong)=
static_cast<ulong>(var->save_result.ulonglong_value);
*/
DBUG_RETURN(false);
}
bool global_update(THD *thd, set_var *var)
{
DBUG_ENTER("Sys_var_multi_enum::global_update");
DBUG_ASSERT(0);
/*
Currently not used: uncomment if this some inheriting class does
not override..
ulong val=
static_cast<ulong>(var->save_result.ulonglong_value);
global_var(ulong)= val;
*/
DBUG_RETURN(false);
}
void session_save_default(THD *thd, set_var *var)
{
DBUG_ENTER("Sys_var_multi_enum::session_save_default");
DBUG_ASSERT(0);
/*
Currently not used: uncomment if this class is used as a base for
a session variable.
int value= find_value((char *)option.def_value);
DBUG_ASSERT(value != -1);
var->save_result.ulonglong_value= value;
*/
DBUG_VOID_RETURN;
}
void global_save_default(THD *thd, set_var *var)
{
DBUG_ENTER("Sys_var_multi_enum::global_save_default");
int value= find_value((char *)option.def_value);
DBUG_ASSERT(value != -1);
var->save_result.ulonglong_value= value;
DBUG_VOID_RETURN;
}
uchar *session_value_ptr(THD *running_thd, THD *target_thd, LEX_STRING *base)
{
DBUG_ENTER("Sys_var_multi_enum::session_value_ptr");
DBUG_ASSERT(0);
/*
Currently not used: uncomment if this class is used as a base for
a session variable.
DBUG_RETURN((uchar*)aliases[session_var(target_thd, ulong)].alias);
*/
DBUG_RETURN(0);
}
uchar *global_value_ptr(THD *thd, LEX_STRING *base)
{
DBUG_ENTER("Sys_var_multi_enum::global_value_ptr");
DBUG_RETURN((uchar*)aliases[global_var(ulong)].alias);
}
private:
/// The number of allowed numeric values.
const uint value_count;
/// Array of all textual aliases.
const ALIAS *aliases;
/// The number of elements of aliases (computed in the constructor).
uint alias_count;
/**
Pointer to the value set by the command line (set by the command
line parser, copied to the global value in fixup_command_line()).
*/
const char *command_line_value;
uint command_line_no_value;
};
/**
The class for string variables. The string can be in character_set_filesystem
or in character_set_system. The string can be allocated with my_malloc()
or not. The state of the initial value is specified in the constructor,
after that it's managed automatically. The value of NULL is supported.
Class specific constructor arguments:
enum charset_enum is_os_charset_arg
Backing store: char*
*/
class Sys_var_charptr: public sys_var
{
public:
Sys_var_charptr(const char *name_arg,
const char *comment, int flag_args, ptrdiff_t off, size_t size,
CMD_LINE getopt,
enum charset_enum is_os_charset_arg,
const char *def_val, PolyLock *lock= 0,
enum binlog_status_enum binlog_status_arg= VARIABLE_NOT_IN_BINLOG,
on_check_function on_check_func= 0,
on_update_function on_update_func= 0,
const char *substitute= 0,
int parse_flag= PARSE_NORMAL)
: sys_var(&all_sys_vars, name_arg, comment, flag_args, off, getopt.id,
getopt.arg_type, SHOW_CHAR_PTR, (intptr) def_val,
lock, binlog_status_arg, on_check_func, on_update_func,
substitute, parse_flag)
{
is_os_charset= is_os_charset_arg == IN_FS_CHARSET;
option.var_type= (flags & ALLOCATED) ? GET_STR_ALLOC : GET_STR;
global_var(const char*)= def_val;
DBUG_ASSERT(size == sizeof(char *));
}
void cleanup()
{
if (flags & ALLOCATED)
my_free(global_var(char*));
flags&= ~ALLOCATED;
}
bool do_check(THD *thd, set_var *var)
{
char buff[STRING_BUFFER_USUAL_SIZE], buff2[STRING_BUFFER_USUAL_SIZE];
String str(buff, sizeof(buff), charset(thd));
String str2(buff2, sizeof(buff2), charset(thd)), *res;
if (!(res=var->value->val_str(&str)))
var->save_result.string_value.str= 0;
else
{
size_t unused;
if (String::needs_conversion(res->length(), res->charset(),
charset(thd), &unused))
{
uint errors;
str2.copy(res->ptr(), res->length(), res->charset(), charset(thd),
&errors);
res= &str2;
}
var->save_result.string_value.str= thd->strmake(res->ptr(), res->length());
var->save_result.string_value.length= res->length();
}
return false;
}
bool session_update(THD *thd, set_var *var)
{
char *new_val= var->save_result.string_value.str;
size_t new_val_len= var->save_result.string_value.length;
char *ptr= ((char *)&thd->variables + offset);
return thd->session_sysvar_res_mgr.update((char **) ptr, new_val,
new_val_len);
}
bool global_update(THD *thd, set_var *var)
{
char *new_val, *ptr= var->save_result.string_value.str;
size_t len=var->save_result.string_value.length;
if (ptr)
{
new_val= (char*) my_memdup(key_memory_Sys_var_charptr_value,
ptr, len+1, MYF(MY_WME));
if (!new_val) return true;
new_val[len]= 0;
}
else
new_val= 0;
if (flags & ALLOCATED)
my_free(global_var(char*));
flags |= ALLOCATED;
global_var(char*)= new_val;
return false;
}
void session_save_default(THD *thd, set_var *var)
{
char *ptr= (char*)(intptr)option.def_value;
var->save_result.string_value.str= ptr;
var->save_result.string_value.length= ptr ? strlen(ptr) : 0;
}
void global_save_default(THD *thd, set_var *var)
{
char *ptr= (char*)(intptr)option.def_value;
var->save_result.string_value.str= ptr;
var->save_result.string_value.length= ptr ? strlen(ptr) : 0;
}
bool check_update_type(Item_result type)
{ return type != STRING_RESULT; }
};
class Sys_var_version : public Sys_var_charptr
{
public:
Sys_var_version(const char *name_arg,
const char *comment, int flag_args, ptrdiff_t off, size_t size,
CMD_LINE getopt,
enum charset_enum is_os_charset_arg,
const char *def_val)
: Sys_var_charptr(name_arg, comment, flag_args, off, size, getopt, is_os_charset_arg, def_val)
{}
~Sys_var_version()
{}
virtual uchar *global_value_ptr(THD *thd, LEX_STRING *base)
{
uchar *value= Sys_var_charptr::global_value_ptr(thd, base);
DBUG_EXECUTE_IF("alter_server_version_str",
{
static const char *altered_value= "some-other-version";
uchar *altered_value_ptr= reinterpret_cast<uchar*> (& altered_value);
value= altered_value_ptr;
});
return value;
}
};
class Sys_var_proxy_user: public sys_var
{
public:
Sys_var_proxy_user(const char *name_arg,
const char *comment, enum charset_enum is_os_charset_arg)
: sys_var(&all_sys_vars, name_arg, comment,
sys_var::READONLY+sys_var::ONLY_SESSION, 0, -1,
NO_ARG, SHOW_CHAR, 0, NULL, VARIABLE_NOT_IN_BINLOG,
NULL, NULL, NULL, PARSE_NORMAL)
{
is_os_charset= is_os_charset_arg == IN_FS_CHARSET;
option.var_type= GET_STR;
}
bool do_check(THD *thd, set_var *var)
{
DBUG_ASSERT(FALSE);
return true;
}
bool session_update(THD *thd, set_var *var)
{
DBUG_ASSERT(FALSE);
return true;
}
bool global_update(THD *thd, set_var *var)
{
DBUG_ASSERT(FALSE);
return false;
}
void session_save_default(THD *thd, set_var *var)
{ DBUG_ASSERT(FALSE); }
void global_save_default(THD *thd, set_var *var)
{ DBUG_ASSERT(FALSE); }
bool check_update_type(Item_result type)
{ return true; }
protected:
virtual uchar *session_value_ptr(THD *running_thd, THD *target_thd, LEX_STRING *base)
{
const char* proxy_user= target_thd->security_context()->proxy_user().str;
return proxy_user[0] ? (uchar *)proxy_user : NULL;
}
};
class Sys_var_external_user : public Sys_var_proxy_user
{
public:
Sys_var_external_user(const char *name_arg, const char *comment_arg,
enum charset_enum is_os_charset_arg)
: Sys_var_proxy_user (name_arg, comment_arg, is_os_charset_arg)
{}
protected:
virtual uchar *session_value_ptr(THD *running_thd, THD *target_thd, LEX_STRING *base)
{
LEX_CSTRING external_user= target_thd->security_context()->external_user();
return external_user.length ? (uchar *) external_user.str : NULL;
}
};
/**
The class for string variables. Useful for strings that aren't necessarily
\0-terminated. Otherwise the same as Sys_var_charptr.
Class specific constructor arguments:
enum charset_enum is_os_charset_arg
Backing store: LEX_STRING
@note
Behaves exactly as Sys_var_charptr, only the backing store is different.
*/
class Sys_var_lexstring: public Sys_var_charptr
{
public:
Sys_var_lexstring(const char *name_arg,
const char *comment, int flag_args, ptrdiff_t off, size_t size,
CMD_LINE getopt,
enum charset_enum is_os_charset_arg,
const char *def_val, PolyLock *lock=0,
enum binlog_status_enum binlog_status_arg=VARIABLE_NOT_IN_BINLOG,
on_check_function on_check_func=0,
on_update_function on_update_func=0,
const char *substitute=0)
: Sys_var_charptr(name_arg, comment, flag_args, off, sizeof(char*),
getopt, is_os_charset_arg, def_val, lock, binlog_status_arg,
on_check_func, on_update_func, substitute)
{
global_var(LEX_STRING).length= strlen(def_val);
DBUG_ASSERT(size == sizeof(LEX_STRING));
*const_cast<SHOW_TYPE*>(&show_val_type)= SHOW_LEX_STRING;
}
bool global_update(THD *thd, set_var *var)
{
if (Sys_var_charptr::global_update(thd, var))
return true;
global_var(LEX_STRING).length= var->save_result.string_value.length;
return false;
}
};
#ifndef DBUG_OFF
/**
@@session.dbug and @@global.dbug variables.
@@dbug variable differs from other variables in one aspect:
if its value is not assigned in the session, it "points" to the global
value, and so when the global value is changed, the change
immediately takes effect in the session.
This semantics is intentional, to be able to debug one session from
another.
*/
class Sys_var_dbug: public sys_var
{
public:
Sys_var_dbug(const char *name_arg,
const char *comment, int flag_args,
CMD_LINE getopt,
const char *def_val, PolyLock *lock=0,
enum binlog_status_enum binlog_status_arg=VARIABLE_NOT_IN_BINLOG,
on_check_function on_check_func=0,
on_update_function on_update_func=0,
const char *substitute=0,
int parse_flag= PARSE_NORMAL)
: sys_var(&all_sys_vars, name_arg, comment, flag_args, 0, getopt.id,
getopt.arg_type, SHOW_CHAR, (intptr)def_val,
lock, binlog_status_arg, on_check_func, on_update_func,
substitute, parse_flag)
{ option.var_type= GET_NO_ARG; }
bool do_check(THD *thd, set_var *var)
{
char buff[STRING_BUFFER_USUAL_SIZE];
String str(buff, sizeof(buff), system_charset_info), *res;
if (!(res=var->value->val_str(&str)))
var->save_result.string_value.str= const_cast<char*>("");
else
var->save_result.string_value.str= thd->strmake(res->ptr(), res->length());
return false;
}
bool session_update(THD *thd, set_var *var)
{
const char *val= var->save_result.string_value.str;
if (!var->value)
DBUG_POP();
else
DBUG_SET(val);
return false;
}
bool global_update(THD *thd, set_var *var)
{
const char *val= var->save_result.string_value.str;
DBUG_SET_INITIAL(val);
return false;
}
void session_save_default(THD *thd, set_var *var)
{ }
void global_save_default(THD *thd, set_var *var)
{
char *ptr= (char*)(intptr)option.def_value;
var->save_result.string_value.str= ptr;
}
uchar *session_value_ptr(THD *running_thd, THD *target_thd, LEX_STRING *base)
{
char buf[256];
DBUG_EXPLAIN(buf, sizeof(buf));
return (uchar*) running_thd->mem_strdup(buf);
}
uchar *global_value_ptr(THD *thd, LEX_STRING *base)
{
char buf[256];
DBUG_EXPLAIN_INITIAL(buf, sizeof(buf));
return (uchar*) thd->mem_strdup(buf);
}
bool check_update_type(Item_result type)
{ return type != STRING_RESULT; }
};
#endif
#define KEYCACHE_VAR(X) sys_var::GLOBAL,offsetof(KEY_CACHE, X), sizeof(((KEY_CACHE *)0)->X)
#define keycache_var_ptr(KC, OFF) (((uchar*)(KC))+(OFF))
#define keycache_var(KC, OFF) (*(ulonglong*)keycache_var_ptr(KC, OFF))
typedef bool (*keycache_update_function)(THD *, KEY_CACHE *, ptrdiff_t, ulonglong);
/**
The class for keycache_* variables. Supports structured names,
keycache_name.variable_name.
Class specific constructor arguments:
everything derived from Sys_var_ulonglong
Backing store: ulonglong
@note these variables can be only GLOBAL
*/
class Sys_var_keycache: public Sys_var_ulonglong
{
keycache_update_function keycache_update;
public:
Sys_var_keycache(const char *name_arg,
const char *comment, int flag_args, ptrdiff_t off, size_t size,
CMD_LINE getopt,
ulonglong min_val, ulonglong max_val, ulonglong def_val,
uint block_size, PolyLock *lock,
enum binlog_status_enum binlog_status_arg,
on_check_function on_check_func,
keycache_update_function on_update_func,
const char *substitute=0)
: Sys_var_ulonglong(name_arg, comment, flag_args,
-1, /* offset, see base class CTOR */
size,
getopt, min_val, max_val, def_val,
block_size, lock, binlog_status_arg, on_check_func, 0,
substitute),
keycache_update(on_update_func)
{
offset= off; /* Remember offset in KEY_CACHE */
option.var_type|= GET_ASK_ADDR;
option.value= (uchar**)1; // crash me, please
keycache_var(dflt_key_cache, off)= def_val;
DBUG_ASSERT(scope() == GLOBAL);
}
bool global_update(THD *thd, set_var *var)
{
ulonglong new_value= var->save_result.ulonglong_value;
LEX_STRING *base_name= &var->base;
KEY_CACHE *key_cache;
/* If no basename, assume it's for the key cache named 'default' */
if (!base_name->length)
base_name= &default_key_cache_base;
key_cache= get_key_cache(base_name);
if (!key_cache)
{ // Key cache didn't exists */
if (!new_value) // Tried to delete cache
return false; // Ok, nothing to do
if (!(key_cache= create_key_cache(base_name->str, base_name->length)))
return true;
}
/**
Abort if some other thread is changing the key cache
@todo This should be changed so that we wait until the previous
assignment is done and then do the new assign
*/
if (key_cache->in_init)
return true;
return keycache_update(thd, key_cache, offset, new_value);
}
uchar *global_value_ptr(THD *thd, LEX_STRING *base)
{
KEY_CACHE *key_cache= get_key_cache(base);
if (!key_cache)
key_cache= &zero_key_cache;
return keycache_var_ptr(key_cache, offset);
}
};
/**
The class for floating point variables
Class specific constructor arguments: min, max
Backing store: double
*/
class Sys_var_double: public sys_var
{
public:
Sys_var_double(const char *name_arg,
const char *comment, int flag_args, ptrdiff_t off, size_t size,
CMD_LINE getopt,
double min_val, double max_val, double def_val, PolyLock *lock=0,
enum binlog_status_enum binlog_status_arg=VARIABLE_NOT_IN_BINLOG,
on_check_function on_check_func=0,
on_update_function on_update_func=0,
const char *substitute=0,
int parse_flag= PARSE_NORMAL)
: sys_var(&all_sys_vars, name_arg, comment, flag_args, off, getopt.id,
getopt.arg_type, SHOW_DOUBLE,
(longlong) getopt_double2ulonglong(def_val),
lock, binlog_status_arg, on_check_func, on_update_func,
substitute, parse_flag)
{
option.var_type= GET_DOUBLE;
option.min_value= (longlong) getopt_double2ulonglong(min_val);
option.max_value= (longlong) getopt_double2ulonglong(max_val);
global_var(double)= (double)option.def_value;
DBUG_ASSERT(min_val <= max_val);
DBUG_ASSERT(min_val <= def_val);
DBUG_ASSERT(max_val >= def_val);
DBUG_ASSERT(size == sizeof(double));
}
bool do_check(THD *thd, set_var *var)
{
my_bool fixed;
double v= var->value->val_real();
var->save_result.double_value= getopt_double_limit_value(v, &option, &fixed);
return throw_bounds_warning(thd, name.str, fixed, v);
}
bool session_update(THD *thd, set_var *var)
{
session_var(thd, double)= var->save_result.double_value;
return false;
}
bool global_update(THD *thd, set_var *var)
{
global_var(double)= var->save_result.double_value;
return false;
}
bool check_update_type(Item_result type)
{
return type != INT_RESULT && type != REAL_RESULT && type != DECIMAL_RESULT;
}
void session_save_default(THD *thd, set_var *var)
{ var->save_result.double_value= global_var(double); }
void global_save_default(THD *thd, set_var *var)
{ var->save_result.double_value= getopt_ulonglong2double(option.def_value); }
};
/**
The class for @test_flags (core_file for now).
It's derived from Sys_var_mybool.
Class specific constructor arguments:
Caller need not pass in a variable as we make up the value on the
fly, that is, we derive it from the global test_flags bit vector.
Backing store: my_bool
*/
class Sys_var_test_flag: public Sys_var_mybool
{
private:
my_bool test_flag_value;
uint test_flag_mask;
public:
Sys_var_test_flag(const char *name_arg, const char *comment, uint mask)
: Sys_var_mybool(name_arg, comment, READ_ONLY GLOBAL_VAR(test_flag_value),
NO_CMD_LINE, DEFAULT(FALSE))
{
test_flag_mask= mask;
}
uchar *global_value_ptr(THD *thd, LEX_STRING *base)
{
test_flag_value= ((test_flags & test_flag_mask) > 0);
return (uchar*) &test_flag_value;
}
};
/**
The class for the @max_user_connections.
It's derived from Sys_var_uint, but non-standard session value
requires a new class.
Class specific constructor arguments:
everything derived from Sys_var_uint
Backing store: uint
*/
class Sys_var_max_user_conn: public Sys_var_uint
{
public:
Sys_var_max_user_conn(const char *name_arg,
const char *comment, int flag_args, ptrdiff_t off, size_t size,
CMD_LINE getopt,
uint min_val, uint max_val, uint def_val,
uint block_size, PolyLock *lock=0,
enum binlog_status_enum binlog_status_arg=VARIABLE_NOT_IN_BINLOG,
on_check_function on_check_func=0,
on_update_function on_update_func=0,
const char *substitute=0)
: Sys_var_uint(name_arg, comment, SESSION, off, size, getopt,
min_val, max_val, def_val, block_size,
lock, binlog_status_arg, on_check_func, on_update_func,
substitute)
{ }
uchar *session_value_ptr(THD *running_thd, THD *target_thd, LEX_STRING *base)
{
const USER_CONN *uc= target_thd->get_user_connect();
if (uc && uc->user_resources.user_conn)
return (uchar*) &(uc->user_resources.user_conn);
return global_value_ptr(running_thd, base);
}
};
// overflow-safe (1 << X)-1
#define MAX_SET(X) ((((1UL << ((X)-1))-1) << 1) | 1)
/**
The class for flagset variables - a variant of SET that allows in-place
editing (turning on/off individual bits). String representations looks like
a "flag=val,flag=val,...". Example: @@optimizer_switch
Class specific constructor arguments:
char* values[] - 0-terminated list of strings of valid values
Backing store: ulonglong
@note
the last value in the values[] array should
*always* be the string "default".
*/
class Sys_var_flagset: public Sys_var_typelib
{
public:
Sys_var_flagset(const char *name_arg,
const char *comment, int flag_args, ptrdiff_t off, size_t size,
CMD_LINE getopt,
const char *values[], ulonglong def_val, PolyLock *lock=0,
enum binlog_status_enum binlog_status_arg=VARIABLE_NOT_IN_BINLOG,
on_check_function on_check_func=0,
on_update_function on_update_func=0,
const char *substitute=0)
: Sys_var_typelib(name_arg, comment, flag_args, off, getopt,
SHOW_CHAR, values, def_val, lock,
binlog_status_arg, on_check_func, on_update_func,
substitute)
{
option.var_type= GET_FLAGSET;
global_var(ulonglong)= def_val;
DBUG_ASSERT(typelib.count > 1);
DBUG_ASSERT(typelib.count <= 65);
DBUG_ASSERT(def_val < MAX_SET(typelib.count));
DBUG_ASSERT(strcmp(values[typelib.count-1], "default") == 0);
DBUG_ASSERT(size == sizeof(ulonglong));
}
bool do_check(THD *thd, set_var *var)
{
char buff[STRING_BUFFER_USUAL_SIZE];
String str(buff, sizeof(buff), system_charset_info), *res;
ulonglong default_value, current_value;
if (var->type == OPT_GLOBAL)
{
default_value= option.def_value;
current_value= global_var(ulonglong);
}
else
{
default_value= global_var(ulonglong);
current_value= session_var(thd, ulonglong);
}
if (var->value->result_type() == STRING_RESULT)
{
if (!(res=var->value->val_str(&str)))
return true;
else
{
char *error;
uint error_len;
var->save_result.ulonglong_value=
find_set_from_flags(&typelib,
typelib.count,
current_value,
default_value,
res->ptr(),
static_cast<uint>(res->length()),
&error, &error_len);
if (error)
{
ErrConvString err(error, error_len, res->charset());
my_error(ER_WRONG_VALUE_FOR_VAR, MYF(0), name.str, err.ptr());
return true;
}
}
}
else
{
longlong tmp=var->value->val_int();
if ((tmp < 0 && ! var->value->unsigned_flag)
|| (ulonglong)tmp > MAX_SET(typelib.count))
return true;
else
var->save_result.ulonglong_value= tmp;
}
return false;
}
bool session_update(THD *thd, set_var *var)
{
session_var(thd, ulonglong)= var->save_result.ulonglong_value;
return false;
}
bool global_update(THD *thd, set_var *var)
{
global_var(ulonglong)= var->save_result.ulonglong_value;
return false;
}
void session_save_default(THD *thd, set_var *var)
{ var->save_result.ulonglong_value= global_var(ulonglong); }
void global_save_default(THD *thd, set_var *var)
{ var->save_result.ulonglong_value= option.def_value; }
uchar *session_value_ptr(THD *running_thd, THD *target_thd, LEX_STRING *base)
{
return (uchar*)flagset_to_string(running_thd, 0, session_var(target_thd, ulonglong),
typelib.type_names);
}
uchar *global_value_ptr(THD *thd, LEX_STRING *base)
{
return (uchar*)flagset_to_string(thd, 0, global_var(ulonglong),
typelib.type_names);
}
};
/**
The class for SET variables - variables taking zero or more values
from the given list. Example: @@sql_mode
Class specific constructor arguments:
char* values[] - 0-terminated list of strings of valid values
Backing store: ulonglong
*/
class Sys_var_set: public Sys_var_typelib
{
public:
Sys_var_set(const char *name_arg,
const char *comment, int flag_args, ptrdiff_t off, size_t size,
CMD_LINE getopt,
const char *values[], ulonglong def_val, PolyLock *lock=0,
enum binlog_status_enum binlog_status_arg=VARIABLE_NOT_IN_BINLOG,
on_check_function on_check_func=0,
on_update_function on_update_func=0,
const char *substitute=0)
: Sys_var_typelib(name_arg, comment, flag_args, off, getopt,
SHOW_CHAR, values, def_val, lock,
binlog_status_arg, on_check_func, on_update_func,
substitute)
{
option.var_type= GET_SET;
global_var(ulonglong)= def_val;
DBUG_ASSERT(typelib.count > 0);
DBUG_ASSERT(typelib.count <= 64);
DBUG_ASSERT(def_val < MAX_SET(typelib.count));
DBUG_ASSERT(size == sizeof(ulonglong));
}
bool do_check(THD *thd, set_var *var)
{
char buff[STRING_BUFFER_USUAL_SIZE];
String str(buff, sizeof(buff), system_charset_info), *res;
if (var->value->result_type() == STRING_RESULT)
{
if (!(res=var->value->val_str(&str)))
return true;
else
{
char *error;
uint error_len;
bool not_used;
var->save_result.ulonglong_value=
find_set(&typelib, res->ptr(),
static_cast<uint>(res->length()), NULL,
&error, &error_len, ¬_used);
/*
note, we only issue an error if error_len > 0.
That is even while empty (zero-length) values are considered
errors by find_set(), these errors are ignored here
*/
if (error_len)
{
ErrConvString err(error, error_len, res->charset());
my_error(ER_WRONG_VALUE_FOR_VAR, MYF(0), name.str, err.ptr());
return true;
}
}
}
else
{
longlong tmp=var->value->val_int();
if ((tmp < 0 && ! var->value->unsigned_flag)
|| (ulonglong)tmp > MAX_SET(typelib.count))
return true;
else
var->save_result.ulonglong_value= tmp;
}
return false;
}
bool session_update(THD *thd, set_var *var)
{
session_var(thd, ulonglong)= var->save_result.ulonglong_value;
return false;
}
bool global_update(THD *thd, set_var *var)
{
global_var(ulonglong)= var->save_result.ulonglong_value;
return false;
}
void session_save_default(THD *thd, set_var *var)
{ var->save_result.ulonglong_value= global_var(ulonglong); }
void global_save_default(THD *thd, set_var *var)
{ var->save_result.ulonglong_value= option.def_value; }
uchar *session_value_ptr(THD *running_thd, THD *target_thd, LEX_STRING *base)
{
return (uchar*)set_to_string(running_thd, 0, session_var(target_thd, ulonglong),
typelib.type_names);
}
uchar *global_value_ptr(THD *thd, LEX_STRING *base)
{
return (uchar*)set_to_string(thd, 0, global_var(ulonglong),
typelib.type_names);
}
};
/**
The class for variables which value is a plugin.
Example: @@default_storage_engine
Class specific constructor arguments:
int plugin_type_arg (for example MYSQL_STORAGE_ENGINE_PLUGIN)
Backing store: plugin_ref
@note
these variables don't support command-line equivalents, any such
command-line options should be added manually to my_long_options in mysqld.cc
*/
class Sys_var_plugin: public sys_var
{
int plugin_type;
public:
Sys_var_plugin(const char *name_arg,
const char *comment, int flag_args, ptrdiff_t off, size_t size,
CMD_LINE getopt,
int plugin_type_arg, char **def_val, PolyLock *lock=0,
enum binlog_status_enum binlog_status_arg=VARIABLE_NOT_IN_BINLOG,
on_check_function on_check_func=0,
on_update_function on_update_func=0,
const char *substitute=0,
int parse_flag= PARSE_NORMAL)
: sys_var(&all_sys_vars, name_arg, comment, flag_args, off, getopt.id,
getopt.arg_type, SHOW_CHAR, (intptr)def_val,
lock, binlog_status_arg, on_check_func, on_update_func,
substitute, parse_flag),
plugin_type(plugin_type_arg)
{
option.var_type= GET_STR;
DBUG_ASSERT(size == sizeof(plugin_ref));
DBUG_ASSERT(getopt.id == -1); // force NO_CMD_LINE
}
bool do_check(THD *thd, set_var *var)
{
char buff[STRING_BUFFER_USUAL_SIZE];
String str(buff,sizeof(buff), system_charset_info), *res;
/* NULLs can't be used as a default storage engine */
if (!(res=var->value->val_str(&str)))
return true;
const LEX_STRING pname= { const_cast<char*>(res->ptr()), res->length() };
plugin_ref plugin;
// special code for storage engines (e.g. to handle historical aliases)
if (plugin_type == MYSQL_STORAGE_ENGINE_PLUGIN)
plugin= ha_resolve_by_name(thd, &pname, FALSE);
else
{
LEX_CSTRING pname_cstr= { pname.str, pname.length };
plugin= my_plugin_lock_by_name(thd, pname_cstr, plugin_type);
}
if (!plugin)
{
// historically different error code
if (plugin_type == MYSQL_STORAGE_ENGINE_PLUGIN)
{
ErrConvString err(res);
my_error(ER_UNKNOWN_STORAGE_ENGINE, MYF(0), err.ptr());
}
return true;
}
var->save_result.plugin= plugin;
return false;
}
void do_update(plugin_ref *valptr, plugin_ref newval)
{
plugin_ref oldval= *valptr;
if (oldval != newval)
{
*valptr= my_plugin_lock(NULL, &newval);
plugin_unlock(NULL, oldval);
}
}
bool session_update(THD *thd, set_var *var)
{
do_update((plugin_ref*)session_var_ptr(thd),
var->save_result.plugin);
return false;
}
bool global_update(THD *thd, set_var *var)
{
do_update((plugin_ref*)global_var_ptr(),
var->save_result.plugin);
return false;
}
void session_save_default(THD *thd, set_var *var)
{
plugin_ref plugin= global_var(plugin_ref);
var->save_result.plugin= my_plugin_lock(thd, &plugin);
}
void global_save_default(THD *thd, set_var *var)
{
LEX_STRING pname;
char **default_value= reinterpret_cast<char**>(option.def_value);
pname.str= *default_value;
pname.length= strlen(pname.str);
plugin_ref plugin;
if (plugin_type == MYSQL_STORAGE_ENGINE_PLUGIN)
plugin= ha_resolve_by_name(thd, &pname, FALSE);
else
{
LEX_CSTRING pname_cstr= {pname.str,pname.length};
plugin= my_plugin_lock_by_name(thd, pname_cstr, plugin_type);
}
DBUG_ASSERT(plugin);
var->save_result.plugin= my_plugin_lock(thd, &plugin);
}
bool check_update_type(Item_result type)
{ return type != STRING_RESULT; }
uchar *session_value_ptr(THD *running_thd, THD *target_thd, LEX_STRING *base)
{
plugin_ref plugin= session_var(target_thd, plugin_ref);
return (uchar*)(plugin ? running_thd->strmake(plugin_name(plugin)->str,
plugin_name(plugin)->length) : 0);
}
uchar *global_value_ptr(THD *thd, LEX_STRING *base)
{
plugin_ref plugin= global_var(plugin_ref);
return (uchar*)(plugin ? thd->strmake(plugin_name(plugin)->str,
plugin_name(plugin)->length) : 0);
}
};
#if defined(ENABLED_DEBUG_SYNC)
/**
The class for @@debug_sync session-only variable
*/
class Sys_var_debug_sync :public sys_var
{
public:
Sys_var_debug_sync(const char *name_arg,
const char *comment, int flag_args,
CMD_LINE getopt,
const char *def_val, PolyLock *lock=0,
enum binlog_status_enum binlog_status_arg=VARIABLE_NOT_IN_BINLOG,
on_check_function on_check_func=0,
on_update_function on_update_func=0,
const char *substitute=0,
int parse_flag= PARSE_NORMAL)
: sys_var(&all_sys_vars, name_arg, comment, flag_args, 0, getopt.id,
getopt.arg_type, SHOW_CHAR, (intptr)def_val,
lock, binlog_status_arg, on_check_func, on_update_func,
substitute, parse_flag)
{
DBUG_ASSERT(scope() == ONLY_SESSION);
option.var_type= GET_NO_ARG;
}
bool do_check(THD *thd, set_var *var)
{
char buff[STRING_BUFFER_USUAL_SIZE];
String str(buff, sizeof(buff), system_charset_info), *res;
if (!(res=var->value->val_str(&str)))
var->save_result.string_value.str= const_cast<char*>("");
else
var->save_result.string_value.str= thd->strmake(res->ptr(), res->length());
return false;
}
bool session_update(THD *thd, set_var *var)
{
extern bool debug_sync_update(THD *thd, char *val_str);
return debug_sync_update(thd, var->save_result.string_value.str);
}
bool global_update(THD *thd, set_var *var)
{
DBUG_ASSERT(FALSE);
return true;
}
void session_save_default(THD *thd, set_var *var)
{
var->save_result.string_value.str= const_cast<char*>("");
var->save_result.string_value.length= 0;
}
void global_save_default(THD *thd, set_var *var)
{
DBUG_ASSERT(FALSE);
}
uchar *session_value_ptr(THD *running_thd, THD *target_thd, LEX_STRING *base)
{
extern uchar *debug_sync_value_ptr(THD *thd);
return debug_sync_value_ptr(running_thd);
}
uchar *global_value_ptr(THD *thd, LEX_STRING *base)
{
DBUG_ASSERT(FALSE);
return 0;
}
bool check_update_type(Item_result type)
{ return type != STRING_RESULT; }
};
#endif /* defined(ENABLED_DEBUG_SYNC) */
/**
The class for bit variables - a variant of boolean that stores the value
in a bit.
Class specific constructor arguments:
ulonglong bitmask_arg - the mask for the bit to set in the ulonglong
backing store
Backing store: ulonglong
@note
This class supports the "reverse" semantics, when the value of the bit
being 0 corresponds to the value of variable being set. To activate it
use REVERSE(bitmask) instead of simply bitmask in the constructor.
@note
variables of this class cannot be set from the command line as
my_getopt does not support bits.
*/
class Sys_var_bit: public Sys_var_typelib
{
ulonglong bitmask;
bool reverse_semantics;
void set(uchar *ptr, ulonglong value)
{
if ((value != 0) ^ reverse_semantics)
(*(ulonglong *)ptr)|= bitmask;
else
(*(ulonglong *)ptr)&= ~bitmask;
}
public:
Sys_var_bit(const char *name_arg,
const char *comment, int flag_args, ptrdiff_t off, size_t size,
CMD_LINE getopt,
ulonglong bitmask_arg, my_bool def_val, PolyLock *lock=0,
enum binlog_status_enum binlog_status_arg=VARIABLE_NOT_IN_BINLOG,
on_check_function on_check_func=0,
on_update_function on_update_func=0,
const char *substitute=0)
: Sys_var_typelib(name_arg, comment, flag_args, off, getopt,
SHOW_MY_BOOL, bool_values, def_val, lock,
binlog_status_arg, on_check_func, on_update_func,
substitute)
{
option.var_type= GET_BOOL;
reverse_semantics= my_count_bits(bitmask_arg) > 1;
bitmask= reverse_semantics ? ~bitmask_arg : bitmask_arg;
set(global_var_ptr(), def_val);
DBUG_ASSERT(def_val < 2);
DBUG_ASSERT(getopt.id == -1); // force NO_CMD_LINE
DBUG_ASSERT(size == sizeof(ulonglong));
}
bool session_update(THD *thd, set_var *var)
{
set(session_var_ptr(thd), var->save_result.ulonglong_value);
return false;
}
bool global_update(THD *thd, set_var *var)
{
set(global_var_ptr(), var->save_result.ulonglong_value);
return false;
}
void session_save_default(THD *thd, set_var *var)
{ var->save_result.ulonglong_value= global_var(ulonglong) & bitmask; }
void global_save_default(THD *thd, set_var *var)
{ var->save_result.ulonglong_value= option.def_value; }
uchar *session_value_ptr(THD *running_thd, THD *target_thd, LEX_STRING *base)
{
running_thd->sys_var_tmp.my_bool_value=
static_cast<my_bool>(reverse_semantics ^
((session_var(target_thd, ulonglong) & bitmask) != 0));
return (uchar*) &running_thd->sys_var_tmp.my_bool_value;
}
uchar *global_value_ptr(THD *thd, LEX_STRING *base)
{
thd->sys_var_tmp.my_bool_value=
static_cast<my_bool>(reverse_semantics ^
((global_var(ulonglong) & bitmask) != 0));
return (uchar*) &thd->sys_var_tmp.my_bool_value;
}
};
/**
The class for variables that have a special meaning for a session,
such as @@timestamp or @@rnd_seed1, their values typically cannot be read
from SV structure, and a special "read" callback is provided.
Class specific constructor arguments:
everything derived from Sys_var_ulonglong
session_special_read_function read_func_arg
Backing store: ulonglong
@note
These variables are session-only, global or command-line equivalents
are not supported as they're generally meaningless.
*/
class Sys_var_session_special: public Sys_var_ulonglong
{
typedef bool (*session_special_update_function)(THD *thd, set_var *var);
typedef ulonglong (*session_special_read_function)(THD *thd);
session_special_read_function read_func;
session_special_update_function update_func;
public:
Sys_var_session_special(const char *name_arg,
const char *comment, int flag_args,
CMD_LINE getopt,
ulonglong min_val, ulonglong max_val, uint block_size,
PolyLock *lock, enum binlog_status_enum binlog_status_arg,
on_check_function on_check_func,
session_special_update_function update_func_arg,
session_special_read_function read_func_arg,
const char *substitute=0)
: Sys_var_ulonglong(name_arg, comment, flag_args, 0,
sizeof(ulonglong), getopt, min_val,
max_val, 0, block_size, lock, binlog_status_arg, on_check_func, 0,
substitute),
read_func(read_func_arg), update_func(update_func_arg)
{
DBUG_ASSERT(scope() == ONLY_SESSION);
DBUG_ASSERT(getopt.id == -1); // NO_CMD_LINE, because the offset is fake
}
bool session_update(THD *thd, set_var *var)
{ return update_func(thd, var); }
bool global_update(THD *thd, set_var *var)
{
DBUG_ASSERT(FALSE);
return true;
}
void session_save_default(THD *thd, set_var *var)
{ var->value= 0; }
void global_save_default(THD *thd, set_var *var)
{ DBUG_ASSERT(FALSE); }
uchar *session_value_ptr(THD *running_thd, THD *target_thd, LEX_STRING *base)
{
running_thd->sys_var_tmp.ulonglong_value= read_func(target_thd);
return (uchar*) &running_thd->sys_var_tmp.ulonglong_value;
}
uchar *global_value_ptr(THD *thd, LEX_STRING *base)
{
DBUG_ASSERT(FALSE);
return 0;
}
};
/**
Similar to Sys_var_session_special, but with double storage.
*/
class Sys_var_session_special_double: public Sys_var_double
{
typedef bool (*session_special_update_function)(THD *thd, set_var *var);
typedef double (*session_special_read_double_function)(THD *thd);
session_special_read_double_function read_func;
session_special_update_function update_func;
public:
Sys_var_session_special_double(const char *name_arg,
const char *comment, int flag_args,
CMD_LINE getopt,
double min_val, double max_val, uint block_size,
PolyLock *lock, enum binlog_status_enum binlog_status_arg,
on_check_function on_check_func,
session_special_update_function update_func_arg,
session_special_read_double_function read_func_arg,
const char *substitute=0)
: Sys_var_double(name_arg, comment, flag_args, 0,
sizeof(double), getopt,
min_val, max_val, 0.0,
lock, binlog_status_arg, on_check_func, 0,
substitute),
read_func(read_func_arg), update_func(update_func_arg)
{
DBUG_ASSERT(scope() == ONLY_SESSION);
DBUG_ASSERT(getopt.id == -1); // NO_CMD_LINE, because the offset is fake
}
bool session_update(THD *thd, set_var *var)
{ return update_func(thd, var); }
bool global_update(THD *thd, set_var *var)
{
DBUG_ASSERT(FALSE);
return true;
}
void session_save_default(THD *thd, set_var *var)
{ var->value= 0; }
void global_save_default(THD *thd, set_var *var)
{ DBUG_ASSERT(FALSE); }
uchar *session_value_ptr(THD *running_thd, THD *target_thd, LEX_STRING *base)
{
running_thd->sys_var_tmp.double_value= read_func(target_thd);
return (uchar *) &running_thd->sys_var_tmp.double_value;
}
uchar *global_value_ptr(THD *thd, LEX_STRING *base)
{
DBUG_ASSERT(FALSE);
return 0;
}
};
/**
The class for read-only variables that show whether a particular
feature is supported by the server. Example: have_compression
Backing store: enum SHOW_COMP_OPTION
@note
These variables are necessarily read-only, only global, and have no
command-line equivalent.
*/
class Sys_var_have: public sys_var
{
public:
Sys_var_have(const char *name_arg,
const char *comment, int flag_args, ptrdiff_t off, size_t size,
CMD_LINE getopt,
PolyLock *lock=0,
enum binlog_status_enum binlog_status_arg=VARIABLE_NOT_IN_BINLOG,
on_check_function on_check_func=0,
on_update_function on_update_func=0,
const char *substitute=0,
int parse_flag= PARSE_NORMAL)
: sys_var(&all_sys_vars, name_arg, comment, flag_args, off, getopt.id,
getopt.arg_type, SHOW_CHAR, 0,
lock, binlog_status_arg, on_check_func, on_update_func,
substitute, parse_flag)
{
DBUG_ASSERT(scope() == GLOBAL);
DBUG_ASSERT(getopt.id == -1);
DBUG_ASSERT(lock == 0);
DBUG_ASSERT(binlog_status_arg == VARIABLE_NOT_IN_BINLOG);
DBUG_ASSERT(is_readonly());
DBUG_ASSERT(on_update == 0);
DBUG_ASSERT(size == sizeof(enum SHOW_COMP_OPTION));
}
bool do_check(THD *thd, set_var *var) {
DBUG_ASSERT(FALSE);
return true;
}
bool session_update(THD *thd, set_var *var)
{
DBUG_ASSERT(FALSE);
return true;
}
bool global_update(THD *thd, set_var *var)
{
DBUG_ASSERT(FALSE);
return true;
}
void session_save_default(THD *thd, set_var *var) { }
void global_save_default(THD *thd, set_var *var) { }
uchar *session_value_ptr(THD *running_thd, THD *target_thd, LEX_STRING *base)
{
DBUG_ASSERT(FALSE);
return 0;
}
uchar *global_value_ptr(THD *thd, LEX_STRING *base)
{
return (uchar*)show_comp_option_name[global_var(enum SHOW_COMP_OPTION)];
}
bool check_update_type(Item_result type) { return false; }
};
/**
Generic class for variables for storing entities that are internally
represented as structures, have names, and possibly can be referred to by
numbers. Examples: character sets, collations, locales,
Class specific constructor arguments:
ptrdiff_t name_offset - offset of the 'name' field in the structure
Backing store: void*
@note
As every such a structure requires special treatment from my_getopt,
these variables don't support command-line equivalents, any such
command-line options should be added manually to my_long_options in mysqld.cc
*/
class Sys_var_struct: public sys_var
{
ptrdiff_t name_offset; // offset to the 'name' property in the structure
public:
Sys_var_struct(const char *name_arg,
const char *comment, int flag_args, ptrdiff_t off, size_t size,
CMD_LINE getopt,
ptrdiff_t name_off, void *def_val, PolyLock *lock=0,
enum binlog_status_enum binlog_status_arg=VARIABLE_NOT_IN_BINLOG,
on_check_function on_check_func=0,
on_update_function on_update_func=0,
const char *substitute=0,
int parse_flag= PARSE_NORMAL)
: sys_var(&all_sys_vars, name_arg, comment, flag_args, off, getopt.id,
getopt.arg_type, SHOW_CHAR, (intptr)def_val,
lock, binlog_status_arg, on_check_func, on_update_func,
substitute, parse_flag),
name_offset(name_off)
{
option.var_type= GET_STR;
/*
struct variables are special on the command line - often (e.g. for
charsets) the name cannot be immediately resolved, but only after all
options (in particular, basedir) are parsed.
thus all struct command-line options should be added manually
to my_long_options in mysqld.cc
*/
DBUG_ASSERT(getopt.id == -1);
DBUG_ASSERT(size == sizeof(void *));
}
bool do_check(THD *thd, set_var *var)
{ return false; }
bool session_update(THD *thd, set_var *var)
{
session_var(thd, const void*)= var->save_result.ptr;
return false;
}
bool global_update(THD *thd, set_var *var)
{
global_var(const void*)= var->save_result.ptr;
return false;
}
void session_save_default(THD *thd, set_var *var)
{ var->save_result.ptr= global_var(void*); }
void global_save_default(THD *thd, set_var *var)
{
void **default_value= reinterpret_cast<void**>(option.def_value);
var->save_result.ptr= *default_value;
}
bool check_update_type(Item_result type)
{ return type != INT_RESULT && type != STRING_RESULT; }
uchar *session_value_ptr(THD *running_thd, THD *target_thd, LEX_STRING *base)
{
uchar *ptr= session_var(target_thd, uchar*);
return ptr ? *(uchar**)(ptr+name_offset) : 0;
}
uchar *global_value_ptr(THD *thd, LEX_STRING *base)
{
uchar *ptr= global_var(uchar*);
return ptr ? *(uchar**)(ptr+name_offset) : 0;
}
};
/**
The class for variables that store time zones
Backing store: Time_zone*
@note
Time zones cannot be supported directly by my_getopt, thus
these variables don't support command-line equivalents, any such
command-line options should be added manually to my_long_options in mysqld.cc
*/
class Sys_var_tz: public sys_var
{
public:
Sys_var_tz(const char *name_arg,
const char *comment, int flag_args, ptrdiff_t off, size_t size,
CMD_LINE getopt,
Time_zone **def_val, PolyLock *lock=0,
enum binlog_status_enum binlog_status_arg=VARIABLE_NOT_IN_BINLOG,
on_check_function on_check_func=0,
on_update_function on_update_func=0,
const char *substitute=0,
int parse_flag= PARSE_NORMAL)
: sys_var(&all_sys_vars, name_arg, comment, flag_args, off, getopt.id,
getopt.arg_type, SHOW_CHAR, (intptr)def_val,
lock, binlog_status_arg, on_check_func, on_update_func,
substitute, parse_flag)
{
DBUG_ASSERT(getopt.id == -1);
DBUG_ASSERT(size == sizeof(Time_zone *));
}
bool do_check(THD *thd, set_var *var)
{
char buff[MAX_TIME_ZONE_NAME_LENGTH];
String str(buff, sizeof(buff), &my_charset_latin1);
String *res= var->value->val_str(&str);
if (!res)
return true;
if (!(var->save_result.time_zone= my_tz_find(thd, res)))
{
ErrConvString err(res);
my_error(ER_UNKNOWN_TIME_ZONE, MYF(0), err.ptr());
return true;
}
return false;
}
bool session_update(THD *thd, set_var *var)
{
session_var(thd, Time_zone*)= var->save_result.time_zone;
return false;
}
bool global_update(THD *thd, set_var *var)
{
global_var(Time_zone*)= var->save_result.time_zone;
return false;
}
void session_save_default(THD *thd, set_var *var)
{
var->save_result.time_zone= global_var(Time_zone*);
}
void global_save_default(THD *thd, set_var *var)
{
var->save_result.time_zone=
*(Time_zone**)(intptr)option.def_value;
}
uchar *session_value_ptr(THD *running_thd, THD *target_thd, LEX_STRING *base)
{
/*
This is an ugly fix for replication: we don't replicate properly queries
invoking system variables' values to update tables; but
CONVERT_TZ(,,@@session.time_zone) is so popular that we make it
replicable (i.e. we tell the binlog code to store the session
timezone). If it's the global value which was used we can't replicate
(binlog code stores session value only).
*/
target_thd->time_zone_used= 1;
return (uchar *)(session_var(target_thd, Time_zone*)->get_name()->ptr());
}
uchar *global_value_ptr(THD *thd, LEX_STRING *base)
{
return (uchar *)(global_var(Time_zone*)->get_name()->ptr());
}
bool check_update_type(Item_result type)
{ return type != STRING_RESULT; }
};
/**
Class representing the 'tx_isolation' system variable. This
variable can also be indirectly set using 'SET TRANSACTION ISOLATION
LEVEL'. This variable is deprecated and will be removed in a
future release. 'transaction_isolation' is used an alternative
instead.
*/
class Sys_var_tx_isolation: public Sys_var_enum
{
public:
Sys_var_tx_isolation(const char *name_arg,
const char *comment, int flag_args, ptrdiff_t off, size_t size,
CMD_LINE getopt,
const char *values[], uint def_val, PolyLock *lock,
enum binlog_status_enum binlog_status_arg,
on_check_function on_check_func,
on_update_function on_update_func=0,
const char *substitute=0)
:Sys_var_enum(name_arg, comment, flag_args, off, size, getopt,
values, def_val, lock, binlog_status_arg, on_check_func,
on_update_func, substitute)
{}
virtual bool session_update(THD *thd, set_var *var);
};
/**
Class representing the tx_read_only system variable for setting
default transaction access mode. This variable is deprecated
and will be removed in future release. 'transaction_read_only'
is used as an alternative instead.
Note that there is a special syntax - SET TRANSACTION READ ONLY
(or READ WRITE) that sets the access mode for the next transaction
only.
*/
class Sys_var_tx_read_only: public Sys_var_mybool
{
public:
Sys_var_tx_read_only(const char *name_arg, const char *comment, int flag_args,
ptrdiff_t off, size_t size, CMD_LINE getopt,
my_bool def_val, PolyLock *lock,
enum binlog_status_enum binlog_status_arg,
on_check_function on_check_func,
on_update_function on_update_func=0,
const char *substitute=0)
:Sys_var_mybool(name_arg, comment, flag_args, off, size, getopt,
def_val, lock, binlog_status_arg, on_check_func,
on_update_func, substitute)
{}
virtual bool session_update(THD *thd, set_var *var);
};
/**
Class representing the sql_log_bin system variable for controlling
whether logging to the binary log is done.
*/
class Sys_var_sql_log_bin: public Sys_var_mybool
{
public:
Sys_var_sql_log_bin(const char *name_arg, const char *comment, int flag_args,
ptrdiff_t off, size_t size, CMD_LINE getopt,
my_bool def_val, PolyLock *lock,
enum binlog_status_enum binlog_status_arg,
on_check_function on_check_func,
on_update_function on_update_func)
:Sys_var_mybool(name_arg, comment, flag_args, off, size, getopt,
def_val, lock, binlog_status_arg, on_check_func,
on_update_func)
{}
uchar *global_value_ptr(THD *thd, LEX_STRING *base)
{
/* Reading GLOBAL SQL_LOG_BIN produces a deprecation warning. */
if (base != NULL)
push_warning_printf(thd, Sql_condition::SL_WARNING,
ER_WARN_DEPRECATED_SYNTAX,
ER(ER_WARN_DEPRECATED_SYNTAX),
"@@global.sql_log_bin", "the constant 1 "
"(since @@global.sql_log_bin is always equal to 1)");
return Sys_var_mybool::global_value_ptr(thd, base);
}
};
/**
A class for @@global.binlog_checksum that has
a specialized update method.
*/
class Sys_var_enum_binlog_checksum: public Sys_var_enum
{
public:
Sys_var_enum_binlog_checksum(const char *name_arg,
const char *comment, int flag_args, ptrdiff_t off, size_t size,
CMD_LINE getopt,
const char *values[], uint def_val, PolyLock *lock,
enum binlog_status_enum binlog_status_arg,
on_check_function on_check_func=0
)
:Sys_var_enum(name_arg, comment, flag_args, off, size, getopt,
values, def_val, lock, binlog_status_arg, on_check_func, NULL)
{}
virtual bool global_update(THD *thd, set_var *var);
};
/**
Class for gtid_next.
*/
class Sys_var_gtid_next: public sys_var
{
public:
Sys_var_gtid_next(const char *name_arg,
const char *comment, int flag_args, ptrdiff_t off, size_t size,
CMD_LINE getopt,
const char *def_val,
PolyLock *lock= 0,
enum binlog_status_enum binlog_status_arg=VARIABLE_NOT_IN_BINLOG,
on_check_function on_check_func=0,
on_update_function on_update_func=0,
const char *substitute=0,
int parse_flag= PARSE_NORMAL)
: sys_var(&all_sys_vars, name_arg, comment, flag_args, off, getopt.id,
getopt.arg_type, SHOW_CHAR, (intptr)def_val,
lock, binlog_status_arg, on_check_func, on_update_func,
substitute, parse_flag)
{
DBUG_ASSERT(size == sizeof(Gtid_specification));
}
bool session_update(THD *thd, set_var *var)
{
DBUG_ENTER("Sys_var_gtid_next::session_update");
char buf[Gtid::MAX_TEXT_LENGTH + 1];
// Get the value
String str(buf, sizeof(buf), &my_charset_latin1);
char* res= NULL;
if (!var->value)
{
// set session gtid_next= default
DBUG_ASSERT(var->save_result.string_value.str);
DBUG_ASSERT(var->save_result.string_value.length);
res= var->save_result.string_value.str;
}
else if (var->value->val_str(&str))
res= var->value->val_str(&str)->c_ptr_safe();
if (!res)
{
my_error(ER_WRONG_VALUE_FOR_VAR, MYF(0), name.str, "NULL");
DBUG_RETURN(true);
}
global_sid_lock->rdlock();
Gtid_specification spec;
if (spec.parse(global_sid_map, res) != RETURN_STATUS_OK)
{
global_sid_lock->unlock();
DBUG_RETURN(true);
}
bool ret= set_gtid_next(thd, spec);
// set_gtid_next releases global_sid_lock
DBUG_RETURN(ret);
}
bool global_update(THD *thd, set_var *var)
{ DBUG_ASSERT(FALSE); return true; }
void session_save_default(THD *thd, set_var *var)
{
DBUG_ENTER("Sys_var_gtid_next::session_save_default");
char* ptr= (char*)(intptr)option.def_value;
var->save_result.string_value.str= ptr;
var->save_result.string_value.length= ptr ? strlen(ptr) : 0;
DBUG_VOID_RETURN;
}
void global_save_default(THD *thd, set_var *var)
{ DBUG_ASSERT(FALSE); }
bool do_check(THD *thd, set_var *var)
{ return false; }
bool check_update_type(Item_result type)
{ return type != STRING_RESULT; }
uchar *session_value_ptr(THD *running_thd, THD *target_thd, LEX_STRING *base)
{
DBUG_ENTER("Sys_var_gtid_next::session_value_ptr");
char buf[Gtid_specification::MAX_TEXT_LENGTH + 1];
global_sid_lock->rdlock();
((Gtid_specification *)session_var_ptr(target_thd))->
to_string(global_sid_map, buf);
global_sid_lock->unlock();
char *ret= running_thd->mem_strdup(buf);
DBUG_RETURN((uchar *)ret);
}
uchar *global_value_ptr(THD *thd, LEX_STRING *base)
{ DBUG_ASSERT(FALSE); return NULL; }
};
#ifdef HAVE_GTID_NEXT_LIST
/**
Class for variables that store values of type Gtid_set.
The back-end storage should be a Gtid_set_or_null, and it should be
set to null by default. When the variable is set for the first
time, the Gtid_set* will be allocated.
*/
class Sys_var_gtid_set: public sys_var
{
public:
Sys_var_gtid_set(const char *name_arg,
const char *comment, int flag_args, ptrdiff_t off, size_t size,
CMD_LINE getopt,
const char *def_val,
PolyLock *lock= 0,
enum binlog_status_enum binlog_status_arg=VARIABLE_NOT_IN_BINLOG,
on_check_function on_check_func=0,
on_update_function on_update_func=0,
const char *substitute=0,
int parse_flag= PARSE_NORMAL)
: sys_var(&all_sys_vars, name_arg, comment, flag_args, off, getopt.id,
getopt.arg_type, SHOW_CHAR, (intptr)def_val,
lock, binlog_status_arg, on_check_func, on_update_func,
substitute, parse_flag)
{
DBUG_ASSERT(size == sizeof(Gtid_set_or_null));
}
bool session_update(THD *thd, set_var *var)
{
DBUG_ENTER("Sys_var_gtid_set::session_update");
Gtid_set_or_null *gsn=
(Gtid_set_or_null *)session_var_ptr(thd);
char *value= var->save_result.string_value.str;
if (value == NULL)
gsn->set_null();
else
{
Gtid_set *gs= gsn->set_non_null(global_sid_map);
if (gs == NULL)
{
my_error(ER_OUT_OF_RESOURCES, MYF(0)); // allocation failed
DBUG_RETURN(true);
}
/*
If string begins with '+', add to the existing set, otherwise
replace existing set.
*/
while (isspace(*value))
value++;
if (*value == '+')
value++;
else
gs->clear();
// Add specified set of groups to Gtid_set.
global_sid_lock->rdlock();
enum_return_status ret= gs->add_gtid_text(value);
global_sid_lock->unlock();
if (ret != RETURN_STATUS_OK)
{
gsn->set_null();
DBUG_RETURN(true);
}
}
DBUG_RETURN(false);
}
bool global_update(THD *thd, set_var *var)
{ DBUG_ASSERT(FALSE); return true; }
void session_save_default(THD *thd, set_var *var)
{
DBUG_ENTER("Sys_var_gtid_set::session_save_default");
global_sid_lock->rdlock();
char *ptr= (char*)(intptr)option.def_value;
var->save_result.string_value.str= ptr;
var->save_result.string_value.length= ptr ? strlen(ptr) : 0;
global_sid_lock->unlock();
DBUG_VOID_RETURN;
}
void global_save_default(THD *thd, set_var *var)
{ DBUG_ASSERT(FALSE); }
bool do_check(THD *thd, set_var *var)
{
DBUG_ENTER("Sys_var_gtid_set::do_check");
String str;
String *res= var->value->val_str(&str);
if (res == NULL)
{
var->save_result.string_value.str= NULL;
DBUG_RETURN(FALSE);
}
DBUG_ASSERT(res->ptr() != NULL);
var->save_result.string_value.str= thd->strmake(res->ptr(), res->length());
if (var->save_result.string_value.str == NULL)
{
my_error(ER_OUT_OF_RESOURCES, MYF(0)); // thd->strmake failed
DBUG_RETURN(1);
}
var->save_result.string_value.length= res->length();
bool ret= !Gtid_set::is_valid(res->ptr());
DBUG_RETURN(ret);
}
bool check_update_type(Item_result type)
{ return type != STRING_RESULT; }
uchar *session_value_ptr(THD *running_thd, THD *target_thd, LEX_STRING *base)
{
DBUG_ENTER("Sys_var_gtid_set::session_value_ptr");
Gtid_set_or_null *gsn= (Gtid_set_or_null *)session_var_ptr(target_thd);
Gtid_set *gs= gsn->get_gtid_set();
if (gs == NULL)
DBUG_RETURN(NULL);
char *buf;
global_sid_lock->rdlock();
buf= (char *)running_thd->alloc(gs->get_string_length() + 1);
if (buf)
gs->to_string(buf);
else
my_error(ER_OUT_OF_RESOURCES, MYF(0)); // thd->alloc failed
global_sid_lock->unlock();
DBUG_RETURN((uchar *)buf);
}
uchar *global_value_ptr(THD *thd, LEX_STRING *base)
{ DBUG_ASSERT(FALSE); return NULL; }
};
#endif
/**
Abstract base class for read-only variables (global or session) of
string type where the value is generated by some function. This
needs to be subclassed; the session_value_ptr or global_value_ptr
function should be overridden.
*/
class Sys_var_charptr_func: public sys_var
{
public:
Sys_var_charptr_func(const char *name_arg, const char *comment,
flag_enum flag_arg)
: sys_var(&all_sys_vars, name_arg, comment, READ_ONLY flag_arg,
0/*off*/, NO_CMD_LINE.id, NO_CMD_LINE.arg_type,
SHOW_CHAR, (intptr)0/*def_val*/,
NULL/*polylock*/, VARIABLE_NOT_IN_BINLOG,
NULL/*on_check_func*/, NULL/*on_update_func*/,
NULL/*substitute*/, PARSE_NORMAL/*parse_flag*/)
{
DBUG_ASSERT(flag_arg == sys_var::GLOBAL || flag_arg == sys_var::SESSION ||
flag_arg == sys_var::ONLY_SESSION);
}
bool session_update(THD *thd, set_var *var)
{ DBUG_ASSERT(FALSE); return true; }
bool global_update(THD *thd, set_var *var)
{ DBUG_ASSERT(FALSE); return true; }
void session_save_default(THD *thd, set_var *var) { DBUG_ASSERT(FALSE); }
void global_save_default(THD *thd, set_var *var) { DBUG_ASSERT(FALSE); }
bool do_check(THD *thd, set_var *var) { DBUG_ASSERT(FALSE); return true; }
bool check_update_type(Item_result type) { DBUG_ASSERT(FALSE); return true; }
virtual uchar *session_value_ptr(THD *running_thd, THD *target_thd, LEX_STRING *base)
{ DBUG_ASSERT(FALSE); return NULL; }
virtual uchar *global_value_ptr(THD *thd, LEX_STRING *base)
{ DBUG_ASSERT(FALSE); return NULL; }
};
/**
Class for @@session.gtid_executed and @@global.gtid_executed.
*/
class Sys_var_gtid_executed : Sys_var_charptr_func
{
public:
Sys_var_gtid_executed(const char *name_arg, const char *comment_arg)
: Sys_var_charptr_func(name_arg, comment_arg, SESSION) {}
uchar *global_value_ptr(THD *thd, LEX_STRING *base)
{
DBUG_ENTER("Sys_var_gtid_executed::global_value_ptr");
global_sid_lock->wrlock();
const Gtid_set *gs= gtid_state->get_executed_gtids();
char *buf= (char *)thd->alloc(gs->get_string_length() + 1);
if (buf == NULL)
my_error(ER_OUT_OF_RESOURCES, MYF(0));
else
gs->to_string(buf);
global_sid_lock->unlock();
DBUG_RETURN((uchar *)buf);
}
public:
uchar *session_value_ptr(THD *running_thd, THD *target_thd, LEX_STRING *base)
{
DBUG_ENTER("Sys_var_gtid_executed::session_value_ptr");
if (!running_thd->gtid_executed_warning_issued)
{
push_warning_printf(running_thd, Sql_condition::SL_WARNING,
ER_WARN_DEPRECATED_SYNTAX_NO_REPLACEMENT,
ER(ER_WARN_DEPRECATED_SYNTAX_NO_REPLACEMENT),
"@@SESSION.GTID_EXECUTED");
running_thd->gtid_executed_warning_issued= true;
}
if (opt_bin_log &&
(target_thd == running_thd)) /* Supported for current thread only. */
{
target_thd->binlog_setup_trx_data();
/*
It is enough to check if the transaction cache is nonempty, we
do not need to check the statement cache. The statement cache
can only be nonempty for single-statement transactions. Since
single-statement transactions are flushed to the binary log
before the next statement gets to execute, there is no chance
that the value of @@session.gtid_executed is read when the
statement cache is nonempty.
*/
if (!target_thd->is_binlog_cache_empty(true))
{
/*
The case sidno == -1 cannot happen since it is not implemented.
The cases sidno == 0 and sidno == -2 mean that we don't own any
GTID, so we should return empty string.
*/
if (target_thd->owned_gtid.sidno > 0)
{
uchar *buf= (uchar *)running_thd->alloc(Gtid::MAX_TEXT_LENGTH + 1);
if (buf == NULL)
my_error(ER_OUT_OF_RESOURCES, MYF(0));
else
target_thd->owned_gtid.to_string(target_thd->owned_sid, (char *)buf);
DBUG_RETURN(buf);
}
}
}
uchar *buf= (uchar *)running_thd->alloc(1);
if (buf == NULL)
my_error(ER_OUT_OF_RESOURCES, MYF(0));
else
buf[0]= 0;
DBUG_RETURN(buf);
}
};
/**
Class for @@session.gtid_purged.
*/
class Sys_var_gtid_purged : public sys_var
{
public:
Sys_var_gtid_purged(const char *name_arg,
const char *comment, int flag_args, ptrdiff_t off, size_t size,
CMD_LINE getopt,
const char *def_val,
PolyLock *lock= 0,
enum binlog_status_enum binlog_status_arg=VARIABLE_NOT_IN_BINLOG,
on_check_function on_check_func=0,
on_update_function on_update_func=0,
const char *substitute=0,
int parse_flag= PARSE_NORMAL)
: sys_var(&all_sys_vars, name_arg, comment, flag_args, off, getopt.id,
getopt.arg_type, SHOW_CHAR, (intptr)def_val,
lock, binlog_status_arg, on_check_func, on_update_func,
substitute, parse_flag)
{}
bool session_update(THD *thd, set_var *var)
{
DBUG_ASSERT(FALSE);
return true;
}
void session_save_default(THD *thd, set_var *var)
{ DBUG_ASSERT(FALSE); }
bool global_update(THD *thd, set_var *var);
void global_save_default(THD *thd, set_var *var)
{
/* gtid_purged does not have default value */
my_error(ER_NO_DEFAULT, MYF(0), var->var->name.str);
}
bool do_check(THD *thd, set_var *var)
{
DBUG_ENTER("Sys_var_gtid_purged::do_check");
char buf[1024];
String str(buf, sizeof(buf), system_charset_info);
String *res= var->value->val_str(&str);
if (!res)
DBUG_RETURN(true);
var->save_result.string_value.str= thd->strmake(res->c_ptr_safe(),
res->length());
if (!var->save_result.string_value.str)
{
my_error(ER_OUT_OF_RESOURCES, MYF(0)); // thd->strmake failed
DBUG_RETURN(true);
}
var->save_result.string_value.length= res->length();
bool ret= Gtid_set::is_valid(res->c_ptr_safe()) ? false : true;
DBUG_PRINT("info", ("ret=%d", ret));
DBUG_RETURN(ret);
}
bool check_update_type(Item_result type)
{ return type != STRING_RESULT; }
uchar *global_value_ptr(THD *thd, LEX_STRING *base)
{
DBUG_ENTER("Sys_var_gtid_purged::global_value_ptr");
const Gtid_set *gs;
global_sid_lock->wrlock();
if (opt_bin_log)
gs= gtid_state->get_lost_gtids();
else
/*
When binlog is off, report @@GLOBAL.GTID_PURGED from
executed_gtids, since @@GLOBAL.GTID_PURGED and
@@GLOBAL.GTID_EXECUTED are always same, so we did not
save gtid into lost_gtids for every transaction for
improving performance.
*/
gs= gtid_state->get_executed_gtids();
char *buf= (char *)thd->alloc(gs->get_string_length() + 1);
if (buf == NULL)
my_error(ER_OUT_OF_RESOURCES, MYF(0));
else
gs->to_string(buf);
global_sid_lock->unlock();
DBUG_RETURN((uchar *)buf);
}
uchar *session_value_ptr(THD *running_thd, THD *target_thd, LEX_STRING *base)
{ DBUG_ASSERT(0); return NULL; }
};
class Sys_var_gtid_owned : Sys_var_charptr_func
{
public:
Sys_var_gtid_owned(const char *name_arg, const char *comment_arg)
: Sys_var_charptr_func(name_arg, comment_arg, SESSION) {}
public:
uchar *session_value_ptr(THD *running_thd, THD *target_thd, LEX_STRING *base)
{
DBUG_ENTER("Sys_var_gtid_owned::session_value_ptr");
char *buf= NULL;
bool remote= (target_thd != running_thd);
if (target_thd->owned_gtid.sidno == 0)
DBUG_RETURN((uchar *)running_thd->mem_strdup(""));
else if (target_thd->owned_gtid.sidno == THD::OWNED_SIDNO_ANONYMOUS)
{
DBUG_ASSERT(gtid_state->get_anonymous_ownership_count() > 0);
DBUG_RETURN((uchar *)running_thd->mem_strdup("ANONYMOUS"));
}
else if (target_thd->owned_gtid.sidno == THD::OWNED_SIDNO_GTID_SET)
{
#ifdef HAVE_GTID_NEXT_LIST
buf= (char *)running_thd->alloc(target_thd->owned_gtid_set.get_string_length() + 1);
if (buf)
{
global_sid_lock->rdlock();
target_thd->owned_gtid_set.to_string(buf);
global_sid_lock->unlock();
}
else
my_error(ER_OUT_OF_RESOURCES, MYF(0));
#else
DBUG_ASSERT(0);
#endif
}
else
{
buf= (char *)running_thd->alloc(Gtid::MAX_TEXT_LENGTH + 1);
if (buf)
{
/* Take the lock if accessing another session. */
if (remote)
global_sid_lock->rdlock();
running_thd->owned_gtid.to_string(target_thd->owned_sid, buf);
if (remote)
global_sid_lock->unlock();
}
else
my_error(ER_OUT_OF_RESOURCES, MYF(0));
}
DBUG_RETURN((uchar *)buf);
}
uchar *global_value_ptr(THD *thd, LEX_STRING *base)
{
DBUG_ENTER("Sys_var_gtid_owned::global_value_ptr");
const Owned_gtids *owned_gtids= gtid_state->get_owned_gtids();
global_sid_lock->wrlock();
char *buf= (char *)thd->alloc(owned_gtids->get_max_string_length());
if (buf)
owned_gtids->to_string(buf);
else
my_error(ER_OUT_OF_RESOURCES, MYF(0)); // thd->alloc failed
global_sid_lock->unlock();
DBUG_RETURN((uchar *)buf);
}
};
#ifdef HAVE_REPLICATION
class Sys_var_gtid_mode : public Sys_var_enum
{
public:
Sys_var_gtid_mode(const char *name_arg,
const char *comment,
int flag_args,
ptrdiff_t off,
size_t size,
CMD_LINE getopt,
const char *values[],
uint def_val,
PolyLock *lock=0,
enum binlog_status_enum binlog_status_arg=VARIABLE_NOT_IN_BINLOG,
on_check_function on_check_func=0) :
Sys_var_enum(name_arg, comment, flag_args, off, size,
getopt, values, def_val, lock, binlog_status_arg,
on_check_func)
{ }
bool global_update(THD *thd, set_var *var)
{
DBUG_ENTER("Sys_var_gtid_mode::global_update");
bool ret= true;
/*
SET GITD_MODE command should ignore 'read-only' and 'super_read_only'
options so that it can update 'mysql.gtid_executed' replication repository
table.
*/
thd->set_skip_readonly_check();
/*
Hold lock_log so that:
- other transactions are not flushed while gtid_mode is changed;
- gtid_mode is not changed while some other thread is rotating
the binlog.
Hold channel_map lock so that:
- gtid_mode is not changed during the execution of some
replication command; particularly CHANGE MASTER. CHANGE MASTER
checks if GTID_MODE is compatible with AUTO_POSITION, and
later it actually updates the in-memory structure for
AUTO_POSITION. If gtid_mode was changed between these calls,
auto_position could be set incompatible with gtid_mode.
Hold global_sid_lock.wrlock so that:
- other transactions cannot acquire ownership of any gtid.
Hold gtid_mode_lock so that all places that don't want to hold
any of the other locks, but want to read gtid_mode, don't need
to take the other locks.
*/
gtid_mode_lock->wrlock();
channel_map.wrlock();
mysql_mutex_lock(mysql_bin_log.get_log_lock());
global_sid_lock->wrlock();
int lock_count= 4;
enum_gtid_mode new_gtid_mode=
(enum_gtid_mode)var->save_result.ulonglong_value;
enum_gtid_mode old_gtid_mode= get_gtid_mode(GTID_MODE_LOCK_SID);
DBUG_ASSERT(new_gtid_mode <= GTID_MODE_ON);
DBUG_PRINT("info", ("old_gtid_mode=%d new_gtid_mode=%d",
old_gtid_mode, new_gtid_mode));
if (new_gtid_mode == old_gtid_mode)
goto end;
// Can only change one step at a time.
if (abs((int)new_gtid_mode - (int)old_gtid_mode) > 1)
{
my_error(ER_GTID_MODE_CAN_ONLY_CHANGE_ONE_STEP_AT_A_TIME, MYF(0));
goto err;
}
// Not allowed with slave_sql_skip_counter
DBUG_PRINT("info", ("sql_slave_skip_counter=%d", sql_slave_skip_counter));
if (new_gtid_mode == GTID_MODE_ON && sql_slave_skip_counter > 0)
{
my_error(ER_CANT_SET_GTID_MODE, MYF(0), "ON",
"@@GLOBAL.SQL_SLAVE_SKIP_COUNTER is greater than zero");
goto err;
}
// Cannot set OFF when some channel uses AUTO_POSITION.
if (new_gtid_mode == GTID_MODE_OFF)
{
for (mi_map::iterator it= channel_map.begin(); it!= channel_map.end(); it++)
{
Master_info *mi= it->second;
DBUG_PRINT("info", ("auto_position for channel '%s' is %d",
mi->get_channel(), mi->is_auto_position()));
if (mi != NULL && mi->is_auto_position())
{
char buf[1024];
sprintf(buf, "replication channel '%.192s' is configured "
"in AUTO_POSITION mode. Execute "
"CHANGE MASTER TO MASTER_AUTO_POSITION = 0 "
"FOR CHANNEL '%.192s' before you set "
"@@GLOBAL.GTID_MODE = OFF.",
mi->get_channel(), mi->get_channel());
my_error(ER_CANT_SET_GTID_MODE, MYF(0), "OFF", buf);
goto err;
}
}
}
// Can't set GTID_MODE != ON when group replication is enabled.
if (is_group_replication_running())
{
DBUG_ASSERT(old_gtid_mode == GTID_MODE_ON);
DBUG_ASSERT(new_gtid_mode == GTID_MODE_ON_PERMISSIVE);
my_error(ER_CANT_SET_GTID_MODE, MYF(0),
get_gtid_mode_string(new_gtid_mode),
"group replication requires @@GLOBAL.GTID_MODE=ON");
goto err;
}
// Compatible with ongoing transactions.
DBUG_PRINT("info", ("anonymous_ownership_count=%d owned_gtids->is_empty=%d",
gtid_state->get_anonymous_ownership_count(),
gtid_state->get_owned_gtids()->is_empty()));
gtid_state->get_owned_gtids()->dbug_print("global owned_gtids");
if (new_gtid_mode == GTID_MODE_ON &&
gtid_state->get_anonymous_ownership_count() > 0)
{
my_error(ER_CANT_SET_GTID_MODE, MYF(0), "ON",
"there are ongoing, anonymous transactions. Before "
"setting @@GLOBAL.GTID_MODE = ON, wait until "
"SHOW STATUS LIKE 'ANONYMOUS_TRANSACTION_COUNT' "
"shows zero on all servers. Then wait for all "
"existing, anonymous transactions to replicate to "
"all slaves, and then execute "
"SET @@GLOBAL.GTID_MODE = ON on all servers. "
"See the Manual for details");
goto err;
}
if (new_gtid_mode == GTID_MODE_OFF &&
!gtid_state->get_owned_gtids()->is_empty())
{
my_error(ER_CANT_SET_GTID_MODE, MYF(0), "OFF",
"there are ongoing transactions that have a GTID. "
"Before you set @@GLOBAL.GTID_MODE = OFF, wait "
"until SELECT @@GLOBAL.GTID_OWNED is empty on all "
"servers. Then wait for all GTID-transactions to "
"replicate to all servers, and then execute "
"SET @@GLOBAL.GTID_MODE = OFF on all servers. "
"See the Manual for details");
goto err;
}
// Compatible with ongoing GTID-violating transactions
DBUG_PRINT("info", ("automatic_gtid_violating_transaction_count=%d",
gtid_state->get_automatic_gtid_violating_transaction_count()));
if (new_gtid_mode >= GTID_MODE_ON_PERMISSIVE &&
gtid_state->get_automatic_gtid_violating_transaction_count() > 0)
{
my_error(ER_CANT_SET_GTID_MODE, MYF(0), "ON_PERMISSIVE",
"there are ongoing transactions that use "
"GTID_NEXT = 'AUTOMATIC', which violate GTID "
"consistency. Adjust your workload to be "
"GTID-consistent before setting "
"@@GLOBAL.GTID_MODE = ON_PERMISSIVE. "
"See the Manual for "
"@@GLOBAL.ENFORCE_GTID_CONSISTENCY for details");
goto err;
}
// Compatible with ENFORCE_GTID_CONSISTENCY.
if (new_gtid_mode == GTID_MODE_ON &&
get_gtid_consistency_mode() != GTID_CONSISTENCY_MODE_ON)
{
my_error(ER_CANT_SET_GTID_MODE, MYF(0), "ON",
"ENFORCE_GTID_CONSISTENCY is not ON");
goto err;
}
// Can't set GTID_MODE=OFF with ongoing calls to
// WAIT_FOR_EXECUTED_GTID_SET or
// WAIT_UNTIL_SQL_THREAD_AFTER_GTIDS.
DBUG_PRINT("info", ("gtid_wait_count=%d", gtid_state->get_gtid_wait_count() > 0));
if (new_gtid_mode == GTID_MODE_OFF &&
gtid_state->get_gtid_wait_count() > 0)
{
my_error(ER_CANT_SET_GTID_MODE, MYF(0), "OFF",
"there are ongoing calls to "
"WAIT_FOR_EXECUTED_GTID_SET or "
"WAIT_UNTIL_SQL_THREAD_AFTER_GTIDS. Before you set "
"@@GLOBAL.GTID_MODE = OFF, ensure that no other "
"client is waiting for GTID-transactions to be "
"committed");
goto err;
}
// Update the mode
global_var(ulong)= new_gtid_mode;
global_sid_lock->unlock();
lock_count= 3;
// Generate note in log
sql_print_information("Changed GTID_MODE from %s to %s.",
gtid_mode_names[old_gtid_mode],
gtid_mode_names[new_gtid_mode]);
// Rotate
{
bool dont_care= false;
if (mysql_bin_log.rotate(true, &dont_care))
goto err;
}
end:
ret= false;
err:
DBUG_ASSERT(lock_count >= 0);
DBUG_ASSERT(lock_count <= 4);
if (lock_count == 4)
global_sid_lock->unlock();
mysql_mutex_unlock(mysql_bin_log.get_log_lock());
channel_map.unlock();
gtid_mode_lock->unlock();
DBUG_RETURN(ret);
}
};
#endif /* HAVE_REPLICATION */
class Sys_var_enforce_gtid_consistency : public Sys_var_multi_enum
{
public:
Sys_var_enforce_gtid_consistency(
const char *name_arg,
const char *comment,
int flag_args,
ptrdiff_t off,
size_t size,
CMD_LINE getopt,
const ALIAS aliases[],
const uint value_count,
uint def_val,
uint command_line_no_value,
PolyLock *lock=0,
enum binlog_status_enum binlog_status_arg=VARIABLE_NOT_IN_BINLOG,
on_check_function on_check_func=0) :
Sys_var_multi_enum(name_arg, comment, flag_args, off, size, getopt,
aliases, value_count, def_val, command_line_no_value,
lock, binlog_status_arg, on_check_func)
{ }
bool global_update(THD *thd, set_var *var)
{
DBUG_ENTER("Sys_var_enforce_gtid_consistency::global_update");
bool ret= true;
/*
Hold global_sid_lock.wrlock so that other transactions cannot
acquire ownership of any gtid.
*/
global_sid_lock->wrlock();
DBUG_PRINT("info", ("var->save_result.ulonglong_value=%llu",
var->save_result.ulonglong_value));
enum_gtid_consistency_mode new_mode=
(enum_gtid_consistency_mode)var->save_result.ulonglong_value;
enum_gtid_consistency_mode old_mode= get_gtid_consistency_mode();
enum_gtid_mode gtid_mode= get_gtid_mode(GTID_MODE_LOCK_SID);
DBUG_ASSERT(new_mode <= GTID_CONSISTENCY_MODE_WARN);
DBUG_PRINT("info", ("old enforce_gtid_consistency=%d "
"new enforce_gtid_consistency=%d "
"gtid_mode=%d ",
old_mode, new_mode, gtid_mode));
if (new_mode == old_mode)
goto end;
// Can't turn off GTID-consistency when GTID_MODE=ON.
if (new_mode != GTID_CONSISTENCY_MODE_ON && gtid_mode == GTID_MODE_ON)
{
my_error(ER_GTID_MODE_ON_REQUIRES_ENFORCE_GTID_CONSISTENCY_ON, MYF(0));
goto err;
}
// If there are ongoing GTID-violating transactions, and we are
// moving from OFF->ON, WARN->ON, or OFF->WARN, generate warning
// or error accordingly.
if (new_mode == GTID_CONSISTENCY_MODE_ON ||
(old_mode == GTID_CONSISTENCY_MODE_OFF &&
new_mode == GTID_CONSISTENCY_MODE_WARN))
{
DBUG_PRINT("info",
("automatic_gtid_violating_transaction_count=%d "
"anonymous_gtid_violating_transaction_count=%d",
gtid_state->get_automatic_gtid_violating_transaction_count(),
gtid_state->get_anonymous_gtid_violating_transaction_count()));
if (gtid_state->get_automatic_gtid_violating_transaction_count() > 0 ||
gtid_state->get_anonymous_gtid_violating_transaction_count() > 0)
{
if (new_mode == GTID_CONSISTENCY_MODE_ON)
{
my_error(ER_CANT_SET_ENFORCE_GTID_CONSISTENCY_ON_WITH_ONGOING_GTID_VIOLATING_TRANSACTIONS, MYF(0));
goto err;
}
else
{
push_warning_printf(thd, Sql_condition::SL_WARNING,
ER_SET_ENFORCE_GTID_CONSISTENCY_WARN_WITH_ONGOING_GTID_VIOLATING_TRANSACTIONS,
"%s", ER(ER_SET_ENFORCE_GTID_CONSISTENCY_WARN_WITH_ONGOING_GTID_VIOLATING_TRANSACTIONS));
}
}
}
// Update the mode
global_var(ulong)= new_mode;
// Generate note in log
sql_print_information("Changed ENFORCE_GTID_CONSISTENCY from %s to %s.",
get_gtid_consistency_mode_string(old_mode),
get_gtid_consistency_mode_string(new_mode));
end:
ret= false;
err:
global_sid_lock->unlock();
DBUG_RETURN(ret);
}
};
#endif /* SYS_VARS_H_INCLUDED */
| 33.967164 | 119 | 0.664509 | [
"vector"
] |
030036265f0801ec551153f36ffe768fe167b5fb | 3,629 | h | C | SOURCES/sim/include/simveh.h | IsraelyFlightSimulator/Negev-Storm | 86de63e195577339f6e4a94198bedd31833a8be8 | [
"Unlicense"
] | 1 | 2021-02-19T06:06:31.000Z | 2021-02-19T06:06:31.000Z | src/sim/include/simveh.h | markbb1957/FFalconSource | 07b12e2c41a93fa3a95b912a2433a8056de5bc4d | [
"BSD-2-Clause"
] | null | null | null | src/sim/include/simveh.h | markbb1957/FFalconSource | 07b12e2c41a93fa3a95b912a2433a8056de5bc4d | [
"BSD-2-Clause"
] | 2 | 2019-08-20T13:35:13.000Z | 2021-04-24T07:32:04.000Z | #ifndef _SIM_VEHICLE_H
#define _SIM_VEHICLE_H
#include "simmover.h"
class BaseBrain;
class FireControlComputer;
class PilotInputs;
class RadioClass;
class WayPointClass;
class FalconDamageMessage;
class FalconDeathMessage;
class FalconEvent;
class SimWeaponClass;
class SMSBaseClass;
class SimVehicleClass : public SimMoverClass
{
protected:
// Controls
BaseBrain* theBrain;
// int numHardpoints;
float ioPerturb;
float irOutput;//me123
// JB 000814
float rBias;
float pBias;
float yBias;
// JB 000814
// how does the thing die
int dyingType;
enum
{
DIE_SMOKE = 0,
DIE_FIREBALL,
DIE_SHORT_FIREBALL,
DIE_INTERMITTENT_FIRE,
DIE_INTERMITTENT_SMOKE
};
// RV - I-Hawk - AC dying time is now randomized. maybe long,short, or sometiems immediate...
// Value is intialized in Aircraft.cpp constructor, and used in simveh.cpp with the dying
// timer...
int dyingTime;
public:
// rates and timers for targeting
VU_TIME nextTargetUpdate;
VU_TIME targetUpdateRate;
VU_TIME nextGeomCalc;
VU_TIME geomCalcRate;
public:
void SendFireMessage(
SimWeaponClass* curWeapon, int type, int startFlag, SimObjectType* targetPtr, VU_ID tgtId = FalconNullId
);
// Avionics
PilotInputs* theInputs;
void InitWeapons (ushort *type, ushort *num);
enum SOI {SOI_HUD, SOI_RADAR, SOI_WEAPON, SOI_FCC}; //MI added SOI_FCC for HSD
SOI curSOI;
void SOIManager(SOI newSOI);
SOI GetSOI(void) {return curSOI;}; //MI
void StepSOI(int dir); //MI
BaseBrain* Brain(void) {return theBrain;};
//Steering Info
WayPointClass* curWaypoint;
WayPointClass* waypoint;
Int32 numWaypoints;
WayPointClass *GetWayPointNo(int n);
virtual void ReceiveOrders (FalconEvent*) {};
void ApplyProximityDamage (void);
// for dying, we no longer send the death message as soon as
// strength goes to 0, we delay until object explodes
FalconDeathMessage *deathMessage;
SimVehicleClass(int type);
SimVehicleClass(VU_BYTE** stream, long *rem);
SimVehicleClass(FILE* filePtr);
virtual ~SimVehicleClass (void);
virtual void InitData();
virtual void CleanupData();
private:
void InitLocalData();
void CleanupLocalData();
public:
virtual void Init (SimInitDataClass* initData);
virtual int Wake (void);
virtual int Sleep (void);
virtual void MakeLocal (void);
virtual void MakeRemote (void);
virtual int Exec (void);
virtual void SetDead (int);
virtual void ApplyDamage (FalconDamageMessage *damageMessage);
virtual FireControlComputer* GetFCC(void) { return NULL; };
virtual SMSBaseClass* GetSMS(void) { return NULL; };
virtual float GetRCSFactor (void);
virtual float GetIRFactor (void);
virtual int GetRadarType (void);
virtual long GetTotalFuel (void) { return -1; }; // KCK: -1 means "unfueled vehicle"
//all ground vehicles and helicopters have pilots until they die
//this determines whether they can talk on the radio or not
virtual int HasPilot (void) { return TRUE;}
virtual int IsVehicle (void) { return TRUE;}
// this function can be called for entities which aren't necessarily
// exec'd in a frame (ie ground units), but need to have their
// gun tracers and (possibly other) weapons serviced
virtual void WeaponKeepAlive( void ) { return; };
// virtual function interface
// serialization functions
virtual int SaveSize();
virtual int Save(VU_BYTE **stream); // returns bytes written
virtual int Save(FILE *file); // returns bytes written
// event handlers
virtual int Handle(VuFullUpdateEvent *event);
virtual int Handle(VuPositionUpdateEvent *event);
virtual int Handle(VuTransferEvent *event);
virtual VU_ERRCODE InsertionCallback(void);
};
#endif
| 27.285714 | 106 | 0.751998 | [
"object"
] |
030ddf4ff338f2739646eb6b9c8000526a16a409 | 3,629 | h | C | Compiler/Tree.h | Cytosine1999/CodeDollar | 817225ad926b12c11fc517f19de290f34ff67807 | [
"MIT"
] | null | null | null | Compiler/Tree.h | Cytosine1999/CodeDollar | 817225ad926b12c11fc517f19de290f34ff67807 | [
"MIT"
] | null | null | null | Compiler/Tree.h | Cytosine1999/CodeDollar | 817225ad926b12c11fc517f19de290f34ff67807 | [
"MIT"
] | null | null | null | //
// Created by cytosine on 18-9-6.
//
#ifndef CODEDOLLAR_TREE_H
#define CODEDOLLAR_TREE_H
#include "iostream"
#include <vector>
#include <iterator>
#include <memory>
using namespace std;
template<typename T>
class uniquePtrIter : iterator<forward_iterator_tag, vector<unique_ptr<T>>> {
public:
typedef typename vector<unique_ptr<T>>::const_iterator iterT;
explicit uniquePtrIter(iterT ptr) : ptr{ptr} {}
uniquePtrIter(const uniquePtrIter &other) = default;
uniquePtrIter &operator=(const uniquePtrIter &other) = default;
uniquePtrIter &operator++() {
ptr++;
return *this;
}
const uniquePtrIter operator++(int) {
const uniquePtrIter tmp{*this};
ptr++;
return tmp;
}
const T &operator*() {
return **ptr;
}
const unique_ptr<T> &operator->() {
return *ptr;
}
bool operator==(const uniquePtrIter &other) const {
return ptr == other.ptr;
}
bool operator!=(const uniquePtrIter &other) const {
return ptr != other.ptr;
}
protected:
iterT ptr;
};
template<typename valueT, typename ownerT>
class uniquePtrIterable {
public:
typedef vector<unique_ptr<valueT>> vectorT;
explicit uniquePtrIterable(const vectorT &vec, ownerT &owner) : vec{vec}, owner{owner} {}
uniquePtrIter<valueT> begin() {
return uniquePtrIter<valueT>{vec.begin()};
}
uniquePtrIter<valueT> end() {
return uniquePtrIter<valueT>{vec.end()};
}
bool notEnd(uniquePtrIter<valueT> ptr) {
return ptr != end() || owner.pushBack();
}
protected:
const vectorT &vec;
ownerT &owner;
};
template<typename T>
class Tree {
public:
typedef T typeT;
typedef unique_ptr<T> typeT_ptr;
explicit Tree() : subNodes{} {}
Tree(const Tree &other) = default;
Tree &operator=(const Tree &other) = default;
size_t size() const {
return subNodes.size();
}
uniquePtrIterable<T, Tree<T>> iter() {
return uniquePtrIterable<T, Tree<T>>{subNodes, *this};
}
virtual bool load() = 0;
T &back() {
return *subNodes.back();
}
virtual ~Tree() = default;
protected:
vector<typeT_ptr> subNodes;
void push_back(typeT *element) {
subNodes.push_back(typeT_ptr{element});
}
};
template<typename T>
class RefVecIter : iterator<forward_iterator_tag, vector<const T *>> {
public:
typedef typename vector<const T *>::const_iterator iterT;
explicit RefVecIter(iterT ptr) : ptr{ptr} {}
RefVecIter(const RefVecIter &other) = default;
RefVecIter &operator=(const RefVecIter &other) = default;
RefVecIter &operator++() {
ptr++;
return *this;
}
const RefVecIter operator++(int) {
const RefVecIter tmp{*this};
ptr++;
return tmp;
}
const T &operator*() {
return **ptr;
}
const T *operator->() {
return *ptr;
}
bool operator==(const RefVecIter &other) const {
return ptr == other.ptr;
}
bool operator!=(const RefVecIter &other) const {
return ptr != other.ptr;
}
protected:
iterT ptr;
};
template<typename T>
class RefVecIterable {
public:
typedef vector<const T *> vectorT;
explicit RefVecIterable(const vectorT &vec) : vec{vec} {}
RefVecIter<T> begin() {
return RefVecIter<T>{vec.begin()};
}
RefVecIter<T> end() {
return RefVecIter<T>{vec.end()};
}
bool notEnd(RefVecIter<T> ptr) {
return ptr != end();
}
protected:
const vectorT &vec;
};
#endif //CODEDOLLAR_TREE_H
| 18.706186 | 93 | 0.615321 | [
"vector"
] |
03127f79d95430093af01ef7105960474cd0098a | 5,188 | h | C | include/bslam/models/SensorModelBeta.h | JoachimClemens/Beta-SLAM | eaa3e5b0dd7d81e4c0f2b30fc29d48d55807c5fa | [
"BSD-3-Clause"
] | 3 | 2019-01-17T21:47:05.000Z | 2021-08-17T05:44:44.000Z | include/bslam/models/SensorModelBeta.h | JoachimClemens/Beta-SLAM | eaa3e5b0dd7d81e4c0f2b30fc29d48d55807c5fa | [
"BSD-3-Clause"
] | null | null | null | include/bslam/models/SensorModelBeta.h | JoachimClemens/Beta-SLAM | eaa3e5b0dd7d81e4c0f2b30fc29d48d55807c5fa | [
"BSD-3-Clause"
] | 2 | 2019-02-16T01:37:14.000Z | 2019-11-20T11:13:21.000Z | /*
* Software License Agreement (BSD License)
*
* Beta-SLAM - Simultaneous localization and grid mapping with beta distributions
* Copyright (c) 2013-2019, Joachim Clemens, Thomas Reineking, Tobias Kluth
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of BSLAM nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef BSLAM_SENSORMODELBETA_H_
#define BSLAM_SENSORMODELBETA_H_
#include <vector>
#include "SensorModel.h"
#include "bslam/utils/aligned_boost_unordered_map.h"
#include "bslam/utils/geometry/Line.h"
#include "bslam/utils/uncertainty/BetaDistribution.h"
#include "bslam/maps/cells/BetaCell.h"
namespace bslam {
template<typename Map, int N>
class SensorModel< Map, BetaCell<N> > {
public:
using ScanMap = aligned_boost_unordered_map< Pointm<N>, BetaCell<N> >;
SensorModel( bool unused = false );
void setParamsConfig();
/**
* @param pHit end point of measurement in world coordinates
* @param scanLine line from sensor origin to hit cell (up to usable range) in map coordinates
* @param hitIdx index of the hit cell in scanLine, number >= scanLine.size() if hit cell is not part of scanLine (e.g. not in usable range)
* @param scanMap cells updated in the current scan (only used in Belief model)
* @param map the map
*
* @return information gained in this step (if CALC_ENTROPY = 1)
*/
inline double inverseModel( const typename Map::WorldPoint &pHit, const Line<N> &scanLine, size_t hitIdx, ScanMap *scanMap, Map *map ) const;
/**
* @param dist distance between measurement and sensor origin (measured range)
* @param bestMu distance between measurement and best matching cell
* @param bestMuMap index of the best matching cell in the map
* @param sensorOrigin origin of sensor in world coordinates
* @param sensorOriginMap origin of sensor in map coordinates
* @param map the map
*
* @return log-likelihood
*/
inline double forwardModel( world_t dist, const typename Map::WorldPoint &bestMu, const typename Map::MapPoint &bestMuMap, const typename Map::WorldPoint &sensorOrigin, const typename Map::MapPoint &sensorOriginMap, const Map &map ) const;
/**
* @param scanMap cells updated in the current scan
* @param map the map
*
* @return information gained in this step (if CALC_ENTROPY = 1)
*/
inline double integrate( ScanMap *scanMap, Map *map ) const;
inline double sigmaSqr() const;
inline double nullLogLikelihood() const;
inline constexpr bool excludeNoHit() const;
inline constexpr int cellsBehind() const;
private:
void computeBetaLUT();
void computePdfLUT();
inline const BetaDistribution& getBeta( world_t dist ) const;
inline double getPdf( world_t dist ) const;
//inline double betaLikelihood( world_t dist, int numCells, const BetaCell<N> **cells, const world_t *distances, int i = -1 ) const;
double m_betaSigmaForward,
m_betaSigmaForwardSqr,
m_betaSigmaForwardFactor,
m_betaSigmaInverse,
m_betaSigmaInverseSqr,
m_betaSigmaInverseFactor,
m_betaRandom,
m_betaPriorP,
m_mapDelta;
bool m_betaExcludeNoHit,
m_scanNoConflict;
int64_t m_betaForwardCellRange;
std::vector<BetaDistribution> m_betaLUT;
std::vector<double> m_pdfLUT;
double m_betaDistScale, // scale factor for distance discretization for beta LUT (controls its resolution)
m_pdfDistScale; // scale factor for distance discretization for PDF LUT (controls its resolution)
BetaDistribution m_betaZero;
static constexpr size_t MAX_SIZE = 5000; // maximum number if entries in LUT (the actual size will be 2*MAX_SIZE, because of the two LUTs)
};
} /* namespace bslam */
#include "SensorModelBeta.hpp"
#endif /* BSLAM_SENSORMODELBETA_H_ */
| 37.594203 | 245 | 0.742097 | [
"geometry",
"vector",
"model"
] |
03155c701ec71f25216de67eca6c2d1887fcc7d3 | 4,736 | h | C | third_party/blink/renderer/core/paint/ng/ng_highlight_painter.h | DamieFC/chromium | 54ce2d3c77723697efd22cfdb02aea38f9dfa25c | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1 | 2020-10-18T02:33:40.000Z | 2020-10-18T02:33:40.000Z | third_party/blink/renderer/core/paint/ng/ng_highlight_painter.h | DamieFC/chromium | 54ce2d3c77723697efd22cfdb02aea38f9dfa25c | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 3 | 2021-05-17T16:28:52.000Z | 2021-05-21T22:42:22.000Z | third_party/blink/renderer/core/paint/ng/ng_highlight_painter.h | DamieFC/chromium | 54ce2d3c77723697efd22cfdb02aea38f9dfa25c | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | // Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_PAINT_NG_NG_HIGHLIGHT_PAINTER_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_PAINT_NG_NG_HIGHLIGHT_PAINTER_H_
#include "third_party/abseil-cpp/absl/types/optional.h"
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/core/editing/frame_selection.h"
#include "third_party/blink/renderer/core/editing/markers/document_marker.h"
#include "third_party/blink/renderer/core/layout/api/selection_state.h"
#include "third_party/blink/renderer/core/layout/geometry/physical_rect.h"
#include "third_party/blink/renderer/core/paint/text_paint_style.h"
#include "third_party/blink/renderer/platform/graphics/dom_node_id.h"
#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
class AffineTransform;
class ComputedStyle;
class FrameSelection;
class LayoutObject;
class NGFragmentItem;
class NGTextPainter;
class NGInlineCursor;
class Node;
struct LayoutSelectionStatus;
struct PaintInfo;
struct PhysicalOffset;
// Highlight overlay painter for LayoutNG. Operates on NGFragmentItem that
// IsText(). Delegates to NGTextPainter to paint the text itself.
class CORE_EXPORT NGHighlightPainter {
STACK_ALLOCATED();
public:
class SelectionPaintState {
STACK_ALLOCATED();
public:
explicit SelectionPaintState(const NGInlineCursor& containing_block);
explicit SelectionPaintState(const NGInlineCursor& containing_block,
const FrameSelection&);
const LayoutSelectionStatus& Status() const { return selection_status_; }
const TextPaintStyle& GetSelectionStyle() const { return selection_style_; }
SelectionState State() const { return state_; }
bool ShouldPaintSelectedTextOnly() const {
return paint_selected_text_only_;
}
void ComputeSelectionStyle(const Document& document,
const ComputedStyle& style,
Node* node,
const PaintInfo& paint_info,
const TextPaintStyle& text_style);
PhysicalRect ComputeSelectionRect(const PhysicalOffset& box_offset);
void PaintSelectionBackground(
GraphicsContext& context,
Node* node,
const Document& document,
const ComputedStyle& style,
const absl::optional<AffineTransform>& rotation);
void MapSelectionRectIntoRotatedSpace(const AffineTransform& rotation);
void PaintSelectedText(NGTextPainter& text_painter,
unsigned length,
const TextPaintStyle& text_style,
DOMNodeId node_id);
void PaintSuppressingTextProperWhereSelected(
NGTextPainter& text_painter,
unsigned start_offset,
unsigned end_offset,
unsigned length,
const TextPaintStyle& text_style,
DOMNodeId node_id);
private:
const LayoutSelectionStatus selection_status_;
TextPaintStyle selection_style_;
const SelectionState state_;
absl::optional<PhysicalRect> selection_rect_;
absl::optional<PhysicalRect> selection_rect_before_rotation_;
const NGInlineCursor& containing_block_;
bool paint_selected_text_only_;
};
explicit NGHighlightPainter(NGTextPainter& text_painter,
const PaintInfo& paint_info,
const NGInlineCursor& cursor,
const NGFragmentItem& fragment_item,
const PhysicalOffset& box_origin,
const ComputedStyle& style,
absl::optional<SelectionPaintState>,
bool is_printing);
enum Phase { kBackground, kForeground };
void Paint(Phase phase);
absl::optional<SelectionPaintState>& Selection() { return selection_; }
absl::optional<AppliedTextDecoration> SelectionDecoration() {
return selection_
? selection_->GetSelectionStyle().selection_text_decoration
: absl::nullopt;
}
private:
NGTextPainter& text_painter_;
const PaintInfo& paint_info_;
const NGInlineCursor& cursor_;
const NGFragmentItem& fragment_item_;
const PhysicalOffset& box_origin_;
const ComputedStyle& style_;
absl::optional<SelectionPaintState> selection_;
const LayoutObject* layout_object_;
Node* node_;
const DocumentMarkerVector markers_;
const bool skip_backgrounds_;
};
} // namespace blink
#endif // THIRD_PARTY_BLINK_RENDERER_CORE_PAINT_NG_NG_HIGHLIGHT_PAINTER_H_
| 35.878788 | 80 | 0.711149 | [
"geometry"
] |
031655432cdf44d7936a0be3a587a192cca8448c | 2,489 | h | C | lib/Logger/LogTopic.h | elfringham/arangodb | 5baaece1c7a5ce73fe016f07ed66255cc555e8cb | [
"BSL-1.0",
"Apache-2.0"
] | null | null | null | lib/Logger/LogTopic.h | elfringham/arangodb | 5baaece1c7a5ce73fe016f07ed66255cc555e8cb | [
"BSL-1.0",
"Apache-2.0"
] | null | null | null | lib/Logger/LogTopic.h | elfringham/arangodb | 5baaece1c7a5ce73fe016f07ed66255cc555e8cb | [
"BSL-1.0",
"Apache-2.0"
] | 1 | 2016-03-30T14:43:34.000Z | 2016-03-30T14:43:34.000Z | ////////////////////////////////////////////////////////////////////////////////
/// DISCLAIMER
///
/// Copyright 2014-2021 ArangoDB GmbH, Cologne, Germany
/// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany
///
/// 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.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Dr. Frank Celler
////////////////////////////////////////////////////////////////////////////////
#pragma once
#include <stddef.h>
#include <atomic>
#include <string>
#include <utility>
#include <vector>
#include "Logger/LogLevel.h"
namespace arangodb {
class LogTopic {
LogTopic& operator=(LogTopic const&) = delete;
public:
static constexpr size_t MAX_LOG_TOPICS = 64;
public:
static std::vector<std::pair<std::string, LogLevel>> logLevelTopics();
static void setLogLevel(std::string const&, LogLevel);
static LogTopic* lookup(std::string const&);
static std::string lookup(size_t topicId);
public:
explicit LogTopic(std::string const& name);
virtual ~LogTopic() = default;
LogTopic(std::string const& name, LogLevel level);
LogTopic(LogTopic const& that)
: _id(that._id), _name(that._name), _displayName(that._displayName) {
_level.store(that._level, std::memory_order_relaxed);
}
LogTopic(LogTopic&& that) noexcept
: _id(that._id),
_name(std::move(that._name)),
_displayName(std::move(that._displayName)) {
_level.store(that._level, std::memory_order_relaxed);
}
public:
size_t id() const { return _id; }
std::string const& name() const { return _name; }
std::string const& displayName() const { return _displayName; }
LogLevel level() const { return _level.load(std::memory_order_relaxed); }
virtual void setLogLevel(LogLevel level) {
_level.store(level, std::memory_order_relaxed);
}
private:
size_t const _id;
std::string const _name;
std::string _displayName;
std::atomic<LogLevel> _level;
};
} // namespace arangodb
| 29.987952 | 80 | 0.664122 | [
"vector"
] |
0317c5f5365abb5890e36befcc2d3914568ac3de | 7,396 | c | C | VS2008/oss-c-sdk-sample/oss-c-sdk-sample/main.c | baiyubin/aliyun-oss-c-sdk-sample | 185afd227b9b427d7c98e87eb132b6205b3f5f85 | [
"MIT"
] | 4 | 2016-12-21T06:37:07.000Z | 2017-07-16T15:18:47.000Z | VS2010/oss-c-sdk-sample/oss-c-sdk-sample/main.c | baiyubin/aliyun-oss-c-sdk-sample | 185afd227b9b427d7c98e87eb132b6205b3f5f85 | [
"MIT"
] | null | null | null | VS2010/oss-c-sdk-sample/oss-c-sdk-sample/main.c | baiyubin/aliyun-oss-c-sdk-sample | 185afd227b9b427d7c98e87eb132b6205b3f5f85 | [
"MIT"
] | 6 | 2016-07-01T09:39:11.000Z | 2019-04-26T02:45:05.000Z | #include "aos_log.h"
#include "aos_util.h"
#include "aos_string.h"
#include "aos_status.h"
#include "oss_auth.h"
#include "oss_util.h"
#include "oss_api.h"
const char OSS_ENDPOINT[] = "<your endpoint>";
const char ACCESS_KEY_ID[] = "<your access key id>";
const char ACCESS_KEY_SECRET[] = "<your access key secret>";
const char BUCKET_NAME[] = "<your bucket name>";
const char OBJECT_NAME[] = "<your object key>";
void init_sample_request_options(oss_request_options_t *options, int is_cname);
void put_object_from_buffer();
void put_object_from_file();
void get_object_to_buffer();
void get_object_to_file();
void delete_object();
int main(int argc, char *argv[])
{
apr_file_t *output = NULL;
aos_pool_t *pool = NULL;
apr_status_t ret;
// initialize http io system, call it olny once
if (aos_http_io_initialize(NULL, 0) != AOSE_OK) {
exit(1);
}
aos_pool_create(&pool, NULL);
// open log file
ret = apr_file_open(&output, "oss-c-sdk-sample.log", APR_FOPEN_CREATE | APR_FOPEN_WRITE | APR_FOPEN_APPEND, APR_OS_DEFAULT, pool);
if (APR_SUCCESS != ret) {
exit(1);
}
// set log file
aos_log_set_output(output);
// set log level
aos_log_set_level(AOS_LOG_INFO);
aos_info_log("start");
// run samples
put_object_from_buffer();
put_object_from_file();
get_object_to_buffer();
get_object_to_file();
delete_object();
// close log file
apr_file_close(output);
aos_pool_destroy(pool);
// deinitialize http io system, call it olny once
aos_http_io_deinitialize();
system("pause");
return 0;
}
void init_sample_request_options(oss_request_options_t *options, int is_cname)
{
options->config = oss_config_create(options->pool);
aos_str_set(&options->config->endpoint, OSS_ENDPOINT);
aos_str_set(&options->config->access_key_id, ACCESS_KEY_ID);
aos_str_set(&options->config->access_key_secret, ACCESS_KEY_SECRET);
options->config->is_cname = is_cname;
options->ctl = aos_http_controller_create(options->pool, 0);
}
void put_object_from_buffer()
{
aos_pool_t *p = NULL;
aos_string_t bucket;
aos_string_t object;
int is_cname = 0;
aos_table_t *headers = NULL;
aos_table_t *resp_headers = NULL;
oss_request_options_t *options = NULL;
aos_list_t buffer;
aos_buf_t *content = NULL;
char *str = "test oss c sdk";
aos_status_t *s = NULL;
aos_pool_create(&p, NULL);
options = oss_request_options_create(p);
init_sample_request_options(options, is_cname);
headers = aos_table_make(p, 1);
apr_table_set(headers, "x-oss-meta-author", "oss");
aos_str_set(&bucket, BUCKET_NAME);
aos_str_set(&object, OBJECT_NAME);
aos_list_init(&buffer);
content = aos_buf_pack(options->pool, str, strlen(str));
aos_list_add_tail(&content->node, &buffer);
s = oss_put_object_from_buffer(options, &bucket, &object,
&buffer, headers, &resp_headers);
if (aos_status_is_ok(s)) {
printf("put object from buffer succeeded\n");
} else {
printf("put object from buffer failed\n");
}
aos_pool_destroy(p);
}
void put_object_from_file()
{
aos_pool_t *p = NULL;
aos_string_t bucket;
aos_string_t object;
int is_cname = 0;
aos_table_t *headers = NULL;
aos_table_t *resp_headers = NULL;
oss_request_options_t *options = NULL;
char *filename = "SouthIsland_NewZealand.jpg";
aos_status_t *s = NULL;
aos_string_t file;
aos_pool_create(&p, NULL);
options = oss_request_options_create(p);
init_sample_request_options(options, is_cname);
headers = aos_table_make(options->pool, 1);
apr_table_set(headers, OSS_CONTENT_TYPE, "image/jpeg");
aos_str_set(&bucket, BUCKET_NAME);
aos_str_set(&object, OBJECT_NAME);
aos_str_set(&file, filename);
s = oss_put_object_from_file(options, &bucket, &object, &file,
headers, &resp_headers);
if (aos_status_is_ok(s)) {
printf("put object from file succeeded\n");
} else {
printf("put object from file failed, code:%d, error_code:%s, error_msg:%s, request_id:%s\n",
s->code, s->error_code, s->error_msg, s->req_id);
}
aos_pool_destroy(p);
}
void get_object_to_buffer()
{
aos_pool_t *p = NULL;
aos_string_t bucket;
aos_string_t object;
int is_cname = 0;
oss_request_options_t *options = NULL;
aos_table_t *headers = NULL;
aos_table_t *params = NULL;
aos_table_t *resp_headers = NULL;
aos_status_t *s = NULL;
aos_list_t buffer;
aos_buf_t *content = NULL;
char *buf = NULL;
int64_t len = 0;
int64_t size = 0;
int64_t pos = 0;
aos_pool_create(&p, NULL);
options = oss_request_options_create(p);
init_sample_request_options(options, is_cname);
aos_str_set(&bucket, BUCKET_NAME);
aos_str_set(&object, OBJECT_NAME);
aos_list_init(&buffer);
s = oss_get_object_to_buffer(options, &bucket, &object,
headers, params, &buffer, &resp_headers);
if (aos_status_is_ok(s)) {
printf("get object to buffer succeeded\n");
}
else {
printf("get object to buffer failed\n");
}
//get buffer len
aos_list_for_each_entry(aos_buf_t, content, &buffer, node) {
len += aos_buf_size(content);
}
buf = aos_pcalloc(p, (apr_size_t)(len + 1));
buf[len] = '\0';
//copy buffer content to memory
aos_list_for_each_entry(aos_buf_t, content, &buffer, node) {
size = aos_buf_size(content);
memcpy(buf + pos, content->pos, (size_t)size);
pos += size;
}
aos_pool_destroy(p);
}
void get_object_to_file()
{
aos_pool_t *p = NULL;
aos_string_t bucket;
char *download_filename = "SouthIsland_NewZealand_New.jpg";
aos_string_t object;
int is_cname = 0;
oss_request_options_t *options = NULL;
aos_table_t *headers = NULL;
aos_table_t *params = NULL;
aos_table_t *resp_headers = NULL;
aos_status_t *s = NULL;
aos_string_t file;
aos_pool_create(&p, NULL);
options = oss_request_options_create(p);
init_sample_request_options(options, is_cname);
aos_str_set(&bucket, BUCKET_NAME);
aos_str_set(&object, OBJECT_NAME);
headers = aos_table_make(p, 0);
aos_str_set(&file, download_filename);
s = oss_get_object_to_file(options, &bucket, &object, headers,
params, &file, &resp_headers);
if (aos_status_is_ok(s)) {
printf("get object to local file succeeded\n");
} else {
printf("get object to local file failed\n");
}
aos_pool_destroy(p);
}
void delete_object()
{
aos_pool_t *p = NULL;
aos_string_t bucket;
aos_string_t object;
int is_cname = 0;
oss_request_options_t *options = NULL;
aos_table_t *resp_headers = NULL;
aos_status_t *s = NULL;
aos_pool_create(&p, NULL);
options = oss_request_options_create(p);
init_sample_request_options(options, is_cname);
aos_str_set(&bucket, BUCKET_NAME);
aos_str_set(&object, OBJECT_NAME);
s = oss_delete_object(options, &bucket, &object, &resp_headers);
if (aos_status_is_ok(s)) {
printf("delete object succeed\n");
} else {
printf("delete object failed\n");
}
aos_pool_destroy(p);
}
| 27.700375 | 134 | 0.663602 | [
"object"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.