blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 4 201 | content_id stringlengths 40 40 | detected_licenses listlengths 0 85 | license_type stringclasses 2
values | repo_name stringlengths 7 100 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 260
values | visit_date timestamp[us] | revision_date timestamp[us] | committer_date timestamp[us] | github_id int64 11.4k 681M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 17
values | gha_event_created_at timestamp[us] | gha_created_at timestamp[us] | gha_language stringclasses 80
values | src_encoding stringclasses 28
values | language stringclasses 1
value | is_vendor bool 1
class | is_generated bool 2
classes | length_bytes int64 8 9.86M | extension stringclasses 52
values | content stringlengths 8 9.86M | authors listlengths 1 1 | author stringlengths 0 119 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
419374f13ade9fa131a113dba26fdb624f04f77f | 4007051ceba757f20cb6a2dc95ed1dbde8249db6 | /matrix_mul/tests/testutil.h | 546d1281ab2d13dfaa9b5231c90ffda5402cf0a3 | [] | no_license | ephemeral2eternity/fastcode | 86f7f277d8470b9e7862683f7b4885bc1742906b | aac4a7fca436e874d3ac19cc03bb0b4ed60108b1 | refs/heads/master | 2021-01-01T05:51:40.271482 | 2016-11-30T23:36:04 | 2016-11-30T23:36:04 | 20,062,046 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 3,591 | h | /*
testutil.h: header file for providing test framework for different kinds of matrix multiplication
Copyright (C) 2011 Abhinav Jauhri (abhinav.jauhri@gmail.com), Carnegie Mellon University - Silicon Valley
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, see <http://www.gnu.org/licenses/>.
*/
#ifndef TESTUTIL_H
#define TESTUTIL_H
#include<stdio.h>
#include<sys/time.h>
#include<stdlib.h>
#include<string.h>
#include <math.h>
#define EPS 1E-3
namespace testutil
{
class TestFrameWork
{
public:
int size, i;
int *matrix_dim;
float *sq_matrix_1;
float *sq_matrix_2;
float *answers;
std::ifstream file;
TestFrameWork()
{
srand((unsigned)time(0));
//initialize();
}
void randomize(float* matrix, int lines, int cols)
{
int i;
for(i = 0; i < lines * cols; i++) {
matrix[i] = (float)rand()/(float)RAND_MAX;
}
}
void tripleloop(float* out, float* in1, float* in2, int m, int n, int k)
{
int i, j, l;
float c = 0.0f;
for(i = 0; i < m; i++) {
for(j = 0; j< n; j++) {
for(l = 0; l < k; l++) {
c += in1[i * k + l] * in2[l * n + j];
}
out[i * n + j] = c;
c = 0.0f;
}
}
}
float diff(float* in1, float* in2, int lines, int cols)
{
int i;
float a = 0;
int max_err = 0;
for(i = 0; i < lines * cols; i++) {
a = fabs(in1[i] - in2[i]);
if (a > max_err) {
max_err = a;
}
}
return max_err;
}
/**
* @brief Initializes all arrays based on the size of the testcase
*/
void
initialize(char *filename)
{
freopen(filename, "r", stdin);
scanf("%d\n", &size);
matrix_dim = new int[size];
int c, i = 0;
while (i < size && (scanf("%d\n", &c) != EOF)) {
matrix_dim[i++] = c;
}
size = i;
fclose(stdin);
}
/**
* @brief Checks whether two arrays have same values or not
*
* @param first1 pointer to the first element in the first array
* @param last1 pointer to the last element in the first array
* @param first2 pointer to the first element in the second array
*
* @return boolean value stating whether the two arrays are equal or not
*/
bool
equals(float *first1, float *last1, float *first2)
{
while( first1 != last1)
{
if (*first1 != *first2) {
return false;
}
first1++;
first2++;
}
return true;
}
/**
* @brief Calculates the current time in milliseconds
* @return double type value of the current time
*/
double wtime(void)
{
double now_time;
struct timeval etstart;
if (gettimeofday(&etstart, NULL) == -1)
perror("Error: calling gettimeofday() not successful.\n");
now_time = ((etstart.tv_sec) * 1000 +
etstart.tv_usec / 1000.0);
return now_time;
}
~TestFrameWork()
{
delete matrix_dim;
}
}; // class Testing
} // namespace testutil
#endif
| [
"chenw@andrew.cmu.edu"
] | chenw@andrew.cmu.edu |
157f6b194e649406464d0688690681dfd51b340e | 771a5f9d99fdd2431b8883cee39cf82d5e2c9b59 | /SDK/BP_HarpoonProjectile_classes.h | 6912bdee3cd165272d6a86290c45034cf4c09052 | [
"MIT"
] | permissive | zanzo420/Sea-Of-Thieves-SDK | 6305accd032cc95478ede67d28981e041c154dce | f56a0340eb33726c98fc53eb0678fa2d59aa8294 | refs/heads/master | 2023-03-25T22:25:21.800004 | 2021-03-20T00:51:04 | 2021-03-20T00:51:04 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 796 | h | #pragma once
// Name: SeaOfThieves, Version: 2.0.23
/*!!DEFINE!!*/
/*!!HELPER_DEF!!*/
/*!!HELPER_INC!!*/
#ifdef _MSC_VER
#pragma pack(push, 0x01)
#endif
namespace CG
{
//---------------------------------------------------------------------------
// Classes
//---------------------------------------------------------------------------
// BlueprintGeneratedClass BP_HarpoonProjectile.BP_HarpoonProjectile_C
// 0x0000 (FullSize[0x0758] - InheritedSize[0x0758])
class ABP_HarpoonProjectile_C : public AHarpoonProjectile
{
public:
static UClass* StaticClass()
{
static auto ptr = UObject::FindClass("BlueprintGeneratedClass BP_HarpoonProjectile.BP_HarpoonProjectile_C");
return ptr;
}
void AfterRead();
void BeforeDelete();
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"40242723+alxalx14@users.noreply.github.com"
] | 40242723+alxalx14@users.noreply.github.com |
d226edc308d03ff574f0780e514272c8e0ff18aa | 88a60ce51b6ac092dc1886225f1d45b1f753dc92 | /lista1/p18.cpp | d6b0c4836a4ae659e170a64a5747946eec998d32 | [] | no_license | helfo2/competitive-programming | cf0aa1e962a6e3ad66f0406653def42f60e5711e | 4db0ecffbf7408e81b26fa1880b4ab94ac9b6b5f | refs/heads/master | 2022-11-22T01:02:01.618468 | 2020-07-27T22:25:09 | 2020-07-27T22:25:09 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 660 | cpp | #include <iostream>
#include <vector>
#include <string>
#include <cstdio>
using namespace std;
int n;
string words[100010];
int g[300][300];
void print(){
for(int i = 1; i < n; i++){
for(int j = 1; j < n; j++){
cout << g[i][j] << " ";
}
cout << endl;
}
}
int main(void){
int t; cin >> t;
while(t--){
cin >> n;
cout << n << endl;
for(int i = 0; i < 300; i++){
for(int j = 0; j < 300; j++){
g[i][j] = 0;
}
}
for(int w = 0; w < n; w++){
cin >> words[w];
// first and last letters
g[words[w][0]-'a'][words[w][words[w].length()-1]-'a']]++;
}
print();
for(int i = 0; i < n; i++){
}
}
return 0;
} | [
"henriqueelferreira@gmail.com"
] | henriqueelferreira@gmail.com |
0d92c1e7dea453252d4c1de52d4f224f2a8d8d8f | 96f80f93bbf083b11b548c5f153f6e853003f1a7 | /VwInclude/VirtualWallConfigFile.cpp | 84d7cdf126988e121ca7af13300bbeaa6a0f897d | [
"Apache-2.0"
] | permissive | fengjixuchui/VwFirewall | 2105fdd2d61eff64bff769b55076ee4e0a7af37c | 9db8d80a22a1605d034e1ade6bef7472df1a8682 | refs/heads/master | 2020-04-30T14:29:40.445164 | 2020-04-22T06:08:58 | 2020-04-22T06:08:58 | 176,892,269 | 0 | 0 | Apache-2.0 | 2020-04-22T06:08:59 | 2019-03-21T07:28:16 | C | GB18030 | C++ | false | false | 5,021 | cpp | // VirtualWallConfigFile.cpp: implementation of the CVirtualWallConfigFile class.
//
//////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "VirtualWallConfigFile.h"
#include "VwEnCodeString.h"
#include "VwConstBase.h"
#include "VwConstAntileechs.h"
#include "DeLib.h"
#pragma comment( lib, "DeLib.lib" )
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
CVirtualWallConfigFile::CVirtualWallConfigFile()
{
m_bInitSucc = InitModule();
}
CVirtualWallConfigFile::~CVirtualWallConfigFile()
{
}
//////////////////////////////////////////////////////////////////////////
// Private
BOOL CVirtualWallConfigFile::InitModule()
{
BOOL bRet = FALSE;
BOOL bLoadCfg = FALSE;
memset( m_szMetaPath, 0, sizeof(m_szMetaPath) );
memset( m_szVwClientDllFile, 0, sizeof(m_szVwClientDllFile) );
memset( m_szVwClientFilterName, 0, sizeof(m_szVwClientFilterName) );
memset( m_szVwClientFilterDesc, 0, sizeof(m_szVwClientFilterDesc) );
memset( m_szDllFileDeLib, 0, sizeof(m_szDllFileDeLib) );
memset( m_szDllFileDeLibNPp, 0, sizeof(m_szDllFileDeLibNPp) );
memset( m_szDllFileDeLibSks, 0, sizeof(m_szDllFileDeLibSks) );
//
// for VirtualWall.dll
//
memset( m_szVwDllName, 0, sizeof(m_szVwDllName) );
memcpy( m_szVwDllName, g_szFilterVwDllName, min( sizeof(g_szFilterVwDllName),sizeof(m_szVwDllName) ) );
delib_xorenc( m_szVwDllName );
memset( m_szFilterVwName, 0, sizeof(m_szFilterVwName) );
memcpy( m_szFilterVwName, g_szFilterVwName, min( sizeof(g_szFilterVwName), sizeof(m_szFilterVwName) ) );
delib_xorenc( m_szFilterVwName );
memset( m_szFilterVwDesc, 0, sizeof(m_szFilterVwDesc) );
memcpy( m_szFilterVwDesc, g_szFilterVwDesc, min( sizeof(g_szFilterVwDesc), sizeof(m_szFilterVwDesc) ) );
delib_xorenc( m_szFilterVwDesc );
//
// for VwClient.dll
//
memset( m_szVwClientDllName, 0, sizeof(m_szVwClientDllName) );
memcpy( m_szVwClientDllName, g_szFilterVwClientDllName, sizeof(g_szFilterVwClientDllName) );
delib_xorenc( m_szVwClientDllName );
memset( m_szVwClientFilterName, 0, sizeof(m_szVwClientFilterName) );
memcpy( m_szVwClientFilterName, g_szFilterVwClientFilterName, sizeof(g_szFilterVwClientFilterName) );
delib_xorenc( m_szVwClientFilterName );
memset( m_szVwClientFilterDesc, 0, sizeof(m_szVwClientFilterDesc) );
memcpy( m_szVwClientFilterDesc, g_szFilterVwClientFilterDesc, sizeof(g_szFilterVwClientFilterDesc) );
delib_xorenc( m_szVwClientFilterDesc );
memcpy( m_szMetaPath, g_szFilterMetaPath, min( sizeof(g_szFilterMetaPath), sizeof(m_szMetaPath) ) );
delib_xorenc( m_szMetaPath );
if ( CModuleInfo::IsInitSucc() )
{
bRet = TRUE;
// 文件路径和可执行路径
_sntprintf( m_szExePath, sizeof(m_szExePath)-sizeof(TCHAR), _T("%s"), CModuleInfo::mb_szModFile );
_sntprintf( m_szAppPath, sizeof(m_szAppPath)-sizeof(TCHAR), _T("%s"), CModuleInfo::mb_szModPath );
_sntprintf( m_szExeMakeCfgMapFilePath, sizeof(m_szExeMakeCfgMapFilePath)-sizeof(TCHAR), _T("%s -make_cfgmap_file"), CModuleInfo::mb_szModFile );
// 日志目录
_sntprintf( m_szLogsPath, sizeof(m_szLogsPath)-sizeof(TCHAR), _T("%s%s"), CModuleInfo::mb_szModPath, CONST_DIR_LOGS );
// 数据库文件路径
_sntprintf( m_szCfgDbFile, sizeof(m_szCfgDbFile)-sizeof(TCHAR), _T("%s%s"), CModuleInfo::mb_szModPath, CONST_CONFIG_DBFILE );
// chg 文件路径
_sntprintf( m_szCfgChgFile, sizeof(m_szCfgChgFile)-sizeof(TCHAR), _T("%s%s"), CModuleInfo::mb_szModPath, CONST_CONFIG_CHGFILE );
// 内存映射文件路径
_sntprintf( m_szCfgMapFile, sizeof(m_szCfgMapFile)-sizeof(TCHAR), "%s%s", CModuleInfo::mb_szModPath, CONST_CONFIG_MAPFILE );
// 核心模块工作情况记录文件
_sntprintf( m_szCoreWorkFile, sizeof(m_szCoreWorkFile)-sizeof(TCHAR), "%s%s\\%s", CModuleInfo::mb_szModPath, CONST_DIR_LOGS, CONST_CORE_WORKFILE );
// StatusBar Ad Ini 文件
_sntprintf( m_szStatusBarAdIni, sizeof(m_szStatusBarAdIni)-sizeof(TCHAR), "%s%s", mb_szWinTmpDir, CONST_STATUSBARAD_INIFILE );
// VirtualWall.dll
_sntprintf( m_szVwDllFile, sizeof(m_szVwDllFile)-sizeof(TCHAR), "%s%s", CModuleInfo::mb_szModPath, m_szVwDllName );
// VwClient.dll
_sntprintf( m_szVwClientDllFile, sizeof(m_szVwClientDllFile)-sizeof(TCHAR), "%s%s", CModuleInfo::mb_szModPath, m_szVwClientDllName );
// VwClient cfg.ini
_sntprintf( m_szVwClientCfgFile, sizeof(m_szVwClientCfgFile)-sizeof(TCHAR), "%s%s", CModuleInfo::mb_szModPath, "cfg.ini" );
// DeLib dll files
_sntprintf( m_szDllFileDeLib, sizeof(m_szDllFileDeLib)-sizeof(TCHAR), "%s%s", CModuleInfo::mb_szSysDir, CONST_DLLFILE_DELIB );
_sntprintf( m_szDllFileDeLibNPp, sizeof(m_szDllFileDeLibNPp)-sizeof(TCHAR), "%s%s", CModuleInfo::mb_szSysDir, CONST_DLLFILE_DELIBNPP );
_sntprintf( m_szDllFileDeLibSks, sizeof(m_szDllFileDeLibSks)-sizeof(TCHAR), "%s%s", CModuleInfo::mb_szSysDir, CONST_DLLFILE_DELIBSKS );
}
return bRet;
}
| [
"liuqixing@gmail.com"
] | liuqixing@gmail.com |
111f17a47646bc1bd3e8d8d191a0a6c200e5fac8 | 3782e25b6db35d82d63bb81e398deab85ef2236e | /Utils/Types/Queue.hpp | 157233d8d72d512943a9d6e502648dad110fb08c | [
"Apache-2.0"
] | permissive | nasa/fprime | e0c8d45dfc0ff08b5ef6c42a31f47430ba92c956 | a56426adbb888ce4f5a8c6a2be3071a25b11da16 | refs/heads/devel | 2023-09-03T15:10:33.578646 | 2023-08-29T15:39:59 | 2023-08-29T15:39:59 | 95,114,723 | 10,071 | 1,426 | Apache-2.0 | 2023-09-08T14:31:00 | 2017-06-22T12:45:27 | C++ | UTF-8 | C++ | false | false | 3,583 | hpp | /*
* Queue.hpp:
*
* FIFO queue of fixed size messages. For use generally where non-concurrent, non-OS backed based FIFO queues are
* necessary. Message size is defined at construction time and all messages enqueued and dequeued must be of that fixed
* size. Wraps circular buffer to perform actual storage of messages. This implementation is not thread safe and the
* expectation is that the user will wrap it in concurrency constructs where necessary.
*
* Created on: July 5th, 2022
* Author: lestarch
*
*/
#ifndef _UTILS_TYPES_QUEUE_HPP
#define _UTILS_TYPES_QUEUE_HPP
#include <FpConfig.hpp>
#include <Fw/Types/BasicTypes.hpp>
#include <Fw/Types/Serializable.hpp>
#include <Utils/Types/CircularBuffer.hpp>
namespace Types {
class Queue {
public:
/**
* \brief constructs an uninitialized queue
*/
Queue();
/**
* \brief setup the queue object to setup storage
*
* The queue must be configured before use to setup storage parameters. This function supplies those parameters
* including depth, and message size. Storage size must be greater than or equal to the depth x message size.
*
* \param storage: storage memory allocation
* \param storage_size: size of the provided allocation
* \param depth: depth of the queue
* \param message_size: size of individual messages
*/
void setup(U8* const storage, const FwSizeType storage_size, const FwSizeType depth, const FwSizeType message_size);
/**
* \brief pushes a fixed-size message onto the back of the queue
*
* Pushes a fixed-size message onto the queue. This performs a copy of the data onto the queue so the user is free
* to dispose the message data as soon as the call returns. Note: message is required to be of the size message_size
* as defined by the construction of the queue. Size is provided as a safety check to ensure the sent size is
* consistent with the expected size of the queue.
*
* This will return a non-Fw::SERIALIZE_OK status when the queue is full.
*
* \param message: message of size m_message_size to enqueue
* \param size: size of the message being sent. Must be equivalent to queue's message size.
* \return: Fw::SERIALIZE_OK on success, something else on failure
*/
Fw::SerializeStatus enqueue(const U8* const message, const FwSizeType size);
/**
* \brief pops a fixed-size message off the front of the queue
*
* Pops a fixed-size message off the front of the queue. This performs a copy of the data into the provided message
* buffer. Note: message is required to be of the size message_size as defined by the construction of the queue. The
* size must be greater or equal to message size, although only message size bytes will be used.
*
* This will return a non-Fw::SERIALIZE_OK status when the queue is empty.
*
* \param message: message of size m_message_size to dequeue
* \param size: size of the buffer being supplied.
* \return: Fw::SERIALIZE_OK on success, something else on failure
*/
Fw::SerializeStatus dequeue(U8* const message, const FwSizeType size);
/**
* Return the largest tracked allocated size
*/
NATIVE_UINT_TYPE get_high_water_mark() const;
/**
* Clear tracking of the largest allocated size
*/
void clear_high_water_mark();
NATIVE_UINT_TYPE getQueueSize() const;
private:
CircularBuffer m_internal;
FwSizeType m_message_size;
};
} // namespace Types
#endif // _UTILS_TYPES_QUEUE_HPP
| [
"noreply@github.com"
] | noreply@github.com |
357a55cadd5eb0ebb1e7e4eed68da0bc15cacbb8 | bf8ff2fa492632b9d0e9a0c191d95456d8ee97ff | /labo3-exe1.cpp | 9aa3b14dcac3ad26cf0712d51a6ad97d5fe02a2b | [] | no_license | Winnguyen1511/CPlusPlus_Basic_LAB | 25c1f38d4b4130a031fd29af200d8927f6ad0471 | 404d96739123ca7f1d9d442f3e0205b5515a12ac | refs/heads/master | 2020-12-03T12:21:08.612016 | 2020-01-02T05:43:58 | 2020-01-02T05:43:58 | 231,314,019 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 840 | cpp | #include <iostream>
#include<iomanip>
using namespace std;
int main()
{
int a,Max,Min;
double sum;
cout<<"Enter integer #1: ";
cin>>a;
Max=a;
Min=a;
sum=a;
cout<<"Enter integer #2: ";
cin>>a;
sum=sum+a;
if (a>Max) {Max=a;}
if(a<Min) {Min=a;}
cout<<"Enter integer #3: ";
cin>>a;
sum=sum+a;
if (a>Max) {Max=a;}
if(a<Min) {Min=a;}
cout<<"Enter integer #4: ";
cin>>a;
sum=sum+a;
if (a>Max) {Max=a;}
if(a<Min) {Min=a;}
cout<<"Enter integer #5: ";
cin>>a;
sum=sum+a;
if (a>Max) {Max=a;}
if(a<Min) {Min=a;}
cout<<"the largest number is: "<<Max<<endl;
cout<<"the least number is: "<<Min<<endl;
sum=sum/5.;
cout<<"the average of the five number you entered is "
<<setprecision(1)<<fixed<<sum;
}
| [
"noreply@github.com"
] | noreply@github.com |
2dc768eecde118203c03b5f9eb1c24e3bc47efe6 | d9df327477b6b3666c770cb7a5aecad74acb44fb | /lab2/include/surface/Planar.h | d383385c220c1f8e6579a0acbd6085d0f170c9ff | [] | no_license | goodmove/oop_course_1 | bd195e0f34fc744a955103122711cb8cf1662f7b | 04ce9384e3dad5b8fc65ea39080e2cd7b4f1fb9f | refs/heads/master | 2021-07-18T06:28:24.035297 | 2017-10-24T17:47:51 | 2017-10-24T17:47:51 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,328 | h | #pragma once
#include "Surface.h"
#include <unordered_map>
#include <string>
using std::unordered_map;
using std::vector;
using std::string;
using std::max;
using std::min;
namespace explorer {
using Point = struct point_s;
enum PointTypes : unsigned char {
Trail = 0, Obstacle, PathTile
};
struct point_s {
public:
point_s();
point_s(size_t, size_t);
bool operator==(point_s) const;
bool operator!=(point_s) const;
string toString() const;
size_t x, y;
};
class PointHash {
public:
size_t operator()(const Point&) const;
};
class Planar : public Surface<Point, size_t> {
public:
using surface_points = vector<vector<unsigned char>>;
using point_vector = vector<Point>;
Planar();
virtual bool isWalkable(const Point&) const override;
bool checkPath(const point_vector&, const Point&, const Point&) const override;
bool setSurface(const surface_points& surface);
surface_points getSurface() const;
size_t getHeight() const;
size_t getWidth() const;
bool isBuilt() const;
protected:
bool isPointWithinBounds(const Point&) const;
bool isPointValid(const Point&) const;
bool isObstacle(bool) const;
surface_points surface_;
bool isBuilt_;
};
} | [
"goodmoveab@gmail.com"
] | goodmoveab@gmail.com |
555330a8419ad52dae6fd68dec33f828ffb1007f | 206174a1082ed90c22ecbbaaa381833b3a7f068c | /PreView.h | c6dd9a2f1d707e7a847311c7f06699b99b4496bd | [] | no_license | fengqing-maker/ffff | 1b646c4b09fc32ad2f931f15db83f09a4ad81eed | 0ff23fb859a14e9156c7b614416fdc48e67befb0 | refs/heads/master | 2022-12-17T06:58:15.033266 | 2020-09-03T02:54:57 | 2020-09-03T02:54:57 | 292,450,929 | 0 | 1 | null | null | null | null | GB18030 | C++ | false | false | 6,089 | h | #if !defined(AFX_PREVIEW_H__03894546_1C39_11D4_B336_00104B13D514__INCLUDED_)
#define AFX_PREVIEW_H__03894546_1C39_11D4_B336_00104B13D514__INCLUDED_
#if _MSC_VER >= 1000
#pragma once
#endif // _MSC_VER >= 1000
// PreView.h : header file
//
/////////////////////////////////////////////////////////////////////////////
// CPreView view
#include "afxpriv.h"
class CMyView;
class CPreView : public CScrollView
{
DECLARE_DYNCREATE(CPreView)
protected:
CPreView(); // protected constructor used by dynamic creation
BOOL SetPrintView(CMyView* pPrintView);
// Attributes
public:
CMyView* m_pOrigView;
CMyView* m_pPrintView;
CPreviewDC* m_pPreviewDC; // Output and attrib DCs Set, not created
CDC m_dcPrint; // Actual printer DC
// Operations
void SetZoomState(UINT nNewState, UINT nPage, CPoint point);
void SetCurrentPage(UINT nPage, BOOL bClearRatios);
// Returns TRUE if in a page rect. Returns the page index
// in nPage and the point converted to 1:1 screen device coordinates
BOOL FindPageRect(CPoint& point, UINT& nPage);
// Returns .cx/.cy as the numerator/denominator pair for the ratio
// using CSize for convenience
virtual CSize CalcScaleRatio(CSize windowSize, CSize actualSize);
virtual void PositionPage(UINT nPage);
virtual void OnDisplayPageNumber(UINT nPage, UINT nPagesDisplayed);
// Operations
public:
void ClosePreview();
// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CPreView)
public:
virtual void OnPrepareDC(CDC* pDC, CPrintInfo* pInfo = NULL);
protected:
virtual void OnDraw(CDC* pDC); // overridden to draw this view
virtual void OnActivateView(BOOL bActivate, CView* pActivateView, CView* pDeactiveView);
virtual void OnUpdate(CView* pSender, LPARAM lHint, CObject* pHint);
//}}AFX_VIRTUAL
void DoZoom(UINT nPage, CPoint point);
void SetScaledSize(UINT nPage);
CSize CalcPageDisplaySize();
CPrintPreviewState* m_pPreviewState; // State to restore
CDialogBar* m_pToolBar; // Toolbar for preview
struct PAGE_INFO
{
CRect rectScreen; // screen rect (screen device units)
CSize sizeUnscaled; // unscaled screen rect (screen device units) 打印纸对应到屏幕坐标的长宽
CSize sizeScaleRatio; // scale ratio (cx/cy)
CSize sizeZoomOutRatio; // scale ratio when zoomed out (cx/cy)
};
PAGE_INFO* m_pPageInfo; // Array of page info structures
//***********************************************************
//PAGE_INFO m_pageInfoArray[2]; // Embedded array for the default implementation
// 每屏可显示10页预览页
PAGE_INFO m_pageInfoArray[10]; // Embedded array for the default implementation
//***********************************************************
BOOL m_bPageNumDisplayed;// Flags whether or not page number has yet
// been displayed on status line
UINT m_nZoomOutPages; // number of pages when zoomed out
UINT m_nZoomState;
UINT m_nMaxPages; // for sanity checks
UINT m_nCurrentPage;
UINT m_nPages; // 预览每屏显示的页数
int m_nSecondPageOffset; // used to shift second page position
int m_nUpdownPageOffset; // 上下页之间的距离
int m_nPreviewLine; // 预览页行数
int m_nLine; // 行数
HCURSOR m_hMagnifyCursor;
CSize m_sizePrinterPPI; // printer pixels per inch
CPoint m_ptCenterPoint;
CPrintInfo* m_pPreviewInfo;
// Implementation
protected:
virtual ~CPreView();
#ifdef _DEBUG
virtual void AssertValid() const;
virtual void Dump(CDumpContext& dc) const;
#endif
// Generated message map functions
//{{AFX_MSG(CPreView)
afx_msg void OnPreviewClose();
afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct);
afx_msg void OnSize(UINT nType, int cx, int cy);
afx_msg void OnHScroll(UINT nSBCode, UINT nPos, CScrollBar* pScrollBar);
afx_msg void OnVScroll(UINT nSBCode, UINT nPos, CScrollBar* pScrollBar);
afx_msg void OnLButtonDown(UINT nFlags, CPoint point);
afx_msg BOOL OnEraseBkgnd(CDC* pDC);
afx_msg void OnNumPageChange();
afx_msg void OnNextPage();
afx_msg void OnPrevPage();
afx_msg void OnPreviewPrint();
afx_msg void OnZoomIn();
afx_msg void OnZoomOut();
afx_msg void OnThreePage();
afx_msg void OnUpdateThreePage(CCmdUI* pCmdUI);
afx_msg void OnSixPage();
afx_msg void OnUpdateSixPage(CCmdUI* pCmdUI);
afx_msg void OnFind();
afx_msg void OnUpdateNumPageChange(CCmdUI* pCmdUI);
afx_msg void OnUpdateNextPage(CCmdUI* pCmdUI);
afx_msg void OnUpdatePrevPage(CCmdUI* pCmdUI);
afx_msg void OnUpdateZoomIn(CCmdUI* pCmdUI);
afx_msg void OnUpdateZoomOut(CCmdUI* pCmdUI);
afx_msg BOOL OnSetCursor(CWnd* pWnd, UINT nHitTest, UINT message);
afx_msg void OnFileNew();
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
friend class CMyView;
friend BOOL CALLBACK _AfxPreviewCloseProc(CFrameWnd* pFrameWnd);
};
// Zoom States
#define ZOOM_OUT 0
#define ZOOM_MIDDLE 1
#define ZOOM_IN 2
class CMyView : public CScrollView
{
protected:
CMyView(); // protected constructor used by dynamic creation
DECLARE_DYNCREATE(CMyView)
// Attributes
public:
// Operations
public:
BOOL DoPrintPreview(UINT nIDResource, CMyView* pPrintView,
CRuntimeClass* pPreviewViewClass, CPrintPreviewState* pState);
// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CMyView)
protected:
virtual void OnDraw(CDC* pDC); // overridden to draw this view
virtual void OnEndPrintPreview(CDC* pDC, CPrintInfo* pInfo, POINT point, CPreView* pView);
//}}AFX_VIRTUAL
// Implementation
protected:
virtual ~CMyView();
#ifdef _DEBUG
virtual void AssertValid() const;
virtual void Dump(CDumpContext& dc) const;
#endif
// Generated message map functions
protected:
//{{AFX_MSG(CMyView)
afx_msg void OnFilePrintPreview();
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
friend class CPreView;
};
/////////////////////////////////////////////////////////////////////////////
//{{AFX_INSERT_LOCATION}}
// Microsoft Developer Studio will insert additional declarations immediately before the previous line.
#endif // !defined(AFX_PREVIEW_H__03894546_1C39_11D4_B336_00104B13D514__INCLUDED_)
| [
"1344465206@qq.com"
] | 1344465206@qq.com |
302b3a98e4bad00fc7f7becd15ea4fe2903c44db | db96b049c8e27f723fcb2f3a99291e631f1a1801 | /src/objtools/writers/aln_writer.cpp | 464c6363d355edf99d76c5e2496491f1982ac307 | [] | no_license | Watch-Later/ncbi-cxx-toolkit-public | 1c3a2502b21c7c5cee2c20c39e37861351bd2c05 | 39eede0aea59742ca4d346a6411b709a8566b269 | refs/heads/master | 2023-08-15T14:54:41.973806 | 2021-10-04T04:03:02 | 2021-10-04T04:03:02 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 18,166 | cpp | /* $Id$
* ===========================================================================
*
* PUBLIC DOMAIN NOTICE
* National Center for Biotechnology Information
*
* This software/database is a "United States Government Work" under the
* terms of the United States Copyright Act. It was written as part of
* the author's official duties as a United States Government employee and
* thus cannot be copyrighted. This software/database is freely available
* to the public for use. The National Library of Medicine and the U.S.
* Government have not placed any restriction on its use or reproduction.
*
* Although all reasonable efforts have been taken to ensure the accuracy
* and reliability of the software and data, the NLM and the U.S.
* Government do not and cannot warrant the performance or results that
* may be obtained by using this software or data. The NLM and the U.S.
* Government disclaim all warranties, express or implied, including
* warranties of performance, merchantability or fitness for any particular
* purpose.
*
* Please cite the author in any work or product based on this material.
*
* ===========================================================================
*
* Authors: Justin Foley
*
* File Description: Write alignment
*
*/
#include <ncbi_pch.hpp>
#include <objects/seqalign/Seq_align.hpp>
#include <objects/seqalign/Dense_seg.hpp>
#include <objects/seqalign/Spliced_seg.hpp>
#include <objects/seqalign/Spliced_exon.hpp>
#include <objects/seqalign/Sparse_seg.hpp>
#include <objects/seqalign/Sparse_align.hpp>
#include <objects/seqalign/Product_pos.hpp>
#include <objects/seqalign/Prot_pos.hpp>
#include <objects/seqalign/Spliced_exon_chunk.hpp>
#include <objects/general/Object_id.hpp>
#include <objects/seq/seq_id_handle.hpp>
#include <objmgr/scope.hpp>
#include <objmgr/bioseq_handle.hpp>
#include <objmgr/seq_vector.hpp>
#include <objmgr/util/sequence.hpp>
#include <objtools/writers/writer_exception.hpp>
#include <objtools/writers/write_util.hpp>
#include <objtools/writers/aln_writer.hpp>
#include <util/sequtil/sequtil_manip.hpp>
BEGIN_NCBI_SCOPE
USING_SCOPE(objects);
// ----------------------------------------------------------------------------
CAlnWriter::CAlnWriter(
CScope& scope,
CNcbiOstream& ostr,
unsigned int uFlags) :
CWriterBase(ostr, uFlags)
{
m_pScope.Reset(&scope);
m_Width = 60;
CGenbankIdResolve::Get().SetLabelType(CSeq_id::eFasta);
};
// ----------------------------------------------------------------------------
CAlnWriter::CAlnWriter(
CNcbiOstream& ostr,
unsigned int uFlags) :
CAlnWriter(*(new CScope(*CObjectManager::GetInstance())), ostr, uFlags)
{
};
// ----------------------------------------------------------------------------
bool CAlnWriter::WriteAlign(
const CSeq_align& align,
const string& name,
const string& descr)
{
switch (align.GetSegs().Which()) {
case CSeq_align::C_Segs::e_Denseg:
return WriteAlignDenseSeg(align.GetSegs().GetDenseg());
case CSeq_align::C_Segs::e_Spliced:
return WriteAlignSplicedSeg(align.GetSegs().GetSpliced());
case CSeq_align::C_Segs::e_Sparse:
return WriteAlignSparseSeg(align.GetSegs().GetSparse());
case CSeq_align::C_Segs::e_Std:
break;
default:
break;
}
return false;
}
// ----------------------------------------------------------------------------
void CAlnWriter::ProcessSeqId(const CSeq_id& id, CBioseq_Handle& bsh, CRange<TSeqPos>& range)
{
if (m_pScope) {
bsh = m_pScope->GetBioseqHandle(id);
range.SetFrom(CRange<TSeqPos>::GetPositionMin());
range.SetToOpen(CRange<TSeqPos>::GetPositionMax());
}
}
// -----------------------------------------------------------------------------
void CAlnWriter::GetSeqString(CBioseq_Handle bsh,
const CRange<TSeqPos>& range,
ENa_strand strand,
string& seq)
{
if (!bsh) {
NCBI_THROW(CObjWriterException,
eBadInput,
"Empty bioseq handle");
}
CSeqVector seq_vec = bsh.GetSeqVector(CBioseq_Handle::eCoding_Iupac, strand);
if (range.IsWhole()) {
seq_vec.GetSeqData(0, bsh.GetBioseqLength(), seq);
}
else {
seq_vec.GetSeqData(range.GetFrom(), range.GetTo(), seq);
}
if (NStr::IsBlank(seq)) {
NCBI_THROW(CObjWriterException,
eBadInput,
"Empty sequence string");
}
}
// -----------------------------------------------------------------------------
bool CAlnWriter::WriteAlignDenseSeg(
const CDense_seg& denseg)
{
if (!denseg.CanGetDim() ||
!denseg.CanGetNumseg() ||
!denseg.CanGetIds() ||
!denseg.CanGetStarts() ||
!denseg.CanGetLens())
{
return false;
}
const auto num_rows = denseg.GetDim();
const auto num_segs = denseg.GetNumseg();
for (int row=0; row<num_rows; ++row)
{
const CSeq_id& id = denseg.GetSeq_id(row);
CRange<TSeqPos> range;
CBioseq_Handle bsh;
ProcessSeqId(id, bsh, range);
if (!bsh) {
NCBI_THROW(CObjWriterException,
eBadInput,
"Unable to fetch Bioseq");
}
string seq_plus;
GetSeqString(bsh, range, eNa_strand_plus, seq_plus);
const CSeqUtil::ECoding coding =
(bsh.IsNucleotide()) ?
CSeqUtil::e_Iupacna :
CSeqUtil::e_Iupacaa;
string seqdata;
for (int seg=0; seg<num_segs; ++seg)
{
const auto start = denseg.GetStarts()[seg*num_rows + row];
const auto len = denseg.GetLens()[seg];
const ENa_strand strand = (denseg.IsSetStrands()) ?
denseg.GetStrands()[seg*num_rows + row] :
eNa_strand_plus;
seqdata += GetSegString(seq_plus, coding, strand, start, len);
}
string best_id = GetBestId(id);
string defline = ">" + best_id;
WriteContiguous(defline, seqdata);
}
return true;
}
// -----------------------------------------------------------------------------
bool CAlnWriter::WriteAlignSplicedSeg(
const CSpliced_seg& spliced_seg)
{
if (!spliced_seg.IsSetExons()) {
return false;
}
CRef<CSeq_id> genomic_id;
if (spliced_seg.IsSetGenomic_id()) {
genomic_id = Ref(new CSeq_id());
genomic_id->Assign(spliced_seg.GetGenomic_id());
}
CRef<CSeq_id> product_id;
if (spliced_seg.IsSetGenomic_id()) {
product_id = Ref(new CSeq_id());
product_id->Assign(spliced_seg.GetProduct_id());
}
ENa_strand genomic_strand =
spliced_seg.IsSetGenomic_strand() ?
spliced_seg.GetGenomic_strand() :
eNa_strand_plus;
ENa_strand product_strand =
spliced_seg.IsSetProduct_strand() ?
spliced_seg.GetProduct_strand() :
eNa_strand_plus;
return WriteSplicedExons(spliced_seg.GetExons(),
spliced_seg.GetProduct_type(),
genomic_id,
genomic_strand,
product_id,
product_strand);
}
unsigned int s_ProductLength(const CProduct_pos& start, const CProduct_pos& end)
{
if (start.Which() != end.Which()) {
NCBI_THROW(CObjWriterException,
eBadInput,
"Unable to determine product length");
}
if (start.Which() == CProduct_pos::e_not_set) {
NCBI_THROW(CObjWriterException,
eBadInput,
"Unable to determine product length");
}
const int length = end.AsSeqPos() - start.AsSeqPos();
return (length >= 0) ? length : -length;
}
// -----------------------------------------------------------------------------
bool CAlnWriter::WriteSplicedExons(const list<CRef<CSpliced_exon>>& exons,
CSpliced_seg::TProduct_type product_type,
CRef<CSeq_id> default_genomic_id, // May be NULL
ENa_strand default_genomic_strand,
CRef<CSeq_id> default_product_id,
ENa_strand default_product_strand)
{
string prev_genomic_id;
string prev_product_id;
for (const CRef<CSpliced_exon>& exon : exons) {
const CSeq_id& genomic_id =
exon->IsSetGenomic_id() ?
exon->GetGenomic_id() :
*default_genomic_id;
const CSeq_id& product_id =
exon->IsSetProduct_id() ?
exon->GetProduct_id() :
*default_product_id;
// Should check to see that the ids are not empty
const ENa_strand genomic_strand =
exon->IsSetGenomic_strand() ?
exon->GetGenomic_strand() :
default_genomic_strand;
const ENa_strand product_strand =
exon->IsSetProduct_strand() ?
exon->GetProduct_strand() :
default_product_strand;
const auto genomic_start = exon->GetGenomic_start();
const auto genomic_end = exon->GetGenomic_end();
if (genomic_end < genomic_start) {
NCBI_THROW(CObjWriterException,
eBadInput,
"Bad genomic location: end < start");
}
const int genomic_length = genomic_end - genomic_start;
const int product_start = exon->GetProduct_start().AsSeqPos();
const int product_end = exon->GetProduct_end().AsSeqPos();
if (product_end < product_start) {
NCBI_THROW(CObjWriterException,
eBadInput,
"Bad product location: end < start");
}
// product_length is now given in nucleotide units
const int product_length = product_end - product_start;
CBioseq_Handle genomic_bsh;
if (m_pScope) {
genomic_bsh = m_pScope->GetBioseqHandle(genomic_id);
}
if (!genomic_bsh) {
NCBI_THROW(CObjWriterException,
eBadInput,
"Unable to resolve genomic sequence");
}
CRange<TSeqPos> genomic_range(genomic_start, genomic_end+1);
string genomic_seq;
GetSeqString(genomic_bsh, genomic_range, genomic_strand, genomic_seq);
CBioseq_Handle product_bsh;
if (m_pScope) {
product_bsh = m_pScope->GetBioseqHandle(product_id);
}
if (!product_bsh) {
NCBI_THROW(CObjWriterException,
eBadInput,
"Unable to resolve product sequence");
}
CRange<TSeqPos> product_range(product_start, product_end+1);
string product_seq;
GetSeqString(product_bsh, product_range, product_strand, product_seq);
if (exon->IsSetParts()) {
AddGaps(product_type, exon->GetParts(), genomic_seq, product_seq);
}
else
if (product_length != genomic_length) {
NCBI_THROW(CObjWriterException,
eBadInput,
"Lengths of genomic and product sequences don't match");
}
WriteContiguous(">" + GetBestId(genomic_id), genomic_seq);
WriteContiguous(">" + GetBestId(product_id), product_seq);
}
return true;
}
// -----------------------------------------------------------------------------
void CAlnWriter::AddGaps(
CSpliced_seg::TProduct_type product_type,
const CSpliced_exon::TParts& exon_chunks,
string& genomic_seq,
string& product_seq)
{
if (exon_chunks.empty()) {
return;
}
string genomic_string;
string product_string;
const unsigned int res_width =
(product_type == CSpliced_seg::eProduct_type_transcript) ?
1 : 3;
// Check that match + mismatch + diag + genomic_ins = genomic_length
int genomic_pos = 0;
int product_pos = 0;
unsigned int interval_width = 0;
for (CRef<CSpliced_exon_chunk> exon_chunk : exon_chunks) {
auto chunk_type = exon_chunk->Which();
switch(chunk_type) {
case CSpliced_exon_chunk::e_Match:
case CSpliced_exon_chunk::e_Mismatch:
case CSpliced_exon_chunk::e_Diag:
switch(chunk_type) {
default:
// compiler, shut up!
break;
case CSpliced_exon_chunk::e_Match:
interval_width = exon_chunk->GetMatch();
break;
case CSpliced_exon_chunk::e_Mismatch:
interval_width = exon_chunk->GetMismatch();
break;
case CSpliced_exon_chunk::e_Diag:
interval_width = exon_chunk->GetDiag();
break;
}
genomic_string.append(genomic_seq, genomic_pos, interval_width);
product_string.append(product_seq, product_pos, (interval_width + (res_width-1))/res_width);
genomic_pos += interval_width;
product_pos += interval_width/res_width;
break;
case CSpliced_exon_chunk::e_Genomic_ins:
interval_width = exon_chunk->GetGenomic_ins();
genomic_string.append(genomic_seq, genomic_pos, interval_width);
product_string.append(interval_width/res_width, '-');
genomic_pos += interval_width;
break;
case CSpliced_exon_chunk::e_Product_ins:
interval_width = exon_chunk->GetProduct_ins();
genomic_string.append(interval_width, '-');
product_string.append(product_seq, product_pos, interval_width/res_width);
product_pos += interval_width/res_width;
break;
default:
break;
}
}
genomic_seq = genomic_string;
product_seq = product_string;
}
// -----------------------------------------------------------------------------
string CAlnWriter::GetSegString(const string& seq_plus,
CSeqUtil::ECoding coding,
const ENa_strand strand,
const int start,
const size_t len)
{
if (start >= 0) {
if (start >= seq_plus.size()) {
NCBI_THROW(CObjWriterException,
eBadInput,
"Bad location: impossible start");
}
if (strand != eNa_strand_minus) {
return seq_plus.substr(start, len);
}
// else
string seq_minus;
CSeqManip::ReverseComplement(seq_plus, coding, start, len, seq_minus);
return seq_minus;
}
return string(len, '-');
}
// -----------------------------------------------------------------------------
bool CAlnWriter::WriteAlignSparseSeg(
const CSparse_seg& sparse_seg)
{
for (CRef<CSparse_align> align : sparse_seg.GetRows())
{
if (!WriteSparseAlign(*align)) {
return false;
}
}
return true;
}
// -----------------------------------------------------------------------------
bool CAlnWriter::WriteSparseAlign(const CSparse_align& sparse_align)
{
const auto num_segs = sparse_align.GetNumseg();
{
const CSeq_id& first_id = sparse_align.GetFirst_id();
CBioseq_Handle bsh;
CRange<TSeqPos> range;
ProcessSeqId(first_id, bsh, range);
if (!bsh) {
NCBI_THROW(CObjWriterException,
eBadInput,
"Unable to resolve ID " + first_id.AsFastaString());
}
const CSeqUtil::ECoding coding =
(bsh.IsNucleotide())?
CSeqUtil::e_Iupacna :
CSeqUtil::e_Iupacaa;
string seq_plus;
GetSeqString(bsh, range, eNa_strand_plus, seq_plus);
string seqdata;
for (int seg=0; seg<num_segs; ++seg) {
const auto start = sparse_align.GetFirst_starts()[seg];
const auto len = sparse_align.GetLens()[seg];
seqdata += GetSegString(seq_plus, coding, eNa_strand_plus, start, len);
}
WriteContiguous(">" + GetBestId(first_id), seqdata);
}
{ // Second row
const CSeq_id& second_id = sparse_align.GetSecond_id();
CBioseq_Handle bsh;
CRange<TSeqPos> range;
ProcessSeqId(second_id, bsh, range);
if (!bsh) {
NCBI_THROW(CObjWriterException,
eBadInput,
"Unable to resolve ID " + second_id.AsFastaString());
}
const CSeqUtil::ECoding coding =
(bsh.IsNucleotide())?
CSeqUtil::e_Iupacna :
CSeqUtil::e_Iupacaa;
string seq_plus;
GetSeqString(bsh, range, eNa_strand_plus, seq_plus);
string seqdata;
const vector<ENa_strand>& strands = sparse_align.IsSetSecond_strands() ?
sparse_align.GetSecond_strands() : vector<ENa_strand>(num_segs, eNa_strand_plus);
for (int seg=0; seg<num_segs; ++seg) {
const auto start = sparse_align.GetFirst_starts()[seg];
const auto len = sparse_align.GetLens()[seg];
seqdata += GetSegString(seq_plus, coding, strands[seg], start, len);
}
WriteContiguous(">" + GetBestId(second_id), seqdata);
}
return true;
}
// -----------------------------------------------------------------------------
void CAlnWriter::WriteContiguous(const string& defline, const string& seqdata)
{
if (defline.back() == '|' && defline.size() > 1)
{
const auto length = defline.size();
m_Os << defline.substr(0,length-1) << "\n";
}
else {
m_Os << defline << "\n";
}
size_t pos=0;
while (pos < seqdata.size()) {
if (IsCanceled()) {
NCBI_THROW(
CObjWriterException,
eInterrupted,
"Processing terminated by user");
}
m_Os << seqdata.substr(pos, m_Width) << "\n";
pos += m_Width;
}
}
// -----------------------------------------------------------------------------
string CAlnWriter::GetBestId(const CSeq_id& id)
{
string best_id;
CGenbankIdResolve::Get().GetBestId(
CSeq_id_Handle::GetHandle(id),
*m_pScope,
best_id);
return best_id;
}
// -----------------------------------------------------------------------------
END_NCBI_SCOPE
| [
"ludwigf@78c7ea69-d796-4a43-9a09-de51944f1b03"
] | ludwigf@78c7ea69-d796-4a43-9a09-de51944f1b03 |
20688969557445714be74fb09a623deb8edfbf18 | 3c9f984766c81ba95f1f4f828fd9c4e6efef9da1 | /SupplyFinanceChain/src/SupplyFinanceChain/protocol/SystemParameters.h | 9be03e0d44f4df4d84214deb8a4f72216d966b0e | [] | no_license | SCF-Team/scfchain | 5f73e3c3a41ac5e33d2637980f428a9b8173fda5 | 41f020da81e1c69a61d0c1698df04cf33b20fc63 | refs/heads/master | 2020-06-26T21:51:29.263077 | 2019-08-05T11:11:24 | 2019-08-05T11:11:24 | 199,766,740 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,252 | h | //------------------------------------------------------------------------------
/*
This file is part of SupplyFinanceChaind: https://github.com/SupplyFinanceChain/SupplyFinanceChaind
Copyright (c) 2012, 2013 SupplyFinanceChain Labs Inc.
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" 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.
*/
//==============================================================================
#ifndef SUPPLYFINANCECHAIN_PROTOCOL_SYSTEMPARAMETERS_H_INCLUDED
#define SUPPLYFINANCECHAIN_PROTOCOL_SYSTEMPARAMETERS_H_INCLUDED
#include <cstdint>
#include <string>
namespace SupplyFinanceChain {
// Various protocol and system specific constant globals.
/* The name of the system. */
static inline
std::string const&
systemName ()
{
static std::string const name = "SupplyFinanceChain";
return name;
}
/** Configure the native currency. */
static
std::uint64_t const
SYSTEM_CURRENCY_GIFT = 1000;
static
std::uint64_t const
SYSTEM_CURRENCY_USERS = 100000000;
/** Number of drops per 1 SFC */
static
std::uint64_t const
SYSTEM_CURRENCY_PARTS = 1000000;
/** Number of drops in the genesis account. */
static
std::uint64_t const
SYSTEM_CURRENCY_START = SYSTEM_CURRENCY_GIFT * SYSTEM_CURRENCY_USERS * SYSTEM_CURRENCY_PARTS;
/* The currency code for the native currency. */
static inline
std::string const&
systemCurrencyCode ()
{
static std::string const code = "SFC";
return code;
}
/** The SFC ledger network's earliest allowed sequence */
static
std::uint32_t constexpr
SFC_LEDGER_EARLIEST_SEQ {32570};
} // SupplyFinanceChain
#endif
| [
"ghubdevelop@protonmail.com"
] | ghubdevelop@protonmail.com |
fa3d4b94f3d743b39d4f7cb65cdb1a01f27b4a20 | 75d24ce86e1fb833974615a8c21521c918f575b4 | /Otask.h | cd885c82099422c24af8448e191f7c1af2cafb6e | [] | no_license | ndilday/virtualu | 059100ec82b46c1def39643fdf7123d05db3796d | 96012dccd26e32460403b3438ca0ce0ef7fe469b | refs/heads/master | 2021-01-10T07:06:13.960690 | 2014-05-22T04:16:38 | 2014-05-22T04:16:38 | 47,211,286 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,515 | h | //Filename : OTASK.H
//Description : Object News
//Owner : Fred
//------------------------------------//
//
// Task array/list properties (for each task):
//
// - shown on both message (normal news) and objective sections on screen
// - will be removed from the objective section after the task offer expires or the task is completed
// - checked monthly the success of the task; add bonus if task is completed
//
//------------------------------------//
#ifndef __OTASK_H
#define __OTASK_H
#include <ONEWS.H>
//--------- Define constant --------------//
//#define DISP_TASKS_COUNT 5 // maximum no. of task message displayed on the screen at a time
//#define TASKS_STR_PARA_LEN 20
//-------- Define task type ---------//
enum { TASK_WHO_NUM=1 };
enum { //, TASKS_DISP_FRIENDLY, TASKS_DISP_PLAYER, TASKS_DISP_NONE };
TASK_DISP_ALL=0
};
//------- Define other constant -------//
//--------- Define task id. ----------//
#define TASK_COUNT 8 //## chea 220999 1 is org. & is the first ele
enum {
TASK_RISE_PERFORMANCE_RATING = 1, // rise value of performance indicator
RISE_EDUCATIONAL_QUALITY, //## chea 220999
RISE_STUDENT_MORALE,
RISE_DEPARTMENT_MORALE,
RISE_FACULTY_RESEARCH,
RISE_FACULTY_DIVERSITY_INDEX,
RISE_USE_OF_IT,
RISE_STAFF_MORALE,
};
//------------------------------------//
// typedef News Task;
//!Subclass of News class. Tasks are shown on both message (normal news)
//!and objective sections on screen. They are removed from the objective
//!section after the task offer expires or the task is completed. The
//!successful completion of the task is checked monthly and a bonus is
//!added for completed tasks.
struct Task : News {
//bool (*complete_func)();
//bool (*expiry_func)();
// temp functions for each task type
bool is_completed_rise_performance();
bool is_completed_rise_educational_quality(); //## chea 220999
bool is_completed_rise_student_morale();
bool is_completed_rise_department_morale();
bool is_completed_rise_faculty_research_Per();
bool is_completed_rise_faculty_diversity_index();
bool is_completed_rise_use_of_IT();
bool is_completed_rise_staff_morale();
// functions for all task types
bool is_expired();
void set_completed();
};
//-------- Define class TaskArray ----------//
//!Array containing the history of the tasks assigned during this game.
//!Responds to init, next_day, and read/write.
class TaskArray : public DynArray {
public:
//------ display options ------//
char task_who_option;
char task_add_flag;
int total_bonus_pt;
float rand_init;
public:
TaskArray();
void init(); // called in ogame.cpp
void deinit(); // called in ogame.cpp
int write_file(File* filePtr);
int read_file(File* filePtr);
void enable() { task_add_flag = 1; }
void disable() { task_add_flag = 0; }
void reset();
void default_setting();
void clear_task_disp();
void next_day();
Task* add_task(int taskId);
void remove(int index);
bool can_add_more_task();
//------ functions for adding task -------//
void rise_performance_rating(int deptRecno, int ratingType,
int target, int src, int month, int year, int bonus);
void rise_educational_quality(int deptRecno, int ratingType,
int target, int src, int month, int year, int bonus);
void rise_student_morale(int deptRecno, int ratingType,
int target, int src, int month, int year, int bonus);
void rise_department_morale(int deptRecno, int ratingType,
int target, int src, int month, int year, int bonus);
void rise_faculty_research_Per(int deptRecno, int ratingType,
int target, int src, int month, int year, int bonus);
void rise_faculty_diversity_index(int deptRecno, int ratingType,
int target, int src, int month, int year, int bonus);
void rise_use_of_IT(int deptRecno, int ratingType,
int target, int src, int month, int year, int bonus);
void rise_staff_morale(int deptRecno, int ratingType,
int target, int src, int month, int year, int bonus);
//--------------------------------------------//
Task* operator[](int recNo);
};
extern TaskArray task_array;
//-------------------------------------------//
#endif
| [
"ndilday@gmail.com"
] | ndilday@gmail.com |
d299db547b50e82a12e6b00048911740d106b465 | 32c10943c14b5e92bcd1d3f421e1539cf799725a | /XRays/includes/lua_bridge/Vector.h | 0c4d3c820e3d490a758b223c062770fa1cc97955 | [] | no_license | supercuglong/XRays | d25245bc6963ed34ba540433d3b165ad72737ef2 | c8b61dcb4cdb8d7156f065a3da9af6a2c9f9e4da | refs/heads/main | 2023-07-17T19:52:11.826768 | 2021-09-06T18:19:43 | 2021-09-06T18:19:43 | 403,798,898 | 2 | 4 | null | 2021-09-07T01:05:22 | 2021-09-07T01:05:20 | null | UTF-8 | C++ | false | false | 1,136 | h | // https://github.com/vinniefalco/LuaBridge
// Copyright 2018, Dmitry Tarakanov
// SPDX-License-Identifier: MIT
#pragma once
#include <vector>
#include "detail/Stack.h"
namespace luabridge {
template <class T> struct Stack<std::vector<T>> {
static void push(lua_State *L, std::vector<T> const &vector) {
lua_createtable(L, static_cast<int>(vector.size()), 0);
for (std::size_t i = 0; i < vector.size(); ++i) {
lua_pushinteger(L, static_cast<lua_Integer>(i + 1));
Stack<T>::push(L, vector[i]);
lua_settable(L, -3);
}
}
static std::vector<T> get(lua_State *L, int index) {
if (!lua_istable(L, index)) {
luaL_error(L, "#%d argument must be a table", index);
}
std::vector<T> vector;
vector.reserve(static_cast<std::size_t>(get_length(L, index)));
int const absindex = lua_absindex(L, index);
lua_pushnil(L);
while (lua_next(L, absindex) != 0) {
vector.push_back(Stack<T>::get(L, -1));
lua_pop(L, 1);
}
return vector;
}
static bool isInstance(lua_State *L, int index) {
return lua_istable(L, index);
}
};
} // namespace luabridge
| [
"lli@DESKTOP-S89EIDG"
] | lli@DESKTOP-S89EIDG |
a2aa17a82af9994ffcb97dd53092951175638045 | 4b15494c1fac858b83d26c99e071580efa554368 | /Source/Allogen/JNI/BridgedDestructor.hpp | 9f26b2c176a021bbd484b4d8d7b4d8ec109f4267 | [
"BSD-3-Clause"
] | permissive | Allogica/Allogen | 87c9b58c26446cfe6ab7e158b5074e3d30ed5d73 | ec3b82544659403896d95ed933890b761b35cddb | refs/heads/master | 2020-07-12T05:46:25.663068 | 2019-05-16T17:23:46 | 2019-05-16T17:23:46 | 94,276,348 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,925 | hpp | /*
* Copyright (c) 2017, Allogica
*
* 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 Allogen 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.
*/
#pragma once
#include <jni.h>
#include "Allogen/JNI/CoffeeCatch.hpp"
namespace Allogen {
namespace JNI {
/**
* This class represents a standard destructor wrapper.
*
* @tparam Class the wrapped class whose destructor is being called
*/
template<typename Class>
struct BridgedDestructor {
public:
/**
* Calls a wrapped C++ destructor from Java code
*
* @tparam Executor the executor type
*
* @param env the JNI environment
* @param jthis the "this" Java object calling the wrapped destructor
* @param executor the code generated executor used to dispatch the destructor to
* the C++ object
*/
template<typename Executor>
static inline void call(JNIEnv* env, jobject jthis, Executor&& executor) {
#if defined(ALLOGEN_JNI_USE_COFFEECATCH)
CoffeeCatchCleaner cleaner;
if (coffeecatch_inside() ||
(coffeecatch_setup() == 0
&& sigsetjmp(*coffeecatch_get_ctx(), 1) == 0)) {
#endif
jclass view = env->GetObjectClass(jthis);
jfieldID field = env->GetFieldID(view, "pointer", "J");
jlong longPtr = env->GetLongField(jthis, field);
auto ptr = reinterpret_cast<std::shared_ptr<Class>*>(longPtr);
executor(ptr);
#if defined(ALLOGEN_JNI_USE_COFFEECATCH)
} else {
CoffeeCatch::_throw(env);
}
#endif
}
};
}
}
| [
"rogiel@rogiel.com"
] | rogiel@rogiel.com |
3711521b7f803e8d59a234981ef8e144931271d1 | 27a70bd4b6abba8b21231b425e7f98ae47d582b9 | /class-olympiad/1394/BWC/6/a.cpp | 34912d82ec566f32f7f90875b577a960121f73ca | [] | no_license | nimacgit/CPP | bc6011176b6a1c840c857fcdaed89df4347bfee9 | da35095c8f3def539f641f959f96d2f3f4d55486 | refs/heads/master | 2020-04-08T00:21:44.668748 | 2018-11-23T15:43:31 | 2018-11-23T15:46:27 | 158,849,201 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 758 | cpp | #include <iostream>
#include <vector>
#include <stdlib.h>
#include <string>
#include <algorithm>
#include <stdio.h>
#include <bits/stdc++.h>
#define mp make_pair
using namespace std;
typedef pair<int, int> pie;
int delta = 648481;
long long pos = (long long)1e17 + 17;
long long fin = (long long)1e17 + (long long)1717171;
const int maxn = 1e7;
bool notp[maxn + 100];
void init()
{
for(long long i = 2; i * i <= fin; i++)
{
long long st = pos/i;
st *= i;
if(st < pos)
st+=i;
for(long long j = st; j <= fin; j+=i)
notp[j - pos] = true;
}
}
int main()
{
init();
long long sum = 1, co = 0;
for(int i = 0; i <= fin-pos; i++)
{
if(!notp[i])
co++;
}
for(int i = 0; i < 17; i++)
sum = (sum * co) % delta;
cout << sum << endl;
}
| [
"michael12sco@yahoo.com"
] | michael12sco@yahoo.com |
80279df4a209305342c5de5c8976498c5665082e | f17905adf464e1c44bfd44ce284f91d833cff19f | /src/llvm/analysis/PointsTo/PointerSubgraphValidator.cpp | cdc4910415effcfad1b014f051771e99cf7a6378 | [
"MIT"
] | permissive | gussmith23/dg | c578fb50d46ed769ed4b3e96939fdd3ac64378dd | a7ab6449806f59a35b8ed08f1ebc1c2ab44004c1 | refs/heads/master | 2021-01-24T08:30:28.231079 | 2018-03-27T13:38:43 | 2018-03-27T13:39:31 | 122,982,059 | 0 | 0 | null | 2018-02-26T14:34:54 | 2018-02-26T14:34:54 | null | UTF-8 | C++ | false | false | 407 | cpp | #include <llvm/IR/Value.h>
#include "PointerSubgraphValidator.h"
namespace dg {
namespace analysis {
namespace pta {
namespace debug {
static const llvm::Value *getValue(PSNode *nd) {
return nd->getUserData<llvm::Value>();
}
/*
*void LLVMPointerSubgraphValidator::reportInvalNumberOfOperands(PSNode *nd) {
*}
*/
} // namespace debug
} // namespace pta
} // namespace analysis
} // namespace dg
| [
"xchalup4@fi.muni.cz"
] | xchalup4@fi.muni.cz |
e971241cfb66add16df2a7449b8c8d7c56f45e6f | 27c872d5c3532d972b4e3eb20e70e82ccda660fc | /content/browser/background_fetch/background_fetch_context.cc | bf049b8e10022b99a05caec3ded8eec188a584b0 | [
"BSD-3-Clause"
] | permissive | adityavs/chromium-1 | 1b084f8ba68803bc6ae88ea7bebec3d2e6cbe210 | 27ae617ee377e19cc5a48c9e80a1863ea03043e3 | refs/heads/master | 2023-03-05T22:13:58.379272 | 2018-07-28T22:10:46 | 2018-07-28T22:10:46 | 139,341,362 | 1 | 0 | null | 2018-07-28T22:10:47 | 2018-07-01T15:42:25 | null | UTF-8 | C++ | false | false | 21,468 | cc | // Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/browser/background_fetch/background_fetch_context.h"
#include <utility>
#include "base/bind_helpers.h"
#include "content/browser/background_fetch/background_fetch_data_manager.h"
#include "content/browser/background_fetch/background_fetch_job_controller.h"
#include "content/browser/background_fetch/background_fetch_metrics.h"
#include "content/browser/background_fetch/background_fetch_registration_id.h"
#include "content/browser/background_fetch/background_fetch_registration_notifier.h"
#include "content/browser/background_fetch/background_fetch_request_match_params.h"
#include "content/browser/background_fetch/background_fetch_scheduler.h"
#include "content/browser/service_worker/service_worker_context_wrapper.h"
#include "content/public/browser/background_fetch_delegate.h"
#include "content/public/browser/browser_context.h"
#include "net/url_request/url_request_context_getter.h"
#include "storage/browser/blob/blob_data_handle.h"
namespace content {
BackgroundFetchContext::BackgroundFetchContext(
BrowserContext* browser_context,
const scoped_refptr<ServiceWorkerContextWrapper>& service_worker_context,
const scoped_refptr<content::CacheStorageContextImpl>&
cache_storage_context)
: browser_context_(browser_context),
service_worker_context_(service_worker_context),
event_dispatcher_(service_worker_context),
registration_notifier_(
std::make_unique<BackgroundFetchRegistrationNotifier>()),
delegate_proxy_(browser_context_->GetBackgroundFetchDelegate()),
weak_factory_(this) {
// Although this lives only on the IO thread, it is constructed on UI thread.
DCHECK_CURRENTLY_ON(BrowserThread::UI);
DCHECK(service_worker_context_);
data_manager_ = std::make_unique<BackgroundFetchDataManager>(
browser_context_, service_worker_context, cache_storage_context);
scheduler_ = std::make_unique<BackgroundFetchScheduler>(data_manager_.get());
delegate_proxy_.SetClickEventDispatcher(base::BindRepeating(
&BackgroundFetchContext::DispatchClickEvent, weak_factory_.GetWeakPtr()));
}
BackgroundFetchContext::~BackgroundFetchContext() {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
service_worker_context_->RemoveObserver(this);
data_manager_->RemoveObserver(this);
}
void BackgroundFetchContext::InitializeOnIOThread() {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
service_worker_context_->AddObserver(this);
data_manager_->AddObserver(this);
data_manager_->InitializeOnIOThread();
data_manager_->GetInitializationData(
base::BindOnce(&BackgroundFetchContext::DidGetInitializationData,
weak_factory_.GetWeakPtr()));
}
void BackgroundFetchContext::DidGetInitializationData(
blink::mojom::BackgroundFetchError error,
std::vector<background_fetch::BackgroundFetchInitializationData>
initialization_data) {
if (error != blink::mojom::BackgroundFetchError::NONE) {
// TODO(crbug.com/780025): Log failures to UMA.
return;
}
for (auto& data : initialization_data) {
CreateController(data.registration_id, data.registration, data.options,
data.icon, data.ui_title, data.num_completed_requests,
data.num_requests, data.active_fetch_guids);
}
}
void BackgroundFetchContext::GetRegistration(
int64_t service_worker_registration_id,
const url::Origin& origin,
const std::string& developer_id,
blink::mojom::BackgroundFetchService::GetRegistrationCallback callback) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
data_manager_->GetRegistration(
service_worker_registration_id, origin, developer_id,
base::BindOnce(&BackgroundFetchContext::DidGetRegistration,
weak_factory_.GetWeakPtr(), std::move(callback)));
}
void BackgroundFetchContext::GetDeveloperIdsForServiceWorker(
int64_t service_worker_registration_id,
const url::Origin& origin,
blink::mojom::BackgroundFetchService::GetDeveloperIdsCallback callback) {
data_manager_->GetDeveloperIdsForServiceWorker(service_worker_registration_id,
origin, std::move(callback));
}
void BackgroundFetchContext::DidGetRegistration(
blink::mojom::BackgroundFetchService::GetRegistrationCallback callback,
blink::mojom::BackgroundFetchError error,
const BackgroundFetchRegistration& registration) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
if (error != blink::mojom::BackgroundFetchError::NONE) {
std::move(callback).Run(error,
base::nullopt /* BackgroundFetchRegistration */);
return;
}
BackgroundFetchRegistration updated_registration(registration);
// The data manager only has the number of bytes from completed downloads, so
// augment this with the number of downloaded bytes from in-progress jobs.
DCHECK(job_controllers_.count(registration.unique_id));
updated_registration.downloaded +=
job_controllers_[registration.unique_id]->GetInProgressDownloadedBytes();
std::move(callback).Run(error, updated_registration);
}
void BackgroundFetchContext::StartFetch(
const BackgroundFetchRegistrationId& registration_id,
const std::vector<ServiceWorkerFetchRequest>& requests,
const BackgroundFetchOptions& options,
const SkBitmap& icon,
blink::mojom::BackgroundFetchService::FetchCallback callback) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
// |registration_id| should be unique even if developer id has been
// duplicated, because the caller of this function generates a new unique_id
// every time, which is what BackgroundFetchRegistrationId's comparison
// operator uses.
DCHECK_EQ(0u, fetch_callbacks_.count(registration_id));
fetch_callbacks_[registration_id] = std::move(callback);
data_manager_->CreateRegistration(
registration_id, requests, options, icon,
base::BindOnce(&BackgroundFetchContext::DidCreateRegistration,
weak_factory_.GetWeakPtr(), registration_id));
}
void BackgroundFetchContext::GetIconDisplaySize(
blink::mojom::BackgroundFetchService::GetIconDisplaySizeCallback callback) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
delegate_proxy_.GetIconDisplaySize(std::move(callback));
}
void BackgroundFetchContext::DidCreateRegistration(
const BackgroundFetchRegistrationId& registration_id,
blink::mojom::BackgroundFetchError error,
const BackgroundFetchRegistration& registration) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
background_fetch::RecordRegistrationCreatedError(error);
auto iter = fetch_callbacks_.find(registration_id);
// The fetch might have been abandoned already if the Service Worker was
// unregistered or corrupted while registration was in progress.
if (iter == fetch_callbacks_.end())
return;
if (error == blink::mojom::BackgroundFetchError::NONE)
std::move(iter->second).Run(error, registration);
else
std::move(iter->second).Run(error, base::nullopt /* registration */);
fetch_callbacks_.erase(registration_id);
}
void BackgroundFetchContext::AddRegistrationObserver(
const std::string& unique_id,
blink::mojom::BackgroundFetchRegistrationObserverPtr observer) {
registration_notifier_->AddObserver(unique_id, std::move(observer));
}
void BackgroundFetchContext::UpdateUI(
const BackgroundFetchRegistrationId& registration_id,
const base::Optional<std::string>& title,
const base::Optional<SkBitmap>& icon,
blink::mojom::BackgroundFetchService::UpdateUICallback callback) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
// The registration must a) still be active, or b) have completed/failed (not
// aborted) with the waitUntil promise from that event not yet resolved.
if (!job_controllers_.count(registration_id.unique_id())) {
std::move(callback).Run(blink::mojom::BackgroundFetchError::INVALID_ID);
return;
}
data_manager_->UpdateRegistrationUI(registration_id, title, icon,
std::move(callback));
}
void BackgroundFetchContext::OnServiceWorkerDatabaseCorrupted(
int64_t service_worker_registration_id) {
AbandonFetches(service_worker_registration_id);
}
void BackgroundFetchContext::AbandonFetches(
int64_t service_worker_registration_id) {
// Abandon all active fetches associated with this service worker.
// BackgroundFetchJobController::Abort() will eventually lead to deletion of
// the controller from job_controllers, hence we can't use a range based
// for-loop here.
for (auto iter = job_controllers_.begin(); iter != job_controllers_.end();
/* no_increment */) {
auto saved_iter = iter;
iter++;
if (service_worker_registration_id ==
blink::mojom::kInvalidServiceWorkerRegistrationId ||
saved_iter->second->registration_id()
.service_worker_registration_id() ==
service_worker_registration_id) {
DCHECK(saved_iter->second);
saved_iter->second->Abort(
BackgroundFetchReasonToAbort::SERVICE_WORKER_UNAVAILABLE);
}
}
for (auto iter = fetch_callbacks_.begin(); iter != fetch_callbacks_.end();
/* no increment */) {
if (service_worker_registration_id ==
blink::mojom::kInvalidServiceWorkerRegistrationId ||
iter->first.service_worker_registration_id() ==
service_worker_registration_id) {
DCHECK(iter->second);
std::move(iter->second)
.Run(blink::mojom::BackgroundFetchError::SERVICE_WORKER_UNAVAILABLE,
base::nullopt /* BackgroundFetchRegistration */);
iter = fetch_callbacks_.erase(iter);
} else
iter++;
}
}
void BackgroundFetchContext::OnRegistrationCreated(
const BackgroundFetchRegistrationId& registration_id,
const BackgroundFetchRegistration& registration,
const BackgroundFetchOptions& options,
const SkBitmap& icon,
int num_requests) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
if (hang_registration_creation_for_testing_) {
// Hang here, to allow time for testing races. For instance, this helps us
// test the behavior when a service worker gets unregistered before the
// controller can be created.
return;
}
// TODO(peter): When this moves to the BackgroundFetchScheduler, only create
// a controller when the background fetch can actually be started.
CreateController(registration_id, registration, options, icon, options.title,
0u /* num_completed_requests */, num_requests,
{} /* outstanding_guids */);
}
void BackgroundFetchContext::OnUpdatedUI(
const BackgroundFetchRegistrationId& registration_id,
const base::Optional<std::string>& title,
const base::Optional<SkBitmap>& icon) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
auto iter = job_controllers_.find(registration_id.unique_id());
if (iter != job_controllers_.end())
iter->second->UpdateUI(title, icon);
}
void BackgroundFetchContext::OnRegistrationDeleted(
int64_t service_worker_registration_id,
const GURL& pattern) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
AbandonFetches(service_worker_registration_id);
}
void BackgroundFetchContext::OnStorageWiped() {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
AbandonFetches(blink::mojom::kInvalidServiceWorkerRegistrationId);
}
void BackgroundFetchContext::CreateController(
const BackgroundFetchRegistrationId& registration_id,
const BackgroundFetchRegistration& registration,
const BackgroundFetchOptions& options,
const SkBitmap& icon,
const std::string& ui_title,
size_t num_completed_requests,
size_t num_requests,
const std::vector<std::string>& outstanding_guids) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
auto controller = std::make_unique<BackgroundFetchJobController>(
&delegate_proxy_, registration_id, options, icon, registration.downloaded,
scheduler_.get(),
// Safe because JobControllers are destroyed before RegistrationNotifier.
base::BindRepeating(&BackgroundFetchRegistrationNotifier::Notify,
base::Unretained(registration_notifier_.get())),
base::BindOnce(
&BackgroundFetchContext::DidFinishJob, weak_factory_.GetWeakPtr(),
base::Bind(&background_fetch::RecordSchedulerFinishedError)));
controller->InitializeRequestStatus(num_completed_requests, num_requests,
outstanding_guids, ui_title);
scheduler_->AddJobController(controller.get());
job_controllers_.emplace(registration_id.unique_id(), std::move(controller));
}
void BackgroundFetchContext::Abort(
const BackgroundFetchRegistrationId& registration_id,
blink::mojom::BackgroundFetchService::AbortCallback callback) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
DidFinishJob(std::move(callback), registration_id,
BackgroundFetchReasonToAbort::ABORTED_BY_DEVELOPER);
}
void BackgroundFetchContext::DidFinishJob(
base::OnceCallback<void(blink::mojom::BackgroundFetchError)> callback,
const BackgroundFetchRegistrationId& registration_id,
BackgroundFetchReasonToAbort reason_to_abort) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
// If |aborted| is true, this will also propagate the event to any active
// JobController for the registration, to terminate in-progress requests.
data_manager_->MarkRegistrationForDeletion(
registration_id,
base::BindOnce(&BackgroundFetchContext::DidMarkForDeletion,
weak_factory_.GetWeakPtr(), registration_id,
reason_to_abort, std::move(callback)));
}
void BackgroundFetchContext::DidMarkForDeletion(
const BackgroundFetchRegistrationId& registration_id,
BackgroundFetchReasonToAbort reason_to_abort,
base::OnceCallback<void(blink::mojom::BackgroundFetchError)> callback,
blink::mojom::BackgroundFetchError error) {
DCHECK(callback);
std::move(callback).Run(error);
// It's normal to get INVALID_ID errors here - it means the registration was
// already inactive (marked for deletion). This happens when an abort (from
// developer or from user) races with the download completing/failing, or even
// when two aborts race. TODO(johnme): Log STORAGE_ERRORs to UMA though.
if (error != blink::mojom::BackgroundFetchError::NONE)
return;
if (reason_to_abort == BackgroundFetchReasonToAbort::ABORTED_BY_DEVELOPER) {
DCHECK(job_controllers_.count(registration_id.unique_id()));
job_controllers_[registration_id.unique_id()]->Abort(reason_to_abort);
}
switch (reason_to_abort) {
case BackgroundFetchReasonToAbort::ABORTED_BY_DEVELOPER:
case BackgroundFetchReasonToAbort::CANCELLED_FROM_UI:
CleanupRegistration(registration_id, {},
mojom::BackgroundFetchState::FAILED);
// TODO(rayankans): Send fetches to the event dispatcher.
event_dispatcher_.DispatchBackgroundFetchAbortEvent(
registration_id, {} /* settled_fetches */, base::DoNothing());
return;
case BackgroundFetchReasonToAbort::TOTAL_DOWNLOAD_SIZE_EXCEEDED:
case BackgroundFetchReasonToAbort::SERVICE_WORKER_UNAVAILABLE:
case BackgroundFetchReasonToAbort::NONE:
// This will send a BackgroundFetchFetched or BackgroundFetchFail event.
data_manager_->GetSettledFetchesForRegistration(
registration_id,
std::make_unique<BackgroundFetchRequestMatchParams>(),
base::BindOnce(&BackgroundFetchContext::DidGetSettledFetches,
weak_factory_.GetWeakPtr(), registration_id));
return;
}
}
void BackgroundFetchContext::DidGetSettledFetches(
const BackgroundFetchRegistrationId& registration_id,
blink::mojom::BackgroundFetchError error,
bool background_fetch_succeeded,
std::vector<BackgroundFetchSettledFetch> settled_fetches,
std::vector<std::unique_ptr<storage::BlobDataHandle>> blob_data_handles) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
if (error != blink::mojom::BackgroundFetchError::NONE) {
CleanupRegistration(registration_id, {} /* fetches */,
mojom::BackgroundFetchState::FAILED,
true /* preserve_info_to_dispatch_click_event */);
return;
}
// The `backgroundfetched` event will be invoked when all requests in the
// registration have completed successfully. In all other cases, the
// `backgroundfetchfail` event will be invoked instead.
if (background_fetch_succeeded) {
event_dispatcher_.DispatchBackgroundFetchedEvent(
registration_id, std::move(settled_fetches),
base::BindOnce(
&BackgroundFetchContext::CleanupRegistration,
weak_factory_.GetWeakPtr(), registration_id,
// The blob uuid is sent as part of |settled_fetches|. Bind
// |blob_data_handles| to the callback to keep them alive
// until the waitUntil event is resolved.
std::move(blob_data_handles),
mojom::BackgroundFetchState::SUCCEEDED,
true /* preserve_info_to_dispatch_click_event */));
} else {
event_dispatcher_.DispatchBackgroundFetchFailEvent(
registration_id, std::move(settled_fetches),
base::BindOnce(
&BackgroundFetchContext::CleanupRegistration,
weak_factory_.GetWeakPtr(), registration_id,
// The blob uuid is sent as part of |settled_fetches|. Bind
// |blob_data_handles| to the callback to keep them alive
// until the waitUntil event is resolved.
std::move(blob_data_handles), mojom::BackgroundFetchState::FAILED,
true /* preserve_info_to_dispatch_click_event */));
}
}
void BackgroundFetchContext::CleanupRegistration(
const BackgroundFetchRegistrationId& registration_id,
const std::vector<std::unique_ptr<storage::BlobDataHandle>>& blob_handles,
mojom::BackgroundFetchState background_fetch_state,
bool preserve_info_to_dispatch_click_event) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
// If we had an active JobController, it is no longer necessary, as the
// notification's UI can no longer be updated after the fetch is aborted, or
// after the waitUntil promise of the backgroundfetched/backgroundfetchfail
// event has been resolved. Store the information we want to persist after
// the controller is gone, in completed_fetches_.
scheduler_->RemoveJobController(registration_id);
if (preserve_info_to_dispatch_click_event) {
completed_fetches_[registration_id.unique_id()] = {registration_id,
background_fetch_state};
}
job_controllers_.erase(registration_id.unique_id());
// At this point, JavaScript can no longer obtain BackgroundFetchRegistration
// objects for this registration, and those objects are the only thing that
// requires us to keep the registration's data around. So once the
// RegistrationNotifier informs us that all existing observers (and hence
// BackgroundFetchRegistration objects) have been garbage collected, it'll be
// safe to delete the registration. This callback doesn't run if the browser
// is shutdown before that happens - BackgroundFetchDataManager::Cleanup acts
// as a fallback in that case, and deletes the registration on next startup.
registration_notifier_->AddGarbageCollectionCallback(
registration_id.unique_id(),
base::BindOnce(&BackgroundFetchContext::LastObserverGarbageCollected,
weak_factory_.GetWeakPtr(), registration_id));
}
void BackgroundFetchContext::DispatchClickEvent(const std::string& unique_id) {
auto iter = completed_fetches_.find(unique_id);
if (iter != completed_fetches_.end()) {
// The fetch has succeeded or failed. (not aborted/cancelled).
event_dispatcher_.DispatchBackgroundFetchClickEvent(
iter->second.first /* registration_id */,
iter->second.second /* background_fetch_state */, base::DoNothing());
completed_fetches_.erase(iter);
return;
}
// The fetch is active, or has been aborted/cancelled.
auto controllers_iter = job_controllers_.find(unique_id);
if (controllers_iter == job_controllers_.end())
return;
event_dispatcher_.DispatchBackgroundFetchClickEvent(
controllers_iter->second->registration_id(),
mojom::BackgroundFetchState::PENDING, base::DoNothing());
}
void BackgroundFetchContext::LastObserverGarbageCollected(
const BackgroundFetchRegistrationId& registration_id) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
data_manager_->DeleteRegistration(
registration_id,
base::BindOnce(&background_fetch::RecordRegistrationDeletedError));
}
void BackgroundFetchContext::Shutdown() {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
BrowserThread::PostTask(
BrowserThread::IO, FROM_HERE,
base::BindOnce(&BackgroundFetchContext::ShutdownOnIO, this));
}
void BackgroundFetchContext::ShutdownOnIO() {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
data_manager_->ShutdownOnIO();
}
void BackgroundFetchContext::SetDataManagerForTesting(
std::unique_ptr<BackgroundFetchDataManager> data_manager) {
DCHECK(data_manager);
data_manager_ = std::move(data_manager);
scheduler_ = std::make_unique<BackgroundFetchScheduler>(data_manager_.get());
}
} // namespace content
| [
"commit-bot@chromium.org"
] | commit-bot@chromium.org |
8f4fbce4c69a364e964ee8da76260d91c4b02426 | a6fbd31d83a34c84b95f9f33521aa49e4377b96d | /Semestre 1/Programacion y algoritmos/prog2017_12_Alvarez_ES/point.hpp | 655a396ef80a10518ed4180b19ab00c94792db80 | [] | no_license | ericksav21/Maestria | d8732dd1670ce552bd881827c27ce0986a5b80eb | 637ef704029677f78ca614c413119ec93fedb813 | refs/heads/master | 2021-01-19T20:08:06.415345 | 2019-01-25T17:17:24 | 2019-01-25T17:17:24 | 101,221,897 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 465 | hpp | #ifndef POINT_H
#define POINT_H
#include <iostream>
#include <string>
#include <algorithm>
#include <cmath>
#include <ctime>
#include <cstdlib>
#include <vector>
#define INF 1000000
class Point {
private:
double x, y;
//Cluster ID
int id;
public:
Point();
Point(double x, double y);
Point(double x, double y, int id);
~Point();
double get_x();
double get_y();
int get_id();
void set_x(double x);
void set_y(double y);
void set_id(int id);
};
#endif | [
"erickalv21@gmail.com"
] | erickalv21@gmail.com |
6d212cf93a4451fadd1cc2c13759ad8531d25647 | 3d99f2ed3b2f0ce30e5ef81c45e721036eae38a8 | /src/RcppExports.cpp | e11664ebaf2cc8c79c96971e7adf50e8f5960f99 | [] | no_license | IMB-Computational-Genomics-Lab/scGPS | 296244465064fd9dc2f9fcfb80af6b43fa9ae797 | 0c3746eaad27b804b61d310f57c24a71935cfcfa | refs/heads/master | 2021-06-01T13:48:53.819039 | 2020-12-03T00:43:35 | 2020-12-03T00:43:35 | 111,049,242 | 4 | 5 | null | 2018-10-26T05:59:04 | 2017-11-17T02:47:39 | R | UTF-8 | C++ | false | false | 5,036 | cpp | // Generated by using Rcpp::compileAttributes() -> do not edit by hand
// Generator token: 10BE3573-1514-4C36-9D1C-5A225CD40393
#include <RcppArmadillo.h>
#include <Rcpp.h>
using namespace Rcpp;
// distvec
double distvec(NumericVector x, NumericVector y);
RcppExport SEXP _scGPS_distvec(SEXP xSEXP, SEXP ySEXP) {
BEGIN_RCPP
Rcpp::RObject rcpp_result_gen;
Rcpp::RNGScope rcpp_rngScope_gen;
Rcpp::traits::input_parameter< NumericVector >::type x(xSEXP);
Rcpp::traits::input_parameter< NumericVector >::type y(ySEXP);
rcpp_result_gen = Rcpp::wrap(distvec(x, y));
return rcpp_result_gen;
END_RCPP
}
// calcDist
NumericMatrix calcDist(NumericMatrix x);
RcppExport SEXP _scGPS_calcDist(SEXP xSEXP) {
BEGIN_RCPP
Rcpp::RObject rcpp_result_gen;
Rcpp::RNGScope rcpp_rngScope_gen;
Rcpp::traits::input_parameter< NumericMatrix >::type x(xSEXP);
rcpp_result_gen = Rcpp::wrap(calcDist(x));
return rcpp_result_gen;
END_RCPP
}
// calcDistArma
arma::mat calcDistArma(const arma::mat& x);
RcppExport SEXP _scGPS_calcDistArma(SEXP xSEXP) {
BEGIN_RCPP
Rcpp::RObject rcpp_result_gen;
Rcpp::RNGScope rcpp_rngScope_gen;
Rcpp::traits::input_parameter< const arma::mat& >::type x(xSEXP);
rcpp_result_gen = Rcpp::wrap(calcDistArma(x));
return rcpp_result_gen;
END_RCPP
}
// rcpp_parallel_distance
NumericMatrix rcpp_parallel_distance(NumericMatrix mat);
RcppExport SEXP _scGPS_rcpp_parallel_distance(SEXP matSEXP) {
BEGIN_RCPP
Rcpp::RObject rcpp_result_gen;
Rcpp::RNGScope rcpp_rngScope_gen;
Rcpp::traits::input_parameter< NumericMatrix >::type mat(matSEXP);
rcpp_result_gen = Rcpp::wrap(rcpp_parallel_distance(mat));
return rcpp_result_gen;
END_RCPP
}
// rcpp_Eucl_distance_NotPar
NumericMatrix rcpp_Eucl_distance_NotPar(NumericMatrix mat);
RcppExport SEXP _scGPS_rcpp_Eucl_distance_NotPar(SEXP matSEXP) {
BEGIN_RCPP
Rcpp::RObject rcpp_result_gen;
Rcpp::RNGScope rcpp_rngScope_gen;
Rcpp::traits::input_parameter< NumericMatrix >::type mat(matSEXP);
rcpp_result_gen = Rcpp::wrap(rcpp_Eucl_distance_NotPar(mat));
return rcpp_result_gen;
END_RCPP
}
// mean_cpp
double mean_cpp(NumericVector x);
RcppExport SEXP _scGPS_mean_cpp(SEXP xSEXP) {
BEGIN_RCPP
Rcpp::RObject rcpp_result_gen;
Rcpp::RNGScope rcpp_rngScope_gen;
Rcpp::traits::input_parameter< NumericVector >::type x(xSEXP);
rcpp_result_gen = Rcpp::wrap(mean_cpp(x));
return rcpp_result_gen;
END_RCPP
}
// var_cpp
double var_cpp(NumericVector x, bool bias);
RcppExport SEXP _scGPS_var_cpp(SEXP xSEXP, SEXP biasSEXP) {
BEGIN_RCPP
Rcpp::RObject rcpp_result_gen;
Rcpp::RNGScope rcpp_rngScope_gen;
Rcpp::traits::input_parameter< NumericVector >::type x(xSEXP);
Rcpp::traits::input_parameter< bool >::type bias(biasSEXP);
rcpp_result_gen = Rcpp::wrap(var_cpp(x, bias));
return rcpp_result_gen;
END_RCPP
}
// tp_cpp
arma::mat tp_cpp(const arma::mat X);
RcppExport SEXP _scGPS_tp_cpp(SEXP XSEXP) {
BEGIN_RCPP
Rcpp::RObject rcpp_result_gen;
Rcpp::RNGScope rcpp_rngScope_gen;
Rcpp::traits::input_parameter< const arma::mat >::type X(XSEXP);
rcpp_result_gen = Rcpp::wrap(tp_cpp(X));
return rcpp_result_gen;
END_RCPP
}
// subset_cpp
arma::mat subset_cpp(NumericMatrix m1in, NumericVector rowidx_in, NumericVector colidx_in);
RcppExport SEXP _scGPS_subset_cpp(SEXP m1inSEXP, SEXP rowidx_inSEXP, SEXP colidx_inSEXP) {
BEGIN_RCPP
Rcpp::RObject rcpp_result_gen;
Rcpp::RNGScope rcpp_rngScope_gen;
Rcpp::traits::input_parameter< NumericMatrix >::type m1in(m1inSEXP);
Rcpp::traits::input_parameter< NumericVector >::type rowidx_in(rowidx_inSEXP);
Rcpp::traits::input_parameter< NumericVector >::type colidx_in(colidx_inSEXP);
rcpp_result_gen = Rcpp::wrap(subset_cpp(m1in, rowidx_in, colidx_in));
return rcpp_result_gen;
END_RCPP
}
// PrinComp_cpp
List PrinComp_cpp(const arma::mat X);
RcppExport SEXP _scGPS_PrinComp_cpp(SEXP XSEXP) {
BEGIN_RCPP
Rcpp::RObject rcpp_result_gen;
Rcpp::RNGScope rcpp_rngScope_gen;
Rcpp::traits::input_parameter< const arma::mat >::type X(XSEXP);
rcpp_result_gen = Rcpp::wrap(PrinComp_cpp(X));
return rcpp_result_gen;
END_RCPP
}
static const R_CallMethodDef CallEntries[] = {
{"_scGPS_distvec", (DL_FUNC) &_scGPS_distvec, 2},
{"_scGPS_calcDist", (DL_FUNC) &_scGPS_calcDist, 1},
{"_scGPS_calcDistArma", (DL_FUNC) &_scGPS_calcDistArma, 1},
{"_scGPS_rcpp_parallel_distance", (DL_FUNC) &_scGPS_rcpp_parallel_distance, 1},
{"_scGPS_rcpp_Eucl_distance_NotPar", (DL_FUNC) &_scGPS_rcpp_Eucl_distance_NotPar, 1},
{"_scGPS_mean_cpp", (DL_FUNC) &_scGPS_mean_cpp, 1},
{"_scGPS_var_cpp", (DL_FUNC) &_scGPS_var_cpp, 2},
{"_scGPS_tp_cpp", (DL_FUNC) &_scGPS_tp_cpp, 1},
{"_scGPS_subset_cpp", (DL_FUNC) &_scGPS_subset_cpp, 3},
{"_scGPS_PrinComp_cpp", (DL_FUNC) &_scGPS_PrinComp_cpp, 1},
{NULL, NULL, 0}
};
RcppExport void R_init_scGPS(DllInfo *dll) {
R_registerRoutines(dll, NULL, CallEntries, NULL, NULL);
R_useDynamicSymbols(dll, FALSE);
}
| [
"quanaibn@gmail.com"
] | quanaibn@gmail.com |
cb2249d070cfc63af8e7e72dff2e629220885ef9 | 3b2bcf4249d55417dcf377d9ff867f685afc32c9 | /include/Portfolio.h | ae1bc82372e576dabf797f1b3f96dac16563ca29 | [] | no_license | jifengthu/CryptoBacktest | 1f38cec81d86506cdbaea0fb7799a8af6fcc9967 | 0bf3f88d7399413499f36bccf817300785f008fd | refs/heads/master | 2023-05-15T06:38:51.222425 | 2021-06-04T21:05:40 | 2021-06-04T21:05:40 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,146 | h | #include "utils.h"
#ifndef Portfolio_H
#define Portfolio_H
using namespace std;
namespace BacktestEngine {
class PortfolioEngine {
public:
string symbol;
vector<MatchResult> match_result_record;
vector<double> portfolio_value_record;
vector<long> ts_record;
vector<double>market_price_record;
vector<double>position_record;
double portfolio_profit = 0;
double position = 0;
double current_market_price;
double prev_market_price;
double active_commission = 0.0003;
double passive_commission = -0.00015;
long current_ts;
Log portfolio_log = Log("portfolio.csv");
vector<Order> OrderList;
PortfolioEngine();
PortfolioEngine(BacktestingConfig config);
// virtual ~PortfolioEngine();
double getFilledVolume(Order order);
double getFinishedFilledVolume(Order order);
void updatePortfolio(double market_price,long ts,vector<MatchResult> match_result_list);
void resetMarketPrice();
void Clean();
};
}
#endif /* Portfolio_H */ | [
"942500342@qq.com"
] | 942500342@qq.com |
3e94e265ff87cee934491cfc06ed1a6adebad47a | 405fba797f6d33b76f8ce41dbed28817d81b36b7 | /source/witchaven/src/view.cpp | ce236784e8216a4eb088d8fa5cbf7bc9371c5841 | [] | no_license | coelckers/NBlood | bed0ed5576906b49fd7da6f8f72622d820f7aa4d | cc8d57ee5d6ac8a3c3f400501df25892cb9db6b1 | refs/heads/master | 2022-01-21T02:31:42.578207 | 2021-12-05T02:10:52 | 2021-12-05T02:10:52 | 240,122,629 | 5 | 0 | null | 2020-02-12T21:50:29 | 2020-02-12T21:50:28 | null | UTF-8 | C++ | false | false | 498 | cpp |
#include "view.h"
#include "menu.h"
#include "witchaven.h"
static int displaytime;
char displaybuf[50];
void StatusMessage(int nTime, const char* fmt, ...)
{
va_list args;
va_start(args, fmt);
vsprintf(displaybuf, fmt, args);
displaytime = nTime;
}
void DisplayStatusMessage()
{
if (displaytime > 0)
{
fancyfontscreen(18, 24, THEFONT, displaybuf);
displaytime -= synctics;
}
}
void StatusMessageDisplayTime(int nTime)
{
displaytime = nTime;
}
| [
"sirlemonhead@outlook.com"
] | sirlemonhead@outlook.com |
ca782ec34368ed536d021f2a9b23101998c74862 | 23627228892aa453d423dfb5789c5a5f1507ac84 | /StringObfuscator/stdafx.cpp | a70ea34101b8326b9510dc3cb10abba58a40ee9d | [] | no_license | cahitbeyaz/StringObfuscator | bc8d052b77901aecf194601c1cc557f7b8f87fcb | 0b7282b9d39e82b1c5af6c21a91d2834015f1eb2 | refs/heads/master | 2021-06-07T16:25:37.698724 | 2016-11-30T11:06:12 | 2016-11-30T11:06:12 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 295 | cpp | // stdafx.cpp : source file that includes just the standard includes
// StringObfuscator.pch will be the pre-compiled header
// stdafx.obj will contain the pre-compiled type information
#include "stdafx.h"
// TODO: reference any additional headers you need in STDAFX.H
// and not in this file
| [
"cahit.beyaz@cardtek.com"
] | cahit.beyaz@cardtek.com |
25abca4b93635c28f113ae9692b3ed1e0e5949a8 | 475580d7b05f7263159ecbf4919fd352103028e0 | /src/ast/visitor.h | b7960fdf53e5feb7aae2aad1e522e8da50cee1ed | [
"MIT"
] | permissive | yandroskaos/oolc | 6a6a89dfa63676fa27c5dcc71ad1355370f86fe0 | 8fa77c44ab090a78b7e3d184e3bfeb00786dbe0f | refs/heads/master | 2020-03-27T23:58:52.553102 | 2018-09-04T15:28:20 | 2018-09-04T15:28:20 | 147,365,345 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,862 | h | #ifndef __VISITOR_H__
#define __VISITOR_H__
#define WILL_VISIT(X) \
void Visit(X* _node) override
#define VISIT(X, Y) \
void X::Visit(Y* _node)
namespace AST
{
//
// AST Nodes
//
struct ProgramNode;
struct InterfaceNode;
struct PrototypeNode;
struct ClassNode;
struct AttributeNode;
struct MethodNode;
struct BlockStatementNode;
struct EmptyStatementNode;
struct WriteStatementNode;
struct ReadStatementNode;
struct IfElseStatementNode;
struct WhileStatementNode;
struct ForStatementNode;
struct ReturnStatementNode;
struct VariableNode;
struct VariableBlockNode;
struct ExpressionStatementNode;
struct NullExprNode;
struct BoolCteExprNode;
struct CharCteExprNode;
struct IntCteExprNode;
struct RealCteExprNode;
struct StringCteExprNode;
struct GreaterExprNode;
struct LesserExprNode;
struct EqualExprNode;
struct NotEqualExprNode;
struct AndExprNode;
struct OrExprNode;
struct PlusExprNode;
struct MinusExprNode;
struct MulExprNode;
struct DivExprNode;
struct AssignmentExprNode;
struct NotExprNode;
struct MinusUnaryExprNode;
struct CastExprNode;
struct NewExprNode;
struct NewArrayExprNode;
struct SlotNode;
struct ThisSlotNode;
struct IdentifierSlotNode;
class Visitor
{
public:
virtual ~Visitor() = default;
//
// Program Structure Nodes
//
virtual void Visit(ProgramNode* _node);
virtual void Visit(InterfaceNode* _node);
virtual void Visit(PrototypeNode* _node);
virtual void Visit(ClassNode* _node);
virtual void Visit(AttributeNode* _node);
virtual void Visit(MethodNode* _node);
//
// Statement Nodes
//
virtual void Visit(BlockStatementNode* _node);
virtual void Visit(EmptyStatementNode* _node);
virtual void Visit(WriteStatementNode* _node);
virtual void Visit(ReadStatementNode* _node);
virtual void Visit(IfElseStatementNode* _node);
virtual void Visit(WhileStatementNode* _node);
virtual void Visit(ForStatementNode* _node);
virtual void Visit(ReturnStatementNode* _node);
virtual void Visit(VariableNode* _node);
virtual void Visit(VariableBlockNode* _node);
virtual void Visit(ExpressionStatementNode* _node);
//
// Expresion Nodes
//
virtual void Visit(NullExprNode* _node);
virtual void Visit(BoolCteExprNode* _node);
virtual void Visit(CharCteExprNode* _node);
virtual void Visit(IntCteExprNode* _node);
virtual void Visit(RealCteExprNode* _node);
virtual void Visit(StringCteExprNode* _node);
virtual void Visit(GreaterExprNode* _node);
virtual void Visit(LesserExprNode* _node);
virtual void Visit(EqualExprNode* _node);
virtual void Visit(NotEqualExprNode* _node);
virtual void Visit(AndExprNode* _node);
virtual void Visit(OrExprNode* _node);
virtual void Visit(PlusExprNode* _node);
virtual void Visit(MinusExprNode* _node);
virtual void Visit(MulExprNode* _node);
virtual void Visit(DivExprNode* _node);
virtual void Visit(AssignmentExprNode* _node);
virtual void Visit(NotExprNode* _node);
virtual void Visit(MinusUnaryExprNode* _node);
virtual void Visit(CastExprNode* _node);
virtual void Visit(NewExprNode* _node);
virtual void Visit(NewArrayExprNode* _node);
virtual void Visit(SlotNode* _node);
virtual void Visit(ThisSlotNode* _node);
virtual void Visit(IdentifierSlotNode* _node);
};
};
#endif
| [
"yandroskaos@gmail.com"
] | yandroskaos@gmail.com |
178ff098bb46d6a8158189784e7326e3d24fedf7 | be9713d262de608a30fad8f64a3762a67c78772d | /VulkanEngineTut/main.cpp | 0d2c6c07e37b02009e95aa92e4773332138f04e1 | [] | no_license | Unique-Username-Yes/VulkanEng | dad0ba4ae67a8b354903c76626035a002fec5cb6 | c3a6485b336c5471b41797dbd93f43fcaa163fee | refs/heads/master | 2021-06-23T12:23:36.955156 | 2021-02-11T10:39:42 | 2021-02-11T10:39:42 | 191,644,359 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,901 | cpp | #define GLFW_INCLUDE_VULKAN
#include <GLFW/glfw3.h>
#include <iostream>
#include <stdexcept>
#include <functional>
#include <cstdlib>
#include <cstring>
#include <optional>
const int WIDTH = 800;
const int HEIGHT = 600;
const std::vector<const char*> validationLayers = {
"VK_LAYER_KHRONOS_validation"
};
#ifdef NDEBUG
const bool enableValidationLayers = false;
#else
const bool enableValidationLayers = true;
#endif
VkResult CreateDebugUtilsMessengerEXT(VkInstance instance, const VkDebugUtilsMessengerCreateInfoEXT *pCreateInfo, const VkAllocationCallbacks *pAllocator, VkDebugUtilsMessengerEXT *pDebugMessenger)
{
auto func = (PFN_vkCreateDebugUtilsMessengerEXT)vkGetInstanceProcAddr(instance, "vkCreateDebugUtilsMessengerEXT");
if (func != nullptr)
return func(instance, pCreateInfo, pAllocator, pDebugMessenger);
else
return VK_ERROR_EXTENSION_NOT_PRESENT;
}
void DestroyUtilsMessengerEXT(VkInstance instance, VkDebugUtilsMessengerEXT debugMessenger, const VkAllocationCallbacks *pAllocator)
{
auto func = (PFN_vkDestroyDebugUtilsMessengerEXT)vkGetInstanceProcAddr(instance, "vkDestroyDebugUtilsMessengerEXT");
if (func != nullptr)
func(instance, debugMessenger, pAllocator);
else
std::cerr << "Could not find proc in messenger destruction" << std::endl;
}
struct QueueFamilyIndices
{
std::optional<uint32_t> graphicsFamily;
bool IsComplete()
{
return graphicsFamily.has_value();
}
};
class TriangleApp
{
public:
void Run()
{
InitWindow();
InitVulkan();
MainLoop();
CleanUp();
}
private:
VkInstance instance;
GLFWwindow *window;
VkDebugUtilsMessengerEXT debugMessenger;
VkPhysicalDevice physicalDevice = VK_NULL_HANDLE;
bool CheckValidationLayerSupport()
{
uint32_t layerCount = 0;
vkEnumerateInstanceLayerProperties(&layerCount, nullptr);
std::vector<VkLayerProperties> availableLayers(layerCount);
vkEnumerateInstanceLayerProperties(&layerCount, availableLayers.data());
for (const char *layerName : validationLayers)
{
bool layerFound = false;
for (const auto &layerProperties : availableLayers)
{
if (strcmp(layerName, layerProperties.layerName) == 0)
{
layerFound = true;
break;
}
}
if (!layerFound)
return false;
}
return true;
}
void InitWindow()
{
glfwInit();
glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API);
glfwWindowHint(GLFW_RESIZABLE, GLFW_FALSE);
window = glfwCreateWindow(WIDTH, HEIGHT, "Vulkan", nullptr, nullptr);
std::cout << "Created Window successfuly" << std::endl;
}
void InitVulkan()
{
CreateInstance();
SetupDebugMessenger();
PickPhysicalDevice();
}
void MainLoop()
{
while (!glfwWindowShouldClose(window))
{
glfwPollEvents();
}
}
void CleanUp()
{
if (enableValidationLayers)
DestroyUtilsMessengerEXT(instance, debugMessenger, nullptr);
vkDestroyInstance(instance, nullptr);
glfwDestroyWindow(window);
glfwTerminate();
}
std::vector<const char*>GetRequiredExtensions()
{
uint32_t glfwExtensionCount = 0;
const char **glfwExtensions;
glfwExtensions = glfwGetRequiredInstanceExtensions(&glfwExtensionCount);
std::vector<const char*>extensions(glfwExtensions, glfwExtensions + glfwExtensionCount);
if (enableValidationLayers)
{
extensions.push_back(VK_EXT_DEBUG_UTILS_EXTENSION_NAME);
}
return extensions;
}
void CreateInstance()
{
if (enableValidationLayers && !CheckValidationLayerSupport())
{
throw std::runtime_error("Validation layer requested, but not available.");
}
VkApplicationInfo appInfo = {};
appInfo.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO;
appInfo.pApplicationName = "TriangleHi";
appInfo.applicationVersion = VK_MAKE_VERSION(1, 0, 0);
appInfo.pEngineName = "No Engine";
appInfo.engineVersion = VK_MAKE_VERSION(1, 0, 0);
appInfo.apiVersion = VK_API_VERSION_1_0;
VkInstanceCreateInfo createInfo = {};
createInfo.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
createInfo.pApplicationInfo = &appInfo;
auto extensions = GetRequiredExtensions();
createInfo.enabledExtensionCount = static_cast<uint32_t>(extensions.size());
createInfo.ppEnabledExtensionNames = extensions.data();
VkDebugUtilsMessengerCreateInfoEXT debugCreateInfo;
if (enableValidationLayers)
{
createInfo.enabledLayerCount = static_cast<uint32_t>(validationLayers.size());
createInfo.ppEnabledLayerNames = validationLayers.data();
PopulateDebugMessengerCreateInfo(debugCreateInfo);
createInfo.pNext = (VkDebugUtilsMessengerCreateInfoEXT *)&debugCreateInfo;
}
else
{
createInfo.enabledLayerCount = 0;
createInfo.pNext = nullptr;
}
if (auto err = vkCreateInstance(&createInfo, nullptr, &instance); err != VK_SUCCESS)
{
throw std::runtime_error("Failed to create instance. Error code: " + err);
}
std::cout << "Initialized vulkan instance successfuly" << std::endl;
}
void PickPhysicalDevice()
{
uint32_t deviceCount = 0;
vkEnumeratePhysicalDevices(instance, &deviceCount, nullptr);
if (deviceCount == 0)
throw std::runtime_error("Failed to find GPU with Vulkan support");
std::vector<VkPhysicalDevice> devices(deviceCount);
vkEnumeratePhysicalDevices(instance, &deviceCount, devices.data());
for (const auto &device : devices)
{
if (IsDeviceSuitable(device))
{
physicalDevice = device;
VkPhysicalDeviceProperties deviceProperties;
vkGetPhysicalDeviceProperties(device, &deviceProperties);
std::cout << "Picked device: " << deviceProperties.deviceName << std::endl;
break;
}
}
if (physicalDevice == VK_NULL_HANDLE)
throw std::runtime_error("Failed to find suitable GPU");
}
bool IsDeviceSuitable(VkPhysicalDevice device)
{
QueueFamilyIndices indices = FindQueueFamilies(device);
return indices.IsComplete();
}
QueueFamilyIndices FindQueueFamilies(VkPhysicalDevice device)
{
QueueFamilyIndices indices;
uint32_t queueFamilyCount = 0;
vkGetPhysicalDeviceQueueFamilyProperties(device, &queueFamilyCount, nullptr);
std::vector<VkQueueFamilyProperties>queueFamilies(queueFamilyCount);
vkGetPhysicalDeviceQueueFamilyProperties(device, &queueFamilyCount, queueFamilies.data());
int i = 0;
for (const auto &queueFamily : queueFamilies)
{
if (queueFamily.queueCount > 0 && queueFamily.queueFlags&VK_QUEUE_GRAPHICS_BIT)
{
indices.graphicsFamily = i;
}
if (indices.IsComplete())
break;
++i;
}
return indices;
}
void PopulateDebugMessengerCreateInfo(VkDebugUtilsMessengerCreateInfoEXT &createInfo)
{
createInfo = {};
createInfo.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_MESSENGER_CREATE_INFO_EXT;
createInfo.messageSeverity = VK_DEBUG_UTILS_MESSAGE_SEVERITY_VERBOSE_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT;
createInfo.messageType = VK_DEBUG_UTILS_MESSAGE_TYPE_GENERAL_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT;
createInfo.pfnUserCallback = DebugCallback;
createInfo.flags = 0;
}
void SetupDebugMessenger()
{
if (!enableValidationLayers)return;
VkDebugUtilsMessengerCreateInfoEXT createInfo;
PopulateDebugMessengerCreateInfo(createInfo);
if (auto err = CreateDebugUtilsMessengerEXT(instance, &createInfo, nullptr, &debugMessenger); err != VK_SUCCESS)
{
throw std::runtime_error("Failed to setup debug message");
}
}
static VKAPI_ATTR VkBool32 VKAPI_CALL DebugCallback(
VkDebugUtilsMessageSeverityFlagBitsEXT messageSeverity,
VkDebugUtilsMessageTypeFlagsEXT messageType,
const VkDebugUtilsMessengerCallbackDataEXT *pCallbackData,
void *pUserData)
{
std::cerr << "Validation layer: " << pCallbackData->pMessage << std::endl;
return VK_FALSE;
}
};
int main()
{
TriangleApp app;
try
{
app.Run();
}
catch (const std::exception &e)
{
std::cerr << e.what() << std::endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
| [
"karmonasedvinas@gmail.com"
] | karmonasedvinas@gmail.com |
99a2bb0ac6e6dc4446afb344605094550460ac4f | 33aa7896d2781ddc2793aef29fe58cb50f14a620 | /otxserver2/path_85x/sources/items.h | c45aeab6798dfb749633944365bede2a12df5f05 | [] | no_license | Drakos1/otxserver | c27114c9fe2b337ce03dba659f3f516d6495d55e | ba73c9e8b706d80f4b5f557a69a319208c4d90ca | refs/heads/master | 2021-01-24T20:13:32.289657 | 2014-10-31T21:21:34 | 2014-10-31T21:21:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,023 | h | ////////////////////////////////////////////////////////////////////////
// OpenTibia - an opensource roleplaying game
////////////////////////////////////////////////////////////////////////
// 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, see <http://www.gnu.org/licenses/>.
////////////////////////////////////////////////////////////////////////
#ifndef __ITEMS__
#define __ITEMS__
#include "otsystem.h"
#include "itemloader.h"
#include "const.h"
#include "enums.h"
#include "position.h"
#include <libxml/parser.h>
#define ITEMS_SIZE 11395
#define ITEMS_INCREMENT 500
#define ITEMS_RANDOMIZATION 50
#define SLOTP_WHEREEVER 0xFFFFFFFF
#define SLOTP_HEAD (1 << 0)
#define SLOTP_NECKLACE (1 << 1)
#define SLOTP_BACKPACK (1 << 2)
#define SLOTP_ARMOR (1 << 3)
#define SLOTP_RIGHT (1 << 4)
#define SLOTP_LEFT (1 << 5)
#define SLOTP_LEGS (1 << 6)
#define SLOTP_FEET (1 << 7)
#define SLOTP_RING (1 << 8)
#define SLOTP_AMMO (1 << 9)
#define SLOTP_DEPOT (1 << 10)
#define SLOTP_TWO_HAND (1 << 11)
#define SLOTP_HAND (SLOTP_LEFT | SLOTP_RIGHT)
enum ItemTypes_t
{
ITEM_TYPE_NONE = 0,
ITEM_TYPE_DEPOT,
ITEM_TYPE_MAILBOX,
ITEM_TYPE_TRASHHOLDER,
ITEM_TYPE_CONTAINER,
ITEM_TYPE_DOOR,
ITEM_TYPE_MAGICFIELD,
ITEM_TYPE_TELEPORT,
ITEM_TYPE_BED,
ITEM_TYPE_KEY,
ITEM_TYPE_RUNE,
ITEM_TYPE_LAST
};
enum FloorChange_t
{
CHANGE_PRE_FIRST = 0,
CHANGE_DOWN = CHANGE_PRE_FIRST,
CHANGE_FIRST = 1,
CHANGE_NORTH = CHANGE_FIRST,
CHANGE_EAST = 2,
CHANGE_SOUTH = 3,
CHANGE_WEST = 4,
CHANGE_FIRST_EX = 5,
CHANGE_NORTH_EX = CHANGE_FIRST_EX,
CHANGE_EAST_EX = 6,
CHANGE_SOUTH_EX = 7,
CHANGE_WEST_EX = 8,
CHANGE_NONE = 9,
CHANGE_PRE_LAST = 8,
CHANGE_LAST = CHANGE_NONE
};
struct Abilities
{
Abilities()
{
memset(skills, 0, sizeof(skills));
memset(skillsPercent, 0, sizeof(skillsPercent));
memset(stats, 0, sizeof(stats));
memset(statsPercent, 0, sizeof(statsPercent));
memset(absorb, 0, sizeof(absorb));
memset(fieldAbsorb, 0, sizeof(fieldAbsorb));
memset(increment, 0, sizeof(increment));
memset(reflect[REFLECT_PERCENT], 0, sizeof(reflect[REFLECT_PERCENT]));
memset(reflect[REFLECT_CHANCE], 0, sizeof(reflect[REFLECT_CHANCE]));
elementType = COMBAT_NONE;
manaShield = invisible = regeneration = preventLoss = preventDrop = false;
speed = healthGain = healthTicks = manaGain = manaTicks = elementDamage = conditionSuppressions = 0;
};
bool manaShield, invisible, regeneration, preventLoss, preventDrop;
CombatType_t elementType;
int16_t elementDamage, absorb[COMBAT_LAST + 1], increment[INCREMENT_LAST + 1],
reflect[REFLECT_LAST + 1][COMBAT_LAST + 1], fieldAbsorb[COMBAT_LAST + 1];
int32_t skills[SKILL_LAST + 1], skillsPercent[SKILL_LAST + 1], stats[STAT_LAST + 1], statsPercent[STAT_LAST + 1],
speed, healthGain, healthTicks, manaGain, manaTicks, conditionSuppressions;
};
class Condition;
class ItemType
{
private:
ItemType(const ItemType&) {} //TODO!
public:
ItemType();
virtual ~ItemType();
Abilities* getAbilities() {if(!abilities) abilities = new Abilities; return abilities;}
bool isGroundTile() const {return (group == ITEM_GROUP_GROUND);}
bool isContainer() const {return (group == ITEM_GROUP_CONTAINER);}
bool isSplash() const {return (group == ITEM_GROUP_SPLASH);}
bool isFluidContainer() const {return (group == ITEM_GROUP_FLUID);}
bool isDoor() const {return (type == ITEM_TYPE_DOOR);}
bool isMagicField() const {return (type == ITEM_TYPE_MAGICFIELD);}
bool isTeleport() const {return (type == ITEM_TYPE_TELEPORT);}
bool isKey() const {return (type == ITEM_TYPE_KEY);}
bool isDepot() const {return (type == ITEM_TYPE_DEPOT);}
bool isMailbox() const {return (type == ITEM_TYPE_MAILBOX);}
bool isTrashHolder() const {return (type == ITEM_TYPE_TRASHHOLDER);}
bool isRune() const {return (type == ITEM_TYPE_RUNE);}
bool isBed() const {return (type == ITEM_TYPE_BED);}
bool hasSubType() const {return (isFluidContainer() || isSplash() || stackable || charges);}
bool hasAbilities() const {return abilities != NULL;}
bool loaded, stopTime, showCount, clientCharges, stackable, showDuration, showCharges, showAttributes, dualWield,
allowDistRead, canReadText, canWriteText, forceSerialize, isVertical, isHorizontal, isHangable,
usable, movable, pickupable, rotable, replacable, lookThrough, walkStack, hasHeight, blockSolid,
blockPickupable, blockProjectile, blockPathFind, allowPickupable, alwaysOnTop, floorChange[CHANGE_LAST],
isAnimation, specialDoor, closingDoor, cache;
MagicEffect_t magicEffect;
FluidTypes_t fluidSource;
WeaponType_t weaponType;
Direction bedPartnerDir;
AmmoAction_t ammoAction;
CombatType_t combatType;
RaceType_t corpseType;
ShootEffect_t shootType;
Ammo_t ammoType;
uint16_t transformBed[PLAYERSEX_MALE + 1], transformUseTo, transformEquipTo, transformDeEquipTo,
id, clientId, maxItems, slotPosition, wieldPosition, speed, maxTextLength, writeOnceItemId, wareId,
premiumDays;
int32_t attack, extraAttack, defense, extraDefense, armor, breakChance, hitChance, maxHitChance,
runeLevel, runeMagLevel, lightLevel, lightColor, decayTo, rotateTo, alwaysOnTopOrder;
int32_t extraAttackChance, extraDefenseChance, attackSpeedChance;
int32_t armorRndMin, armorRndMax, defenseRndMin, defenseRndMax, extraDefenseRndMin,
extraDefenseRndMax, attackRndMin, attackRndMax, extraAttackRndMin, extraAttackRndMax,
attackSpeedRndMin, attackSpeedRndMax;
uint32_t shootRange, charges, decayTime, attackSpeed, wieldInfo, minReqLevel, minReqMagicLevel,
worth, levelDoor, date;
std::string name, pluralName, article, description, text, writer, runeSpellName, vocationString;
Condition* condition;
Abilities* abilities;
itemgroup_t group;
ItemTypes_t type;
float weight;
};
template<typename A>
class Array
{
public:
Array(uint32_t n);
virtual ~Array() {clear();}
void clear()
{
if(m_data && m_size)
{
free(m_data);
m_size = 0;
}
}
void reload();
A getElement(uint32_t id);
const A getElement(uint32_t id) const;
void addElement(A a, uint32_t pos);
uint32_t size() {return m_size;}
private:
A* m_data;
uint32_t m_size;
};
template<typename A>
Array<A>::Array(uint32_t n)
{
m_data = (A*)malloc(sizeof(A) * n);
memset(m_data, 0, sizeof(A) * n);
m_size = n;
}
template<typename A>
void Array<A>::reload()
{
m_data = (A*)malloc(sizeof(A) * m_size);
memset(m_data, 0, sizeof(A) * m_size);
}
template<typename A>
A Array<A>::getElement(uint32_t id)
{
if(id < m_size)
return m_data[id];
return 0;
}
template<typename A>
const A Array<A>::getElement(uint32_t id) const
{
if(id < m_size)
return m_data[id];
return 0;
}
template<typename A>
void Array<A>::addElement(A a, uint32_t pos)
{
if(pos >= m_size)
{
m_data = (A*)realloc(m_data, sizeof(A) * (pos + ITEMS_INCREMENT));
memset(m_data + m_size, 0, sizeof(A) * (pos + ITEMS_INCREMENT - m_size));
m_size = pos + ITEMS_INCREMENT;
}
m_data[pos] = a;
}
struct RandomizationBlock
{
int32_t fromRange, toRange, chance;
};
typedef std::map<int16_t, RandomizationBlock> RandomizationMap;
typedef std::map<int32_t, int32_t> IntegerMap;
class Items
{
public:
Items(): m_randomizationChance(ITEMS_RANDOMIZATION), items(ITEMS_SIZE) {}
virtual ~Items() {clear();}
bool reload();
int32_t loadFromOtb(std::string);
bool loadFromXml();
void parseItemNode(xmlNodePtr itemNode, uint32_t id);
void addItemType(ItemType* iType);
ItemType& getItemType(int32_t id);
const ItemType& getItemType(int32_t id) const;
const ItemType& operator[](int32_t id) const {return getItemType(id);}
int32_t getItemIdByName(const std::string& name);
const ItemType& getItemIdByClientId(int32_t spriteId) const;
uint16_t getRandomizedItem(uint16_t id);
uint8_t getRandomizationChance() const {return m_randomizationChance;}
const RandomizationBlock getRandomization(int16_t id) {return randomizationMap[id];}
uint32_t size() {return items.size();}
const IntegerMap getMoneyMap() const {return moneyMap;}
const ItemType* getElement(uint32_t id) const {return items.getElement(id);}
static uint32_t dwMajorVersion;
static uint32_t dwMinorVersion;
static uint32_t dwBuildNumber;
private:
uint8_t m_randomizationChance;
void clear();
void parseRandomizationBlock(int32_t id, int32_t fromId, int32_t toId, int32_t chance);
Array<ItemType*> items;
RandomizationMap randomizationMap;
IntegerMap moneyMap;
IntegerMap reverseItemMap;
};
#endif
| [
"mattyx14@users.noreply.github.com"
] | mattyx14@users.noreply.github.com |
86349a040fb36d749075161ddbc0285831781e18 | 08369613577450af45fca5d68e11df03a0ed2999 | /library/modules/tool/modelexport/source/toolmodelhierarchy.cpp | 5b75a5521390aed22a70f80dade3ef49d5194ac5 | [] | no_license | IreNox/tiki3 | 50e81a4a0dd120a37063f8cd6ea3045528350a5a | 2f29b3d7ab30217b3bd46d85ce8ec9032c1c1d54 | refs/heads/master | 2020-04-12T06:34:00.290425 | 2018-05-24T09:37:35 | 2018-05-24T09:37:35 | 12,142,108 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,340 | cpp |
#include "tiki/modelexport/toolmodelhierarchy.hpp"
#include "tiki/io/xmlreader.hpp"
#include "tiki/container/list.hpp"
#include "toolmodelsource.hpp"
namespace tiki
{
ToolModelHierarchy::ToolModelHierarchy()
{
m_pXml = nullptr;
m_finalJointCount = TIKI_SIZE_T_MAX;
m_hasFinalIndices = false;
}
void ToolModelHierarchy::create( const XmlReader* pXml, const _XmlElement* pHierarchyNode, const _XmlElement* pGeometriesNode, float scale )
{
TIKI_ASSERT( pXml );
m_pXml = pXml;
List< ToolModelGeometryInstance > instances;
if ( pHierarchyNode != nullptr )
{
List< ToolModelJoint > nodes;
searchNodes( nodes, pHierarchyNode );
m_joints.create( nodes.getBegin(), nodes.getCount() );
for (uint i = 0u; i < m_joints.getCount(); ++i)
{
ToolModelJoint& joint = m_joints[ i ];
const XmlAttribute* pIdAtt = pXml->findAttributeByName( "id", joint.pNode );
TIKI_ASSERT( pIdAtt );
joint.name = pIdAtt->content;
joint.crc = crcString( joint.name );
matrix::createIdentity( joint.skinToBone );
const XmlElement* pMatrix = pXml->findFirstChild( "matrix", joint.pNode );
if ( pMatrix == nullptr )
{
continue;
}
parseMatrix( joint.defaultPose, pMatrix->content, scale );
const XmlElement* pInstanceNode = pXml->findFirstChild( "instance_geometry", joint.pNode );
if ( pInstanceNode != nullptr )
{
const XmlAttribute* pUrlAtt = pXml->findAttributeByName( "url", pInstanceNode );
if ( pUrlAtt == nullptr )
{
continue;
}
const string geometryId = string( pUrlAtt->content ).subString( 1u );
const XmlElement* pGeometrieNode = pXml->findFirstChild( "geometry", pGeometriesNode );
while ( pGeometrieNode != nullptr )
{
const XmlAttribute* pGeometrieNodeIdAtt = pXml->findAttributeByName( "id", pGeometrieNode );
if ( pGeometrieNodeIdAtt != nullptr && geometryId == pGeometrieNodeIdAtt->content )
{
ToolModelGeometryInstance& instance = instances.add();
instance.pNode = pGeometrieNode;
instance.geometryId = geometryId;
instance.worldTransform = joint.defaultPose;
}
pGeometrieNode = pXml->findNext( "geometry", pGeometrieNode );
}
}
}
}
if ( instances.getCount() == 0u )
{
const XmlElement* pGeometrieNode = pXml->findFirstChild( "geometry", pGeometriesNode );
while ( pGeometrieNode != nullptr )
{
const XmlAttribute* pIdAtt = pXml->findAttributeByName( "id", pGeometrieNode );
if ( pIdAtt == nullptr )
{
continue;
}
ToolModelGeometryInstance& instance = instances.add();
instance.pNode = pGeometrieNode;
instance.geometryId = pIdAtt->content;
instance.worldTransform = Matrix44::identity;
pGeometrieNode = pXml->findNext( "geometry", pGeometrieNode );
}
}
m_instances.create( instances.getBegin(), instances.getCount() );
}
void ToolModelHierarchy::dispose()
{
m_pXml = nullptr;
m_joints.dispose();
m_instances.dispose();
}
const ToolModelJoint* ToolModelHierarchy::getJointByName( const string& name ) const
{
const crc32 crc = crcString( name );
for (uint i = 0u; i < m_joints.getCount(); ++i)
{
const ToolModelJoint& joint = m_joints[ i ];
if ( joint.crc == crc )
{
return &joint;
}
}
return nullptr;
}
void ToolModelHierarchy::markJointAsUsed( const ToolModelJoint& constJoint )
{
const uint index = m_joints.getIndexOf( &constJoint );
ToolModelJoint& joint = m_joints[ index ];
joint.used = true;
}
void ToolModelHierarchy::setBindMatrix( const ToolModelJoint& constJoint, const Matrix44& matrix )
{
const uint index = m_joints.getIndexOf( &constJoint );
ToolModelJoint& joint = m_joints[ index ];
joint.skinToBone = matrix;
}
void ToolModelHierarchy::searchNodes( List< ToolModelJoint >& targetList, const XmlElement* pNode )
{
const XmlElement* pChild = m_pXml->findFirstChild( "node", pNode );
const uint parentIndex = targetList.getCount() - 1u;
while ( pChild )
{
ToolModelJoint joint;
joint.index = uint32( targetList.getCount() );
joint.pNode = pChild;
joint.pParentNode = pNode;
joint.parentIndex = uint32( parentIndex );
joint.used = false;
joint.finalIndex = uint32( TIKI_SIZE_T_MAX );
joint.finalParentIndex = uint32( TIKI_SIZE_T_MAX );
targetList.add( joint );
searchNodes( targetList, pChild );
pChild = m_pXml->findNext( "node", pChild );
}
}
void ToolModelHierarchy::calculateFinalIndices()
{
// mark parents as used
for (uint i = 0u; i < m_joints.getCount(); ++i)
{
if ( m_joints[ i ].parentIndex != TIKI_SIZE_T_MAX )
{
uint parentIndex = m_joints[ i ].parentIndex;
while ( parentIndex != TIKI_SIZE_T_MAX )
{
m_joints[ parentIndex ].used = true;
parentIndex = m_joints[ parentIndex ].parentIndex;
}
}
}
uint32 index = 0u;
Array< uint32 > mappingTable;
mappingTable.create( m_joints.getCount() );
for (uint i = 0u; i < m_joints.getCount(); ++i)
{
if ( m_joints[ i ].used )
{
mappingTable[ i ] = index;
m_joints[ i ].finalIndex = index;
m_joints[ i ].finalParentIndex = mappingTable[ m_joints[ i ].parentIndex ];
index++;
}
}
m_finalJointCount = index;
m_hasFinalIndices = true;
mappingTable.dispose();
}
} | [
"mail@timboden.de"
] | mail@timboden.de |
1cca1c45a039b850303a2d5ccfb4b8638f2788f4 | a2206795a05877f83ac561e482e7b41772b22da8 | /Source/PV/build/Qt/Core/moc_pqFlatTreeViewEventPlayer.cxx | 772586f3de173de8a426bc11b13c9df672b2a2a6 | [] | no_license | supreethms1809/mpas-insitu | 5578d465602feb4d6b239a22912c33918c7bb1c3 | 701644bcdae771e6878736cb6f49ccd2eb38b36e | refs/heads/master | 2020-03-25T16:47:29.316814 | 2018-08-08T02:00:13 | 2018-08-08T02:00:13 | 143,947,446 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,631 | cxx | /****************************************************************************
** Meta object code from reading C++ file 'pqFlatTreeViewEventPlayer.h'
**
** Created by: The Qt Meta Object Compiler version 63 (Qt 4.8.6)
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/
#include "../../../ParaView/Qt/Core/pqFlatTreeViewEventPlayer.h"
#if !defined(Q_MOC_OUTPUT_REVISION)
#error "The header file 'pqFlatTreeViewEventPlayer.h' doesn't include <QObject>."
#elif Q_MOC_OUTPUT_REVISION != 63
#error "This file was generated using the moc from 4.8.6. It"
#error "cannot be used with the include files from this version of Qt."
#error "(The moc has changed too much.)"
#endif
QT_BEGIN_MOC_NAMESPACE
static const uint qt_meta_data_pqFlatTreeViewEventPlayer[] = {
// content:
6, // revision
0, // classname
0, 0, // classinfo
0, 0, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
0, // flags
0, // signalCount
0 // eod
};
static const char qt_meta_stringdata_pqFlatTreeViewEventPlayer[] = {
"pqFlatTreeViewEventPlayer\0"
};
void pqFlatTreeViewEventPlayer::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a)
{
Q_UNUSED(_o);
Q_UNUSED(_id);
Q_UNUSED(_c);
Q_UNUSED(_a);
}
const QMetaObjectExtraData pqFlatTreeViewEventPlayer::staticMetaObjectExtraData = {
0, qt_static_metacall
};
const QMetaObject pqFlatTreeViewEventPlayer::staticMetaObject = {
{ &pqWidgetEventPlayer::staticMetaObject, qt_meta_stringdata_pqFlatTreeViewEventPlayer,
qt_meta_data_pqFlatTreeViewEventPlayer, &staticMetaObjectExtraData }
};
#ifdef Q_NO_DATA_RELOCATION
const QMetaObject &pqFlatTreeViewEventPlayer::getStaticMetaObject() { return staticMetaObject; }
#endif //Q_NO_DATA_RELOCATION
const QMetaObject *pqFlatTreeViewEventPlayer::metaObject() const
{
return QObject::d_ptr->metaObject ? QObject::d_ptr->metaObject : &staticMetaObject;
}
void *pqFlatTreeViewEventPlayer::qt_metacast(const char *_clname)
{
if (!_clname) return 0;
if (!strcmp(_clname, qt_meta_stringdata_pqFlatTreeViewEventPlayer))
return static_cast<void*>(const_cast< pqFlatTreeViewEventPlayer*>(this));
return pqWidgetEventPlayer::qt_metacast(_clname);
}
int pqFlatTreeViewEventPlayer::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = pqWidgetEventPlayer::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
return _id;
}
QT_END_MOC_NAMESPACE
| [
"mpasVM@localhost.org"
] | mpasVM@localhost.org |
6ee3fc4a8e979f9c471c67003111f1c7e21d33a2 | 66688136c619b655dc35f3f69b6c33dd218da65b | /code/Common_engine/remote_bitrate_estimator/overuse_detector.cc | c1c50693d4ec2e60fc48b36f0ae9dbfb8c8123b8 | [] | no_license | forssil/GCCPT | 6ddc0f5707d314fddeeb8be831ad06250b686791 | 0249f5a115b96e7741c0292b5fc3a4e61a53c43c | refs/heads/master | 2021-06-19T00:12:58.608196 | 2015-10-08T01:17:35 | 2015-10-08T01:17:35 | 32,770,766 | 0 | 0 | null | 2015-04-15T07:21:05 | 2015-03-24T02:16:19 | null | UTF-8 | C++ | false | false | 13,837 | cc | /*
* Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include <math.h>
#include <stdlib.h> // fabsf
#if _WIN32
#include <windows.h>
#endif
#include "overuse_detector.h"
#include "remote_rate_control.h"
#include "rtp_rtcp/source/rtp_utility.h"
#include "utile/interface/trace.h"
#ifdef WEBRTC_BWE_MATLAB
extern MatlabEngine eng; // global variable defined elsewhere
#endif
enum { kOverUsingTimeThreshold = 100 };
enum { kMinFramePeriodHistoryLength = 60 };
namespace webrtc {
OveruseDetector::OveruseDetector(const OverUseDetectorOptions& options)
: options_(options),
current_frame_(),
prev_frame_(),
num_of_deltas_(0),
slope_(options_.initial_slope),
offset_(options_.initial_offset),
E_(),
process_noise_(),
avg_noise_(options_.initial_avg_noise),
var_noise_(options_.initial_var_noise),
threshold_(options_.initial_threshold),
ts_delta_hist_(),
prev_offset_(0.0),
time_over_using_(-1),
over_use_counter_(0),
hypothesis_(kBwNormal),
time_of_last_received_packet_(-1)
#ifdef WEBRTC_BWE_MATLAB
, plots_()
#endif
{
memcpy(E_, options_.initial_e, sizeof(E_));
memcpy(process_noise_, options_.initial_process_noise,
sizeof(process_noise_));
}
OveruseDetector::~OveruseDetector() {
#ifdef WEBRTC_BWE_MATLAB
if (plots_.plot1_) {
eng.DeletePlot(plots_.plot1_);
plots_.plot1_ = NULL;
}
if (plots_.plot2_) {
eng.DeletePlot(plots_.plot2_);
plots_.plot2_ = NULL;
}
if (plots_.plot3_) {
eng.DeletePlot(plots_.plot3_);
plots_.plot3_ = NULL;
}
if (plots_.plot4_) {
eng.DeletePlot(plots_.plot4_);
plots_.plot4_ = NULL;
}
#endif
ts_delta_hist_.clear();
}
void OveruseDetector::Update(uint16_t packet_size,
int64_t timestamp_ms,
uint32_t timestamp,
const int64_t now_ms) {
time_of_last_received_packet_ = now_ms;
#ifdef WEBRTC_BWE_MATLAB
// Create plots
const int64_t startTimeMs = nowMS;
if (plots_.plot1_ == NULL) {
plots_.plot1_ = eng.NewPlot(new MatlabPlot());
plots_.plot1_->AddLine(1000, "b.", "scatter");
}
if (plots_.plot2_ == NULL) {
plots_.plot2_ = eng.NewPlot(new MatlabPlot());
plots_.plot2_->AddTimeLine(30, "b", "offset", startTimeMs);
plots_.plot2_->AddTimeLine(30, "r--", "limitPos", startTimeMs);
plots_.plot2_->AddTimeLine(30, "k.", "trigger", startTimeMs);
plots_.plot2_->AddTimeLine(30, "ko", "detection", startTimeMs);
// plots_.plot2_->AddTimeLine(30, "g", "slowMean", startTimeMs);
}
if (plots_.plot3_ == NULL) {
plots_.plot3_ = eng.NewPlot(new MatlabPlot());
plots_.plot3_->AddTimeLine(30, "b", "noiseVar", startTimeMs);
}
if (plots_.plot4_ == NULL) {
plots_.plot4_ = eng.NewPlot(new MatlabPlot());
// plots_.plot4_->AddTimeLine(60, "b", "p11", startTimeMs);
// plots_.plot4_->AddTimeLine(60, "r", "p12", startTimeMs);
plots_.plot4_->AddTimeLine(60, "g", "p22", startTimeMs);
// plots_.plot4_->AddTimeLine(60, "g--", "p22_hat", startTimeMs);
// plots_.plot4_->AddTimeLine(30, "b.-", "deltaFs", startTimeMs);
}
#endif
bool new_timestamp = (timestamp != current_frame_.timestamp);
if (timestamp_ms >= 0) {
if (prev_frame_.timestamp_ms == -1 && current_frame_.timestamp_ms == -1) {
SwitchTimeBase();
}
new_timestamp = (timestamp_ms != current_frame_.timestamp_ms);
}
if (current_frame_.timestamp == -1) {
// This is the first incoming packet. We don't have enough data to update
// the filter, so we store it until we have two frames of data to process.
current_frame_.timestamp = timestamp;
current_frame_.timestamp_ms = timestamp_ms;
} else if (!PacketInOrder(timestamp, timestamp_ms)) {
return;
} else if (new_timestamp) {
// First packet of a later frame, the previous frame sample is ready.
WEBRTC_TRACE(kTraceStream, kTraceRtpRtcp, -1, "Frame complete at %I64i",
current_frame_.complete_time_ms);
if (prev_frame_.complete_time_ms >= 0) { // This is our second frame.
int64_t t_delta = 0;
double ts_delta = 0;
TimeDeltas(current_frame_, prev_frame_, &t_delta, &ts_delta);
UpdateKalman(t_delta, ts_delta, current_frame_.size, prev_frame_.size);
}
prev_frame_ = current_frame_;
// The new timestamp is now the current frame.
current_frame_.timestamp = timestamp;
current_frame_.timestamp_ms = timestamp_ms;
current_frame_.size = 0;
}
// Accumulate the frame size
current_frame_.size += packet_size;
current_frame_.complete_time_ms = now_ms;
}
BandwidthUsage OveruseDetector::State() const {
return hypothesis_;
}
double OveruseDetector::NoiseVar() const {
return var_noise_;
}
void OveruseDetector::SetRateControlRegion(RateControlRegion region) {
switch (region) {
case kRcMaxUnknown: {
threshold_ = options_.initial_threshold;
break;
}
case kRcAboveMax:
case kRcNearMax: {
threshold_ = options_.initial_threshold / 2;
break;
}
}
}
int64_t OveruseDetector::time_of_last_received_packet() const {
return time_of_last_received_packet_;
}
void OveruseDetector::SwitchTimeBase() {
current_frame_.size = 0;
current_frame_.complete_time_ms = -1;
current_frame_.timestamp = -1;
prev_frame_ = current_frame_;
}
void OveruseDetector::TimeDeltas(const FrameSample& current_frame,
const FrameSample& prev_frame,
int64_t* t_delta,
double* ts_delta) {
assert(t_delta);
assert(ts_delta);
num_of_deltas_++;
if (num_of_deltas_ > 1000) {
num_of_deltas_ = 1000;
}
if (current_frame.timestamp_ms == -1) {
uint32_t timestamp_diff = current_frame.timestamp - prev_frame.timestamp;
*ts_delta = timestamp_diff / 90.0;
} else {
*ts_delta = current_frame.timestamp_ms - prev_frame.timestamp_ms;
}
*t_delta = current_frame.complete_time_ms - prev_frame.complete_time_ms;
assert(*ts_delta > 0);
}
bool OveruseDetector::PacketInOrder(uint32_t timestamp, int64_t timestamp_ms) {
if (current_frame_.timestamp_ms == -1 && current_frame_.timestamp > -1) {
return InOrderTimestamp(timestamp, current_frame_.timestamp);
} else if (current_frame_.timestamp_ms > 0) {
// Using timestamps converted to NTP time.
return timestamp_ms > current_frame_.timestamp_ms;
}
// This is the first packet.
return true;
}
bool OveruseDetector::InOrderTimestamp(uint32_t timestamp,
uint32_t prev_timestamp) {
uint32_t timestamp_diff = timestamp - prev_timestamp;
// Assume that a diff this big must be due to reordering. Don't update
// with reordered samples.
return (timestamp_diff < 0x80000000);
}
double OveruseDetector::CurrentDrift() {
return 1.0;
}
void OveruseDetector::UpdateKalman(int64_t t_delta,
double ts_delta,
uint32_t frame_size,
uint32_t prev_frame_size) {
const double min_frame_period = UpdateMinFramePeriod(ts_delta);
const double drift = CurrentDrift();
// Compensate for drift
const double t_ts_delta = t_delta - ts_delta / drift;
double fs_delta = static_cast<double>(frame_size) - prev_frame_size;
// Update the Kalman filter
const double scale_factor = min_frame_period / (1000.0 / 30.0);
E_[0][0] += process_noise_[0] * scale_factor;
E_[1][1] += process_noise_[1] * scale_factor;
if ((hypothesis_ == kBwOverusing && offset_ < prev_offset_) ||
(hypothesis_ == kBwUnderusing && offset_ > prev_offset_)) {
E_[1][1] += 10 * process_noise_[1] * scale_factor;
}
const double h[2] = {fs_delta, 1.0};
const double Eh[2] = {E_[0][0]*h[0] + E_[0][1]*h[1],
E_[1][0]*h[0] + E_[1][1]*h[1]};
const double residual = t_ts_delta - slope_*h[0] - offset_;
const bool stable_state =
(BWE_MIN(num_of_deltas_, 60) * fabsf(offset_) < threshold_);
// We try to filter out very late frames. For instance periodic key
// frames doesn't fit the Gaussian model well.
if (fabsf(residual) < 3 * sqrt(var_noise_)) {
UpdateNoiseEstimate(residual, min_frame_period, stable_state);
} else {
UpdateNoiseEstimate(3 * sqrt(var_noise_), min_frame_period, stable_state);
}
const double denom = var_noise_ + h[0]*Eh[0] + h[1]*Eh[1];
const double K[2] = {Eh[0] / denom,
Eh[1] / denom};
const double IKh[2][2] = {{1.0 - K[0]*h[0], -K[0]*h[1]},
{-K[1]*h[0], 1.0 - K[1]*h[1]}};
const double e00 = E_[0][0];
const double e01 = E_[0][1];
// Update state
E_[0][0] = e00 * IKh[0][0] + E_[1][0] * IKh[0][1];
E_[0][1] = e01 * IKh[0][0] + E_[1][1] * IKh[0][1];
E_[1][0] = e00 * IKh[1][0] + E_[1][0] * IKh[1][1];
E_[1][1] = e01 * IKh[1][0] + E_[1][1] * IKh[1][1];
// Covariance matrix, must be positive semi-definite
assert(E_[0][0] + E_[1][1] >= 0 &&
E_[0][0] * E_[1][1] - E_[0][1] * E_[1][0] >= 0 &&
E_[0][0] >= 0);
#ifdef WEBRTC_BWE_MATLAB
// plots_.plot4_->Append("p11",E_[0][0]);
// plots_.plot4_->Append("p12",E_[0][1]);
plots_.plot4_->Append("p22", E_[1][1]);
// plots_.plot4_->Append("p22_hat", 0.5*(process_noise_[1] +
// sqrt(process_noise_[1]*(process_noise_[1] + 4*var_noise_))));
// plots_.plot4_->Append("deltaFs", fsDelta);
plots_.plot4_->Plot();
#endif
slope_ = slope_ + K[0] * residual;
prev_offset_ = offset_;
offset_ = offset_ + K[1] * residual;
Detect(ts_delta);
#ifdef WEBRTC_BWE_MATLAB
plots_.plot1_->Append("scatter",
static_cast<double>(current_frame_.size) - prev_frame_.size,
static_cast<double>(t_delta - ts_delta));
plots_.plot1_->MakeTrend("scatter", "slope", slope_, offset_, "k-");
plots_.plot1_->MakeTrend("scatter", "thresholdPos",
slope_, offset_ + 2 * sqrt(var_noise_), "r-");
plots_.plot1_->MakeTrend("scatter", "thresholdNeg",
slope_, offset_ - 2 * sqrt(var_noise_), "r-");
plots_.plot1_->Plot();
plots_.plot2_->Append("offset", offset_);
plots_.plot2_->Append("limitPos", threshold_/BWE_MIN(num_of_deltas_, 60));
plots_.plot2_->Plot();
plots_.plot3_->Append("noiseVar", var_noise_);
plots_.plot3_->Plot();
#endif
}
double OveruseDetector::UpdateMinFramePeriod(double ts_delta) {
double min_frame_period = ts_delta;
if (ts_delta_hist_.size() >= kMinFramePeriodHistoryLength) {
std::list<double>::iterator first_item = ts_delta_hist_.begin();
ts_delta_hist_.erase(first_item);
}
std::list<double>::iterator it = ts_delta_hist_.begin();
for (; it != ts_delta_hist_.end(); it++) {
min_frame_period = BWE_MIN(*it, min_frame_period);
}
ts_delta_hist_.push_back(ts_delta);
return min_frame_period;
}
void OveruseDetector::UpdateNoiseEstimate(double residual,
double ts_delta,
bool stable_state) {
if (!stable_state) {
return;
}
// Faster filter during startup to faster adapt to the jitter level
// of the network alpha is tuned for 30 frames per second, but
double alpha = 0.01;
if (num_of_deltas_ > 10*30) {
alpha = 0.002;
}
// Only update the noise estimate if we're not over-using
// beta is a function of alpha and the time delta since
// the previous update.
const double beta = pow(1 - alpha, ts_delta * 30.0 / 1000.0);
avg_noise_ = beta * avg_noise_
+ (1 - beta) * residual;
var_noise_ = beta * var_noise_
+ (1 - beta) * (avg_noise_ - residual) * (avg_noise_ - residual);
if (var_noise_ < 1e-7) {
var_noise_ = 1e-7;
}
}
BandwidthUsage OveruseDetector::Detect(double ts_delta) {
if (num_of_deltas_ < 2) {
return kBwNormal;
}
const double T = BWE_MIN(num_of_deltas_, 60) * offset_;
if (fabsf(T) > threshold_) {
if (offset_ > 0) {
if (time_over_using_ == -1) {
// Initialize the timer. Assume that we've been
// over-using half of the time since the previous
// sample.
time_over_using_ = ts_delta / 2;
} else {
// Increment timer
time_over_using_ += ts_delta;
}
over_use_counter_++;
if (time_over_using_ > kOverUsingTimeThreshold
&& over_use_counter_ > 1) {
if (offset_ >= prev_offset_) {
#ifdef _DEBUG
if (hypothesis_ != kBwOverusing) {
WEBRTC_TRACE(kTraceStream, kTraceRtpRtcp, -1, "BWE: kBwOverusing");
}
#endif
time_over_using_ = 0;
over_use_counter_ = 0;
hypothesis_ = kBwOverusing;
#ifdef WEBRTC_BWE_MATLAB
plots_.plot2_->Append("detection", offset_); // plot it later
#endif
}
}
#ifdef WEBRTC_BWE_MATLAB
plots_.plot2_->Append("trigger", offset_); // plot it later
#endif
} else {
#ifdef _DEBUG
if (hypothesis_ != kBwUnderusing) {
WEBRTC_TRACE(kTraceStream, kTraceRtpRtcp, -1, "BWE: kBwUnderUsing");
}
#endif
time_over_using_ = -1;
over_use_counter_ = 0;
hypothesis_ = kBwUnderusing;
}
} else {
#ifdef _DEBUG
if (hypothesis_ != kBwNormal) {
WEBRTC_TRACE(kTraceStream, kTraceRtpRtcp, -1, "BWE: kBwNormal");
}
#endif
time_over_using_ = -1;
over_use_counter_ = 0;
hypothesis_ = kBwNormal;
}
return hypothesis_;
}
} // namespace webrtc
| [
"gh228@sina.com"
] | gh228@sina.com |
fbc4d7360fdec918a9063f44e62938cccda59e80 | b2bb7e4a25f8522a5b8073b945b5dfdd57bc51f7 | /lib/ops/arithmops.cpp | 0b3d2865e598237d286efeccab40cb01ad91b3aa | [] | no_license | MercuriXito/PicProcess | 55945b60d5b986aa809559dd51c00364ec1cf58a | f31c8c1b3d017acd453555eed4f187a6d956d687 | refs/heads/master | 2022-11-17T19:31:02.535207 | 2020-07-19T15:25:43 | 2020-07-19T15:25:43 | 280,893,977 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,388 | cpp | #include <exception>
#include <QDebug>
#include "arithmops.h"
#include "wimage.h"
#include "lib/libcaller.h"
#define debug(x)( qDebug() << (x))
#define max(x, y)( (x) > (y) ? (x):(y))
#define min(x, y)( (x) < (y) ? (x):(y))
ArithmOps::ArithmOps()
{
}
//typedef struct info{
// bool doChannel;
// bool doSize;
// bool doReSize;
// bool doMaxSize;
// bool doCenterAligned;
// int cx1, cy1, cx2, cy2, oWidth, oHeight;
// bool success;
// info():
// doChannel(false), doSize(false), doReSize(false), doMaxSize(false),
// doCenterAligned(false), cx1(0),cy1(0),cx2(0),cy2(0),oWidth(0),oHeight(0),
// success(false){}
//}Info;
inline QRgb Pixel(const WImage& image, int x, int y){
if(x < 0 || x >= image.width() || y < 0 || y >= image.height() ) return 0;
return image.pixel(x, y);
}
inline QRgb Pixel(const QImage& image, int x, int y){
if(x < 0 || x >= image.width() || y < 0 || y >= image.height() ) return 0;
return image.pixel(x, y);
}
inline int clip0256(int x){
return min(255, max(x, 0));
}
inline int mod0256(int x){
return (x + 255) % 255;
}
inline int perPixelAdd(int a, int b){return a + b;}
inline int perPixelSub(int a, int b){return a - b;}
inline int perPixelMul(int a, int b){return a * b;}
inline int perPixelDiv(int a, int b){ if(b == 0) return 255; return a / b; }
inline int perPixelAnd(int a, int b){
if(b == 0) return 0; return a;
};
inline int perPixelOr(int a, int b){
if(b > 0) return a; return 0;
};
// flag related
uint ArithmOps::constructFlag(bool doCenterAligned, bool doScale, bool useMode){
uint flag = 0;
flag |= ( doCenterAligned );
flag |= ( doScale << 1 );
flag |= ( useMode << 2);
return flag;
}
void ArithmOps::destructFlag(uint flag, bool &doCenterAligned, bool &doScale, bool &useMod){
doCenterAligned = flag & 1;
doScale = flag & 2;
useMod = flag & 4;
}
bool ArithmOps::calPerPixel(WImage &image, const WImage &image2, int (*fun)(int, int), uint flag){
// 设定:
// 0. 一切大小以image的大小为主
// 解决 Size 不匹配的问题:
// 1. 中心对齐,或者是左上角对齐: doCenterShift 参数控制
// 2. image2 进行 scale: doScale 参数控制
// 解决显示时超过255的问题:
// 1. 两种处理的方法,一种是取模,一种是clip: 由 useMod 参数控制,默认是 clip
bool doCenterAligned, doScale, useMod;
ArithmOps::destructFlag(flag, doCenterAligned, doScale, useMod);
QImage op2 = image2;
if( doScale ){
op2 = image2.scaled(image.width(), image.height());
doCenterAligned = false;
}
int hw1 = image.width() / 2, hh1 = image.height() / 2, hw2 = op2.width() / 2, hh2 = op2.height() / 2;
int xshift = hw2 - hw1, yshift = hh2 - hh1;
int outWidth = image.width();
int outHeight = image.height();
for(int i = 0; i < outWidth; ++i){
for(int j = 0; j < outHeight; ++j){
QRgb i1 = Pixel(image, i, j);
QRgb i2 = Pixel(op2, i + xshift * doCenterAligned, j + yshift * doCenterAligned); // doCenterAligned or Not
int r, g, b;
if(useMod){
r = mod0256( fun( qRed(i1) , qRed(i2) ) ) ;
g = mod0256( fun( qGreen(i1) , qGreen(i2) ) ) ;
b = mod0256( fun( qBlue(i1) , qBlue(i2)) );
}else{
r = clip0256( fun( qRed(i1) , qRed(i2) ) ) ;
g = clip0256( fun( qGreen(i1) , qGreen(i2) ) ) ;
b = clip0256( fun( qBlue(i1) , qBlue(i2)) );
}
image.setPixel(i,j,QColor(r, g, b).rgb());
}
}
return true;
}
//Info resovleStatus(const WImage& image1, const WImage& image2, ArithmOps::ArithmOption opt){
// uchar status = opt & 0x000000ff;
// uchar statusChannel = (status & 0x000000f0) >> 4;
// uchar statusSize = status & 0x0000000f;
// bool image1IsGrayScale = image1.isGrayscale();
// bool image2IsGrayScale = image2.isGrayscale();
// int outWidth = image1.width(), outHeight = image1.height();
// Info info;
// // check channels
// switch (statusChannel) {
// case 0:{
// if(image1IsGrayScale ^ image2IsGrayScale){
// debug("Channel Match Failed"); debug(image1IsGrayScale); debug(image2IsGrayScale);
// return info;
// }}; break;
// case 1: info.doChannel = true ;break;
// default: debug("Not Seen Channel Status:"); debug(statusChannel); return info; break;
// }
// // check size
// switch (statusSize) {
// case 0: if(!(image1.height() == image2.height() && image1.width() == image2.width())){
// debug("Size Match Failed");
// debug(image1.height()); debug(image2.height()); debug(image1.width()); debug(image2.width());
// return info;
// }; break;
// case 1: { // rescale image2
// info.doSize = true; info.doReSize = true;
// };break;
// case 2:{ // find max
// info.doSize = false;
// info.doMaxSize = true; outWidth = max(image1.width(), image2.width()); outHeight = max(image1.height(), image2.height());}
// case 3:{
// info.doSize = false;
// info.doMaxSize = true; outWidth = max(image1.width(), image2.width()); outHeight = max(image1.height(), image2.height());
// // center aligned during adding
// int hw1 = image1.width() / 2, hh1 = image1.height() / 2, hw2 = image2.width() / 2, hh2 = image2.height();
// int hw = max(hw1, hw2), hh = max(hh1, hh2);
// info.cx1 = hw - hw1; info.cx2 = hw - hw2; info.cy1 = hh - hh1; info.cy2 = hh - hh2;
// };break;
// default: debug("Not Seen Size Status:"); debug(statusSize); return info; break;
// }
// info.oWidth = outWidth; info.oHeight = outHeight;
// info.success = true;
// return info;
//}
bool ArithmOps::add(WImage& image , const WImage& image2, uint flag){
return ArithmOps::calPerPixel(image, image2, perPixelAdd, flag);
}
WImage ArithmOps::add(const WImage& image, const WImage& image2 , uint flag){
WImage* res = image.deepcopy();
ArithmOps::add(*res, image2, flag);
return *res;
}
bool ArithmOps::minus(WImage& image , const WImage& image2, uint flag){
return ArithmOps::calPerPixel(image, image2, perPixelSub, flag);
}
WImage ArithmOps::minus(const WImage& image, const WImage& image2, uint flag){
WImage* res = image.deepcopy();
ArithmOps::minus(*res, image2, flag);
return *res;
}
bool ArithmOps::mul(WImage& image , const WImage& image2, uint flag){
return ArithmOps::calPerPixel(image, image2, perPixelMul, flag);
}
WImage ArithmOps::mul(const WImage& image , const WImage& image2, uint flag){
WImage* res = image.deepcopy();
ArithmOps::mul(*res, image2, flag);
return *res;
}
bool ArithmOps::div(WImage& image , const WImage& image2, uint flag){
return ArithmOps::calPerPixel(image, image2, perPixelDiv, flag);
}
WImage ArithmOps::div(const WImage& image, const WImage& image2, uint flag){
WImage* res = image.deepcopy();
ArithmOps::div(*res, image2, flag);
return *res;
}
// logicstic
bool ArithmOps::neg(WImage& image){
int outWidth = image.width();
int outHeight = image.height();
for(int i = 0; i < outWidth; ++i){
for(int j = 0; j < outHeight; ++j){
QRgb rgb = image.pixel(i, j);
int r = qRed(rgb);
int g = qGreen(rgb);
int b = qBlue(rgb);
image.setPixel(i, j, QColor(255 - r, 255 - g, 255 - b).rgb());
}
}
return true;
}
WImage ArithmOps::neg(const WImage& image){
WImage res = *image.deepcopy();
ArithmOps::neg(res);
return res;
}
bool ArithmOps::orI(WImage& image, const WImage& image2, uint flag){
return ArithmOps::calPerPixel(image, image2, perPixelAdd, flag);
}
WImage ArithmOps::orI(const WImage& image, const WImage& image2 , uint flag){
WImage* res = image.deepcopy();
ArithmOps::orI(*res, image2, flag);
return *res;
}
bool ArithmOps::andI(WImage& image , const WImage& image2 , uint flag){
return ArithmOps::calPerPixel(image, image2, perPixelOr, flag);
}
WImage ArithmOps::andI(const WImage& image, const WImage& image2 , uint flag){
WImage* res = image.deepcopy();
ArithmOps::andI(*res, image2, flag);
return *res;
}
| [
"victor_tochen@foxmail.com"
] | victor_tochen@foxmail.com |
e35a2151c520ba03f828e09d5da7684490122ccc | 03ea247fdc81c75d838ac0af45fcc1c83505e315 | /Source/main.cpp | 55a29f4760933c25385069735c4d3455de366c9b | [] | no_license | Jesse-V/CS5400_Final_Project | 9682b2313babfb0ff0106f684fc3f875de36ce06 | a824418394968c0cfa8a7e87e112f80ed417c613 | refs/heads/master | 2020-05-18T21:55:51.894816 | 2013-05-03T17:58:51 | 2013-05-03T17:58:51 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,687 | cpp |
#include "Application.hpp"
#include <iostream>
std::shared_ptr<Application> application; //make_unique is not included in C++11 yet...
void displayCallback()
{
application->render();
}
void keyCallback(unsigned char key, int x, int y)
{
application->onKey(key, x, y);
}
void specialKeyCallback(int key, int x, int y)
{
application->onSpecialKey(key, x, y);
}
/* Initializes glut. Sets the window size and title to the specified values */
void initializeGlutWindow(int width, int height, const std::string& windowTitle)
{
glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_DEPTH);
glutInitWindowSize(width, height);
glutCreateWindow(windowTitle.c_str());
std::cout << width << ", " << height << " " << (width / (float)height) << std::endl;
}
int main(int argc, char **argv)
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_DEPTH);
initializeGlutWindow(glutGet(GLUT_SCREEN_WIDTH), glutGet(GLUT_SCREEN_HEIGHT), "Final OpenGL Project - Jesse Victors");
GLenum glew_status = glewInit();
if (glew_status != GLEW_OK)
{
fprintf(stderr, "Error: %s\n", glewGetErrorString(glew_status));
return EXIT_FAILURE;
}
try
{
application = std::make_shared<Application>(glutGet(GLUT_SCREEN_WIDTH), glutGet(GLUT_SCREEN_HEIGHT));
glutDisplayFunc(displayCallback);
glutKeyboardFunc(keyCallback);
glutSpecialFunc(specialKeyCallback);
//glutMotionFunc(onMouseMotion);
//glutMouseFunc(onMouseClick);
std::cout << "Finished assembly. Launching application..." << std::endl;
glutMainLoop();
}
catch (std::exception& e)
{
std::cerr << std::endl;
std::cerr << e.what();
std::cerr << std::endl;
}
return EXIT_SUCCESS;
}
| [
"jvictors@jessevictors.com"
] | jvictors@jessevictors.com |
c713af0c6638f868f3b70da7093e0ac4adee9c65 | d3333397f9819965b74063152710f205e639361e | /ADSWeather/src/ADSWeather.h | 60f2995d4454efc80f3d431fe294c05f44a8aef0 | [
"BSD-3-Clause"
] | permissive | OladapoAjala/libraries | ea5345fffcb28f95bb321a1bbdfc200313ef4be6 | 46d8955c0de3d58a8147b76f063f545f4401585c | refs/heads/master | 2020-04-30T04:42:27.315375 | 2019-03-19T23:43:33 | 2019-03-19T23:43:33 | 176,615,578 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,707 | h | /**********************************************************
** @file ADSWeather.cpp
** @author John Cape
** @copyright Argent Data Systems, Inc. - All rights reserved
**
** Argent Data Systems weather station Arduino library.
** This library provides a set of functions for interfacing
** with the Argent Data Systesm weather station sensor package
** These sensors consist of a rain gauge, a wind vane and an
** anemometer. The anemometer and the rain gauge should be
** connected to digital input pins on one side and ground on
** the other. The weather vane is a variable resistor.
** It should be connected to an analog input pin on one side
** and ground on the other. The analog input pin needs to be
** connected to 5V from the Arduion through a 10K Ohm resistor.
**
*/
#ifndef ADSWeather_h
#define ADSWeather_h
#include "Arduino.h"
class ADSWeather
{
public:
ADSWeather(int rainPin, int windDirPin, int windSpdPin);
int getRain();
int getWindDirection();
int getWindSpeed();
int getWindGust();
void update();
static void countRain();
static void countAnemometer();
private:
int _rainPin;
int _windDirPin;
int _windSpdPin;
int _rain;
int _windDir;
int _windSpd;
int _windSpdMax;
unsigned long _nextCalc;
unsigned long _timer;
unsigned int _vaneSample[50]; //50 samples from the sensor for consensus averaging
unsigned int _vaneSampleIdx;
unsigned int _windDirBin[16];
unsigned int _gust[30]; //Array of 50 wind speed values to calculate maximum gust speed.
unsigned int _gustIdx;
int _readRainAmmount();
int _readWindDir();
int _readWindSpd();
void _setBin(unsigned int windVane);
};
//static void countRain();
#endif | [
"ajalaoladapoemmanuel.ao@gmail.com"
] | ajalaoladapoemmanuel.ao@gmail.com |
e5b326619f1cd33da3019cb11b9c453ec3e68110 | 1184a4581c557f44b8ec9e16f944ae2ef9f3f64f | /c_cpp/examples/esp8266/esp8266_arduino.ino | baaf1bcdc2c4c5d0b3df25d6d1c586113c45c3c0 | [
"MIT"
] | permissive | obastemur/iot_client | 3aa52136db92e366f088fb26e64a4c68e7c00dfa | be90f07474e8f71f5d4b2350ab4ab6b44c7e77ba | refs/heads/master | 2021-07-17T13:43:59.440722 | 2020-06-04T16:19:15 | 2020-06-04T16:19:15 | 165,143,885 | 2 | 5 | MIT | 2019-11-06T23:00:50 | 2019-01-10T23:00:04 | C++ | UTF-8 | C++ | false | false | 3,368 | ino | // Copyright (c) Oguz Bastemur. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
#include "src/iotc/iotc.h"
#include "src/iotc/common/string_buffer.h"
#include <ESP8266WiFi.h>
// #define WIFI_SSID "<ENTER WIFI SSID HERE>"
// #define WIFI_PASSWORD "<ENTER WIFI PASSWORD HERE>"
// const char* scopeId = "<ENTER SCOPE ID HERE>";
// const char* deviceId = "<ENTER DEVICE ID HERE>";
// const char* deviceKey = "<ENTER DEVICE primary/secondary KEY HERE>";
static IOTContext context = NULL;
void connect_wifi() {
Serial.begin(9600);
WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
LOG_VERBOSE("Connecting WiFi..");
while (WiFi.status() != WL_CONNECTED) {
delay(500);
}
}
static bool isConnected = false;
void onEvent(IOTContext ctx, IOTCallbackInfo *callbackInfo) {
if (strcmp(callbackInfo->eventName, "ConnectionStatus") == 0) {
LOG_VERBOSE("Is connected ? %s (%d)", callbackInfo->statusCode == IOTC_CONNECTION_OK ? "YES" : "NO", callbackInfo->statusCode);
isConnected = callbackInfo->statusCode == IOTC_CONNECTION_OK;
}
AzureIOT::StringBuffer buffer;
if (callbackInfo->payloadLength > 0) {
buffer.initialize(callbackInfo->payload, callbackInfo->payloadLength);
}
LOG_VERBOSE("- [%s] event was received. Payload => %s", callbackInfo->eventName, buffer.getLength() ? *buffer : "EMPTY");
if (strcmp(callbackInfo->eventName, "Command") == 0) {
LOG_VERBOSE("- Command name was => %s\r\n", callbackInfo->tag);
}
}
static unsigned prevMillis = 0, loopId = 0;
void setup()
{
connect_wifi();
// Azure IOT Central setup
int errorCode = iotc_init_context(&context);
if (errorCode != 0) {
LOG_ERROR("Error initializing IOTC. Code %d", errorCode);
return;
}
iotc_set_logging(IOTC_LOGGING_API_ONLY);
// for the simplicity of this sample, used same callback for all the events below
iotc_on(context, "MessageSent", onEvent, NULL);
iotc_on(context, "Command", onEvent, NULL);
iotc_on(context, "ConnectionStatus", onEvent, NULL);
iotc_on(context, "SettingsUpdated", onEvent, NULL);
iotc_on(context, "Error", onEvent, NULL);
errorCode = iotc_connect(context, scopeId, deviceKey, deviceId, IOTC_CONNECT_SYMM_KEY);
if (errorCode != 0) {
LOG_ERROR("Error @ iotc_connect. Code %d", errorCode);
return;
}
prevMillis = millis();
}
void loop()
{
if (isConnected) {
unsigned long ms = millis();
if (ms - prevMillis > 15000) { // send telemetry every 15 seconds
char msg[64] = {0};
int pos = 0, errorCode = 0;
prevMillis = ms;
if (loopId++ % 2 == 0) {
pos = snprintf(msg, sizeof(msg) - 1, "{\"accelerometerX\": %d}", 10 + (rand() % 20));
errorCode = iotc_send_telemetry(context, msg, pos);
} else {
pos = snprintf(msg, sizeof(msg) - 1, "{\"dieNumber\":%d}", 1 + (rand() % 5));
errorCode = iotc_send_property(context, msg, pos);
}
msg[pos] = 0;
if (errorCode != 0) {
LOG_ERROR("Sending message has failed with error code %d", errorCode);
}
}
iotc_do_work(context); // do background work for iotc
}
}
| [
"ogbastem@microsoft.com"
] | ogbastem@microsoft.com |
0ad0cad382228541862c4805476aa69138404edf | e4f93064a729d05ec4ae014038f59347ad191273 | /legacy/master-slave/slaves/motion_planning_segment.h | bc1b261e94d51ccb0a42d93013432c535a7d9fac | [] | no_license | joschu/surgical | 221c349f8ba4e2c9c636931232821ce320004bac | 5b26795b0cc2cb8ba02e3a4a27d2c0568134d83e | refs/heads/master | 2021-01-17T22:52:12.573487 | 2011-07-19T00:56:31 | 2011-07-19T00:56:31 | 1,912,239 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,972 | h | #ifndef _MOTION_PLANNING_SEGMENT_H_
#define _MOTION_PLANNING_SEGMENT_H_
#include "util.h"
#include <stdlib.h>
/* A motion planning segment is a "part" of a whole multi-planner. It can be defined in terms of absolute start and end positions, or
relative ones, and has knowledge of its preceding segment (or NULL if there was none) */
class Motion_planning_segment{
public:
Motion_planning_segment* _prev_segment;
double _duration;
double _absolute_start_pos[num_dof];
bool _has_absolute_start_pos;
Motion_planning_segment(double duration, Motion_planning_segment* prev_segment=NULL);
~Motion_planning_segment();
/* For the case of the very first segment: this will set an absolute start position, which overrides any possible backwards checking. If this is set, no matter what
*,it will be considered the start position. */
void set_absolute_start_pos(double* absolute_start_pos);
/* Populates start_pos with the position which I am starting at. Returns false if it is unable to do so due to constraints. */
bool get_start(double* start_pos);
void get_last_target(double* last_target);
/* Sets the grip positions to what the start position as */
void set_grips_to_start(double* pos_to_alter);
/* Populates goal_pos with the position which I end at, including all offsets */
virtual bool get_goal(double* goal_pos)=0;
/* Uses interpolation to calculate, on the fly, where I should be aiming for at a given time. For visual, this will act as a "polling" time as well, to check
whether it's time for a visual servo. For non visual, this is simply an interpolation between start and end, with no offsets required. Returns false if
there is not enough information to compute this. */
virtual bool get_position_at_time(double* position, double time);
};
#endif
| [
"sameep.tandon@gmail.com"
] | sameep.tandon@gmail.com |
857d64d43ed801d42365f2c4500594ffc5d1deed | 78c5ae2317bfb57d176ce2124d3a4013b9120b5f | /swig/javafmod_win/examples/simple_event.cpp | cdc59c857e556e8e8980b19e5de23f520f7f646c | [] | no_license | Kleptine/javafmod | 7c7ed76b6399d820752e7813a7eabe699ae5147a | 1582e7bf1db5a4f480f0f74b79e65884a97f17ce | refs/heads/master | 2016-08-12T19:17:23.879445 | 2016-01-27T08:05:35 | 2016-01-27T08:05:35 | 50,490,607 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,633 | cpp | /*==============================================================================
Simple Event Example
Copyright (c), Firelight Technologies Pty, Ltd 2012-2014.
This example demonstrates the various ways of playing an event.
#### Explosion Event ####
This event is played as a one-shot and released immediately after it has been
created.
#### Looping Ambience Event ####
A single instance is started or stopped based on user input.
#### Cancel Event ####
This instance is started and if already playing, restarted.
==============================================================================*/
#include "fmod_studio.hpp"
#include "fmod.hpp"
#include "common.h"
#include "time.h"
int FMOD_Main()
{
//void *extraDriverData = NULL;
Common_Init(NULL);
FMOD::Studio::System* system = NULL;
ERRCHECK( FMOD::Studio::System::create(&system) );
// The example Studio project is authored for 5.1 sound, so set up the system output mode to match
//
//ERRCHECK( lowLevelSystem->setSoftwareFormat(0, FMOD_SPEAKERMODE_5POINT1, 0) );
ERRCHECK( system->initialize(32, FMOD_STUDIO_INIT_NORMAL, FMOD_INIT_NORMAL, NULL) );
FMOD::System* lowLevelSystem = NULL;
ERRCHECK( system->getLowLevelSystem(&lowLevelSystem) );
FMOD_ADVANCEDSETTINGS set = {0};
set.cbSize = sizeof(FMOD_ADVANCEDSETTINGS);
lowLevelSystem->getAdvancedSettings(&set);
srand(time(NULL));
set.cbSize = sizeof(FMOD_ADVANCEDSETTINGS);
set.randomSeed = rand();
printf("%d\n",set.randomSeed);
lowLevelSystem->setAdvancedSettings(&set);
FMOD::Studio::Bank* masterBank = NULL;
ERRCHECK( system->loadBankFile(Common_MediaPath("Master Bank.bank"), FMOD_STUDIO_LOAD_BANK_NORMAL, &masterBank) );
FMOD::Studio::Bank* stringsBank = NULL;
ERRCHECK( system->loadBankFile(Common_MediaPath("Master Bank.strings.bank"), FMOD_STUDIO_LOAD_BANK_NORMAL, &stringsBank) );
FMOD::Studio::Bank* ambienceBank = NULL;
ERRCHECK( system->loadBankFile(Common_MediaPath("Surround_Ambience.bank"), FMOD_STUDIO_LOAD_BANK_NORMAL, &ambienceBank) );
FMOD::Studio::Bank* menuBank = NULL;
ERRCHECK( system->loadBankFile(Common_MediaPath("UI_Menu.bank"), FMOD_STUDIO_LOAD_BANK_NORMAL, &menuBank) );
FMOD::Studio::Bank* weaponsBank = NULL;
ERRCHECK( system->loadBankFile(Common_MediaPath("Weapons.bank"), FMOD_STUDIO_LOAD_BANK_NORMAL, &weaponsBank) );
FMOD::Studio::Bank* characterBank = NULL;
ERRCHECK( system->loadBankFile(Common_MediaPath("Character.bank"), FMOD_STUDIO_LOAD_BANK_NORMAL, &characterBank) );
// Get the Looping Ambience event
FMOD::Studio::EventDescription* loopingAmbienceDescription = NULL;
ERRCHECK( system->getEvent("event:/Ambience/Country", &loopingAmbienceDescription) );
FMOD::Studio::EventInstance* loopingAmbienceInstance = NULL;
ERRCHECK( loopingAmbienceDescription->createInstance(&loopingAmbienceInstance) );
// Get the 4 Second Surge event
FMOD::Studio::EventDescription* cancelDescription = NULL;
ERRCHECK( system->getEvent("event:/Character/Hand Foley/Doorknob", &cancelDescription) );
FMOD::Studio::EventInstance* cancelInstance = NULL;
ERRCHECK( cancelDescription->createInstance(&cancelInstance) );
// Get the Single Explosion event
FMOD::Studio::EventDescription* explosionDescription = NULL;
ERRCHECK( system->getEvent("event:/Explosions/Single Explosion", &explosionDescription) );
// Start loading explosion sample data and keep it in memory
ERRCHECK( explosionDescription->loadSampleData() );
do
{
Common_Update();
if (Common_BtnPress(BTN_ACTION1))
{
// One-shot event
FMOD::Studio::EventInstance* eventInstance = NULL;
ERRCHECK( explosionDescription->createInstance(&eventInstance) );
ERRCHECK( eventInstance->start() );
// Release will clean up the instance when it completes
ERRCHECK( eventInstance->release() );
}
if (Common_BtnPress(BTN_ACTION2))
{
ERRCHECK( loopingAmbienceInstance->start() );
}
if (Common_BtnPress(BTN_ACTION3))
{
ERRCHECK( loopingAmbienceInstance->stop(FMOD_STUDIO_STOP_IMMEDIATE) );
}
if (Common_BtnPress(BTN_ACTION4))
{
// Calling start on an instance will cause it to restart if it's already playing
ERRCHECK( cancelInstance->start() );
}
ERRCHECK( system->update() );
Common_Draw("==================================================");
Common_Draw("Simple Event Example.");
Common_Draw("Copyright (c) Firelight Technologies 2014-2014.");
Common_Draw("==================================================");
Common_Draw("");
Common_Draw("Press %s to fire and forget the explosion", Common_BtnStr(BTN_ACTION1));
Common_Draw("Press %s to start the looping ambience", Common_BtnStr(BTN_ACTION2));
Common_Draw("Press %s to stop the looping ambience", Common_BtnStr(BTN_ACTION3));
Common_Draw("Press %s to start/restart the cancel sound", Common_BtnStr(BTN_ACTION4));
Common_Draw("Press %s to quit", Common_BtnStr(BTN_QUIT));
Common_Sleep(50);
} while (!Common_BtnPress(BTN_QUIT));
ERRCHECK( weaponsBank->unload() );
ERRCHECK( menuBank->unload() );
ERRCHECK( ambienceBank->unload() );
ERRCHECK( stringsBank->unload() );
ERRCHECK( masterBank->unload() );
ERRCHECK( characterBank->unload() );
ERRCHECK( system->release() );
Common_Close();
return 0;
}
| [
"kleptine@gmail.com"
] | kleptine@gmail.com |
1cf5b9e413d371c995d0243d764d91b00f83f8a5 | 100786afbc0d0d854c4b2dcabb19df484cc8eed7 | /MFC-Example-Snippets/pch-MFC-Example-Snippets.hpp | c4d22516376f5c8f9c2382add0cd120716ee0421 | [] | no_license | Lester-Dowling/MFC-Example-Snippets-2015 | 4f83c18b2ca59dcb025d28aed280355b199765ae | d36cfd746d03430eca685a399a7dd889ce45b54b | refs/heads/master | 2021-01-12T03:37:59.073687 | 2017-02-05T20:10:54 | 2017-02-05T20:10:54 | 78,243,106 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,551 | hpp | #pragma once
#include "targetver.h"
#include <afx.h> // C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\atlmfc\include\afx.h
#include <afxwin.h> // C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\atlmfc\include\afxwin.h
#include <afxext.h> // C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\atlmfc\include\afxext.h
#include <atlbase.h> // C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\atlmfc\include\atlbase.h
#include <atlstr.h> // C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\atlmfc\include\atlstr.h
#include <afxdisp.h> // C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\atlmfc\include\afxdisp.h
#include <afxdtctl.h> // C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\atlmfc\include\afxdtctl.h
#include <afxcmn.h> // C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\atlmfc\include\afxcmn.h
#include <afxcontrolbars.h> // C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\atlmfc\include\afxcontrolbars.h
#include <afxsock.h> // C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\atlmfc\include\afxsock.h
#include <afxdialogex.h> // C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\atlmfc\include\afxdialogex.h
#include <afxdhtml.h> // C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\atlmfc\include\afxdhtml.h
#include <WindowsX.h> // C:\Program Files (x86)\Windows Kits\10\Include\10.0.14393.0\shared\windowsx.h
#include <strsafe.h> // C:\Program Files (x86)\Windows Kits\10\Include\10.0.14393.0\shared\strsafe.h
#include <combaseapi.h> // C:\Program Files (x86)\Windows Kits\10\Include\10.0.14393.0\um\combaseapi.h
#include <CommDlg.h> // C:\Program Files (x86)\Windows Kits\10\Include\10.0.14393.0\um\commdlg.h
#include <Stringapiset.h> // C:\Program Files (x86)\Windows Kits\10\Include\10.0.14393.0\um\stringapiset.h
#include <xpsobjectmodel_1.h> // C:\Program Files (x86)\Windows Kits\10\Include\10.0.14393.0\um\xpsobjectmodel_1.h
#include <DocumentTarget.h> // C:\Program Files (x86)\Windows Kits\10\Include\10.0.14393.0\um\DocumentTarget.h
#include <wininet.h> // C:\Program Files (x86)\Windows Kits\10\Include\10.0.14393.0\um\WinInet.h
#ifndef NDEBUG
#include <crtdbg.h> // C:\Program Files (x86)\Windows Kits\10\Include\10.0.14393.0\ucrt\crtdbg.h
#endif
#undef min
#undef max
#ifdef _UNICODE
#if defined _M_IX86
#pragma comment(linker,"/manifestdependency:\"type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='x86' publicKeyToken='6595b64144ccf1df' language='*'\"")
#elif defined _M_X64
#pragma comment(linker,"/manifestdependency:\"type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='amd64' publicKeyToken='6595b64144ccf1df' language='*'\"")
#else
#pragma comment(linker,"/manifestdependency:\"type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='*' publicKeyToken='6595b64144ccf1df' language='*'\"")
#endif
#endif
#include <cassert> // C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\include\cassert
#include <cstddef> // C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\include\cstddef
#include <cstdint> // C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\include\cstdint
#include <ctime> // C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\include\ctime
#include <cstdio> // C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\include\cstdio
#include <cstdlib> // C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\include\cstdlib
#include <string> // C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\include\string
#include <functional> // C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\include\functional
#include <algorithm> // C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\include\algorithm
#include <new> // C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\include\new
#include <memory> // C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\include\memory
#include <vector> // C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\include\vector
#include <map>
#include <stdexcept> // C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\include\stdexcept
#include <iostream> // C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\include\iostream
#include <sstream> // C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\include\sstream
#include <limits> // C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\include\limits
#include <iterator> // C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\include\iterator
#include <initializer_list> // C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\include\initializer_list
#include <boost/signals2.hpp> // C:\boost_MSVC_2015_x64\include\boost-1_62\boost\signals2.hpp
#include <boost/bind.hpp> // C:\boost_MSVC_2015_x64\include\boost-1_62\boost\bind.hpp
template <class Interface>
inline void SafeRelease(Interface** interfaceToRelease)
{
if (*interfaceToRelease != nullptr)
{
(*interfaceToRelease)->Release();
(*interfaceToRelease) = nullptr;
}
}
// This macro is the same as IMPLEMENT_OLECREATE, except it passes TRUE
// for the bMultiInstance parameter to the COleObjectFactory constructor.
// We want a separate instance of this application to be launched for
// each automation proxy object requested by automation controllers.
#ifndef IMPLEMENT_OLECREATE2
#define IMPLEMENT_OLECREATE2(class_name, external_name, app_clsid) \
const AFX_DATADEF GUID class_name::guid = app_clsid; \
AFX_DATADEF COleObjectFactory class_name::factory(class_name::guid, \
RUNTIME_CLASS(class_name), TRUE, _T(external_name));
#endif // IMPLEMENT_OLECREATE2
| [
"L.J.Dowling@mac.com"
] | L.J.Dowling@mac.com |
a6c93a6653d251e5afdcf943563b3128d85c80f2 | eeae960edea02bef1e147fe0ba4bf947e67d6619 | /mb/pagerank/util/Check.hpp | 062f80dfd7e1ab556108640afbd95212bbfc0fff | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | efzulian/micro-benchmarks | a3e6d7c66cb7f8c3719c21d8dd4185c26d655990 | 722ee036b302ad394fbd8f0b27ac5c3101d3d531 | refs/heads/master | 2020-04-23T02:53:09.520089 | 2019-02-20T20:35:22 | 2019-02-20T20:35:22 | 170,859,647 | 0 | 0 | NOASSERTION | 2019-02-15T12:11:04 | 2019-02-15T12:11:04 | null | UTF-8 | C++ | false | false | 1,229 | hpp | #pragma once
#include <stdio.h>
#include <stdlib.h>
#include <vector>
#include <gtest/gtest.h>
template<typename T>
bool consistentRowLength( std::vector<std::vector<T> > &a )
{
size_t n = a.size();
size_t rowLength = a[0].size();
for( size_t i = 0; i<n; ++i )
{
if( rowLength != a[i].size() )
return false;
}
return true;
}
template<typename T>
bool sameDim( std::vector<std::vector<T> > &a, std::vector<std::vector<T> > &b )
{
if(!consistentRowLength(a)) return false;
if(!consistentRowLength(b)) return false;
return (a.size() == b.size()) && (a[0].size() == b[0].size());
}
template<typename T>
void Vector_FLOAT_EQ( std::vector<T> const &a, std::vector<T> const &b )
{
EXPECT_EQ( a.size(), b.size() );
for( int i = 0; i<a.size(); ++i )
{
EXPECT_FLOAT_EQ( a[i], b[i]);
}
}
template<typename T>
void Matrix_FLOAT_EQ( std::vector<std::vector<T> > const &a, std::vector<std::vector<T> > const &b )
{
EXPECT_EQ( consistentRowLength( a ), true );
EXPECT_EQ( consistentRowLength( b ), true );
EXPECT_EQ( a.size(), b.size() );
EXPECT_EQ( a[0].size(), b[0].size() );
for( int i = 0; i<a.size(); ++i )
{
for( int j = 0; j<a[0].size(); ++j )
{
EXPECT_FLOAT_EQ( a[i][j], b[i][j]);
}
}
}
| [
"fabian@schuiki.ch"
] | fabian@schuiki.ch |
5a5352428872264607befe81ccbef9a691a83e68 | 3c827d5cf90bdf7631d9bb7b73f9764a99588960 | /static_data_member&static_member_function.cpp | 88d2a803278bd508582602c94b7106392323f966 | [] | no_license | AnkushSingh2108/OOPS | ac23f64bf12cc1cf5a681669aba616d04482299a | 04ce2e618cbfd1f50c41f001742dc2f44a3f7050 | refs/heads/main | 2023-01-21T08:01:14.527980 | 2020-12-05T04:01:21 | 2020-12-05T04:01:21 | 318,696,591 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 579 | cpp | #include<iostream>
using namespace std;
class myclass{
private:
int x;
static int count; // static data member
public:
myclass(){
count++;
}
static int getcount() // static member function
{
return count;
}
};
// initialization
int myclass :: count=0;
int main(int argc, char const *argv[])
{
cout<<"Initial count "<<myclass::getcount()<<endl;
myclass obj, obj1;
cout<<"Count after two object: "<<myclass::getcount()<<endl;
return 0;
}
| [
"noreply@github.com"
] | noreply@github.com |
a5ce486cf71238d1f925be28f320a7417f3de822 | dca653bb975528bd1b8ab2547f6ef4f48e15b7b7 | /tags/wxPy-2.8.1.1/include/wx/gtk/dc.h | a778ba23db3c0dfec6e7047f8ce170618b9c1c65 | [] | no_license | czxxjtu/wxPython-1 | 51ca2f62ff6c01722e50742d1813f4be378c0517 | 6a7473c258ea4105f44e31d140ea5c0ae6bc46d8 | refs/heads/master | 2021-01-15T12:09:59.328778 | 2015-01-05T20:55:10 | 2015-01-05T20:55:10 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,686 | h | /////////////////////////////////////////////////////////////////////////////
// Name: wx/gtk/dc.h
// Purpose:
// Author: Robert Roebling
// Id: $Id$
// Copyright: (c) 1998 Robert Roebling
// Licence: wxWindows licence
/////////////////////////////////////////////////////////////////////////////
#ifndef __GTKDCH__
#define __GTKDCH__
//-----------------------------------------------------------------------------
// constants
//-----------------------------------------------------------------------------
#ifndef MM_TEXT
#define MM_TEXT 0
#define MM_ISOTROPIC 1
#define MM_ANISOTROPIC 2
#define MM_LOMETRIC 3
#define MM_HIMETRIC 4
#define MM_TWIPS 5
#define MM_POINTS 6
#define MM_METRIC 7
#endif
//-----------------------------------------------------------------------------
// coordinates transformations
//-----------------------------------------------------------------------------
inline wxCoord wxDCBase::DeviceToLogicalX(wxCoord x) const
{
return wxRound((x - m_deviceOriginX) / m_scaleX) * m_signX + m_logicalOriginX;
}
inline wxCoord wxDCBase::DeviceToLogicalY(wxCoord y) const
{
return wxRound((y - m_deviceOriginY) / m_scaleY) * m_signY + m_logicalOriginY;
}
inline wxCoord wxDCBase::DeviceToLogicalXRel(wxCoord x) const
{
return wxRound(x / m_scaleX);
}
inline wxCoord wxDCBase::DeviceToLogicalYRel(wxCoord y) const
{
return wxRound(y / m_scaleY);
}
inline wxCoord wxDCBase::LogicalToDeviceX(wxCoord x) const
{
return wxRound((x - m_logicalOriginX) * m_scaleX) * m_signX + m_deviceOriginX;
}
inline wxCoord wxDCBase::LogicalToDeviceY(wxCoord y) const
{
return wxRound((y - m_logicalOriginY) * m_scaleY) * m_signY + m_deviceOriginY;
}
inline wxCoord wxDCBase::LogicalToDeviceXRel(wxCoord x) const
{
return wxRound(x * m_scaleX);
}
inline wxCoord wxDCBase::LogicalToDeviceYRel(wxCoord y) const
{
return wxRound(y * m_scaleY);
}
//-----------------------------------------------------------------------------
// wxDC
//-----------------------------------------------------------------------------
class WXDLLIMPEXP_CORE wxDC : public wxDCBase
{
public:
wxDC();
virtual ~wxDC() { }
#if wxUSE_PALETTE
void SetColourMap( const wxPalette& palette ) { SetPalette(palette); };
#endif // wxUSE_PALETTE
// Resolution in pixels per logical inch
virtual wxSize GetPPI() const;
virtual bool StartDoc( const wxString& WXUNUSED(message) ) { return true; }
virtual void EndDoc() { }
virtual void StartPage() { }
virtual void EndPage() { }
virtual void SetMapMode( int mode );
virtual void SetUserScale( double x, double y );
virtual void SetLogicalScale( double x, double y );
virtual void SetLogicalOrigin( wxCoord x, wxCoord y );
virtual void SetDeviceOrigin( wxCoord x, wxCoord y );
virtual void SetAxisOrientation( bool xLeftRight, bool yBottomUp );
virtual void ComputeScaleAndOrigin();
virtual GdkWindow* GetGDKWindow() const { return NULL; }
virtual wxBitmap GetSelectedBitmap() const { return wxNullBitmap; }
protected:
// implementation
// --------------
wxCoord XDEV2LOG(wxCoord x) const
{
return DeviceToLogicalX(x);
}
wxCoord XDEV2LOGREL(wxCoord x) const
{
return DeviceToLogicalXRel(x);
}
wxCoord YDEV2LOG(wxCoord y) const
{
return DeviceToLogicalY(y);
}
wxCoord YDEV2LOGREL(wxCoord y) const
{
return DeviceToLogicalYRel(y);
}
wxCoord XLOG2DEV(wxCoord x) const
{
return LogicalToDeviceX(x);
}
wxCoord XLOG2DEVREL(wxCoord x) const
{
return LogicalToDeviceXRel(x);
}
wxCoord YLOG2DEV(wxCoord y) const
{
return LogicalToDeviceY(y);
}
wxCoord YLOG2DEVREL(wxCoord y) const
{
return LogicalToDeviceYRel(y);
}
// base class pure virtuals implemented here
virtual void DoSetClippingRegion(wxCoord x, wxCoord y, wxCoord width, wxCoord height);
virtual void DoGetSizeMM(int* width, int* height) const;
public:
// GTK-specific member variables
// not sure what for, but what is a mm on a screen you don't know the size
// of?
double m_mm_to_pix_x,
m_mm_to_pix_y;
bool m_needComputeScaleX,
m_needComputeScaleY; // not yet used
private:
DECLARE_ABSTRACT_CLASS(wxDC)
};
// this must be defined when wxDC::Blit() honours the DC origian and needed to
// allow wxUniv code in univ/winuniv.cpp to work with versions of wxGTK
// 2.3.[23]
#ifndef wxHAS_WORKING_GTK_DC_BLIT
#define wxHAS_WORKING_GTK_DC_BLIT
#endif
#endif // __GTKDCH__
| [
"RD@c3d73ce0-8a6f-49c7-b76d-6d57e0e08775"
] | RD@c3d73ce0-8a6f-49c7-b76d-6d57e0e08775 |
8b1accb97e90dedb2d5f60431c1e483b76a0447e | 5012f1a7f9d746c117f04ff56f7ebe6d5fc9128f | /1.Server/2.Midware/KFPlugin/KFFtp/ftp/Definements.h | 4867767785ba9f4ed6636cdb8aea5be425df6535 | [
"Apache-2.0"
] | permissive | hw233/KFrame | c9badd576ab7c75f4e5aea2cfb3b20f6f102177f | a7e300c301225d0ba3241abcf81e871d8932f326 | refs/heads/master | 2023-05-11T07:50:30.349114 | 2019-01-25T08:20:11 | 2019-01-25T08:20:11 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,650 | h | #ifndef INC_DEFINEMENTS_H
#define INC_DEFINEMENTS_H
#include <string>
#include <set>
#include <time.h>
#include <assert.h>
#include <stdlib.h>
//#define USE_BOOST_SMART_PTR
//#define USE_STD_SMART_PTR // since C++11
#if defined(WIN32) || defined(_WIN32) || defined(__WIN32__) || defined(__TOS_WIN__)
#ifndef WIN32
#define WIN32
#endif
#elif defined(unix) || defined(__unix) || defined(__unix__)
#ifndef unix
#define unix
#endif
#define override
#endif
#ifdef WIN32
#include <winsock2.h>
#include <windows.h>
#if _MSC_VER < 1500
#define override
#endif
#else
#include <errno.h> // needed for errno
#include <string.h> // needed for strerror
#include <unistd.h>
#define Sleep sleep
typedef char* LPTSTR;
typedef const char* LPCTSTR;
typedef int BOOL;
typedef unsigned int UINT;
typedef unsigned int* PUINT;
typedef char TCHAR;
typedef const char* LPCSTR;
typedef char* LPSTR;
typedef unsigned int DWORD;
typedef unsigned short USHORT;
typedef unsigned int ULONG;
#endif
#ifndef VERIFY
#define VERIFY
#endif
#ifndef ASSERT
#define ASSERT assert
#endif
// definements for unicode support
#if defined _UNICODE || defined UNICODE
#ifndef _UNICODE
#define _UNICODE
#endif
#ifndef UNICODE
#define UNICODE
#endif
typedef std::wstring tstring;
typedef std::wostream tostream;
typedef std::wofstream tofstream;
typedef std::wostringstream tostringstream;
typedef std::wistringstream tistringstream;
typedef std::wstringstream tstringstream;
typedef std::wstreambuf tstreambuf;
#define tcin wcin
#define tcout wcout
#define tcerr wcerr
#define tclog wclog
#define tcstoul wcstoul
#define tcschr wcschr
#define tcsncmp wcsncmp
#define tisdigit iswdigit
#if _MSC_VER >= 1500
#define tsprintf(buffer, numberOfChars, format, ...) swprintf_s(buffer, numberOfChars, format, __VA_ARGS__)
#else
#define tsprintf(buffer, numberOfChars, format, ...) swprintf(buffer, format, __VA_ARGS__)
#endif
#define tcsncpy wcsncpy
#define ttol wcstol
#ifndef _T
#define _T(x) L ## x
#endif
#else
typedef std::string tstring;
typedef std::ostream tostream;
typedef std::ofstream tofstream;
typedef std::ostringstream tostringstream;
typedef std::istringstream tistringstream;
typedef std::stringstream tstringstream;
typedef std::streambuf tstreambuf;
#define tcin cin
#define tcout cout
#define tcerr cerr
#define tclog clog
#define tcstoul strtoul
#define tcschr strchr
#define tcsncmp strncmp
#define tisdigit isdigit
#if _MSC_VER >= 1500
#define tsprintf(buffer, numberOfChars, format, ...) sprintf_s(buffer, numberOfChars, format, __VA_ARGS__)
#else
#define tsprintf(buffer, numberOfChars, format, ...) sprintf(buffer, format, __VA_ARGS__)
#endif
#define tcsncpy strncpy
#define ttol strtol
#ifndef _T
#define _T
#endif
#endif
namespace nsHelper
{
#ifdef WIN32
/// Class with static functions to get information about an error.
class CError
{
public:
static DWORD GetLastError() {
return ::GetLastError();
}
static tstring GetErrorDescription( int iErrorCode = GetLastError() )
{
LPVOID lpMsgBuf = NULL;
FormatMessageA( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
NULL, iErrorCode, MAKELANGID( LANG_NEUTRAL, SUBLANG_DEFAULT ), // Default language
reinterpret_cast<LPTSTR>( &lpMsgBuf ), 0, NULL );
tstring strErrorDescription;
if ( lpMsgBuf )
{
strErrorDescription = reinterpret_cast<LPTSTR>( lpMsgBuf );
LocalFree( lpMsgBuf );
}
return strErrorDescription;
}
};
#else
/// Class with static functions to get information about an error.
class CError
{
public:
static DWORD GetLastError() {
return errno;
}
static tstring GetErrorDescription( int iErrorCode = GetLastError() )
{
return strerror( iErrorCode );
}
};
#endif
/// Class with static functions to do string conversions.
class CCnv
{
public:
static long TStringToLong( const tstring& strIn )
{
TCHAR* pStopString = 0;
#ifdef _UNICODE
return wcstol( &*strIn.begin(), &pStopString, 10 );
#else
return strtol( &*strIn.begin(), &pStopString, 10 );
#endif
}
static std::string ConvertToString( const tstring& strIn )
{
std::string strOut;
return ConvertToString( strIn, strOut );
}
static std::string& ConvertToString( const tstring& strIn, std::string& strOut )
{
#ifdef _UNICODE
if ( strIn.size() == 0 )
{
strOut.clear();
}
else
{
strOut.resize( strIn.size() );
wcstombs( &*strOut.begin(), strIn.c_str(), strOut.size() );
}
#else
strOut = strIn;
#endif
return strOut;
}
static tstring ConvertToTString( const char* szIn )
{
tstring strOut;
return ConvertToTString( szIn, strOut );
}
static tstring& ConvertToTString( const char* szIn, tstring& strOut )
{
#ifdef _UNICODE
if ( strlen( szIn ) == 0 )
{
strOut.clear();
}
else
{
strOut.resize( strlen( szIn ) );
mbstowcs( &*strOut.begin(), szIn, strOut.size() );
}
#else
strOut = szIn;
#endif
return strOut;
}
};
/// Base class for implementing the notification stuff.
/// @remarks Inherit public (instead of private) because it wouldn't compile under Dev-C++
template <typename T, typename T2>
class CObserverPatternBase : public std::set<T>
{
public:
typedef typename std::set<T> base_type;
typedef typename std::set<T>::iterator iterator;
~CObserverPatternBase()
{
for ( iterator it = base_type::begin(); it != base_type::end(); it = base_type::begin() )
( *it )->Detach( static_cast<T2>( this ) );
}
bool Attach( T p )
{
if ( this->find( p ) != base_type::end() )
return false;
this->insert( p );
p->Attach( static_cast<T2>( this ) );
return true;
}
bool Detach( T p )
{
if ( this->find( p ) == base_type::end() )
return false;
this->erase( p );
p->Detach( static_cast<T2>( this ) );
return true;
}
};
/// @brief Calculates elapsed CPU time.
/// Is useful for calculating transfer rates.
class CTimer
{
public:
CTimer() : m_dfStart( clock() ) {}
/// Restarts the timer.
void Restart() {
m_dfStart = clock();
}
/// Get the elapsed time in seconds.
double GetElapsedTime() const
{
return ( static_cast<double>( clock() ) - m_dfStart ) / CLOCKS_PER_SEC;
}
private:
double m_dfStart; ///< elapsed CPU time for process (start of measurement)
};
}
#endif // INC_DEFINEMENTS_H
| [
"lori227@qq.com"
] | lori227@qq.com |
32d6160af1f9af9c5298377006c0cd8a2b67a3fa | 6b32c1931d449204298466f48a6883b7e67f3a31 | /src/Minigames/ProjectEuler/problems/Problem94.cpp | 15dc51e7dbffcf77a51c180311e05e78c69529ef | [] | no_license | abroussard11/amb | 578783cc686532b642fa35fc3eefd424781744e9 | 279647b7d75bc9c175e31144494dec5c385af58e | refs/heads/master | 2021-01-16T21:24:20.919134 | 2015-02-02T17:20:20 | 2015-02-02T17:20:20 | 24,677,642 | 0 | 0 | null | 2014-10-06T02:26:17 | 2014-10-01T12:30:46 | C++ | UTF-8 | C++ | false | false | 417 | cpp | /*
* Problem94.cpp
*
*/
#include <string>
#include <Minigames/ProjectEuler/problems/Problem94.h>
namespace Minigames {
namespace ProjectEuler {
Problem94::Problem94()
{
// Empty
}
Problem94::~Problem94()
{
// Empty
}
std::string Problem94::getSolution()
{
std::string answer("This problem has not yet been solved");
return answer;
}
} /* namespace ProjectEuler */
} /* namespace Minigames */
| [
"abroussard11@gmail.com"
] | abroussard11@gmail.com |
0da3b0abe6e64f3966f9862948a0b37b2aa3d481 | 3dd33c9f166710c7bac46aaadaed2acd0102c41e | /src/markovChain.cpp | 0afdb2bab4206a052453737f4a27bff8b7167b5b | [] | no_license | eheinzen/elo | d473e723e1935d5368adf088da773cb1298a084b | 00286b91608eeaed8fc9cb51da1e6e8d1f3f3715 | refs/heads/master | 2023-08-22T22:00:21.412632 | 2023-08-22T17:04:26 | 2023-08-22T17:04:26 | 98,652,949 | 34 | 6 | null | 2019-12-12T16:21:07 | 2017-07-28T13:37:08 | R | UTF-8 | C++ | false | false | 1,331 | cpp | #include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::export]]
List eloMarkovChain(NumericMatrix teamA, NumericMatrix teamB, NumericVector winsA, NumericVector weightsA, NumericVector weightsB,
NumericVector weights, NumericMatrix k, int nTeams)
{
// this function uses 0-based indexing, since the incoming vectors used -1L
int nGames = winsA.size();
int ncolA = teamA.ncol(), ncolB = teamB.ncol();
NumericMatrix out(nTeams, nTeams);
NumericVector N_i(nTeams);
for(int g = 0; g < nGames; g++)
{
for(int i = 0; i < ncolA; i++)
{
for(int j = 0; j < ncolB; j++)
{
int a = teamA(g, i), b = teamB(g, j);
double w = weights[g]*weightsA[i]*weightsB[j];
N_i[a] += w;
N_i[b] += w;
double iWon = winsA[g];
// (to, from)
out(b, a) += w*(k(g, 0)*(1.0 - iWon) + (1.0 - k(g, 0))*iWon); // if j won, go to j with prob=k; else if i won, go with prob=(1-k)
out(a, b) += w*(k(g, 1)*iWon + (1.0 - k(g, 1))*(1.0 - iWon));
out(a, a) += w*(k(g, 0)*iWon + (1.0 - k(g, 0))*(1.0 - iWon));
out(b, b) += w*(k(g, 1)*(1.0 - iWon) + (1.0 - k(g, 1))*iWon);
}
}
}
for(int j = 0; j < nTeams; j++)
{
if(N_i[j] > 0.0)
{
out(_, j) = out(_, j) / N_i[j];
}
}
return List::create(out, N_i);
}
| [
"heinzen.ethan@mayo.edu"
] | heinzen.ethan@mayo.edu |
f9ffb0a3765f43a0d53a571df9bf563413b9b46c | 50b4ad814a3ce89b4836264b4510e01fe38d7a5b | /src/colaBinarios.cpp | cb6a77afaa50f10e24e109f0394cb56db825243d | [] | no_license | MarcosTort/tarea5 | 416f0d2f8dbaf0e9239ea88c48bfdba7a73939cd | 6a8ac4ee6bce6e5aca2965b513a9610a87afa9b7 | refs/heads/main | 2023-05-25T14:56:56.006572 | 2021-06-09T11:45:37 | 2021-06-09T11:45:37 | 371,979,562 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,338 | cpp | #include "../include/binario.h"
#include "../include/utils.h"
#include "../include/colaBinarios.h"
#include "stddef.h"
#include"assert.h"
// Representación de TColaBinarios'.
// Se debe definir en colaBinarios.cpp
// struct _rep_colaBinarios;
// Declaración del tipo 'TColaBinarios'
struct celda{
TBinario bin;
celda *sig;
};
struct _rep_colaBinarios {
celda *primero;
celda *ultimo;
};
/*
Devuelve una 'TColaBinarios' vacía (sin elementos).
El tiempo de ejecución en el peor caso es O(1).
*/
TColaBinarios crearColaBinarios(){
TColaBinarios nuevo = new _rep_colaBinarios;
nuevo->primero = NULL;
nuevo->ultimo = NULL;
return nuevo;
}
/*
Encola 'b' en 'c'.
Devuelve 'c'.
El tiempo de ejecución en el peor caso es O(1).
*/
TColaBinarios encolar(TBinario b, TColaBinarios c){
celda *nuevo = new celda;
nuevo->bin = b;
nuevo->sig = NULL;
if(estaVaciaColaBinarios(c)){
c->primero = c->ultimo =nuevo;
}
else{
c->ultimo->sig = nuevo;
}
c->ultimo = nuevo;
return c;
}
/*
Remueve de 'c' el elemento que está en el frente.
Si estaVaciaColaBinarios(c) no hace nada.
Devuelve 'c'.
NO libera la memoria del elemento removido.
El tiempo de ejecución en el peor caso es O(1).
*/
TColaBinarios desencolar(TColaBinarios c){
celda *aux = c->primero;
if(!estaVaciaColaBinarios(c)){
c->primero = c->primero->sig ;
if(aux->sig == NULL)
c->ultimo = NULL;
}
aux->sig = NULL;
delete aux;
return c;
}
/*
Libera la memoria asignada a 'c', pero NO la de sus elementos.
El tiempo de ejecución en el peor caso es O(n), siendo 'n' la cantidad
de elementos de 'c'.
*/
void liberarColaBinarios(TColaBinarios c){
celda *aux;
while (c->primero != NULL){
aux = c->primero;
c->primero = c->primero->sig;
delete aux;
}
delete c;
}
/*
Devuelve 'true' si y solo si 'c' es vacía (no tiene elementos).
El tiempo de ejecución en el peor caso es O(1).
*/
bool estaVaciaColaBinarios(TColaBinarios c)
{
return ((c->primero == NULL) && (c->ultimo == NULL));
}
/*
Devuelve el elemento que está en el frente de 'c'.
Precondición: ! estaVaciaColaBinarios(c);
El tiempo de ejecución en el peor caso es O(1).
*/
TBinario frente(TColaBinarios c){
assert(c->primero != NULL);
return c->primero->bin;
}
| [
"noreply@github.com"
] | noreply@github.com |
97ebd0f46b0638368b12fd74061b18f7cd490f16 | cc1e89626619c7c78298a5a2b35f9ca1bb44e12d | /src/musicmaniac/AlbumsModel.cpp | f42caaa468d86c1bc2d1b6dd22dc0eb2d2006e89 | [] | no_license | AdrienPensart/MusicManiac | 8307f47431f0e42f493aeb9468bd3004d435ad64 | 225e0234f3082c3576c4cbe33c8cfc36b352cc82 | refs/heads/master | 2021-01-21T04:27:41.184165 | 2016-06-04T15:37:15 | 2016-06-04T15:37:15 | 32,606,742 | 1 | 0 | null | 2020-09-19T04:23:01 | 2015-03-20T20:57:12 | C++ | UTF-8 | C++ | false | false | 4,851 | cpp | #include "AlbumsModel.hpp"
#include "common/Utility.hpp"
#include <QDebug>
#include <set>
AlbumsModel::AlbumsModel(QObject *parent) :
QAbstractTableModel(parent) {
}
AlbumsModel::~AlbumsModel() {
}
int AlbumsModel::rowCount(const QModelIndex& parent) const {
return parent.isValid() ? 0 : (int)items.size();
}
int AlbumsModel::columnCount(const QModelIndex& parent) const {
return parent.isValid() ? 0 : COLUMN_COUNT;
}
const Album * AlbumsModel::itemAt(int row) const {
if(row >= 0 && row < rowCount()) {
return &(items.at(row));
}
return 0;
}
Qt::ItemFlags AlbumsModel::flags(const QModelIndex &index) const {
if (!index.isValid()) {
return Qt::ItemIsEnabled;
}
/*
if(index.column() == COLUMN_KEYWORDS || index.column() == COLUMN_RATING) {
return QAbstractItemModel::flags(index) | Qt::ItemIsEditable;
}
*/
return QAbstractItemModel::flags(index);// | Qt::ItemIsEditable;
}
QVariant AlbumsModel::data(const QModelIndex& index, int role) const {
if(!index.isValid()) {
return QVariant();
}
if (index.row() >= rowCount()) {
return QVariant();
}
if(role == Qt::TextAlignmentRole) {
return int(Qt::AlignHCenter | Qt::AlignVCenter);
}
if(role == Qt::DisplayRole || role == Qt::EditRole) {
auto item = itemAt(index.row());
if(item) {
return infoAtColumn(item, index.column());
}
}
return QVariant();
}
bool AlbumsModel::setData (const QModelIndex & index, const QVariant & value, int role) {
/*
if (index.isValid() && role == Qt::EditRole) {
// "Setting data : " + value.toString().toStdString();
Playlist * rowMusic = musicAt(index.row());
if(rowMusic) {
switch(index.column()) {
case COLUMN_RATING:
rowMusic->setRating(value.toDouble());
break;
case COLUMN_KEYWORDS:
rowMusic->setKeywords(value.toString().toStdString());
break;
case COLUMN_GENRE:
rowMusic->setGenre(value.toString().toStdString());
break;
}
emit dataChanged(index, index);
return true;
}
}
*/
return false;
}
QVariant AlbumsModel::headerData(int section, Qt::Orientation orientation, int role) const {
if(role == Qt::DisplayRole && orientation == Qt::Horizontal) {
switch(section) {
case COLUMN_NAME:
return tr("Name");
break;
case COLUMN_ARTISTS:
return tr("Artists");
break;
case COLUMN_GENRES:
return tr("Genres");
break;
case COLUMN_DURATION:
return tr("Duration");
break;
case COLUMN_RATING:
return tr("Rating");
break;
case COLUMN_KEYWORDS:
return tr("Keywords");
break;
case COLUMN_SONG_COUNT:
return tr("Songs");
break;
default:
return tr("Undefined column");
}
}
return QVariant();
}
QVariant AlbumsModel::infoAtColumn(const Album * item, int column) const {
if(!item) {
return QVariant();
}
switch(column) {
case COLUMN_NAME:
return item->first.c_str();
break;
case COLUMN_ARTISTS:
{
std::set<std::string> artists;
for(const auto& song : item->second){
artists.insert(song.second->getArtist());
}
return Common::implode(artists).c_str();
}
break;
case COLUMN_GENRES:
{
std::set<std::string> genres;
for(const auto& song : item->second){
genres.insert(song.second->getGenre());
}
return Common::implode(genres).c_str();
}
break;
case COLUMN_DURATION:
{
int totalSeconds = 0;
for(const auto& song : item->second){
totalSeconds += song.second->getDurationInSeconds();
}
return secondsToString(totalSeconds).c_str();
}
break;
case COLUMN_RATING:
{
double totalRating = 0.0;
for(const auto& song : item->second){
totalRating += song.second->getRating();
}
totalRating /= (double)item->second.size();
return totalRating;
}
break;
case COLUMN_KEYWORDS:
{
std::set<std::string> keywords;
for(const auto& song : item->second){
auto songKeywords = song.second->getSplittedKeywords();
keywords.insert(songKeywords.begin(), songKeywords.end());
}
return Common::implode(keywords).c_str();
}
break;
case COLUMN_SONG_COUNT:
return (int)item->second.size();
break;
default:
return tr("Undefined");
}
return QVariant();
}
| [
"adrien.pensart@corp.ovh.ca"
] | adrien.pensart@corp.ovh.ca |
bbc3726c510af17bbcd7c86dccb6c04eda87b54e | 18533a3786d4542fd7f70f461494d0ea585171df | /src/QtUtils.h | 5a7ebc4129889565be96b6623b71dbfd0489e89f | [] | no_license | hulaishun/QtUtils | 079eace3dc16304983f0cb1aecc6fac61bb81505 | fd74d4961769b6f82b0881110de7b136c4232ae5 | refs/heads/master | 2021-01-25T10:35:43.910226 | 2018-03-01T02:00:26 | 2018-03-01T02:00:50 | 123,364,259 | 4 | 4 | null | null | null | null | UTF-8 | C++ | false | false | 145 | h | #ifndef QTUTILS_H
#define QTUTILS_H
#include "qtutils_global.h"
class QTUTILS_EXPORT QtUtils
{
public:
QtUtils();
};
#endif // QTUTILS_H
| [
"hulaishun@yiwei.com"
] | hulaishun@yiwei.com |
6ac6b3c60d79a09db561d155a56623693590024a | 4da928f16d1ca218332673dce24f7b9d694d98e2 | /PhantomSword/RawModel.cpp | fd88cc2953602b91afdd6d4e8fc8818ebb423d7f | [] | no_license | haoxiner/PhantomSword | b7c92c86120ad0a149a4c9c53b94645f2a39f01e | f7c34b477f2be7cf1007e00bfd7cad34f7224989 | refs/heads/master | 2021-01-11T01:30:21.919340 | 2016-10-14T04:04:56 | 2016-10-14T04:04:56 | 70,698,536 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 150 | cpp | #include "RawModel.h"
RawModel::RawModel(GLuint vaoID, int indicesCount)
:vaoID_(vaoID), indicesCount_(indicesCount)
{
}
RawModel::~RawModel()
{
}
| [
"haoxiner@vip.qq.com"
] | haoxiner@vip.qq.com |
66508075c5e7968d6d74068655611900335ac61f | b477c286a70bfb065170d42ccf9d2519d04f430c | /hw4b.cpp | 6ed82dcb3fb10280672e3ebd616e170798272e34 | [] | no_license | markpytel/CS5303 | 17fa674ae1c15dd34943441e50e141f48492a7ff | 150a38a094e7337294482e14ac2a67693892c3e8 | refs/heads/master | 2018-12-31T23:47:23.011074 | 2015-04-23T15:49:22 | 2015-04-23T15:49:22 | 34,465,912 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,389 | cpp |
//
// Mark Pytel
// CS5303 homework #4b
//
/*
I understand that using, receiving or giving unauthorized assistance in
writing this assignment is in violation of academic regulations and is subject to academic discipline, including a grade of 0 for this assignment with no chance of a making up the assignment, forfeiture of credit for the course, probation and dismissal from NYU.
By submitting this work I am certifying that I did not cheat!
*/
#include <iostream>
#include <math.h>
using namespace std;
int main()
{
cout.setf(ios::fixed);
cout.setf(ios::showpoint);
cout.precision(2);
char calculation = 'y';
while ((calculation == 'y') || (calculation == 'Y'))
{
int month = 0;
double goal = 0;
double monthly_deposit = 0;
double monthly_interest_rate = 0;
double balance = 0;
double interest_paid = 0;
double total_interest_paid = 0;
double final_deposit = 0;
double yearly_interest_rate_input = 0;
double yearly_interest_rate = 0;
cout << "Please enter the amount of the down payment $: ";
cin >> goal;
cout << endl;
cout << "Please enter the yearly interest rate %: ";
cin >> yearly_interest_rate_input;
yearly_interest_rate = yearly_interest_rate_input / 100;
monthly_interest_rate = yearly_interest_rate / 12;
cout << endl;
cout << "Please enter amount of the monthly payment $: ";
cin >> monthly_deposit;
cout << endl;
cout << "MONTH BALANCE PAYMENT INTEREST SHORTAGE" << endl;
cout << endl;
double shortage = goal - balance;
while ((round(balance * 100) / 100) != goal)
{
month++;
shortage = shortage - monthly_deposit - interest_paid;
cout << month << " " << balance << " " << monthly_deposit << " " << interest_paid << " " << shortage << endl;
total_interest_paid = total_interest_paid + interest_paid;
balance = balance + monthly_deposit + interest_paid;
interest_paid = balance * monthly_interest_rate;
if (shortage < (monthly_deposit + interest_paid))
{
final_deposit = shortage - interest_paid;
monthly_deposit = final_deposit;
}
}
cout << endl;
cout << "Total amount of months needed: " << month << endl;
cout << endl;
cout << "Total interest earned: " << total_interest_paid << endl;
cout << endl;
cout << "Would you like to do another calculation(Y/N)? ";
cin >> calculation;
cout << endl;
cout << endl;
}
return 0;
} | [
"markpytel@gmail.com"
] | markpytel@gmail.com |
199af7d623fade0d3082efd6b7bcbea500b24dda | 21b60622b20ed08874a606711b5a5f53ea663811 | /src/lib/ast/function-node.cc | eb6be790ca6d24ee626fcefaa4528341c89ad157 | [
"Apache-2.0"
] | permissive | edobashira/thraxwin | 93ba1f191e0b84f0939514ec62ca801f39661c0b | 78c0700650871797c5b6e6b7525d66105206fa4d | refs/heads/master | 2021-01-01T18:11:31.083316 | 2011-05-26T10:03:37 | 2011-05-26T10:03:37 | 1,803,527 | 3 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,474 | cc | // 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 2005-2011 Google, Inc.
// Author: ttai@google.com (Terry Tai)
#include <thrax/function-node.h>
#include <iostream>
#include <string>
#include <thrax/collection-node.h>
#include <thrax/identifier-node.h>
#include <thrax/walker.h>
#include <thrax/compat/stlfunctions.h>
namespace thrax {
FunctionNode::FunctionNode(IdentifierNode* name,
CollectionNode* arguments,
CollectionNode* body)
: Node(), name_(name), arguments_(arguments), body_(body) {}
FunctionNode::~FunctionNode() {
delete name_;
delete arguments_;
delete body_;
}
IdentifierNode* FunctionNode::GetName() const {
return name_;
}
CollectionNode* FunctionNode::GetArguments() const {
return arguments_;
}
CollectionNode* FunctionNode::GetBody() const {
return body_;
}
void FunctionNode::Accept(AstWalker* walker) {
walker->Visit(this);
}
} // namespace thrax
| [
"paul@edobashira.com"
] | paul@edobashira.com |
4645f71cde2405eaa39d3eb2227c2a5ccdfc00fa | 30dddfb5461138735146ddae09e94192f05937ce | /SRCS/ENTITIES/OBJECTS/Serialize.hpp | d9e88846f5fb5473cc45eb93904b825bdfdf7bbd | [
"MIT"
] | permissive | Dreinale/Bomberman_project | 496e54c6f67bedca21dfebe2ce7bed77ac41d86b | ed98d44f54906b1e3f7941b58d8e1493711f355b | refs/heads/main | 2023-06-02T23:58:40.358192 | 2021-06-25T17:20:44 | 2021-06-25T17:20:44 | 380,306,115 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 496 | hpp | /*
** EPITECH PROJECT, 2021
** serialize_hpp
** File description:
** serialize_hpp
*/
#ifndef serialize
#define serialize
#include <cstdio>
#include <iostream>
#include <fstream>
#include <cstdarg>
//#include <bits/stdc++.h>
#include <vector>
#include <string>
class Serialize {
public:
static void delete_line(const char *file_name, int n);
virtual void pack() = 0;
static bool isEmpty(std::string file);
protected:
private:
};
#endif /* !serialize_hpp */
| [
"57537430+Dreinale@users.noreply.github.com"
] | 57537430+Dreinale@users.noreply.github.com |
ac0e65f1c8b7a438cd192cd6e22a7f88d330b569 | 9aeb798920fa46790ea3dbe2c92ef147ed6705c6 | /1007/main.cpp | 9427d09343b93da13553fff5d555b1e89b899b30 | [] | no_license | syan1987/ACM-ICPC | 71107a208a126ab390b2ec95512601d2e1d6f69e | 460660a8c5eaa79c267b0f7c7bcb338438008bcb | refs/heads/master | 2020-04-09T19:29:56.206193 | 2014-11-27T03:22:49 | 2014-11-27T03:22:49 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 939 | cpp | #include <iostream>
#include <string>
using namespace std;
int measure1(string dna, int length) {
int result = 0;
for (int i = 0; i < length; i++) {
for (int j = i+1; j < length; j++) {
if (dna.at(i) > dna.at(j)) {
result++;
}
}
}
return result;
}
int main (int argc, char * const argv[]) {
int num, length;
cin >> length >> num;
string list[num];
int measure[num];
for (int i = 0; i < num; i++) {
cin >> list[i];
measure[i] = measure1(list[i], length);
}
//sort list based on measure
for (int i = 0; i < num; i++) {
int min = i;
for (int j = i + 1; j < num; j++) {
if (measure[min] > measure[j]) {
min = j;
}
}
if (min != i) {
string tmp = list[i];
list[i] = list[min];
list[min] = tmp;
int tmpint = measure[i];
measure[i] = measure[min];
measure[min] = tmpint;
}
}
//print out
for (int i = 0; i < num; i++) {
cout << list[i] << endl;
}
return 0;
}
| [
"yanshuo1987@gmail.com"
] | yanshuo1987@gmail.com |
752117c4184b622be933237160d1f90afb42b235 | c56bcde04453ba80f618042f4fd79e37e3880b57 | /include/GroupBVHTranslator.h | 89fe3f7e32b63c563239326527f250c588f4b38e | [] | no_license | jack111331/Ray | aa71a346d558b36fe13257de00cbcf75865c4ec3 | c174783f9c98ac420f934b042f918c6239281452 | refs/heads/master | 2023-06-21T00:20:04.207217 | 2021-07-08T09:04:49 | 2021-07-08T09:04:49 | 307,962,200 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,182 | h | //
// Created by Edge on 2021/1/9.
//
#ifndef RAY_GROUPBVHTRANSLATOR_H
#define RAY_GROUPBVHTRANSLATOR_H
#include "GroupObj.h"
#include "Lambertian.h"
#include "GLUtil.h"
class GroupBVHTranslator {
public:
struct Node {
Node() : boundingBoxMin(), boundingBoxMax(), lrLeaf() {}
Vec4f boundingBoxMin;
Vec4f boundingBoxMax;
Vec4i lrLeaf;
};
GroupBVHTranslator(Scene *scene) : m_group(&scene->m_group[0]), m_tlasSize(0), m_meshTable(scene->m_meshTable),
m_materialTable(scene->m_materialTable) {
int nodeCount = 0;
int totalVertices = 0;
for (auto mesh: m_meshTable) {
BLASNode *blasNode = (BLASNode *) mesh.second;
if (blasNode->getBLASNodeType() == BLASNode::BLASNodeType::TRIANGLE_GROUP) {
TriangleGroup *triangleGroup = (TriangleGroup *) mesh.second;
nodeCount += blasNode->m_accel->m_octree->m_nodeCount;
m_blasRootStartIndicesList.push_back(nodeCount);
triangleGroup->m_accel->flattenBVH(totalVertices);
m_meshRootStartIndicesList.push_back(m_flattenBVHIndices.size());
m_flattenBVHIndices.insert(m_flattenBVHIndices.end(),
triangleGroup->m_accel->m_octree->m_packedIndices.begin(),
triangleGroup->m_accel->m_octree->m_packedIndices.end());
for (auto primitive: triangleGroup->m_nodeList) {
m_flattenBVHVertices.push_back(Vec4f(primitive->m_coord, 1.0f));
m_flattenBVHNormals.push_back(Vec4f(primitive->m_normal, 0.0f));
}
totalVertices = m_flattenBVHVertices.size();
}
}
for (auto material: m_materialTable) {
m_materialList.push_back(material.second->getProperty());
m_materialIdTable[material.second] = m_materialList.size()-1;
}
traverseInitGroupFirstStage(m_group);
m_meshNodeList.resize(nodeCount);
m_blasNodeList.resize(m_meshInstanceSize);
m_tlasNodeList.resize(m_tlasSize);
int meshId = 0;
for (auto mesh: m_meshTable) {
BLASNode *blasNode = (BLASNode *) mesh.second;
if (blasNode->getBLASNodeType() == BLASNode::BLASNodeType::TRIANGLE_GROUP) {
TriangleGroup *triangleGroup = (TriangleGroup *) mesh.second;
traverseInitMeshNode(triangleGroup->m_accel->m_octree->m_root, nullptr,
m_meshRootStartIndicesList[meshId]);
meshId++;
}
}
m_transformMatList.resize(m_meshInstanceSize);
m_materialInstanceList.resize(m_meshInstanceSize);
traverseInitBLASGroupSecondStage(m_group, nullptr);
traverseInitTLASGroupSecondStage(m_group, nullptr);
m_nodeList.insert(m_nodeList.end(), m_meshNodeList.begin(), m_meshNodeList.end());
m_nodeList.insert(m_nodeList.end(), m_blasNodeList.begin(), m_blasNodeList.end());
m_nodeList.insert(m_nodeList.end(), m_tlasNodeList.begin(), m_tlasNodeList.end());
m_tlasStartNodeIndex = m_meshNodeList.size() + m_blasNodeList.size() + m_group->m_inTwoLevelBVHId;
reduceNode(m_tlasStartNodeIndex);
// TODO compress mesh and blas space
#ifdef DEBUG_FLAG
std::cout << "TLAS Start Node Index " << m_tlasStartNodeIndex << ", mesh instance size " << m_meshInstanceSize
<< " , tlas size " << m_tlasSize << std::endl;
std::cout << "flattenBVHIndices " << m_flattenBVHIndices.size() << std::endl;
for (int i = 0; i < m_flattenBVHIndices.size(); i += 3) {
std::cout << m_flattenBVHIndices[i] << " " << m_flattenBVHIndices[i + 1] << " "
<< m_flattenBVHIndices[i + 2]
<< std::endl;
}
std::cout << "node" << std::endl;
for (int i = 0; i < m_nodeList.size(); ++i) {
std::cout << "(" << m_nodeList[i].boundingBoxMin.x << ", " << m_nodeList[i].boundingBoxMin.y << ", "
<< m_nodeList[i].boundingBoxMin.z << ") (" << m_nodeList[i].boundingBoxMax.x << ", "
<< m_nodeList[i].boundingBoxMax.y << ", " << m_nodeList[i].boundingBoxMax.z << ") " << " "
<< m_nodeList[i].lrLeaf.x << " " << m_nodeList[i].lrLeaf.y << " " << m_nodeList[i].lrLeaf.z
<< std::endl;
}
#endif
// initialize ssbo
RayUtil::generateStaticSSBO(m_meshIndicesSSBO, m_flattenBVHIndices.data(),
m_flattenBVHIndices.size() * sizeof(uint32_t));
RayUtil::generateDynamicSSBO(m_bvhSSBO, m_nodeList.data(), m_nodeList.size() * sizeof(Node));
RayUtil::generateStaticSSBO(m_meshVerticesSSBO, m_flattenBVHVertices.data(),
m_flattenBVHVertices.size() * sizeof(Vec4f));
RayUtil::generateStaticSSBO(m_meshNormalsSSBO, m_flattenBVHNormals.data(),
m_flattenBVHNormals.size() * sizeof(Vec4f));
RayUtil::generateDynamicSSBO(m_transformSSBO, m_transformMatList.data(),
m_transformMatList.size() * sizeof(glm::mat4));
RayUtil::generateDynamicSSBO(m_materialSSBO, m_materialList.data(), m_materialList.size() * sizeof(Material::MaterialProperty));
RayUtil::generateDynamicSSBO(m_materialInstanceSSBO, m_materialInstanceList.data(),
m_materialInstanceList.size() * sizeof(uint32_t));
// reserve all transform node and selector node, but transform will goes to concrete geometry
}
void updateTranslator() {
m_curTlas = 0;
traverseInitTLASGroupSecondStage(m_group, nullptr);
m_nodeList.resize(m_meshNodeList.size() + m_blasNodeList.size());
m_nodeList.insert(m_nodeList.end(), m_tlasNodeList.begin(), m_tlasNodeList.end());
m_tlasStartNodeIndex = m_meshNodeList.size() + m_blasNodeList.size() + m_group->m_inTwoLevelBVHId;
reduceNode(m_tlasStartNodeIndex);
RayUtil::updateSSBO(m_bvhSSBO, &m_nodeList[m_meshNodeList.size() + m_blasNodeList.size()],
(m_meshNodeList.size() + m_blasNodeList.size()) * sizeof(Node),
m_tlasNodeList.size() * sizeof(Node));
}
private:
void traverseInitGroupFirstStage(ObjectNode *node);
void traverseInitBLASGroupSecondStage(ObjectNode *node, ObjectNode *rightNode,
const glm::mat4 &transformMat = glm::mat4(1.0f));
void traverseInitTLASGroupSecondStage(ObjectNode *node, ObjectNode *rightNode);
void traverseInitMeshNode(OctreeNode *node, OctreeNode *rightNode, int meshStartIndices);
void reduceNode(int nodeIdx);
GroupObj *m_group;
int m_tlasSize = 0;
int m_meshInstanceSize = 0;
std::vector<Node> m_meshNodeList;
std::vector<Node> m_blasNodeList;
std::vector<Node> m_tlasNodeList;
// node for all 3 above nodes
std::vector<Node> m_nodeList;
// final layout is [meshNode, blasNode, tlasNode]
int m_curMesh = 0;
int m_curBlas = 0;
int m_curTlas = 0;
int m_curMeshInstance = 0;
std::vector<uint32_t> m_flattenBVHIndices;
std::vector<Vec4f> m_flattenBVHVertices;
std::vector<Vec4f> m_flattenBVHNormals;
std::vector<glm::mat4> m_transformMatList;
std::vector<uint32_t> m_materialInstanceList;
std::vector<int> m_blasRootStartIndicesList;
std::vector<int> m_meshRootStartIndicesList;
const std::map<std::string, Material *> &m_materialTable;
const std::map<std::string, ObjectNode *> &m_meshTable;
std::vector<Material::MaterialProperty> m_materialList;
std::map<Material *, int> m_materialIdTable;
public:
int m_tlasStartNodeIndex = 0;
uint32_t m_meshIndicesSSBO;
uint32_t m_meshVerticesSSBO;
uint32_t m_meshNormalsSSBO;
uint32_t m_transformSSBO;
uint32_t m_materialInstanceSSBO;
uint32_t m_bvhSSBO;
uint32_t m_materialSSBO;
};
#endif //RAY_GROUPBVHTRANSLATOR_H
| [
"jack111331@gmail.com"
] | jack111331@gmail.com |
465c1cf564950357a6b5e4568fd3839b3f5ffc55 | 551ae64e1377a43dbf72addd7cee48804e7660e4 | /src/cores/virtuanes/NES/PadEX/EXPAD_SpaceShadowGun.cpp | 99f5146ed1617a3314401928185ef3a3b2751bae | [] | no_license | xonn83/Virtuanes3DS_bottom | 03eb1e60bac4c22078725da520227b7ea2bcd706 | 7e481d9b9084a290ad68102df8d22df6daaffe0e | refs/heads/master | 2022-11-26T06:43:57.129188 | 2020-07-30T05:38:56 | 2020-07-30T05:38:56 | 279,630,073 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,424 | cpp | //////////////////////////////////////////////////////////////////////////
// Zapper //
//////////////////////////////////////////////////////////////////////////
void EXPAD_SpaceShadowGun::Reset()
{
bomb_bits = 0;
zapper_button = 0;
}
void EXPAD_SpaceShadowGun::Strobe()
{
bomb_bits = nes->pad->pad1bit & 0xFC;
bomb_bits |= zapper_button & 0x02;
}
BYTE EXPAD_SpaceShadowGun::Read4016()
{
BYTE data = (bomb_bits & 0x01)<<1;
bomb_bits >>= 1;
return data;
}
BYTE EXPAD_SpaceShadowGun::Read4017()
{
BYTE data = 0x08;
if( zapper_button & 0x01 ) {
data |= 0x10;
}
if( nes->GetZapperHit() ) {
//if( DirectDraw.GetZapperHit() >= 0xFE )
// data &= ~0x08;
}
return data;
}
void EXPAD_SpaceShadowGun::Sync()
{
nes->GetZapperPos( zapper_x, zapper_y );
zapper_button = 0;
//if( ::GetAsyncKeyState(VK_LBUTTON)&0x8000 )
// zapper_button |= 0x01;
//if( ::GetAsyncKeyState(VK_RBUTTON)&0x8000 )
// zapper_button |= 0x02;
}
void EXPAD_SpaceShadowGun::SetSyncData( INT type, LONG data )
{
if( type == 0 ) {
zapper_x = data;
} else if( type == 1 ) {
zapper_y = data;
} else if( type == 2 ) {
zapper_button = data;
}
}
LONG EXPAD_SpaceShadowGun::GetSyncData( INT type )
{
LONG data = 0;
if( type == 0 ) {
data = zapper_x;
} else if( type == 1 ) {
data = zapper_y;
} else if( type == 2 ) {
data = zapper_button;
}
return data;
}
| [
"cuentadtt@gmail.com"
] | cuentadtt@gmail.com |
49fe1927567531af61d55156d19d6fd1c0254ec0 | a5d67c07acd4c260f41e7b0207580980b3dd6264 | /每日一题/acw/ACW3814矩阵变换.cpp | 178fc52ca1e9aefced0fbe0c0abcb37ed205899b | [] | no_license | Graham-ella/leetcode | 8e48564a1addd0ac28cbe4ba5ffaf800526b8df8 | 8eeb1090bc0e38eb30b435f7acd8891a3b3bf7dd | refs/heads/main | 2023-08-13T00:54:15.581436 | 2021-09-26T12:57:40 | 2021-09-26T12:57:40 | 372,477,504 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 871 | cpp | #include <iostream>
#include <cstring>
#include <algorithm>
#include <unordered_map>
using namespace std;
/*
题干:
对于n*n的矩阵,可以选择任意列来变换
输出:这个矩阵经过变换后 全为1的行的最大数量
思路:
1、这种列的变换不会影响到行之间的相等关系
2、任意行都可以通过这种变化变成全1
意思就是说某一些行你想要把它变成全1那么和它不相等的行就不能是全1,
否则它们就是相等了
因此其实相等于就是找到出现最多次数的那一行就行 利用哈希表就行
*/
int main(){
int n;
cin >> n;
unordered_map<string,int> cnt;
while(n--){
string str;
cin >> str;
cnt[str]++;
}//统计每行出现的次数
int res = 0;
// for(auto& v:cnt) res = max(res,v.second);
for(auto& [k,v]:cnt) res = max(res,v);
cout<<res<<endl;
return 0;
} | [
"3235962608@qq.com"
] | 3235962608@qq.com |
348cba8510fbcd2ff550c2e3306c3986cadf1a4e | 417bfea5338c7bf9f36ddac28767cdfdc02a1ed3 | /libswarmio/src/swarmio/simulator/LinearPathTelemetrySimulator.cpp | fc2102dba6d4a17fe48d6caa3d81454c037b0605 | [
"Apache-2.0"
] | permissive | cpswarm/swarmio | 02f9d5e174b8c1ff22984d9538fe8fa314564cb9 | 798ae469ec48b958f9e88cf89e4f88b3f5b519fe | refs/heads/master | 2022-05-09T23:58:44.159895 | 2022-04-21T09:23:32 | 2022-04-21T09:23:32 | 173,924,826 | 7 | 1 | Apache-2.0 | 2019-11-07T11:58:34 | 2019-03-05T10:23:27 | C++ | UTF-8 | C++ | false | false | 2,114 | cpp | #include <swarmio/simulator/LinearPathTelemetrySimulator.h>
#include <swarmio/data/Variant.pb.h>
#include <swarmio/data/discovery/Schema.pb.h>
using namespace swarmio;
using namespace swarmio::simulator;
using namespace std::chrono_literals;
LinearPathTelemetrySimulator::LinearPathTelemetrySimulator(services::telemetry::Service& telemetryService, const std::string& name, SimulatedLocation firstPoint, SimulatedLocation secondPoint, std::chrono::seconds duration)
: _telemetryService(telemetryService), _firstPoint(firstPoint), _secondPoint(secondPoint), _duration(duration), _shouldStop(false), _name(name)
{
// Set schema
data::discovery::Field field;
auto& subfields = *field.mutable_schema()->mutable_fields();
subfields["longitude"].set_type(data::discovery::Type::DOUBLE);
subfields["latitude"].set_type(data::discovery::Type::DOUBLE);
subfields["altitude"].set_type(data::discovery::Type::DOUBLE);
telemetryService.SetFieldDefinitionForKey(name, field, false);
// Start thread
_thread = std::make_unique<std::thread>(&LinearPathTelemetrySimulator::Worker, this);
}
void LinearPathTelemetrySimulator::Worker()
{
uint64_t unit = _duration.count() * 20;
uint64_t cycle = 0;
while(!_shouldStop)
{
// Calculate current stage
double stage = (cycle % unit) / (double)unit * 2.0;
if (stage > 1.0)
{
stage = 2.0 - stage;
}
// Build value
data::Variant value;
auto& pairs = *value.mutable_map_value()->mutable_pairs();
pairs["longitude"].set_double_value(_firstPoint.GetLongitude() + (_secondPoint.GetLongitude() - _firstPoint.GetLongitude()) * stage);
pairs["latitude"].set_double_value(_firstPoint.GetLatitude() + (_secondPoint.GetLatitude() - _firstPoint.GetLatitude()) * stage);
pairs["altitude"].set_double_value(_firstPoint.GetAltitude() + (_secondPoint.GetAltitude() - _firstPoint.GetAltitude()) * stage);
_telemetryService.SetValue(_name, value);
// Next cycle
++cycle;
std::this_thread::sleep_for(100ms);
}
} | [
"balint.janvari@search-lab.hu"
] | balint.janvari@search-lab.hu |
2577902df033bfd222ff8dcaff5c0eb2a72d55a7 | a769ee0f50f74d3637a5554e68a44795d54100a6 | /ASAP/navigation2/navigation.h | 9b34dade0742169cedb0adaf5dd1cff25a2fb2f1 | [] | no_license | tapasjain/oga-uct | 7b2e62b1ff7a6acb5827e5cdb69f4316ec464e28 | 03e8a0062f8f4ccd4203b23f68e0401f5b005a20 | refs/heads/master | 2020-09-07T10:03:35.807907 | 2016-04-30T13:45:50 | 2016-04-30T13:45:50 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,255 | h | #include <iostream>
#include <iomanip>
#include <strings.h>
#define DISCOUNT 1
#define ROWS 3
#define COLUMNS 5
#define INIX 4
#define INIY 0
#define FINALX 4
#define FINALY 2
class state_t {
short x_;
short y_;
public:
state_t(short x = INIX, short y = INIY)
: x_(x), y_(y) { }
state_t(const state_t &s)
: x_(s.x_), y_(s.y_) { }
~state_t() { }
size_t hash() const {
return (x_ << (8*sizeof(short))) | (y_);
}
bool in_grid(short rows, short cols) const {
return (x_ >= 0) && (x_ < COLUMNS) && (y_ >= 0) && (y_ < ROWS);
}
std::pair<int, int> direction(Problem::action_t a) const {
switch( a ) {
case 0: return std::make_pair(0, 1);
case 1: return std::make_pair(1, 0);
case 2: return std::make_pair(0, -1);
case 3: return std::make_pair(-1, 0);
//default: return std::make_pair(-1, -1);
}
}
state_t apply(Problem::action_t a) const {
std::pair<int, int> dir = direction(a);
return state_t(x_ + dir.first, y_ + dir.second);
}
const state_t& operator=( const state_t &s) {
x_ = s.x_;
y_ = s.y_;
return *this;
}
bool operator==(const state_t &s) const {
return (x_ == s.x_) && (y_ == s.y_) ;
}
bool operator!=(const state_t &s) const {
return (x_ != s.x_) || (y_ != s.y_) ;
}
bool operator<(const state_t &s) const {
return (x_ < s.x_) ||
((x_ == s.x_) && (y_ < s.y_));
}
void print(std::ostream &os) const {
os << "(" << x_ << "," << y_ << ")";
}
friend class problem_t;
};
inline std::ostream& operator<<(std::ostream &os, const state_t &s) {
s.print(os);
return os;
}
class problem_t : public Problem::problem_t<state_t> {
int rows_;
int cols_;
float disappearance_prob_[ROWS*COLUMNS];
state_t init_;
state_t goal_;
static const float default_disappearance_prob_[];
public:
problem_t(int rows, int cols,
int init_x = INIX, int init_y = INIY,
int goal_x = std::numeric_limits<int>::max(),
int goal_y = std::numeric_limits<int>::max())
: Problem::problem_t<state_t>(DISCOUNT),
rows_(rows), cols_(cols), init_(init_x, init_y), goal_(goal_x, goal_y) {
if( (goal_x == std::numeric_limits<int>::max()) ||
(goal_y == std::numeric_limits<int>::max()) ) {
goal_.x_ =FINALX;
goal_.y_=FINALY; //state_t(rows - 1, cols - 1);
}
bcopy(default_disappearance_prob_, disappearance_prob_, ROWS*COLUMNS * sizeof(float));
}
virtual ~problem_t() { }
virtual Problem::action_t number_actions(const state_t &s) const { return 4; }
virtual const state_t& init() const { return init_; }
virtual bool terminal(const state_t &s) const {
return (s.x_ == goal_.x_) && (s.y_ == goal_.y_);
}
virtual bool dead_end(const state_t &s) const { return false; }
virtual bool applicable(const state_t &s, ::Problem::action_t a) const {
return s.apply(a).in_grid(ROWS, COLUMNS);
}
virtual float cost(const state_t &s, Problem::action_t a) const {
return terminal(s.apply(a)) ? 0 : 1;
}
virtual float calculate_transition(const state_t s1, const state_t s2, Problem::action_t a) const {
state_t next_s = s1.apply(a);
float p = disappearance_prob_[next_s.y_*COLUMNS+next_s.x_];
if(s2 == init_)
{
if(next_s == init_)
return 1.0;
else
return p;
}
else
{
if(s2 == next_s)
return (1-p);
else
return 0;
}
}
virtual void sample_factored( const state_t &s, Problem::action_t a, state_t &next_state) const {
std::vector<std::pair<state_t, float>> outcomes;
next(s, a, outcomes);
float r = Random::real();
for(unsigned i = 0; i < outcomes.size(); ++i)
{
if(r <= outcomes[i].second)
{
next_state = outcomes[i].first;
break;
}
else
{
r = r - outcomes[i].second;
}
}
}
virtual void next(const state_t &s, Problem::action_t a, std::vector<std::pair<state_t,float> > &outcomes) const {
++expansions_;
outcomes.clear();
outcomes.reserve(2);
state_t next_s = s.apply(a);
assert(next_s.in_grid(rows_, cols_));
float p=disappearance_prob_[next_s.y_*COLUMNS+next_s.x_];
outcomes.push_back(std::make_pair(next_s,1-p));
outcomes.push_back(std::make_pair(init_,p));
}
virtual void print(std::ostream &os) const { }
};
const float problem_t::default_disappearance_prob_[] = {
// 0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,
// 0.1,0.1,0.2,0.2,0.2,0.3,0.3,0.4,0.4,0.5,0.5,0.5,0.6,0.7,0.7,0.7,0.8,0.3,0.9,0.9,
// 0.1,0.1,0.1,0.2,0.2,0.3,0.3,0.4,0.4,0.5,0.5,0.6,0.6,0.6,0.7,0.7,0.7,0.3,0.9,0.9,
// 0.1,0.1,0.1,0.2,0.2,0.3,0.3,0.4,0.4,0.5,0.5,0.6,0.6,0.7,0.7,0.7,0.8,0.3,0.9,0.9,
// 0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0
0.0,0.0,0.0,0.0,0.0,
0.04,0.24,0.49,0.70,0.92,
0.0,0.0,0.0,0.0,0.0
};
// const float problem_t::default_disappearance_prob_[] = {
// 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,
// 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,
// 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,
// 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,
// 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,
// };
// const float problem_t::default_disappearance_prob_[] = {
// 0.0,0.0,0.0,0.0,
// 0.5,0.3,0.6,0.9,
// 0.0,0.0,0.0,0.0
// };
inline std::ostream& operator<<(std::ostream &os, const problem_t &p) {
p.print(os);
return os;
}
class scaled_heuristic_t : public Heuristic::heuristic_t<state_t> {
const Heuristic::heuristic_t<state_t> *h_;
float multiplier_;
public:
scaled_heuristic_t(const Heuristic::heuristic_t<state_t> *h, float multiplier = 1.0)
: h_(h), multiplier_(multiplier) { }
virtual ~scaled_heuristic_t() { }
virtual float value(const state_t &s) const {
return h_->value(s) * multiplier_;
}
virtual void reset_stats() const { }
virtual float setup_time() const { return 0; }
virtual float eval_time() const { return 0; }
virtual size_t size() const { return 0; }
virtual void dump(std::ostream &os) const { }
float operator()(const state_t &s) const { return value(s); }
};
class zero_heuristic_t: public Heuristic::heuristic_t<state_t> {
public:
zero_heuristic_t() { }
virtual ~zero_heuristic_t() { }
virtual float value(const state_t &s) const { return 0; }
virtual void reset_stats() const { }
virtual float setup_time() const { return 0; }
virtual float eval_time() const { return 0; }
virtual size_t size() const { return 0; }
virtual void dump(std::ostream &os) const { }
float operator()(const state_t &s) const { return value(s); }
};
| [
"ankit.s.anand@gmail.com"
] | ankit.s.anand@gmail.com |
ffb476f5e1791a876a35c043205cacdcc1c6f5be | f556301fd9bdba0e463bb6f08bd83db0fd258a8d | /extensions/gen/mojo/public/cpp/bindings/tests/struct_headers_unittest.test-mojom-shared-message-ids.h | bde8895fd32f35c0496bd266a2adc0bef9f2a765 | [
"LicenseRef-scancode-unknown-license-reference",
"BSD-3-Clause"
] | permissive | blockspacer/chromium_base_conan | ce7c0825b6a62c2c1272ccab5e31f15d316aa9ac | 726d2a446eb926f694e04ab166c0bbfdb40850f2 | refs/heads/master | 2022-09-14T17:13:27.992790 | 2022-08-24T11:04:58 | 2022-08-24T11:04:58 | 225,695,691 | 18 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 873 | h | // mojo/public/cpp/bindings/tests/struct_headers_unittest.test-mojom-shared-message-ids.h is auto generated by mojom_bindings_generator.py, do not edit
// Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef MOJO_PUBLIC_CPP_BINDINGS_TESTS_STRUCT_HEADERS_UNITTEST_TEST_MOJOM_SHARED_MESSAGE_IDS_H_
#define MOJO_PUBLIC_CPP_BINDINGS_TESTS_STRUCT_HEADERS_UNITTEST_TEST_MOJOM_SHARED_MESSAGE_IDS_H_
#include <stdint.h>
namespace mojo {
namespace test {
namespace struct_headers_unittest {
namespace mojom {
namespace internal {
} // namespace internal
} // namespace mojom
} // namespace struct_headers_unittest
} // namespace test
} // namespace mojo
#endif // MOJO_PUBLIC_CPP_BINDINGS_TESTS_STRUCT_HEADERS_UNITTEST_TEST_MOJOM_SHARED_MESSAGE_IDS_H_ | [
"user@email.ru"
] | user@email.ru |
5f8ec232031a017c9e179aacf198ec26744dcf67 | 86dae49990a297d199ea2c8e47cb61336b1ca81e | /c/杂项/辗转相除法-递归.cpp | aa9b153cbce572c85bb5e9cfcf67d3577e63a88a | [] | no_license | yingziyu-llt/OI | 7cc88f6537df0675b60718da73b8407bdaeb5f90 | c8030807fe46b27e431687d5ff050f2f74616bc0 | refs/heads/main | 2023-04-04T03:59:22.255818 | 2021-04-11T10:15:03 | 2021-04-11T10:15:03 | 354,771,118 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 216 | cpp | #include<stdio.h>
int gcd(int n,int m)
{
int r=n%m;
if(r==0)
return m;
else
return gcd(m,r);
}
int main()
{
int m,n,ans;
scanf("%d %d",&n,&m);
ans=gcd(n,m);
printf("%d",ans);
return 0;
}
| [
"linletian1@sina.com"
] | linletian1@sina.com |
d1dfd0dd65061dfaf40b626ee8244e0f50bab59c | b3bb502d2cf0d899d8f592eda831e33324c3bb1b | /dan/myframe.cpp | 2807e0a28e6f17b4b308a1e082b707e7b2858ae8 | [] | no_license | rpzhu/Qt-Opencv | 276ac730b143d2f42553ef946797d598c2ad164a | 8b00990d72587175c6fd0dde583a53ae62978f04 | refs/heads/master | 2020-04-14T10:35:07.274974 | 2019-01-02T06:01:18 | 2019-01-02T06:01:18 | 163,790,978 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,964 | cpp | #include "myframe.h"
#include <QPainter>
#include <QTimerEvent>
#include <QDebug>
#include <QRect>
#include <QImage>
#include <QColor>
#include <QDebug>
#include <QSize>
#include <QRegion>
#include "shoudongceshi.h"
#include <QImageReader>
#include <QCursor>
extern QImage * get_image;
//volatile float bei = 1;
extern volatile int function;
myframe::myframe(QWidget *parent)
: QLabel(parent),rec_scare_times(0)
{
scale = 1;
rec_scale = 1;
memset(rec_points,0,sizeof(rec_points));
memset(a,0,sizeof(a));
b.clear();
//m_points.clear();
Polygon_points.clear();
opencv_points.clear();
c.clear();
rec_index = 0;
movex = 0;
movey = 0;
m_pressflag = false;
isPolygonScreenShot = false;
isRecScreenShot = false;
isOk = false;
// m_picture.fromImage(*get_image);
this->setPixmap(m_picture);
m_picture.load("./temp.png");//注意从文件浏览器复制粘贴的路径为反斜杠,改成正斜扛
//img = imread("C:/Users/zhu/Desktop/20161213100118.png",1);
width = m_picture.width();//获得画布宽度
height = m_picture.height();//获得画布高度。
qDebug()<<width;
this->setMinimumWidth(width);
this->setMinimumHeight(height);
}
myframe::~myframe()
{
//m_points.clear();
Polygon_points.clear();
// opencv_points.clear();
memset(rec_points,0,sizeof(rec_points));
b.clear();
}
void myframe::paintEvent ( QPaintEvent * event )
{
this->setMinimumWidth(width*scale);
this->setMinimumHeight(height*scale);
QPainter painter(this);
Mat temp1(width*scale, height*scale, CV_8U, Scalar(0));
imgmask = temp1;
m_picture = m_picture.scaled(QSize(width*scale,height*scale));
//将图片的宽和高都扩大两倍,并且在给定的矩形内保持宽高的比值
// m_picture.save("C:/Users/zhu/Desktop/b.png");
QBrush brush(Qt::white);
painter.setBackground(brush);
painter.drawPixmap(0,0,m_picture);
QPen pen(Qt::red, 1);
painter.setPen(pen);
if(isRecScreenShot)
{
painter.drawPoint(rec_points[0]);
painter.drawPoint(rec_points[1]);
QRect selecter(rec_points[0],rec_points[1]);
painter.drawRect(selecter);
area = selecter;
}
if(isPolygonScreenShot)
{
QPen pen(Qt::red, 1);
painter.setPen(pen);
m_polygon = QPolygon(Polygon_points);
painter.drawPoints(Polygon_points);
painter.drawPolygon(m_polygon);
if(isOk)
{
QPixmap ok_picture = m_picture;
QPainter p(&ok_picture);
QRect full(0,0,ok_picture.width(),ok_picture.height());
// p.setBrush(QColor(255,255,255,255));
p.setBrush(QColor(0,0,0,130));
p.setClipRegion(QRegion(full)-QRegion(m_polygon));
p.drawRect(full);
p.end();
int xmax, xmin, ymax, ymin;
bool x = MaxMinx(m_polygon, &xmax, &xmin);
bool y = MaxMiny(m_polygon, &ymax, &ymin) ;
qDebug()<<xmin<<","<< xmax<<","<< ymin<<","<<ymax;
QRect ok_polygon(QPoint(xmin,ymin),QPoint(xmax,ymax));
QPixmap pp;
pp = ok_picture.copy(ok_polygon);
//////////////////////////////////////////////////
pp = pp.scaled(QSize(pp.width()/scale,pp.height()/scale));
///////////////////////////////////////
pp.save("./a.png");
//p.setBrush(QColor(255,255,255,255));
isOk = false;
//qDebug()<<"多边形";
update();
}
}
}
void myframe::mouseMoveEvent ( QMouseEvent * event )
{
if(m_pressflag)
{
QPoint pos = event->pos();
endpos = pos;
m_curpos = pos;
//m_points.append(pos);
// update();
}
if(function == 1)
{
x_offset = startpos.x()-endpos.x();
y_offset = startpos.y()-endpos.y();
emit dragSignal(x_offset,y_offset);
}
if(function == 3)
{
if(isPolygonScreenShot)
{
}
}
QWidget::mouseMoveEvent(event);
}
void myframe::mousePressEvent ( QMouseEvent * event )
{
m_pressflag = true ;
if(function == 1)
{
this->setCursor(Qt::ClosedHandCursor);
}
startpos = event->pos();
endpos = event->pos();
int x = startpos.x();
int y = startpos.y();
if(function == 3 && event->button()==Qt::LeftButton)
{
current_scale = scale;
isRecScreenShot = false;
Polygon_points.append(startpos);
b = Polygon_points;
isPolygonScreenShot = true;
//opencv_points.append(Point(x,y));
opencv_points.resize(Polygon_points.size());
opencv_points[0].push_back(Point(x,y));
c.clear();
c = opencv_points;
update();
}
if(function == 2 && event->button()==Qt::LeftButton)
{
isPolygonScreenShot = false;
current_scale = scale;
if(rec_index == 1)
{
isRecScreenShot = true;
}
if(rec_index == 2)
{
memset(rec_points,0,sizeof(rec_points));
rec_index = 0;
}
rec_points[rec_index] = startpos;
if(rec_index == 1)
{
a[0]= rec_points[0];
a[1]= rec_points[1];
update();
}
rec_index++;
}
// m_points.clear();//清空数组
}
void myframe::mouseReleaseEvent ( QMouseEvent * event )
{
endpos = event->pos();
if(function == 2)
{
QRect selecter (startpos,endpos);//不用等号。此为构建函数。
// area = selecter;
}
m_pressflag = false ;
if(function == 1)
{
this->setCursor(Qt::OpenHandCursor);
}
if(function == 3)
{
m_region = QRegion(m_polygon);
}
if(event->button()==Qt::RightButton)
{
// function = 0;
isRecScreenShot = false;
isPolygonScreenShot = false;
isOk = false;
rec_scare_times = 0;
rec_scale = 1;
qDebug()<<"hello ````"<<endl;
if(Polygon_points.size() != 0)
{
Polygon_points.clear();
opencv_points.clear();
c.clear();
b.clear();
}
memset(rec_points,0,sizeof(rec_points));
memset(a,0,sizeof(a));
update();
}
}
bool myframe::MaxMinx(QVector <QPoint> array, int* xmax, int* xmin)
{
if (array.size() < 1) {
return false;
}
*xmax = array[0].x();
*xmin = array[0].x();
size_t array_size = array.size();
for (int i = 1; i < array_size; ++i) {
if (array[i].x() > *xmax) {
*xmax = array[i].x();
} else if (array[i].x() < *xmin) {
*xmin = array[i].x();
}
}
return true;
}
bool myframe::MaxMiny(QVector<QPoint> array, int *ymax, int *ymin)
{
if (array.size() < 1) {
return false;
}
*ymax = array[0].y();
*ymin = array[0].y();
size_t array_size = array.size();
for (int i = 1; i < array_size; ++i) {
if (array[i].y() > *ymax) {
*ymax = array[i].y();
} else if (array[i].y() < *ymin) {
*ymin = array[i].y();
}
}
return true;
}
void myframe::PaintRecSlot()
{
function = 2;
// if(!(m_points.isEmpty()))
// {
// m_points.clear();
// }
//update();
}
void myframe::PaintPolygonSlot()
{
function = 3;
// if(!(Polygon_points.isEmpty()))
// {
// Polygon_points.clear();
// }
}
void myframe::ZoomInSlot()
{
scale = scale +0.25;
qDebug()<<scale;
if(isRecScreenShot)
{
rec_scale = rec_scale + 0.25;
qDebug()<<rec_scale;
rec_points[0] = (a[0]/current_scale)*((1)*scale);
rec_points[1] = (a[1]/current_scale)*((1)*scale);
}
if(isPolygonScreenShot)
{
for(int polygon_index = 0 ;polygon_index<Polygon_points.size();polygon_index++)
{
Polygon_points[polygon_index] = (b[polygon_index]/current_scale)*scale;
// opencv_points[0][polygon_index].x = (c[0][polygon_index].x/current_scale)*scale;
// opencv_points[0][polygon_index].y = (c[0][polygon_index].y/current_scale)*scale;
pt[0][polygon_index] = Point((c[0][polygon_index].x/current_scale)*scale,(c[0][polygon_index].y/current_scale)*scale);
ppt[0] = {pt[0]};
npt[0] = {Polygon_points.size()};
}
Scalar color = Scalar(255,255,255);
fillPoly(imgmask, ppt, npt, 1, color);
// imshow("te",imgmask);
// Mat r;
// QImage a("C:/Users/zhu/Desktop/b.png");
// img = QImage2Mat(a);
//// // bitwise_and(img, imgmask, r);
//// imshow("Bit_and", r);
// img.copyTo(r , imgmask);
// p1 [0]= &opencv_points[0];
// int a = Polygon_points.size();
// Point b[1][a];
// const Point* ppt[1] = {opencv_points[0]};
// //int a = Polygon_points.size();
// npt[0] = {a};
}
//bei = scale;
m_picture.load("./temp.png");//必须重载,不然图片会失真。
update();
}
void myframe::ZoomOutSlot()
{
qDebug()<<"suoxiao";
scale = scale - 0.25;
//bei = scale;
m_picture.load("./temp.png");;
if(isRecScreenShot)
{
rec_scale = rec_scale - 0.25;
rec_points[0] = (a[0]/current_scale)*((1)*scale);
rec_points[1] = (a[1]/current_scale)*((1)*scale);
}
if(isPolygonScreenShot)
{
for(int polygon_index = 0 ;polygon_index<Polygon_points.size();polygon_index++)
{
Polygon_points[polygon_index] = (b[polygon_index]/current_scale)*scale;
}
}
update();
}
void myframe::okSlot()
{
qDebug()<<"ok";
if(isRecScreenShot)
{
p=m_picture.copy(area);
/////////////////////////////////////////////////////
p = p.scaled(QSize(p.width()/scale,p.height()/scale));
////////////////////////////////////////////
p.save("./a.png");
}
if(isPolygonScreenShot)
{
isOk = true;
// QPixmap p = m_picture;
update();
}
}
//QImage myframe::Mat2QImage(const Mat &src)
//{
// cv::Mat temp; // make the same cv::Mat
// cvtColor(src, temp,CV_BGR2RGB); // cvtColor Makes a copt, that what i need
// QImage dest((const uchar *) temp.data, temp.cols, temp.rows, temp.step, QImage::Format_RGB888);
// dest.bits(); // enforce deep copy, see documentation
// // of QImage::QImage ( const uchar * data, int width, int height, Format format )
// return dest;
//}
//Mat myframe::QImage2Mat(const QImage &src)
//{
// cv::Mat tmp(src.height(),src.width(),CV_8U,(uchar*)src.bits(),src.bytesPerLine());
// cv::Mat result; // deep copy just in case (my lack of knowledge with open cv)
// cvtColor(tmp, result,CV_RGB2BGR);
// return result;
//}
| [
"872207648@qq.com"
] | 872207648@qq.com |
674c2f743caec4e1dd167b5c7dc0475fb4af9294 | dadaa057480479e3796063c7f0ee03b5d7775642 | /2. FirstSteps/20311018/circle/circle.cpp | 74f66c78accd38bb642ec69c1bcd48d6b2ff8fb7 | [
"MIT"
] | permissive | Mitaka01-eng/CS104 | 8c5f45cd70098d5f06764c022bc03eca52217250 | 5281b1519e0cf41f314003112a811747a2143bd4 | refs/heads/main | 2023-03-27T18:14:17.934925 | 2021-03-30T16:08:47 | 2021-03-30T16:08:47 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 300 | cpp | #include<iostream>
#include<cmath>
using namespace std;
int main()
{
float r, p, s;
float PI = acos(-1.0); // 3.14
cout << "r=";
cin >> r;
p = 2 * PI * r;
s = PI * pow(r, 2);
cout << "p=" << p << endl;
cout << "s=" << s << endl;
return 0;
} | [
"noreply@github.com"
] | noreply@github.com |
dfdab8e2c2e0c488ef33842e502fa26f6aae5692 | ffff723a6c8527b45299a7e6aec3044c9b00e923 | /PS/BOJ/1010/1010.cc | ad7abfdccbd6dd5f92e0969eb2559494262387d3 | [] | no_license | JSYoo5B/TIL | 8e3395a106656e090eeb0260fa0b0dba985d3beb | 3f9ce4c65451512cfa2279625e44a844d476b68f | refs/heads/master | 2022-03-14T09:15:59.828223 | 2022-02-26T01:30:41 | 2022-02-26T01:30:41 | 231,383,838 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 385 | cc | #include <iostream>
using namespace std;
long long combination(int object, int sample) {
long long result = 1;
for (int i = 1; i <= sample; i++) {
result *= (object - i + 1);
result /= i;
}
return result;
}
int main(void) {
int cases;
cin >> cases;
for (int i = 0; i < cases; i++) {
int west, east;
cin >> west >> east;
cout << combination(east, west) << '\n';
}
} | [
"jsyoo5b@gmail.com"
] | jsyoo5b@gmail.com |
3c0e8a8f97c6310aa98aaec0ba8316617ea8b66d | dc2e0d49f99951bc40e323fb92ea4ddd5d9644a0 | /SDK/ThirdLibrary/include/activemq-cpp/decaf/util/LinkedList.cpp | bd566a01d826410c8a88a00390abb80ba80b7768 | [] | no_license | wenyu826/CecilySolution | 8696290d1723fdfe6e41ce63e07c7c25a9295ded | 14c4ba9adbb937d0ae236040b2752e2c7337b048 | refs/heads/master | 2020-07-03T06:26:07.875201 | 2016-11-19T07:04:29 | 2016-11-19T07:04:29 | 74,192,785 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 847 | cpp | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "LinkedList.h"
| [
"626955115@qq.com"
] | 626955115@qq.com |
85b0d2ef8c53297997ede2ab68648781a09b6778 | 5ebd5cee801215bc3302fca26dbe534e6992c086 | /blazetest/src/mathtest/dvecsvecinner/VHaVCa.cpp | 31773d9043885881fc0a7289a84688504fc70754 | [
"BSD-3-Clause"
] | permissive | mhochsteger/blaze | c66d8cf179deeab4f5bd692001cc917fe23e1811 | fd397e60717c4870d942055496d5b484beac9f1a | refs/heads/master | 2020-09-17T01:56:48.483627 | 2019-11-20T05:40:29 | 2019-11-20T05:41:35 | 223,951,030 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,074 | cpp | //=================================================================================================
/*!
// \file src/mathtest/dvecsvecinner/VHaVCa.cpp
// \brief Source file for the VHaVCa dense vector/sparse vector inner product math test
//
// Copyright (C) 2012-2019 Klaus Iglberger - All Rights Reserved
//
// This file is part of the Blaze library. You can redistribute it and/or modify it under
// the terms of the New (Revised) BSD License. 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 names of the Blaze development group 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.
*/
//=================================================================================================
//*************************************************************************************************
// Includes
//*************************************************************************************************
#include <cstdlib>
#include <iostream>
#include <blaze/math/CompressedVector.h>
#include <blaze/math/HybridVector.h>
#include <blazetest/mathtest/Creator.h>
#include <blazetest/mathtest/dvecsvecinner/OperationTest.h>
#include <blazetest/system/MathTest.h>
#ifdef BLAZE_USE_HPX_THREADS
# include <hpx/hpx_main.hpp>
#endif
//=================================================================================================
//
// MAIN FUNCTION
//
//=================================================================================================
//*************************************************************************************************
int main()
{
std::cout << " Running 'VHaVCa'..." << std::endl;
using blazetest::mathtest::TypeA;
try
{
// Vector type definitions
using VHa = blaze::HybridVector<TypeA,128UL>;
using VCa = blaze::CompressedVector<TypeA>;
// Creator type definitions
using CVHa = blazetest::Creator<VHa>;
using CVCa = blazetest::Creator<VCa>;
// Running tests with small vectors
for( size_t i=0UL; i<=6UL; ++i ) {
for( size_t j=0UL; j<=i; ++j ) {
RUN_DVECSVECINNER_OPERATION_TEST( CVHa( i ), CVCa( i, j ) );
}
}
// Running tests with large vectors
RUN_DVECSVECINNER_OPERATION_TEST( CVHa( 127UL ), CVCa( 127UL, 13UL ) );
RUN_DVECSVECINNER_OPERATION_TEST( CVHa( 128UL ), CVCa( 128UL, 16UL ) );
}
catch( std::exception& ex ) {
std::cerr << "\n\n ERROR DETECTED during dense vector/sparse vector inner product:\n"
<< ex.what() << "\n";
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
//*************************************************************************************************
| [
"klaus.iglberger@gmail.com"
] | klaus.iglberger@gmail.com |
0dbf24b9be450f8bca48551dafb8213d5894d7a4 | 27fceff05ded45465dbbba658a2cc5079f30130b | /extern/TGUI-0.7.8/src/TGUI/Global.cpp | 8094779c947ad5133141c9a3b22caddf224e6811 | [
"MIT",
"Zlib"
] | permissive | towzeur/PLT_2021 | 8e053517a6973a5dd6407adbe58937592b01d1ad | c2598b387929f76ec8766e4e4741efc1a0c0379d | refs/heads/master | 2023-02-21T19:18:58.960318 | 2021-01-29T03:06:45 | 2021-01-29T03:06:45 | 297,877,100 | 4 | 2 | MIT | 2021-01-29T03:06:46 | 2020-09-23T06:39:47 | C++ | UTF-8 | C++ | false | false | 9,227 | cpp | /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// TGUI - Texus's Graphical User Interface
// Copyright (C) 2012-2017 Bruno Van de Velde (vdv_b@tgui.eu)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it freely,
// subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented;
// you must not claim that you wrote the original software.
// If you use this software in a product, an acknowledgment
// in the product documentation would be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such,
// and must not be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source distribution.
//
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#include <TGUI/Global.hpp>
#include <TGUI/Clipboard.hpp>
#include <TGUI/Texture.hpp>
#include <TGUI/Loading/Deserializer.hpp>
#include <functional>
#include <cctype>
#include <cmath>
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
namespace tgui
{
Clipboard TGUI_Clipboard;
bool TGUI_TabKeyUsageEnabled = true;
std::string TGUI_ResourcePath = "";
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void enableTabKeyUsage()
{
TGUI_TabKeyUsageEnabled = true;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void disableTabKeyUsage()
{
TGUI_TabKeyUsageEnabled = false;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void setResourcePath(const std::string& path)
{
TGUI_ResourcePath = path;
if (!TGUI_ResourcePath.empty())
{
if (TGUI_ResourcePath[TGUI_ResourcePath.length()-1] != '/')
TGUI_ResourcePath.push_back('/');
}
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
const std::string& getResourcePath()
{
return TGUI_ResourcePath;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
bool compareFloats(float x, float y)
{
return (std::abs(x - y) < 0.0000001f);
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
bool isWhitespace(char character)
{
if (character == ' ' || character == '\t' || character == '\r' || character == '\n')
return true;
else
return false;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
int stoi(const std::string& value)
{
int result = 0;
std::istringstream iss(value);
iss.imbue(std::locale::classic());
iss >> result;
if (iss.fail())
result = 0;
return result;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
float stof(const std::string& value)
{
float result = 0;
std::istringstream iss(value);
iss.imbue(std::locale::classic());
iss >> result;
if (iss.fail())
result = 0;
return result;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
bool extractBoolFromString(const std::string& property, const std::string& value)
{
if ((value == "true") || (value == "True") || (value == "TRUE") || (value == "1"))
return true;
else if ((value == "false") || (value == "False") || (value == "FALSE") || (value == "0"))
return false;
else
throw Exception{"Failed to parse boolean value of property '" + property + "'."};
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
bool removeWhitespace(const std::string& line, std::string::const_iterator& c)
{
while (c != line.end())
{
if ((*c == ' ') || (*c == '\t') || (*c == '\r'))
++c;
else
return true;
}
return false;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
std::string toLower(std::string str)
{
for (std::string::iterator i = str.begin(); i != str.end(); ++i)
*i = static_cast<char>(std::tolower(*i));
return str;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
std::string trim(std::string str)
{
str.erase(str.begin(), std::find_if(str.begin(), str.end(), [](int c) { return !std::isspace(c); }));
str.erase(std::find_if(str.rbegin(), str.rend(), [](int c) { return !std::isspace(c); }).base(), str.end());
return str;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
std::vector<std::string> split(const std::string& str, char delim)
{
std::vector<std::string> tokens;
std::size_t start = 0;
std::size_t end = 0;
while ((end = str.find(delim, start)) != std::string::npos) {
tokens.push_back(str.substr(start, end - start));
start = end + 1;
}
tokens.push_back(str.substr(start));
return tokens;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
sf::Color calcColorOpacity(const sf::Color& color, float alpha)
{
if (alpha == 1)
return color;
else
return {color.r, color.g, color.b, static_cast<sf::Uint8>(color.a * alpha)};
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
float getTextVerticalCorrection(const std::shared_ptr<sf::Font>& font, unsigned int characterSize, sf::Uint32 style)
{
if (!font)
return 0;
bool bold = (style & sf::Text::Bold) != 0;
// Calculate the height of the first line (char size = everything above baseline, height + top = part below baseline)
float lineHeight = characterSize
+ font->getGlyph('g', characterSize, bold).bounds.height
+ font->getGlyph('g', characterSize, bold).bounds.top;
// Get the line spacing sfml returns
float lineSpacing = font->getLineSpacing(characterSize);
// Calculate the offset of the text
return lineHeight - lineSpacing;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
unsigned int findBestTextSize(const std::shared_ptr<sf::Font>& font, float height, int fit)
{
if (!font)
return 0;
if (height < 2)
return 1;
std::vector<unsigned int> textSizes(static_cast<std::size_t>(height));
for (unsigned int i = 0; i < static_cast<unsigned int>(height); ++i)
textSizes[i] = i + 1;
auto high = std::lower_bound(textSizes.begin(), textSizes.end(), height, [&font](unsigned int charSize, float h){ return font->getLineSpacing(charSize) < h; });
if (high == textSizes.end())
return static_cast<unsigned int>(height);
float highLineSpacing = font->getLineSpacing(*high);
if (highLineSpacing == height)
return *high;
auto low = high - 1;
float lowLineSpacing = font->getLineSpacing(*low);
if (fit < 0)
return *low;
else if (fit > 0)
return *high;
else
{
if (std::abs(height - lowLineSpacing) < std::abs(height - highLineSpacing))
return *low;
else
return *high;
}
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
| [
"towzeur@gmail.com"
] | towzeur@gmail.com |
094be4472f1e82efbfa49e3f56c9443a88fc8474 | ad273708d98b1f73b3855cc4317bca2e56456d15 | /aws-cpp-sdk-macie2/source/model/ListClassificationJobsResult.cpp | f9732fb7e8e2580734eaf151b043cc74a0d6f6f9 | [
"MIT",
"Apache-2.0",
"JSON"
] | permissive | novaquark/aws-sdk-cpp | b390f2e29f86f629f9efcf41c4990169b91f4f47 | a0969508545bec9ae2864c9e1e2bb9aff109f90c | refs/heads/master | 2022-08-28T18:28:12.742810 | 2020-05-27T15:46:18 | 2020-05-27T15:46:18 | 267,351,721 | 1 | 0 | Apache-2.0 | 2020-05-27T15:08:16 | 2020-05-27T15:08:15 | null | UTF-8 | C++ | false | false | 1,731 | cpp | /*
* 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.
*/
#include <aws/macie2/model/ListClassificationJobsResult.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <aws/core/AmazonWebServiceResult.h>
#include <aws/core/utils/StringUtils.h>
#include <aws/core/utils/UnreferencedParam.h>
#include <utility>
using namespace Aws::Macie2::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
using namespace Aws;
ListClassificationJobsResult::ListClassificationJobsResult()
{
}
ListClassificationJobsResult::ListClassificationJobsResult(const Aws::AmazonWebServiceResult<JsonValue>& result)
{
*this = result;
}
ListClassificationJobsResult& ListClassificationJobsResult::operator =(const Aws::AmazonWebServiceResult<JsonValue>& result)
{
JsonView jsonValue = result.GetPayload().View();
if(jsonValue.ValueExists("items"))
{
Array<JsonView> itemsJsonList = jsonValue.GetArray("items");
for(unsigned itemsIndex = 0; itemsIndex < itemsJsonList.GetLength(); ++itemsIndex)
{
m_items.push_back(itemsJsonList[itemsIndex].AsObject());
}
}
if(jsonValue.ValueExists("nextToken"))
{
m_nextToken = jsonValue.GetString("nextToken");
}
return *this;
}
| [
"aws-sdk-cpp-automation@github.com"
] | aws-sdk-cpp-automation@github.com |
f0cda4755fa0f6182953977fea679e972458237b | 0883d8e2e538c23697cfceef75724f3112989652 | /gfg_num_ways_with_k_sum.cpp | eae736de9d4aa737d0268fb0026c636569ca32c6 | [] | no_license | dhrubajrk/practice.geeksforgeeks.org | e47424e512c35a744ee1b0c25b683de05ea9899c | 7bad84f0db362cdf693584fb99e6d498d8259169 | refs/heads/master | 2020-12-31T01:22:37.723390 | 2016-04-12T09:03:34 | 2016-04-12T09:03:34 | 56,047,293 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 610 | cpp | #include<bits/stdc++.h>
using namespace std;
int count1,n;
int arr[11][11];
void countWays(int i,int j,int k)
{
if(k<0)
return;
if(((k==0)&&(i==n-1))&&(j==n-1))
count1++;
if(i<n-1)
countWays(i+1,j,k-arr[i+1][j]);
if(j<n-1)
countWays(i,j+1,k-arr[i][j+1]);
}
int main()
{
int t,k;
cin>>t;
while(t--)
{
cin>>k>>n;
for(int i=0;i<n;++i)
for(int j=0;j<n;++j)
cin>>arr[i][j];
count1=0;
countWays(0,0,k-arr[0][0]);
cout<<count1<<"\n";
}
return 0;
}
| [
"dhruba.jrkarmakar.apm12@itbhu.ac.in"
] | dhruba.jrkarmakar.apm12@itbhu.ac.in |
ca67605eb0500e7e821c687dde07639266943bf0 | ec30d1c3465e54ec7bbaad8130750ca225cf2546 | /examplecontent/ExamplePlugins/ExampleParticleIdPlugin.cc | a23a2f907bdf2f9e165f84a2dad5a9a224b37068 | [] | no_license | therealendrju/WorkshopContent | ab800bbfab147ef26c94d87fbeff8257657cbcf3 | 29ab76ea2438305c00ac8992594dcb8ad6a2333f | refs/heads/master | 2021-01-20T16:42:14.651736 | 2016-06-28T20:13:19 | 2016-06-28T20:13:19 | 63,157,664 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,505 | cc | /**
* @file WorkshopContent/examplecontent/ExamplePlugins/ExampleParticleIdPlugin.cc
*
* @brief Implementation of the example particle id plugin class.
*
* $Log: $
*/
#include "Pandora/AlgorithmHeaders.h"
#include "examplecontent/ExamplePlugins/ExampleParticleIdPlugin.h"
using namespace pandora;
namespace example_content
{
ExampleParticleIdPlugin::ExampleParticleIdPlugin() :
m_exampleParameter(0)
{
}
//------------------------------------------------------------------------------------------------------------------------------------------
bool ExampleParticleIdPlugin::IsMatch(const Cluster *const /*pCluster*/) const
{
// Particle id plugins are instantiated and registed (with the Pandora plugin manager) via the client app. They are then
// associated with particular particle id "slots" via the PandoraSettings xml file e.g. MuonPlugin, ElectronPlugin
// Each plugin can have configurable parameters and must provide an implementation of an IsMatch(const Cluster *const) function.
return false;
}
//------------------------------------------------------------------------------------------------------------------------------------------
StatusCode ExampleParticleIdPlugin::ReadSettings(const TiXmlHandle xmlHandle)
{
PANDORA_RETURN_RESULT_IF_AND_IF(STATUS_CODE_SUCCESS, STATUS_CODE_NOT_FOUND, !=, XmlHelper::ReadValue(xmlHandle,
"ExampleParameter", m_exampleParameter));
return STATUS_CODE_SUCCESS;
}
} // namespace example_content
| [
"marshall@hep.phy.cam.ac.uk"
] | marshall@hep.phy.cam.ac.uk |
6c2437189e4197cbc10f63a8fb1f29f43a645c79 | 32a0c579d4da91ece7995f677b17c5acdee49096 | /bkhoffM/ui-5-3-2/moc/moc_motor.cpp | 7605f59fa181665e612b25dc12de72c0274521f1 | [] | no_license | mpdunning/epicsDisplays | e2bb7367fc36f26011581652633dd00a441e2858 | 3ecbaa04d3387b09c3c14eecb91e8c6441b6f7cc | refs/heads/master | 2021-01-11T03:46:23.698891 | 2016-10-28T22:48:35 | 2016-10-28T22:48:35 | 71,293,017 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,128 | cpp | /****************************************************************************
** Meta object code from reading C++ file 'motor.h'
**
** Created by: The Qt Meta Object Compiler version 67 (Qt 5.3.2)
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/
#include "../motor.h"
#include <QtCore/qbytearray.h>
#include <QtCore/qmetatype.h>
#if !defined(Q_MOC_OUTPUT_REVISION)
#error "The header file 'motor.h' doesn't include <QObject>."
#elif Q_MOC_OUTPUT_REVISION != 67
#error "This file was generated using the moc from 5.3.2. It"
#error "cannot be used with the include files from this version of Qt."
#error "(The moc has changed too much.)"
#endif
QT_BEGIN_MOC_NAMESPACE
struct qt_meta_stringdata_Motor_t {
QByteArrayData data[6];
char stringdata[41];
};
#define QT_MOC_LITERAL(idx, ofs, len) \
Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \
qptrdiff(offsetof(qt_meta_stringdata_Motor_t, stringdata) + ofs \
- idx * sizeof(QByteArrayData)) \
)
static const qt_meta_stringdata_Motor_t qt_meta_stringdata_Motor = {
{
QT_MOC_LITERAL(0, 0, 5),
QT_MOC_LITERAL(1, 6, 7),
QT_MOC_LITERAL(2, 14, 0),
QT_MOC_LITERAL(3, 15, 7),
QT_MOC_LITERAL(4, 23, 13),
QT_MOC_LITERAL(5, 37, 3)
},
"Motor\0closing\0\0myClose\0_valueChanged\0"
"val"
};
#undef QT_MOC_LITERAL
static const uint qt_meta_data_Motor[] = {
// content:
7, // revision
0, // classname
0, 0, // classinfo
3, 14, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
0, // flags
1, // signalCount
// signals: name, argc, parameters, tag, flags
1, 0, 29, 2, 0x06 /* Public */,
// slots: name, argc, parameters, tag, flags
3, 0, 30, 2, 0x08 /* Private */,
4, 1, 31, 2, 0x08 /* Private */,
// signals: parameters
QMetaType::Void,
// slots: parameters
QMetaType::Void,
QMetaType::Void, QMetaType::QString, 5,
0 // eod
};
void Motor::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a)
{
if (_c == QMetaObject::InvokeMetaMethod) {
Motor *_t = static_cast<Motor *>(_o);
switch (_id) {
case 0: _t->closing(); break;
case 1: _t->myClose(); break;
case 2: _t->_valueChanged((*reinterpret_cast< const QString(*)>(_a[1]))); break;
default: ;
}
} else if (_c == QMetaObject::IndexOfMethod) {
int *result = reinterpret_cast<int *>(_a[0]);
void **func = reinterpret_cast<void **>(_a[1]);
{
typedef void (Motor::*_t)();
if (*reinterpret_cast<_t *>(func) == static_cast<_t>(&Motor::closing)) {
*result = 0;
}
}
}
}
const QMetaObject Motor::staticMetaObject = {
{ &QDialog::staticMetaObject, qt_meta_stringdata_Motor.data,
qt_meta_data_Motor, qt_static_metacall, 0, 0}
};
const QMetaObject *Motor::metaObject() const
{
return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject;
}
void *Motor::qt_metacast(const char *_clname)
{
if (!_clname) return 0;
if (!strcmp(_clname, qt_meta_stringdata_Motor.stringdata))
return static_cast<void*>(const_cast< Motor*>(this));
if (!strcmp(_clname, "Ui::Motor"))
return static_cast< Ui::Motor*>(const_cast< Motor*>(this));
return QDialog::qt_metacast(_clname);
}
int Motor::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QDialog::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
if (_c == QMetaObject::InvokeMetaMethod) {
if (_id < 3)
qt_static_metacall(this, _c, _id, _a);
_id -= 3;
} else if (_c == QMetaObject::RegisterMethodArgumentMetaType) {
if (_id < 3)
*reinterpret_cast<int*>(_a[0]) = -1;
_id -= 3;
}
return _id;
}
// SIGNAL 0
void Motor::closing()
{
QMetaObject::activate(this, &staticMetaObject, 0, 0);
}
QT_END_MOC_NAMESPACE
| [
"mdunning@slac.stanford.edu"
] | mdunning@slac.stanford.edu |
205788510069e59cc97b592e33f9701978ab8997 | 38c10c01007624cd2056884f25e0d6ab85442194 | /content/renderer/background_sync/background_sync_client_impl.cc | ea6562327368bab33b667792ea3fef47458816cc | [
"BSD-3-Clause"
] | permissive | zenoalbisser/chromium | 6ecf37b6c030c84f1b26282bc4ef95769c62a9b2 | e71f21b9b4b9b839f5093301974a45545dad2691 | refs/heads/master | 2022-12-25T14:23:18.568575 | 2016-07-14T21:49:52 | 2016-07-23T08:02:51 | 63,980,627 | 0 | 2 | BSD-3-Clause | 2022-12-12T12:43:41 | 2016-07-22T20:14:04 | null | UTF-8 | C++ | false | false | 3,470 | cc | // Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/renderer/background_sync/background_sync_client_impl.h"
#include "content/child/background_sync/background_sync_provider.h"
#include "content/child/background_sync/background_sync_type_converters.h"
#include "content/renderer/service_worker/service_worker_context_client.h"
#include "third_party/WebKit/public/platform/Platform.h"
#include "third_party/WebKit/public/platform/WebThread.h"
#include "third_party/WebKit/public/platform/modules/background_sync/WebSyncProvider.h"
#include "third_party/WebKit/public/platform/modules/background_sync/WebSyncRegistration.h"
namespace content {
// static
void BackgroundSyncClientImpl::Create(
int64 service_worker_registration_id,
mojo::InterfaceRequest<BackgroundSyncServiceClient> request) {
new BackgroundSyncClientImpl(service_worker_registration_id, request.Pass());
}
BackgroundSyncClientImpl::~BackgroundSyncClientImpl() {}
BackgroundSyncClientImpl::BackgroundSyncClientImpl(
int64 service_worker_registration_id,
mojo::InterfaceRequest<BackgroundSyncServiceClient> request)
: service_worker_registration_id_(service_worker_registration_id),
binding_(this, request.Pass()),
callback_seq_num_(0) {}
void BackgroundSyncClientImpl::Sync(int64_t handle_id,
const SyncCallback& callback) {
DCHECK(!blink::Platform::current()->mainThread()->isCurrentThread());
// Get a registration for the given handle_id from the provider. This way
// the provider knows about the handle and can delete it once Blink releases
// it.
// TODO(jkarlin): Change the WebSyncPlatform to support
// DuplicateRegistrationHandle and then this cast can go.
BackgroundSyncProvider* provider = static_cast<BackgroundSyncProvider*>(
blink::Platform::current()->backgroundSyncProvider());
if (provider == nullptr) {
// This can happen if the renderer is shutting down when sync fires. See
// crbug.com/543898. No need to fire the callback as the browser will
// automatically fail all pending sync events when the mojo connection
// closes.
return;
}
// TODO(jkarlin): Find a way to claim the handle safely without requiring a
// round-trip IPC.
int64_t id = ++callback_seq_num_;
sync_callbacks_[id] = callback;
provider->DuplicateRegistrationHandle(
handle_id, base::Bind(&BackgroundSyncClientImpl::SyncDidGetRegistration,
base::Unretained(this), id));
}
void BackgroundSyncClientImpl::SyncDidGetRegistration(
int64_t callback_id,
BackgroundSyncError error,
SyncRegistrationPtr registration) {
SyncCallback callback;
auto it = sync_callbacks_.find(callback_id);
DCHECK(it != sync_callbacks_.end());
callback = it->second;
sync_callbacks_.erase(it);
if (error != BACKGROUND_SYNC_ERROR_NONE) {
callback.Run(SERVICE_WORKER_EVENT_STATUS_ABORTED);
return;
}
ServiceWorkerContextClient* client =
ServiceWorkerContextClient::ThreadSpecificInstance();
if (!client) {
callback.Run(SERVICE_WORKER_EVENT_STATUS_ABORTED);
return;
}
scoped_ptr<blink::WebSyncRegistration> web_registration =
mojo::ConvertTo<scoped_ptr<blink::WebSyncRegistration>>(registration);
client->DispatchSyncEvent(*web_registration, callback);
}
} // namespace content
| [
"zeno.albisser@hemispherian.com"
] | zeno.albisser@hemispherian.com |
bb13ca628781324f7c94c6fa722960d963af52c9 | 03a6c3b969c03b7a6dd0d6d2a4f7911d8d2ecc01 | /dp/fx/xml/src/EffectLoader.cpp | 5d5e917a14cada99c147bf0d73519b1848a1a730 | [] | no_license | theomission/pipeline | 99c77d83326b0831cd997cb2e19249fdc2667512 | 8a2e1c9d79ba4b3b6f9328355d017ed7a303a9cd | refs/heads/master | 2021-01-12T21:16:33.048158 | 2015-09-21T14:22:07 | 2015-09-21T16:00:54 | 44,364,667 | 1 | 0 | null | 2015-10-16T05:42:10 | 2015-10-16T05:42:10 | null | UTF-8 | C++ | false | false | 60,458 | cpp | // Copyright NVIDIA Corporation 2012
// 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 NVIDIA 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 ``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 <dp/util/File.h>
#include <dp/util/Singleton.h>
#include <dp/fx/xml/EffectLoader.h>
#include <dp/fx/ParameterConversion.h>
#include <dp/fx/ParameterGroupLayout.h>
#include <dp/fx/inc/EffectDataPrivate.h>
#include <dp/fx/inc/EffectLibraryImpl.h>
#include <dp/fx/inc/FileSnippet.h>
#include <dp/fx/inc/ParameterGroupDataPrivate.h>
#include <dp/fx/inc/ParameterGroupSnippet.h>
#include <dp/fx/inc/SnippetListSnippet.h>
#include <dp/fx/inc/StringSnippet.h>
#include <dp/DP.h>
#include <boost/bind.hpp>
#include <boost/tokenizer.hpp>
#include <tinyxml.h>
#include <iostream>
#include <map>
#include <utility>
#include <exception>
#include <boost/make_shared.hpp>
using namespace dp::util;
using std::auto_ptr;
using std::map;
using std::string;
using std::vector;
namespace dp
{
namespace fx
{
namespace xml
{
/************************************************************************/
/* ShaderPipelineImpl */
/************************************************************************/
DEFINE_PTR_TYPES( ShaderPipelineImpl );
class ShaderPipelineImpl : public ShaderPipeline
{
public:
static ShaderPipelineImplSharedPtr create()
{
return( std::shared_ptr<ShaderPipelineImpl>( new ShaderPipelineImpl() ) );
}
void addStage( const Stage& stage )
{
DP_ASSERT( std::find_if( m_stages.begin(), m_stages.end(), boost::bind( &Stage::domain, _1) == stage.domain ) == m_stages.end() );
m_stages.push_back( stage );
}
protected:
ShaderPipelineImpl()
{}
};
/************************************************************************/
/* Technique */
/************************************************************************/
TechniqueSharedPtr Technique::create( std::string const& type )
{
return( std::shared_ptr<Technique>( new Technique( type ) ) );
}
Technique::Technique( std::string const & type)
: m_type( type )
{
}
void Technique::addDomainSnippet( dp::fx::Domain domain, std::string const & signature, dp::fx::SnippetSharedPtr const & snippet )
{
if ( m_domainSignatures.find( domain ) != m_domainSignatures.end()
&& m_domainSignatures[domain].find( signature ) != m_domainSignatures[domain].end() )
{
throw std::runtime_error( std::string( "signature " + signature + " has already been added to the domain" ) );
}
m_domainSignatures[domain][signature] = snippet;
}
Technique::SignatureSnippets const & Technique::getSignatures( dp::fx::Domain domain ) const
{
DomainSignatures::const_iterator it = m_domainSignatures.find( domain );
if (it == m_domainSignatures.end() )
{
throw std::runtime_error( "There're no signatures for the given domain" );
}
return it->second;
}
std::string const & Technique::getType() const
{
return m_type;
}
/************************************************************************/
/* DomainSpec */
/************************************************************************/
DomainSpecSharedPtr DomainSpec::create( std::string const & name, dp::fx::Domain domain, ParameterGroupSpecsContainer const & specs, bool transparent, Techniques const & techniques )
{
return( std::shared_ptr<DomainSpec>( new DomainSpec( name, domain, specs, transparent, techniques ) ) );
}
DomainSpec::DomainSpec( std::string const & name, dp::fx::Domain domain, ParameterGroupSpecsContainer const & specs, bool transparent, Techniques const & techniques )
: m_name( name )
, m_domain( domain )
, m_parameterGroups( specs )
, m_transparent( transparent )
, m_techniques( techniques)
{
}
TechniqueSharedPtr DomainSpec::getTechnique( std::string const & name )
{
Techniques::const_iterator it = m_techniques.find( name );
if ( it != m_techniques.end() )
{
return it->second;
}
// The DomainSpec's technique doesn't match the queried one.
// Return nullptr so that it's going to be ignored.
return TechniqueSharedPtr::null;
}
DomainSpec::ParameterGroupSpecsContainer const & DomainSpec::getParameterGroups() const
{
return m_parameterGroups;
}
dp::fx::Domain DomainSpec::getDomain() const
{
return m_domain;
}
bool DomainSpec::isTransparent() const
{
return m_transparent;
}
/************************************************************************/
/* DomainData */
/************************************************************************/
DomainDataSharedPtr DomainData::create( DomainSpecSharedPtr const & domainSpec, std::string const & name, std::vector<dp::fx::ParameterGroupDataSharedPtr> const & parameterGroupDatas, bool transparent )
{
return( std::shared_ptr<DomainData>( new DomainData( domainSpec, name, parameterGroupDatas, transparent ) ) );
}
DomainData::DomainData( DomainSpecSharedPtr const & domainSpec, std::string const & name, std::vector<dp::fx::ParameterGroupDataSharedPtr> const & parameterGroupDatas, bool transparent )
: m_domainSpec( domainSpec )
, m_parameterGroupDatas( new ParameterGroupDataSharedPtr[domainSpec->getParameterGroups().size()] )
, m_name( name )
, m_transparent( transparent )
{
DomainSpec::ParameterGroupSpecsContainer const & parameterGroupSpecs = domainSpec->getParameterGroups();
for ( std::vector<dp::fx::ParameterGroupDataSharedPtr>::const_iterator it = parameterGroupDatas.begin(); it != parameterGroupDatas.end(); ++it )
{
dp::fx::ParameterGroupSpecSharedPtr parameterGroupSpec = (*it)->getParameterGroupSpec();
DomainSpec::ParameterGroupSpecsContainer::const_iterator itParameterGroupSpec = std::find( parameterGroupSpecs.begin(), parameterGroupSpecs.end(), parameterGroupSpec );
if ( itParameterGroupSpec == parameterGroupSpecs.end() )
{
throw std::runtime_error( "ParameterGroupSpec does not exist for given ParameterGroupData" );
}
m_parameterGroupDatas[ std::distance( parameterGroupSpecs.begin(), itParameterGroupSpec ) ] = *it;
}
}
DomainSpecSharedPtr const & DomainData::getDomainSpec() const
{
return m_domainSpec;
}
ParameterGroupDataSharedPtr const & DomainData::getParameterGroupData( DomainSpec::ParameterGroupSpecsContainer::const_iterator it ) const
{
return m_parameterGroupDatas[ std::distance( m_domainSpec->getParameterGroups().begin(), it ) ];
}
std::string const & DomainData::getName() const
{
return m_name;
}
bool DomainData::getTransparent() const
{
return m_transparent;
}
/************************************************************************/
/* EffectSpec */
/************************************************************************/
EffectSpecSharedPtr EffectSpec::create( std::string const & name, DomainSpecs const & domainSpecs )
{
return( std::shared_ptr<EffectSpec>( new EffectSpec( name, domainSpecs ) ) );
}
EffectSpec::EffectSpec( std::string const & name, DomainSpecs const & domainSpecs )
: dp::fx::EffectSpec( name, EST_PIPELINE, gatherParameterGroupSpecs( domainSpecs ), gatherTransparency( domainSpecs ) )
, m_domainSpecs( domainSpecs )
{
}
EffectSpec::DomainSpecs const & EffectSpec::getDomainSpecs() const
{
return m_domainSpecs;
}
DomainSpecSharedPtr const & EffectSpec::getDomainSpec( dp::fx::Domain domainSpec ) const
{
DomainSpecs::const_iterator it = m_domainSpecs.find( domainSpec );
if ( m_domainSpecs.end() == it )
{
throw std::runtime_error( "missing DomainSpec for given domain" );
}
return it->second;
}
EffectSpec::ParameterGroupSpecsContainer EffectSpec::gatherParameterGroupSpecs( DomainSpecs const & domainSpecs )
{
// gather all ParameterGroupSpecs and ensure that each one exists only once
std::set<dp::fx::ParameterGroupSpecSharedPtr> gatheredSpecs;
for ( DomainSpecs::const_iterator it = domainSpecs.begin(); it != domainSpecs.end(); ++it )
{
for (DomainSpec::ParameterGroupSpecsContainer::const_iterator it2 = it->second->getParameterGroups().begin(); it2 != it->second->getParameterGroups().end(); ++it2 )
{
gatheredSpecs.insert(*it2);
}
}
ParameterGroupSpecsContainer returnValue;
std::copy( gatheredSpecs.begin(), gatheredSpecs.end(), std::back_inserter( returnValue ) );
return returnValue;
}
bool EffectSpec::gatherTransparency( DomainSpecs const & domainSpecs )
{
bool transparency = false;
for ( DomainSpecs::const_iterator it = domainSpecs.begin(); it != domainSpecs.end(); ++it )
{
transparency |= it->second->isTransparent();
}
return transparency;
}
// Public interface functions ########################################
dp::fx::Domain getDomainFromString( std::string const & domain )
{
// OpenGL
if ( domain == "vertex" ) return dp::fx::DOMAIN_VERTEX;
if ( domain == "fragment" ) return dp::fx::DOMAIN_FRAGMENT;
if ( domain == "geometry" ) return dp::fx::DOMAIN_GEOMETRY;
if ( domain == "tessellation_control" ) return dp::fx::DOMAIN_TESSELLATION_CONTROL;
if ( domain == "tessellation_evaluation") return dp::fx::DOMAIN_TESSELLATION_EVALUATION;
throw std::runtime_error("unknown domain type: " + domain );
}
EffectLoaderSharedPtr EffectLoader::create( EffectLibraryImpl * effectLibrary )
{
return( std::shared_ptr<EffectLoader>( new EffectLoader( effectLibrary ) ) );
}
EffectLoader::EffectLoader( EffectLibraryImpl * effectLibrary )
: dp::fx::EffectLoader( effectLibrary )
{
// Map for getContainerParameterTypeFromGLSLType()
// These are the built-in GLSL variables types:
m_mapGLSLtoPT.insert(std::make_pair("float", static_cast<unsigned int>(PT_FLOAT32)));
m_mapGLSLtoPT.insert(std::make_pair("vec2", PT_FLOAT32 | PT_VECTOR2));
m_mapGLSLtoPT.insert(std::make_pair("vec3", PT_FLOAT32 | PT_VECTOR3));
m_mapGLSLtoPT.insert(std::make_pair("vec4", PT_FLOAT32 | PT_VECTOR4));
m_mapGLSLtoPT.insert(std::make_pair("int", static_cast<unsigned int>(PT_INT32)));
m_mapGLSLtoPT.insert(std::make_pair("ivec2", PT_INT32 | PT_VECTOR2));
m_mapGLSLtoPT.insert(std::make_pair("ivec3", PT_INT32 | PT_VECTOR3));
m_mapGLSLtoPT.insert(std::make_pair("ivec4", PT_INT32 | PT_VECTOR4));
m_mapGLSLtoPT.insert(std::make_pair("uint", static_cast<unsigned int>(PT_UINT32)));
m_mapGLSLtoPT.insert(std::make_pair("uvec2", PT_UINT32 | PT_VECTOR2));
m_mapGLSLtoPT.insert(std::make_pair("uvec3", PT_UINT32 | PT_VECTOR3));
m_mapGLSLtoPT.insert(std::make_pair("uvec4", PT_UINT32 | PT_VECTOR4));
m_mapGLSLtoPT.insert(std::make_pair("bool", static_cast<unsigned int>(PT_BOOL)));
m_mapGLSLtoPT.insert(std::make_pair("bvec2", PT_BOOL | PT_VECTOR2));
m_mapGLSLtoPT.insert(std::make_pair("bvec3", PT_BOOL | PT_VECTOR3));
m_mapGLSLtoPT.insert(std::make_pair("bvec4", PT_BOOL | PT_VECTOR4));
m_mapGLSLtoPT.insert(std::make_pair("mat2", PT_FLOAT32 | PT_MATRIX2x2));
m_mapGLSLtoPT.insert(std::make_pair("mat2x2", PT_FLOAT32 | PT_MATRIX2x2));
m_mapGLSLtoPT.insert(std::make_pair("mat2x3", PT_FLOAT32 | PT_MATRIX2x3));
m_mapGLSLtoPT.insert(std::make_pair("mat2x4", PT_FLOAT32 | PT_MATRIX2x4));
m_mapGLSLtoPT.insert(std::make_pair("mat3x2", PT_FLOAT32 | PT_MATRIX3x2));
m_mapGLSLtoPT.insert(std::make_pair("mat3", PT_FLOAT32 | PT_MATRIX3x3));
m_mapGLSLtoPT.insert(std::make_pair("mat3x3", PT_FLOAT32 | PT_MATRIX3x3));
m_mapGLSLtoPT.insert(std::make_pair("mat3x4", PT_FLOAT32 | PT_MATRIX3x4));
m_mapGLSLtoPT.insert(std::make_pair("mat4x2", PT_FLOAT32 | PT_MATRIX4x2));
m_mapGLSLtoPT.insert(std::make_pair("mat4x3", PT_FLOAT32 | PT_MATRIX4x3));
m_mapGLSLtoPT.insert(std::make_pair("mat4", PT_FLOAT32 | PT_MATRIX4x4));
m_mapGLSLtoPT.insert(std::make_pair("mat4x4", PT_FLOAT32 | PT_MATRIX4x4));
m_mapGLSLtoPT.insert(std::make_pair("double", static_cast<unsigned int>(PT_FLOAT64)));
m_mapGLSLtoPT.insert(std::make_pair("dvec2", PT_FLOAT64 | PT_VECTOR2));
m_mapGLSLtoPT.insert(std::make_pair("dvec3", PT_FLOAT64 | PT_VECTOR3));
m_mapGLSLtoPT.insert(std::make_pair("dvec4", PT_FLOAT64 | PT_VECTOR4));
m_mapGLSLtoPT.insert(std::make_pair("dmat2", PT_FLOAT64 | PT_MATRIX2x2));
m_mapGLSLtoPT.insert(std::make_pair("dmat2x2", PT_FLOAT64 | PT_MATRIX2x2));
m_mapGLSLtoPT.insert(std::make_pair("dmat2x3", PT_FLOAT64 | PT_MATRIX2x3));
m_mapGLSLtoPT.insert(std::make_pair("dmat2x4", PT_FLOAT64 | PT_MATRIX2x4));
m_mapGLSLtoPT.insert(std::make_pair("dmat3x2", PT_FLOAT64 | PT_MATRIX3x2));
m_mapGLSLtoPT.insert(std::make_pair("dmat3", PT_FLOAT64 | PT_MATRIX3x3));
m_mapGLSLtoPT.insert(std::make_pair("dmat3x3", PT_FLOAT64 | PT_MATRIX3x3));
m_mapGLSLtoPT.insert(std::make_pair("dmat3x4", PT_FLOAT64 | PT_MATRIX3x4));
m_mapGLSLtoPT.insert(std::make_pair("dmat4x2", PT_FLOAT64 | PT_MATRIX4x2));
m_mapGLSLtoPT.insert(std::make_pair("dmat4x3", PT_FLOAT64 | PT_MATRIX4x3));
m_mapGLSLtoPT.insert(std::make_pair("dmat4", PT_FLOAT64 | PT_MATRIX4x4));
m_mapGLSLtoPT.insert(std::make_pair("dmat4x4", PT_FLOAT64 | PT_MATRIX4x4));
m_mapGLSLtoPT.insert(std::make_pair("sampler1D", PT_SAMPLER_PTR | PT_SAMPLER_1D));
m_mapGLSLtoPT.insert(std::make_pair("sampler2D", PT_SAMPLER_PTR | PT_SAMPLER_2D));
m_mapGLSLtoPT.insert(std::make_pair("sampler3D", PT_SAMPLER_PTR | PT_SAMPLER_3D));
m_mapGLSLtoPT.insert(std::make_pair("samplerCube", PT_SAMPLER_PTR | PT_SAMPLER_CUBE));
m_mapGLSLtoPT.insert(std::make_pair("sampler2DRect", PT_SAMPLER_PTR | PT_SAMPLER_2D_RECT));
m_mapGLSLtoPT.insert(std::make_pair("sampler1DArray", PT_SAMPLER_PTR | PT_SAMPLER_1D_ARRAY));
m_mapGLSLtoPT.insert(std::make_pair("sampler2DArray", PT_SAMPLER_PTR | PT_SAMPLER_2D_ARRAY));
m_mapGLSLtoPT.insert(std::make_pair("samplerBuffer", PT_SAMPLER_PTR | PT_SAMPLER_BUFFER));
m_mapGLSLtoPT.insert(std::make_pair("sampler2DMS", PT_SAMPLER_PTR | PT_SAMPLER_2D_MULTI_SAMPLE));
m_mapGLSLtoPT.insert(std::make_pair("sampler2DMSArray", PT_SAMPLER_PTR | PT_SAMPLER_2D_MULTI_SAMPLE_ARRAY));
m_mapGLSLtoPT.insert(std::make_pair("samplerCubeArray", PT_SAMPLER_PTR | PT_SAMPLER_CUBE_ARRAY)); // DAR Only exists in GLSL 4.00++
m_mapGLSLtoPT.insert(std::make_pair("sampler1DShadow", PT_SAMPLER_PTR | PT_SAMPLER_1D_SHADOW));
m_mapGLSLtoPT.insert(std::make_pair("sampler2DShadow", PT_SAMPLER_PTR | PT_SAMPLER_2D_SHADOW));
m_mapGLSLtoPT.insert(std::make_pair("sampler2DRectShadow", PT_SAMPLER_PTR | PT_SAMPLER_2D_RECT_SHADOW));
m_mapGLSLtoPT.insert(std::make_pair("sampler1DArrayShadow", PT_SAMPLER_PTR | PT_SAMPLER_1D_ARRAY_SHADOW));
m_mapGLSLtoPT.insert(std::make_pair("sampler2DArrayShadow", PT_SAMPLER_PTR | PT_SAMPLER_2D_ARRAY_SHADOW));
m_mapGLSLtoPT.insert(std::make_pair("samplerCubeShadow", PT_SAMPLER_PTR | PT_SAMPLER_CUBE_SHADOW));
m_mapGLSLtoPT.insert(std::make_pair("samplerCubeArrayShadow", PT_SAMPLER_PTR | PT_SAMPLER_CUBE_ARRAY_SHADOW));
// m_mapGLSLtoPT.insert(std::make_pair("RiXInternal?", PT_NATIVE));
// These are invented variable types and not valid GLSL variables
// These are used to support OptiX rtBuffer<format>, rtBuffer<format, 2>, rtBuffer<format, 3>.
// Not really needed. The developer programming the render pipeline must define buffers.
//m_mapGLSLtoPT.insert(std::make_pair("buffer1D", PT_BUFFER_PTR | PT_BUFFER_1D));
//m_mapGLSLtoPT.insert(std::make_pair("buffer2D", PT_BUFFER_PTR | PT_BUFFER_2D));
//m_mapGLSLtoPT.insert(std::make_pair("buffer3D", PT_BUFFER_PTR | PT_BUFFER_3D));
// These are added to be able to handle smaller data types than int
// inside EffectSpecs parameter groups on scene graph side.
// Code generation will cast them to the next bigger supported format in GLSL.
m_mapGLSLtoPT.insert(std::make_pair("enum", static_cast<unsigned int>(PT_ENUM)));
m_mapGLSLtoPT.insert(std::make_pair("char", static_cast<unsigned int>(PT_INT8)));
m_mapGLSLtoPT.insert(std::make_pair("char2", PT_INT8 | PT_VECTOR2));
m_mapGLSLtoPT.insert(std::make_pair("char3", PT_INT8 | PT_VECTOR3));
m_mapGLSLtoPT.insert(std::make_pair("char4", PT_INT8 | PT_VECTOR4));
m_mapGLSLtoPT.insert(std::make_pair("uchar", static_cast<unsigned int>(PT_UINT8)));
m_mapGLSLtoPT.insert(std::make_pair("uchar2", PT_UINT8 | PT_VECTOR2));
m_mapGLSLtoPT.insert(std::make_pair("uchar3", PT_UINT8 | PT_VECTOR3));
m_mapGLSLtoPT.insert(std::make_pair("uchar4", PT_UINT8 | PT_VECTOR4));
m_mapGLSLtoPT.insert(std::make_pair("short", static_cast<unsigned int>(PT_INT16)));
m_mapGLSLtoPT.insert(std::make_pair("short2", PT_INT16 | PT_VECTOR2));
m_mapGLSLtoPT.insert(std::make_pair("short3", PT_INT16 | PT_VECTOR3));
m_mapGLSLtoPT.insert(std::make_pair("short4", PT_INT16 | PT_VECTOR4));
m_mapGLSLtoPT.insert(std::make_pair("ushort", static_cast<unsigned int>(PT_UINT16)));
m_mapGLSLtoPT.insert(std::make_pair("ushort2", PT_UINT16 | PT_VECTOR2));
m_mapGLSLtoPT.insert(std::make_pair("ushort3", PT_UINT16 | PT_VECTOR3));
m_mapGLSLtoPT.insert(std::make_pair("ushort4", PT_UINT16 | PT_VECTOR4));
m_mapGLSLtoPT.insert(std::make_pair("longlong", static_cast<unsigned int>(PT_INT64)));
m_mapGLSLtoPT.insert(std::make_pair("longlong2", PT_INT64 | PT_VECTOR2));
m_mapGLSLtoPT.insert(std::make_pair("longlong3", PT_INT64 | PT_VECTOR3));
m_mapGLSLtoPT.insert(std::make_pair("longlong4", PT_INT64 | PT_VECTOR4));
m_mapGLSLtoPT.insert(std::make_pair("ulonglong", static_cast<unsigned int>(PT_UINT64)));
m_mapGLSLtoPT.insert(std::make_pair("ulonglong2", PT_UINT64 | PT_VECTOR2));
m_mapGLSLtoPT.insert(std::make_pair("ulonglong3", PT_UINT64 | PT_VECTOR3));
m_mapGLSLtoPT.insert(std::make_pair("ulonglong4", PT_UINT64 | PT_VECTOR4));
// generate inverse map for writer
for ( std::map<std::string, unsigned int>::iterator it = m_mapGLSLtoPT.begin(); it != m_mapGLSLtoPT.end(); ++it )
{
m_mapPTtoGLSL.insert( make_pair(it->second, it->first) );
}
// some files still reside in dpfx
m_fileFinder.addSearchPath( dp::home() + "/media/dpfx" );
m_fileFinder.addSearchPath( dp::home() + "/media/textures" );
}
EffectLoader::~EffectLoader()
{
}
bool EffectLoader::loadEffects(const string &inputFilename )
{
// Make sure Windows partition letters are always the same case.
std::string filename = inputFilename;
if ( ( 1 < filename.length() ) && ( filename[1] == ':' ) )
{
filename[0] = ::toupper( filename[0] );
}
DP_ASSERT( dp::util::fileExists( filename ) );
if ( m_loadedFiles.find( filename ) == m_loadedFiles.end() )
{
// This search path is going to be used to find the files referenced inside the XML effects description.
std::string dir = dp::util::getFilePath( filename );
bool addedSearchPath = m_fileFinder.addSearchPath( dir );
std::unique_ptr<TiXmlDocument> doc(new TiXmlDocument(filename.c_str()));
if ( !doc )
{
return false;
}
if ( !doc->LoadFile() )
{
std::cerr << "failed to load " << filename << "!" << std::endl;
return false;
}
TiXmlHandle libraryHandle = doc->FirstChildElement( "library" ); // The required XML root node.
TiXmlElement * root = libraryHandle.Element();
if ( ! root )
{
return false;
}
m_loadedFiles.insert( filename );
parseLibrary( root );
if ( addedSearchPath )
{
m_fileFinder.removeSearchPath( dir );
}
}
return true;
}
bool EffectLoader::getShaderSnippets( const dp::fx::ShaderPipelineConfiguration& configuration
, dp::fx::Domain domain
, std::string& entrypoint // TODO remove entrypoint
, std::vector<dp::fx::SnippetSharedPtr>& snippets )
{
snippets.clear();
dp::fx::xml::EffectSpecSharedPtr const& effectSpec = dp::fx::EffectLibrary::instance()->getEffectSpec( configuration.getName() ).inplaceCast<dp::fx::xml::EffectSpec>();
// All other domains have only one set of code snippets per technique and ignore the signature.
dp::fx::Domain signatureDomain = DOMAIN_FRAGMENT;
std::string signature;
switch ( domain )
{
case DOMAIN_VERTEX:
case DOMAIN_GEOMETRY:
case DOMAIN_TESSELLATION_CONTROL:
case DOMAIN_TESSELLATION_EVALUATION:
{
// Geometry shaders need to be matched to the underlying domain. (See FIXME above.)
DomainSpecSharedPtr const & signatureDomainSpec = effectSpec->getDomainSpec( signatureDomain );
DP_ASSERT( signatureDomainSpec );
dp::fx::xml::TechniqueSharedPtr const & signatureTechnique = signatureDomainSpec->getTechnique( configuration.getTechnique() );
if ( !signatureTechnique )
{
return false; // Ignore domains which don't have a matching technique.
}
Technique::SignatureSnippets const & signatureSnippets = signatureTechnique->getSignatures( signatureDomain );
DP_ASSERT( signatureSnippets.size() == 1 );
signature = signatureSnippets.begin()->first;
}
// Intentional fall through!
case DOMAIN_FRAGMENT:
{
DomainSpecSharedPtr const & domainSpec = effectSpec->getDomainSpec( domain );
dp::fx::xml::TechniqueSharedPtr const & technique = domainSpec->getTechnique( configuration.getTechnique() );
if ( !technique )
{
return false; // Ignore domains which don't have a matching technique.
}
Technique::SignatureSnippets const & signatureSnippets = technique->getSignatures( domain );
// signature.empty() means we didn't ask for a geometry shader, but one of the system or fragment level domains. Latter have a single snippets block per technique.
Technique::SignatureSnippets::const_iterator it = (signature.empty()) ? signatureSnippets.begin() : signatureSnippets.find( signature );
DP_ASSERT( it != signatureSnippets.end() );
snippets.push_back( it->second );
}
break;
default:
DP_ASSERT(!" EffectLoader::getShaderSnippets(): Unexpected domain." );
return false;
}
return true;
}
// Private helper functions ########################################
EffectLoader::EffectElementType EffectLoader::getTypeFromElement(TiXmlElement *element)
{
if (!element)
{
return EET_NONE;
}
string value = element->Value();
// DAR TODO Use a map.
if (value == "enum") return EET_ENUM;
if (value == "effect") return EET_EFFECT;
if (value == "parameterGroup") return EET_PARAMETER_GROUP;
if (value == "parameter") return EET_PARAMETER;
if (value == "parameterGroupData") return EET_PARAMETER_GROUP_DATA;
if (value == "technique") return EET_TECHNIQUE;
if (value == "glsl") return EET_GLSL;
if (value == "source") return EET_SOURCE;
if (value == "include") return EET_INCLUDE;
if (value == "PipelineSpec") return EET_PIPELINE_SPEC;
if (value == "PipelineData") return EET_PIPELINE_DATA;
return EET_UNKNOWN;
}
unsigned int EffectLoader::getParameterTypeFromGLSLType( const string &glslType )
{
std::map<string, unsigned int>::const_iterator it = m_mapGLSLtoPT.find(glslType);
if (it != m_mapGLSLtoPT.end())
{
return (*it).second;
}
DP_ASSERT( !"EffectLoader::getParameterTypeFromGLSLType(): Type not found." );
return PT_UNDEFINED; // Return something which indicates an error and isn't going to work further down.
}
SnippetSharedPtr EffectLoader::getSourceSnippet( string const & filename )
{
std::string name = m_fileFinder.find( filename );
if ( name.empty() )
{
throw std::runtime_error( std::string("EffectLoader::loadSource(): File " + filename + "not found." ) );
}
return( std::make_shared<FileSnippet>( name ) );
}
SnippetSharedPtr EffectLoader::getParameterSnippet( string const & inout, string const & type, TiXmlElement *element )
{
std::ostringstream oss;
const char * location = element->Attribute( "location" );
if ( location )
{
oss << "layout(location = " + string( location ) + ") ";
}
DP_ASSERT( element->Attribute( "name" ) );
oss << inout + string( " " ) + type + string( " " ) + string( element->Attribute( "name" ) ) + string( ";\n" );
return( std::make_shared<StringSnippet>( oss.str() ) );
}
void EffectLoader::parseLibrary( TiXmlElement * root )
{
TiXmlHandle xmlHandle = root->FirstChildElement();
TiXmlElement *element = xmlHandle.Element();
while ( element )
{
switch( getTypeFromElement( element ) )
{
case EET_ENUM :
parseEnum( element );
break;
case EET_EFFECT :
parseEffect( element );
break;
case EET_PARAMETER_GROUP :
parseParameterGroup( element );
break;
case EET_PARAMETER_GROUP_DATA :
parseParameterGroupData( element );
break;
case EET_INCLUDE:
parseInclude( element );
break;
case EET_PIPELINE_SPEC:
parsePipelineSpec( element );
break;
case EET_PIPELINE_DATA:
parsePipelineData( element );
break;
default :
DP_ASSERT( !"Unknown element type in Library" );
break;
}
element = element->NextSiblingElement();
}
}
void EffectLoader::parseEnum( TiXmlElement * element )
{
DP_ASSERT( element->Attribute( "type" ) );
string type = element->Attribute( "type" );
DP_ASSERT( element->Attribute( "values" ) );
string values = element->Attribute( "values" );
vector<string> valueVector;
boost::tokenizer<boost::char_separator<char>> tokenizer( values, boost::char_separator<char>( " " ) );
for ( boost::tokenizer<boost::char_separator<char>>::const_iterator it = tokenizer.begin(); it != tokenizer.end() ; ++it )
{
valueVector.push_back( *it );
}
EnumSpecSharedPtr spec = EnumSpec::create( type, valueVector );
getEffectLibrary()->registerSpec( spec );
// add this enum type to the GLSL->PT map
m_mapGLSLtoPT[type] = PT_ENUM;
}
void EffectLoader::parseLightEffect( TiXmlElement * effect)
{
DP_ASSERT( effect->Attribute( "id" ) );
string id = effect->Attribute( "id" );
const char * transparent = effect->Attribute( "transparent" );
bool isTransparent = ( transparent && ( strcmp( transparent, "true" ) == 0 ) );
TiXmlHandle xmlHandle = effect->FirstChildElement();
TiXmlElement *element = xmlHandle.Element();
EffectSpec::ParameterGroupSpecsContainer pgsc;
while ( element )
{
EffectElementType eet = getTypeFromElement( element );
switch( eet )
{
case EET_PARAMETER_GROUP:
{
ParameterGroupSpecSharedPtr pgs = parseParameterGroup( element );
DP_ASSERT( find( pgsc.begin(), pgsc.end(), pgs ) == pgsc.end() );
pgsc.push_back( pgs );
}
break;
default:
DP_ASSERT( !"Unknown element type in Effect" );
break;
}
element = element->NextSiblingElement();
}
dp::fx::EffectSpecSharedPtr es = dp::fx::EffectSpec::create( id, dp::fx::EffectSpec::EST_LIGHT, pgsc, isTransparent );
dp::fx::EffectSpecSharedPtr registeredEffectSpec = getEffectLibrary()->registerSpec( es, this );
if ( es == registeredEffectSpec )
{
EffectDataPrivateSharedPtr effectData = EffectDataPrivate::create( registeredEffectSpec, registeredEffectSpec->getName() );
getEffectLibrary()->registerEffectData( effectData );
for ( EffectSpec::iterator it = registeredEffectSpec->beginParameterGroupSpecs(); it != registeredEffectSpec->endParameterGroupSpecs(); ++it )
{
effectData->setParameterGroupData( it, getEffectLibrary()->getParameterGroupData( (*it)->getName() ) );
}
}
}
void EffectLoader::parseDomainSpec( TiXmlElement * effect )
{
DP_ASSERT( effect->Attribute( "id" ) );
DP_ASSERT( effect->Attribute( "domain" ) );
std::string id = effect->Attribute( "id" );
std::string domainString = effect->Attribute( "domain" );
dp::fx::Domain domain = getDomainFromString( domainString );
DomainSpecs::const_iterator it = m_domainSpecs.find( id );
if ( it != m_domainSpecs.end() )
{
DomainSpecSharedPtr const & domainSpec = it->second;
if ( domainSpec->getDomain() == domain )
{
throw std::runtime_error( "DomainSpec " + id + " with domain " + domainString + " has already been registered" );
}
}
const char * transparent = effect->Attribute( "transparent" );
bool isTransparent = ( transparent && ( strcmp( transparent, "true" ) == 0 ) );
TiXmlHandle xmlHandle = effect->FirstChildElement();
TiXmlElement *element = xmlHandle.Element();
DomainSpec::Techniques techniques;
DomainSpec::ParameterGroupSpecsContainer pgsc;
while ( element )
{
EffectElementType eet = getTypeFromElement( element );
switch( eet )
{
case EET_PARAMETER_GROUP:
{
ParameterGroupSpecSharedPtr pgs = parseParameterGroup( element );
DP_ASSERT( find( pgsc.begin(), pgsc.end(), pgs ) == pgsc.end() );
pgsc.push_back( pgs );
}
break;
case EET_TECHNIQUE:
{
TechniqueSharedPtr technique = parseTechnique( element, domain );
techniques[technique->getType()] = technique;
}
break;
default:
DP_ASSERT( !"Unknown element type in Effect" );
break;
}
element = element->NextSiblingElement();
}
// register DomainSpec
DomainSpecSharedPtr domainSpec = DomainSpec::create( id, domain, pgsc, isTransparent, techniques );
m_domainSpecs[id] = domainSpec;
// register DomainData
std::vector<dp::fx::ParameterGroupDataSharedPtr> parameterGroupDatas;
DomainSpec::ParameterGroupSpecsContainer const & parameterGroupSpecs = domainSpec->getParameterGroups();
for ( DomainSpec::ParameterGroupSpecsContainer::const_iterator it = parameterGroupSpecs.begin(); it != parameterGroupSpecs.end(); ++it )
{
parameterGroupDatas.push_back( getEffectLibrary()->getParameterGroupData( (*it)->getName() ) );
}
m_domainDatas[id] = DomainData::create( domainSpec, id, parameterGroupDatas, false );
}
void EffectLoader::parseEffect( TiXmlElement * effect )
{
if ( !effect->Attribute( "id" ) )
{
throw std::runtime_error( "DomainSpec is missing attribute 'id'" );
}
if ( !effect->Attribute( "domain" ) )
{
throw std::runtime_error( "DomainSpec is missing attribute 'domain'" );
}
std::string domain = effect->Attribute( "domain" );
if ( domain == "light" ) // Invented domain "light shader" to special case this.
{
parseLightEffect( effect );
}
else
{
parseDomainSpec( effect );
}
}
TechniqueSharedPtr EffectLoader::parseTechnique( TiXmlElement *technique, dp::fx::Domain domain )
{
char const * type = technique->Attribute( "type" );
if ( type )
{
TechniqueSharedPtr newTechnique = Technique::create( type );
TiXmlHandle xmlHandle = technique->FirstChildElement();
TiXmlElement *element = xmlHandle.Element();
while ( element )
{
EffectElementType elementType = getTypeFromElement( element );
switch ( elementType )
{
case EET_GLSL:
{
char const * signature = element->Attribute( "signature" );
if ( signature )
{
SnippetSharedPtr snippet = parseSources(element);
newTechnique->addDomainSnippet( domain, signature, snippet );
}
else
{
throw std::runtime_error("glsl tag is missing signature attribute");
}
}
break;
default:
throw std::runtime_error( std::string("Expected glsl or cuda tag. Found invalid tag ") + element->Value() );
break;
}
element = element->NextSiblingElement();
}
return newTechnique;
}
else
{
throw std::runtime_error("Technique tag is missing type attribute");
}
return TechniqueSharedPtr();
}
ParameterGroupSpecSharedPtr EffectLoader::parseParameterGroup( TiXmlElement * pg )
{
if ( pg->Attribute( "ref" ) )
{
string ref = pg->Attribute( "ref" );
const ParameterGroupSpecSharedPtr& spec = getEffectLibrary()->getParameterGroupSpec( ref );
DP_ASSERT( spec && "invalid ParameterGroupSpec reference");
return spec;
}
else
{
DP_ASSERT( pg->Attribute( "id" ) );
string id = pg->Attribute( "id" );
TiXmlHandle xmlHandle = pg->FirstChildElement();
TiXmlElement *element = xmlHandle.Element();
vector<ParameterSpec> psc;
while ( element )
{
switch( getTypeFromElement( element ) )
{
case EET_PARAMETER :
parseParameter( element, psc );
break;
default :
DP_ASSERT( !"Unknown element type in ParameterGroup" );
break;
}
element = element->NextSiblingElement();
}
ParameterGroupSpecSharedPtr spec = ParameterGroupSpec::create( id, psc );
ParameterGroupSpecSharedPtr registeredSpec = getEffectLibrary()->registerSpec( spec );
if( registeredSpec == spec ) // a new spec had been added
{
ParameterGroupDataSharedPtr data = ParameterGroupDataPrivate::create( registeredSpec, registeredSpec->getName() );
getEffectLibrary()->registerParameterGroupData( data );
}
return registeredSpec;
}
}
void EffectLoader::parseParameter( TiXmlElement * param, vector<ParameterSpec> & psc )
{
DP_ASSERT( param->Attribute( "type" ) );
string type = param->Attribute( "type" );
DP_ASSERT( param->Attribute( "name" ) );
string name = param->Attribute( "name" );
DP_ASSERT( param->Attribute( "semantic" ) );
Semantic semantic = stringToSemantic( param->Attribute( "semantic" ) );
std::string value = param->Attribute( "value" ) ? param->Attribute( "value" ) : "";
std::string annotation = param->Attribute( "annotation" ) ? param->Attribute( "annotation" ) : "";
int arraySize = 0;
// Ok, this sets the integer to zero if the attribute is not found.
param->Attribute("size", &arraySize);
unsigned int typeId = getParameterTypeFromGLSLType( type );
if ( typeId == PT_ENUM )
{
DP_ASSERT( semantic == SEMANTIC_VALUE );
psc.push_back( ParameterSpec( name, getEffectLibrary()->getEnumSpec( type ), arraySize, value, annotation ) );
}
else if ( ( ( typeId & PT_POINTER_TYPE_MASK ) == PT_SAMPLER_PTR ) && !value.empty() )
{
DP_ASSERT( arraySize == 0 );
std::string fileName = m_fileFinder.findRecursive( value );
psc.push_back( ParameterSpec( name, typeId, semantic, arraySize, fileName.empty() ? value : fileName, annotation ) );
}
else
{
psc.push_back( ParameterSpec( name, typeId, semantic, arraySize, value, annotation ) );
}
}
void EffectLoader::parseInclude( TiXmlElement* include )
{
const char* file = include->Attribute("file");
if ( !file )
{
std::cerr << "include not found: " << include << std::endl;
DP_ASSERT( include->Attribute("include") );
}
else
{
getEffectLibrary()->loadEffects( file, m_fileFinder );
}
}
SnippetSharedPtr EffectLoader::parseSources( TiXmlElement * effect )
{
TiXmlHandle xmlHandle = effect->FirstChildElement();
TiXmlElement *element = xmlHandle.Element();
std::vector<SnippetSharedPtr> snippets;
while (element)
{
switch ( getTypeFromElement( element ) )
{
case EET_SOURCE:
{
if ( element->Attribute( "file" ) )
{
char const *filename = element->Attribute( "file" );
std::string name = m_fileFinder.find( filename );
if ( !name.empty() )
{
snippets.push_back( std::make_shared<FileSnippet>( name ) );
}
else
{
throw std::runtime_error( std::string("source not found: ") + filename );
}
}
else if ( element->Attribute( "input" ) )
{
snippets.push_back( getParameterSnippet( "in", element->Attribute( "input" ), element ) );
}
else if ( element->Attribute( "output" ) )
{
snippets.push_back( getParameterSnippet( "out", element->Attribute( "output" ), element ) );
}
else if ( element->Attribute( "string" ) )
{
snippets.push_back( std::make_shared<StringSnippet>( element->Attribute( "string" ) ) );
}
else
{
DP_ASSERT( !"EffectLibrary::getShaderSource: unknown Attribute in EffectElementType EET_SOURCE" );
}
}
break;
default:
throw std::runtime_error( std::string("invalid source tag: ") + element->Value() );
break;
}
element = element->NextSiblingElement();
}
return( std::make_shared<SnippetListSnippet>( snippets ) );
}
ParameterGroupDataSharedPtr EffectLoader::parseParameterGroupData( TiXmlElement * pg )
{
ParameterGroupDataPrivateSharedPtr parameterGroupData;
// Newly defined paramererGroupData.
if ( pg->Attribute( "id" ) && pg->Attribute( "spec" ) )
{
std::string id = pg->Attribute( "id" );
std::string spec = pg->Attribute( "spec" );
const ParameterGroupSpecSharedPtr& parameterGroupSpec = getEffectLibrary()->getParameterGroupSpec( spec );
if ( !parameterGroupSpec )
{
throw std::runtime_error( "Couldn't find parameterGroupSpec " + spec + " for parameterGroupData " + id );
}
if ( m_parameterGroupDataLookup.find( id ) != m_parameterGroupDataLookup.end() )
{
throw std::runtime_error( "parameterGroupData for " + id + " already exists" );
}
parameterGroupData = ParameterGroupDataPrivate::create( parameterGroupSpec, id );
TiXmlHandle xmlHandle = pg->FirstChildElement();
TiXmlElement *element = xmlHandle.Element();
while ( element )
{
switch( getTypeFromElement( element ) )
{
case EET_PARAMETER :
parseParameterData( element, parameterGroupData );
break;
default :
std::cerr << "Unknown element type " << element->Value() << "in ParameterGroupData" << std::endl;
DP_ASSERT( !"Unknown element type in ParameterGroup" );
break;
}
element = element->NextSiblingElement();
}
m_parameterGroupDataLookup[id] = parameterGroupData;
}
else if ( pg->Attribute( "ref" ) ) // Reference existing parameterGroupData defined before.
{
std::string ref = pg->Attribute( "ref" );
// Verify that the ParameterGroupData has been seen before.
ParameterGroupDataLookup::const_iterator itpgd = m_parameterGroupDataLookup.find( ref );
if ( itpgd == m_parameterGroupDataLookup.end() )
{
throw std::runtime_error( "parameterGroupData for " + ref + " not found in global scope." );
}
parameterGroupData = itpgd->second.staticCast<dp::fx::ParameterGroupDataPrivate>();
}
else
{
DP_ASSERT( !"Missing 'id', 'spec', or 'ref' for parameterGroupData." );
}
return parameterGroupData;
}
void EffectLoader::parseParameterData( TiXmlElement * param, const dp::fx::ParameterGroupDataPrivateSharedPtr& pgd )
{
DP_ASSERT( param->Attribute( "name" ) );
DP_ASSERT( param->Attribute( "value" ) );
string name = param->Attribute( "name" );
string value = param->Attribute( "value" );
ParameterGroupSpec::iterator it = pgd->getParameterGroupSpec()->findParameterSpec( name );
if ( it == pgd->getParameterGroupSpec()->endParameterSpecs() )
{
std::cerr << "Parameter " << name << " unknown in ParameterGroupSpec " << pgd->getParameterGroupSpec()->getName() << std::endl;
DP_ASSERT( !"unknown parameter type" );
}
else
{
if ( isParameterPointer(it->first) )
{
pgd->setParameter( it, value.c_str() );
}
else if ( isParameterEnum(it->first) )
{
getValueFromString( it->first.getEnumSpec(), it->first.getArraySize(), value, reinterpret_cast<dp::fx::EnumSpec::StorageType*>(pgd->getValuePointer( it ) ) );
}
else
{
getValueFromString( it->first.getType(), it->first.getArraySize(), value, pgd->getValuePointer( it ) );
}
}
}
// pipeline
void EffectLoader::parsePipelineSpec( TiXmlElement * effect )
{
// DAR FIXME Add all domain names.
static const char *domains[] =
{
// OpenGL
"vertex"
, "tessellation_control"
, "tessellation_evaluation"
, "geometry"
, "fragment"
};
static const size_t numShaderDomains = sizeof(domains) / sizeof(domains[0]);
if ( effect->Attribute( "id" ) )
{
string id( effect->Attribute( "id" ) );
EffectSpec::DomainSpecs domainSpecs;
for (size_t i = 0; i < numShaderDomains; ++i)
{
const char *pName = effect->Attribute( domains[i] );
if ( pName )
{
string name( pName );
DomainSpecs::iterator itDomainSpec = m_domainSpecs.find( name );
if ( itDomainSpec == m_domainSpecs.end() )
{
throw std::runtime_error( std::string("Pipeline '" + id + "' references undefined DomainSpec '" + name + "'") );
}
DomainSpecSharedPtr const & domainSpec = itDomainSpec->second;
if ( !domainSpecs.insert( std::make_pair( domainSpec->getDomain(), domainSpec ) ).second ) // DAR FIXME Do we need the domain definition inside this domain spec? It's defined by the PipelineSpec now.
{
throw std::runtime_error( std::string("There's already another EffectSpec for the domain specified by '") + name + "' in the pipeline '" + id + "'" );
}
}
}
dp::fx::EffectSpecSharedPtr es = dp::fx::xml::EffectSpec::create( id, domainSpecs );
dp::fx::EffectSpecSharedPtr registeredEffectSpec = getEffectLibrary()->registerSpec( es, this );
if ( es == registeredEffectSpec )
{
EffectDataPrivateSharedPtr effectData = EffectDataPrivate::create( registeredEffectSpec, registeredEffectSpec->getName() );
getEffectLibrary()->registerEffectData( effectData );
for ( EffectSpec::iterator it = registeredEffectSpec->beginParameterGroupSpecs(); it != registeredEffectSpec->endParameterGroupSpecs(); ++it )
{
effectData->setParameterGroupData( it, getEffectLibrary()->getParameterGroupData( (*it)->getName() ) );
}
}
}
else
{
throw std::runtime_error( "Pipeline tag is missing attribute 'id'" );
}
}
void EffectLoader::parsePipelineData( TiXmlElement * effect )
{
if ( effect->Attribute( "id") && effect->Attribute( "spec" ) )
{
string id = effect->Attribute( "id" );
string spec = effect->Attribute( "spec" );
dp::fx::EffectSpecSharedPtr effectSpec = dp::fx::EffectLibrary::instance()->getEffectSpec( spec );
EffectDataPrivateSharedPtr newEffectData = dp::fx::EffectDataPrivate::create( effectSpec, id );
// Default initialize the newEffectData! Only the ParameterGroupData specified inside the XML will be overwritten below.
for ( EffectSpec::iterator it = effectSpec->beginParameterGroupSpecs(); it != effectSpec->endParameterGroupSpecs(); ++it )
{
newEffectData->setParameterGroupData( it, dp::fx::EffectLibrary::instance()->getParameterGroupData( (*it)->getName() ) );
}
TiXmlHandle xmlHandle = effect->FirstChildElement();
TiXmlElement *element = xmlHandle.Element();
while ( element )
{
EffectElementType eet = getTypeFromElement( element );
switch( eet )
{
case EET_PARAMETER_GROUP_DATA:
{
const ParameterGroupDataSharedPtr& parameterGroupData = parseParameterGroupData( element ); // This handles newly defined and referenced programParameterGroupData
DP_ASSERT( parameterGroupData );
// Find the ParameterGroupSpec name the ParameterGroupData should be written to.
const ParameterGroupSpecSharedPtr& pgs = parameterGroupData->getParameterGroupSpec();
dp::fx::EffectSpec::iterator ites = effectSpec->findParameterGroupSpec( pgs->getName() );
if ( ites == effectSpec->endParameterGroupSpecs() )
{
throw std::runtime_error( std::string( "Couldn't find parameterGroupSpec ") + spec );
}
// Overwrite the default ParameterGroupData of the effect with the instanced values defined in the PipelineData.
newEffectData->setParameterGroupData( ites, parameterGroupData );
break;
}
default :
DP_ASSERT( !"Unknown element type in PipelineData" );
break;
}
element = element->NextSiblingElement();
}
// Make the EffectData known to the effect library.
getEffectLibrary()->registerEffectData( newEffectData );
}
else
{
throw std::runtime_error( "PipelineData tag is missing attribute 'id' or 'spec'" );
}
}
ShaderPipelineSharedPtr EffectLoader::generateShaderPipeline( const ShaderPipelineConfiguration& configuration )
{
ShaderPipelineImplSharedPtr shaderPipeline = ShaderPipelineImpl::create();
EffectSpecSharedPtr effectSpec = dp::fx::EffectLibrary::instance()->getEffectSpec( configuration.getName() ).staticCast<dp::fx::xml::EffectSpec>();
EffectSpec::DomainSpecs const & domainSpecs = effectSpec->getDomainSpecs();
for ( EffectSpec::DomainSpecs::const_iterator it = domainSpecs.begin(); it != domainSpecs.end(); ++it )
{
DP_ASSERT( it->first != DOMAIN_PIPELINE );
ShaderPipeline::Stage stage;
stage.domain = it->first;
stage.parameterGroupSpecs = it->second->getParameterGroups();
// generate snippets
std::vector<dp::fx::SnippetSharedPtr> snippets;
if ( getShaderSnippets( configuration, stage.domain, stage.entrypoint, snippets ) )
{
stage.source = std::make_shared<SnippetListSnippet>( snippets );
if ( stage.domain == DOMAIN_VERTEX
|| stage.domain == DOMAIN_GEOMETRY
|| stage.domain == DOMAIN_TESSELLATION_CONTROL
|| stage.domain == DOMAIN_TESSELLATION_EVALUATION)
{
stage.systemSpecs.push_back( "sys_matrices" );
stage.systemSpecs.push_back( "sys_camera" );
}
else if ( stage.domain == DOMAIN_FRAGMENT )
{
stage.systemSpecs.push_back( "sys_Fragment" );
}
shaderPipeline->addStage( stage );
}
}
return shaderPipeline;
}
bool EffectLoader::effectHasTechnique( dp::fx::EffectSpecSharedPtr const& effectSpec, std::string const& techniqueName, bool /*rasterizer*/ )
{
bool hasTechnique = true;
EffectSpecSharedPtr xmlEffectSpec = effectSpec.staticCast<dp::fx::xml::EffectSpec>();
for ( EffectSpec::DomainSpecs::const_iterator it = xmlEffectSpec->getDomainSpecs().begin() ; it != xmlEffectSpec->getDomainSpecs().end() && hasTechnique ; ++it )
{
switch( it->second->getDomain() )
{
case DOMAIN_VERTEX :
case DOMAIN_TESSELLATION_CONTROL :
case DOMAIN_TESSELLATION_EVALUATION :
case DOMAIN_GEOMETRY :
case DOMAIN_FRAGMENT :
hasTechnique = !!it->second->getTechnique( techniqueName );
break;
default :
break;
}
}
return( hasTechnique );
}
/************************************************************************/
/* */
/************************************************************************/
bool EffectLoader::save( const EffectDataSharedPtr& effectData, const std::string& filename )
{
// DAR FIXME!!!!
DP_ASSERT( !"Re-implement the new format!" );
/**************************************************************************
<?xml version="1.0"?>
<library>
<effectData id="..." spec="..." >
<parameterGroupData id="..." spec="..." >
<parameter name="faceWindingCCW" value="true" />
</parameterGroupData>
<parameterGroupData id="..." spec="standardDirectedLightParameters">
<parameter name="ambient" value="0.0 0.0 0.0" />
<parameter name="diffuse" value="1.0 1.0 1.0" />
<parameter name="specular" value="1.0 1.0 1.0" />
<parameter name="direction" value="0.0 0.0 -1.0" />
</parameterGroup>
</effectdata>
</library>
**************************************************************************/
TiXmlDocument xmlDocument;
TiXmlDeclaration* declaration = new TiXmlDeclaration( "1.0", "", "" );
xmlDocument.LinkEndChild( declaration );
TiXmlElement* elementLibrary = new TiXmlElement("library");
TiXmlElement* elementEffectData = new TiXmlElement("effectData");
elementEffectData->SetAttribute( "id", effectData->getName().c_str() );
elementEffectData->SetAttribute( "spec", effectData->getEffectSpec()->getName().c_str() );
dp::fx::EffectSpecSharedPtr const & effectSpec = effectData->getEffectSpec();
for ( EffectSpec::iterator itPgs = effectSpec->beginParameterGroupSpecs(); itPgs != effectSpec->endParameterGroupSpecs(); ++itPgs )
{
const dp::fx::ParameterGroupDataSharedPtr& parameterGroupData = effectData->getParameterGroupData( itPgs );
TiXmlElement* elementParameterGroupData = new TiXmlElement("parameterGroupData");
elementParameterGroupData->SetAttribute( "id", parameterGroupData->getName().c_str() );
elementParameterGroupData->SetAttribute( "spec", (*itPgs)->getName().c_str() );
for ( ParameterGroupSpec::iterator itPs = (*itPgs)->beginParameterSpecs(); itPs != (*itPgs)->endParameterSpecs(); ++itPs )
{
TiXmlElement* elementParameter = new TiXmlElement("parameter");
elementParameter->SetAttribute( "name", itPs->first.getName().c_str() );
unsigned int type = itPs->first.getType();
if ( isParameterEnum( itPs->first ) )
{
elementParameter->SetAttribute( "value",
dp::fx::getStringFromValue( itPs->first.getEnumSpec(), itPs->first.getArraySize(),
reinterpret_cast<const dp::fx::EnumSpec::StorageType*>(parameterGroupData->getParameter( itPs ) ) ).c_str() );
}
else if ( isParameterPointer( itPs->first ) )
{
const char* value = reinterpret_cast<const char *>( parameterGroupData->getParameter( itPs ) );
if ( value )
{
elementParameter->SetAttribute( "value", value);
}
else
{
elementParameter->SetAttribute( "value", "");
}
}
else
{
elementParameter->SetAttribute( "value", dp::fx::getStringFromValue( type, itPs->first.getArraySize(), parameterGroupData->getParameter( itPs ) ).c_str() );
}
elementParameterGroupData->LinkEndChild( elementParameter );
}
elementEffectData->LinkEndChild( elementParameterGroupData );
}
elementLibrary->LinkEndChild( elementEffectData );
xmlDocument.LinkEndChild( elementLibrary );
xmlDocument.SaveFile( filename.c_str() );
return true;
}
} // xml
} // fx
} // dp
namespace
{
bool registerEffectLibrary()
{
dp::fx::EffectLibraryImpl *eli = dynamic_cast<dp::fx::EffectLibraryImpl*>( dp::fx::EffectLibrary::instance() );
DP_ASSERT( eli );
if ( eli )
{
eli->registerEffectLoader( dp::fx::xml::EffectLoader::create( eli ), ".xml" );
return true;
}
return false;
}
} // namespace anonymous
extern "C"
{
DP_FX_API bool dp_fx_xml_initialized = registerEffectLibrary();
}
| [
"matavenrath@nvidia.com"
] | matavenrath@nvidia.com |
0d652672990d51686faf57840d6280a8d4664efb | 3fef56efe52dd97c4942d8b8021d69c28b8b4e1e | /Problemset/1359B - New Theatre Square.cpp | b4947066220ffa44630b295467bcc1fc93b90f64 | [] | no_license | naiyer-abbas/Code-Forces | 384850c939b4243499ffd446092ff69a3e3ea8b0 | aca143949efe1583cdc9c8f71cb0e21b5d14fa1e | refs/heads/master | 2023-05-07T00:53:17.811357 | 2021-05-26T17:48:37 | 2021-05-26T17:48:37 | 327,666,421 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,577 | cpp | #include <bits/stdc++.h>
using namespace std;
#define ll long long int
#define ull unsigned long long int
#define pb push_back
#define mp make_pair
#define fast ios_base :: sync_with_stdio(0); cin.tie(0); cout.tie(0);
#define MOD 1000000007
int main()
{
fast;
int t;
cin >> t;
while(t --)
{
int n, m , x ,y;
cin >> n >> m >> x >> y ;
char arr[n][m];
int white = 0;
for(int i = 0; i < n; i++)
{
for(int j = 0; j < m; j++)
{
cin >> arr[i][j];
if(arr[i][j] == '.')
{
white ++;
}
}
}
// when we only have to use 1x1
if(2 * x <= y)
{
cout << white * x << endl;
continue;
}
else
{
int ans = 0;
for(int i = 0; i < n; i++)
{
for(int j = 0; j < m; j++)
{
if(arr[i][j] == '.')
{
if(j < m - 1 && arr[i][j + 1] == '.')
{
ans += y;
arr[i][j] = '*';
arr[i][j + 1] = '*';
}
else
{
ans += x;
arr[i][j] = '*';
}
}
}
}
cout << ans << endl;
}
}
}
| [
"nairabbas123@gmail.com"
] | nairabbas123@gmail.com |
3e3f97ec0bddc1730b44633adcaaee71049238ab | b450007cc9851c0cc0ce24c2bb7fccf4be7f2e0b | /PixelChamp-master/baseHeader.h | 918e2331897c7ecbe550ebdf1e1244fd00cd0a09 | [] | no_license | roek2/Pixel-Champ | 16b0cb9226e47ab7fcb04d0cbaeacde4850953d6 | b7e5d0ca7cfeedf7061c69892e2ced9959fef3e8 | refs/heads/master | 2021-01-10T04:25:27.776055 | 2015-09-28T18:08:40 | 2015-09-28T18:08:40 | 43,317,623 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,030 | h | #include "SDL.h"
#include "SDL_image.h"
#ifndef BASEHEADER
#define BASEHEADER
//a simple point struct
struct point{
int x;
int y;
};
class base
{
public:
//checks if two sdl_rects collide withe ach other
bool check_collision( SDL_Rect A, SDL_Rect B );
//a second collision detection method which has a larger collsion box, used in correlation with ground collision
bool check_collision2( SDL_Rect A, SDL_Rect B ); //rename
//has a larder collision box and is used for pulling mtiles
bool check_collision3( SDL_Rect A, SDL_Rect B ); //rename
//checks if the bottom of one rect is touching the top of another
bool ground_collision( SDL_Rect A, SDL_Rect B );
//checks if the top of one rect is touching the bottom of another
bool roof_collision( SDL_Rect A, SDL_Rect B );
//checks if the right of one rect is touching the left of another
bool left_collision( SDL_Rect A, SDL_Rect B );
//checks if the right of one rect is touching the left of another, used for pulling mtiles
bool left_collision2( SDL_Rect A, SDL_Rect B );
//checks if the left of one rect is touching the right of another
bool right_collision( SDL_Rect A, SDL_Rect B );
//checks if the left of one rect is touching the bottom of another, used for pulling mtiles
bool right_collision2( SDL_Rect A, SDL_Rect B );
//no idea
bool turret_collision( SDL_Rect A, SDL_Rect B );
//used to check if a point collides with a sdl_rect
bool point_collision( point test, SDL_Rect B );
bool fix_collision( SDL_Rect A, SDL_Rect B );
bool check_collision4( SDL_Rect A, SDL_Rect B );
bool ground_collision2( SDL_Rect A, SDL_Rect B );
};
#endif
| [
"karl.roe2.dcu@gmail.com"
] | karl.roe2.dcu@gmail.com |
934239154d79b405d08a041b7d19ecb87a623690 | 548ea735038e2650b2bc50d2202bc45e9e2787af | /TornadoEngine/Source/Developer/ShareDev/Builder/PreBuilderGameObject_Model.h | 1d37bdfb839b542ff82dcf7f75dfac58695f570c | [] | no_license | xeddmc/MMO-Framework | 9b12595975ddd17f1c29840c25f3431f9ce90e8c | 590d5da8c3faef96aa263bbc9189fde2106660a9 | refs/heads/master | 2021-01-18T18:51:23.838062 | 2016-04-30T16:10:09 | 2016-04-30T16:10:09 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 868 | h | /*
Author: Gudakov Ramil Sergeevich a.k.a. Gauss
Гудаков Рамиль Сергеевич
Contacts: [ramil2085@mail.ru, ramil2085@gmail.com]
See for more information License.h.
*/
#ifndef PreBuilderGameObject_ModelH
#define PreBuilderGameObject_ModelH
#include "TypeDef.h"
#include "PreBuilderGameObject.h"
class DllExport TPreBuilderGameObject_Model : public TPreBuilderGameObject
{
public:
TPreBuilderGameObject_Model();
virtual ~TPreBuilderGameObject_Model();
virtual void SetObjectItem(TMapItem::TObject* pObjectItem);
virtual std::string GetStrDesc();
virtual TGameObject* GetGameObject();
virtual bool GenerateTask(TVectorTypeTask& vecTypeTask);
virtual void TakeTask_Ogre(TListTaskOgre& listOgre);
virtual void TakeTask_Bullet(TListTaskBullet& listBullet);
virtual void TakeTask_OpenAL(TListTaskOpenAL& listOpenAL);
};
#endif
| [
"ramil2085@mail.ru"
] | ramil2085@mail.ru |
8b14b30c32a12e0f952a8976f4ebec0bc448ba64 | 5e274ad2fbf7829245c0820b61deebc4479ed546 | /숫자진법변환/숫자진법변환/main.cpp | 404196f2dc2e8248203410ec3f198178df26a2c3 | [] | no_license | DaEunKim/ClassCpp | 0d693b7372508bcc8201c47a3a10de8830a63e6c | b4648f22e68e093898573287736299ae61f272a9 | refs/heads/master | 2021-01-18T19:57:23.471846 | 2017-06-19T08:26:50 | 2017-06-19T08:26:50 | 86,922,141 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,720 | cpp | //
// main.cpp
// 숫자진법변환
//
// Created by 김다은 on 2017. 4. 11..
// Copyright © 2017년 김다은. All rights reserved.
//
#include <iostream>
#include <cstdlib>
#include <fstream>
#include <string>
using namespace std;
int Mul(int a, int b){
int mul = 1;
for(int i = 0; i<b; i++){
mul *= a;
}
return mul;
}
int toInt(char c){
if('0' <= c && c <= '9')
return c - '0';
else if('A'<=c && c<='Z')
return c - 'A' + 10;
return c - 'a' + 10;
}
char toChar(int n){
if (n < 10)
return n + '0';
return 'a' + (n-10);
}
int toTen(string n, int s)
{
int sum = 0;
int len = (int)n.size();
for(int i=0; i<len;i++){
char c = n.at(i);
int toint = toInt(c);
int mul = Mul(s, len-i-1);
sum += toint*mul;
}
return sum;
}
void printZinSu(int n, int t){
int rest[32]={0,};
int i = 0;
while(n>=t){
rest[i] = n%t;
n = n/t;
i++;
}
rest[i++] = n%t;
for(int j = i-1;j>=0;j--){
char c = toChar(rest[j]);
cout<<c;
}
cout<<endl;
}
int main(void){
ifstream inStream;
inStream.open("/Users/Dani/Documents/ClassCpp/숫자진법변환/숫자진법변환/input.txt");
if(inStream.fail()){
cerr<<"input file opening failed.\n";
exit(1);
}
int T;
inStream >> T;
for(int z = 0; z < T; z++){
int s;//진법
string n;//수
int t;//바꿀 진법
inStream >> s >> n >> t;
int middle = toTen(n, s);
printZinSu(middle, t);
}
inStream.close();
}
| [
"ekdms717@kookmin.ac.kr"
] | ekdms717@kookmin.ac.kr |
37c581fc6055e13f4fa1e27ad4a6e0bb8b8d063c | ec3168b1d6dad4a8cdb88cad1af5d8edf5d91aff | /LightSource.h | 2543fb3e1c194efd47c2376775296e8119c8e09b | [] | no_license | nelsonlaw/ray-trace-demo | 1036f916833fcdc10e4daa24031a592e79af6090 | 8430701757a545b9792962d515dd2f38af42cd42 | refs/heads/master | 2021-01-11T17:44:00.413096 | 2017-10-18T14:36:38 | 2017-10-18T14:36:38 | 79,828,374 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 599 | h | // LightSource.h: interface for the CLightSource class.
//
//////////////////////////////////////////////////////////////////////
#pragma once
#include "v3.h"
class CLightSource
{
public:
CLightSource(float,float,float,int);
CLightSource(float,float,float,float,float,float,int);
void TurnOn();
void TurnOff();
void SetColor(float,float,float);
void Draw();
virtual ~CLightSource();
int m_nID;
V3 position;
V3 color;
bool m_bON; // on or off
void Select();
void UnSelect();
bool IsSelected();
private:
bool m_bSelected;
};
typedef CLightSource LIGHTSOURCE, *LPLIGHTSOURCE;
| [
"iamnelsonlaw@gmail.com"
] | iamnelsonlaw@gmail.com |
a14ed6da0d210f2d26966eecf1f29191f429c7d8 | 3b9b4049a8e7d38b49e07bb752780b2f1d792851 | /src/ui/gfx/win/direct_manipulation.cc | ee50937e640aede5cb36794d2b7560abb66c2e7b | [
"BSD-3-Clause",
"Apache-2.0"
] | permissive | webosce/chromium53 | f8e745e91363586aee9620c609aacf15b3261540 | 9171447efcf0bb393d41d1dc877c7c13c46d8e38 | refs/heads/webosce | 2020-03-26T23:08:14.416858 | 2018-08-23T08:35:17 | 2018-09-20T14:25:18 | 145,513,343 | 0 | 2 | Apache-2.0 | 2019-08-21T22:44:55 | 2018-08-21T05:52:31 | null | UTF-8 | C++ | false | false | 3,504 | cc | // Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/gfx/win/direct_manipulation.h"
#include "base/win/windows_version.h"
namespace gfx {
namespace win {
// static
std::unique_ptr<DirectManipulationHelper>
DirectManipulationHelper::CreateInstance() {
std::unique_ptr<DirectManipulationHelper> instance;
if (base::win::GetVersion() >= base::win::VERSION_WIN10)
instance.reset(new DirectManipulationHelper);
return instance;
}
DirectManipulationHelper::DirectManipulationHelper() {}
DirectManipulationHelper::~DirectManipulationHelper() {}
void DirectManipulationHelper::Initialize(HWND window) {
DCHECK(::IsWindow(window));
// TODO(ananta)
// Remove the CHECK statements here and below and replace them with logs
// when this code stabilizes.
HRESULT hr = manager_.CreateInstance(CLSID_DirectManipulationManager,
nullptr, CLSCTX_INPROC_SERVER);
CHECK(SUCCEEDED(hr));
hr = compositor_.CreateInstance(CLSID_DCompManipulationCompositor,
nullptr, CLSCTX_INPROC_SERVER);
CHECK(SUCCEEDED(hr));
hr = manager_->GetUpdateManager(IID_PPV_ARGS(update_manager_.Receive()));
CHECK(SUCCEEDED(hr));
hr = compositor_->SetUpdateManager(update_manager_.get());
CHECK(SUCCEEDED(hr));
hr = frame_info_.QueryFrom(compositor_.get());
CHECK(SUCCEEDED(hr));
hr = manager_->CreateViewport(frame_info_.get(), window,
IID_PPV_ARGS(view_port_outer_.Receive()));
CHECK(SUCCEEDED(hr));
//
// Enable the desired configuration for each viewport.
//
DIRECTMANIPULATION_CONFIGURATION configuration =
DIRECTMANIPULATION_CONFIGURATION_INTERACTION
| DIRECTMANIPULATION_CONFIGURATION_TRANSLATION_X
| DIRECTMANIPULATION_CONFIGURATION_TRANSLATION_Y
| DIRECTMANIPULATION_CONFIGURATION_TRANSLATION_INERTIA
| DIRECTMANIPULATION_CONFIGURATION_RAILS_X
| DIRECTMANIPULATION_CONFIGURATION_RAILS_Y
| DIRECTMANIPULATION_CONFIGURATION_SCALING
| DIRECTMANIPULATION_CONFIGURATION_SCALING_INERTIA;
hr = view_port_outer_->ActivateConfiguration(configuration);
CHECK(SUCCEEDED(hr));
}
void DirectManipulationHelper::SetBounds(const gfx::Rect& bounds) {
base::win::ScopedComPtr<IDirectManipulationPrimaryContent>
primary_content_outer;
HRESULT hr = view_port_outer_->GetPrimaryContent(
IID_PPV_ARGS(primary_content_outer.Receive()));
CHECK(SUCCEEDED(hr));
base::win::ScopedComPtr<IDirectManipulationContent> content_outer;
hr = content_outer.QueryFrom(primary_content_outer.get());
CHECK(SUCCEEDED(hr));
RECT rect = bounds.ToRECT();
hr = view_port_outer_->SetViewportRect(&rect);
CHECK(SUCCEEDED(hr));
hr = content_outer->SetContentRect(&rect);
CHECK(SUCCEEDED(hr));
}
void DirectManipulationHelper::Activate(HWND window) {
DCHECK(::IsWindow(window));
manager_->Activate(window);
}
void DirectManipulationHelper::Deactivate(HWND window) {
DCHECK(::IsWindow(window));
manager_->Deactivate(window);
}
void DirectManipulationHelper:: HandleMouseWheel(HWND window, UINT message,
WPARAM w_param, LPARAM l_param) {
MSG msg = { window, message, w_param, l_param};
HRESULT hr = view_port_outer_->SetContact(DIRECTMANIPULATION_MOUSEFOCUS);
if (SUCCEEDED(hr)) {
BOOL handled = FALSE;
manager_->ProcessInput(&msg, &handled);
view_port_outer_->ReleaseContact(DIRECTMANIPULATION_MOUSEFOCUS);
}
}
} // namespace win.
} // namespace gfx.
| [
"changhyeok.bae@lge.com"
] | changhyeok.bae@lge.com |
5aa0d152ee3bda01c9dc1578e05ced78b3df8b7f | 38d2a9f6b5ce131caf17fc62384547df688b91a7 | /hmailserver/source/Server/COM/InterfaceServerMessages.h | 35017878aa1ca8c9f80931a04b6dcc87bc307e8c | [] | no_license | martinknafve/hmailserver | 52ba7a50c59558d0b6064802df29e90a9614687e | 707bcf05f4e1b38a9bf6ad7e1ed774237af1e2b2 | refs/heads/master | 2016-09-06T06:11:27.196192 | 2014-07-02T09:40:14 | 2014-07-02T09:40:14 | 15,649,163 | 4 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,073 | h | // Copyright (c) 2010 Martin Knafve / hMailServer.com.
// http://www.hmailserver.com
#pragma once
#include "../hMailServer/resource.h" // main symbols
#include "../hMailServer/hMailServer.h"
#include "../common/bo/ServerMessages.h"
#if defined(_WIN32_WCE) && !defined(_CE_DCOM) && !defined(_CE_ALLOW_SINGLE_THREADED_OBJECTS_IN_MTA)
#error "Single-threaded COM objects are not properly supported on Windows CE platform, such as the Windows Mobile platforms that do not include full DCOM support. Define _CE_ALLOW_SINGLE_THREADED_OBJECTS_IN_MTA to force ATL to support creating single-thread COM object's and allow use of it's single-threaded COM object implementations. The threading model in your rgs file was set to 'Free' as that is the only threading model supported in non DCOM Windows CE platforms."
#endif
// InterfaceServerMessages
class ATL_NO_VTABLE InterfaceServerMessages :
public CComObjectRootEx<CComSingleThreadModel>,
public CComCoClass<InterfaceServerMessages, &CLSID_ServerMessages>,
public IDispatchImpl<IInterfaceServerMessages, &IID_IInterfaceServerMessages, &LIBID_hMailServer, /*wMajor =*/ 1, /*wMinor =*/ 0>,
public HM::COMAuthenticator
{
public:
InterfaceServerMessages()
{
}
DECLARE_REGISTRY_RESOURCEID(IDR_INTERFACESERVERMESSAGES)
BEGIN_COM_MAP(InterfaceServerMessages)
COM_INTERFACE_ENTRY(IInterfaceServerMessages)
COM_INTERFACE_ENTRY(IDispatch)
END_COM_MAP()
DECLARE_PROTECT_FINAL_CONSTRUCT()
HRESULT FinalConstruct()
{
return S_OK;
}
void FinalRelease()
{
}
STDMETHOD(Refresh)();
STDMETHOD(get_Item)(/*[in]*/ long Index, /*[out, retval]*/ IInterfaceServerMessage **pVal);
STDMETHOD(get_Count)(/*[out, retval]*/ long *pVal);
STDMETHOD(get_ItemByDBID)(/*[in]*/ long lDBID, /*[out, retval]*/ IInterfaceServerMessage** pVal);
STDMETHOD(get_ItemByName)(/*[in]*/ BSTR sName, /*[out, retval]*/ IInterfaceServerMessage** pVal);
bool LoadSettings();
public:
shared_ptr<HM::ServerMessages> m_pServerMessages;
};
OBJECT_ENTRY_AUTO(__uuidof(ServerMessages), InterfaceServerMessages)
| [
"martin@hmailserver.com"
] | martin@hmailserver.com |
706e10ea7a786c49ba78a6696c5b79321afa839e | f5dd9f52bae77be8aa720616fecc0f1f8a97ccb6 | /LTo_Step.h | abe52e8d046e5b4b3a9b645cc4419daa58b4f234 | [] | no_license | kalden/ppsim_hierarchical_cpp | 53a37e9073a212a6ebf91ae7ba324889c7a936b2 | 6c02e416189d30c47ca2e9340cad39f96133fece | refs/heads/master | 2020-03-22T15:23:59.553018 | 2018-07-09T07:51:58 | 2018-07-09T07:51:58 | 140,249,876 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 331 | h | #ifndef ROBOCALC_ROBOT_LTO_STEP_H_
#define ROBOCALC_ROBOT_LTO_STEP_H_
#include "Operations.h"
#include "System_Parameters.h"
#include "LTo_Attributes.h"
class LTo_Step: public Operations, public System_Parameters, public LTo_Attributes {
public:
LTo_Step(
);
virtual ~LTo_Step();
void Sensors();
void Actuators();
};
#endif
| [
"kieran.alden@gmail.com"
] | kieran.alden@gmail.com |
379cc3a43ef3bfa8f447be7f9c2719e1b53c1fb7 | 595e8140870d5b2d6b98a7568b9fc77d0e23b94d | /Problem.h | 3075ab211954feaea11dde5af2c39f901b3a3b48 | [] | no_license | SurlySilverback/TileSolver | 2a050555ca289acae39edd65c829cc9ac60cfc6b | 2a8efdb4c25c270ceaa9bad03788e65a54f631d4 | refs/heads/master | 2021-06-14T11:32:46.594219 | 2017-02-18T04:29:30 | 2017-02-18T04:29:30 | 81,029,528 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 679 | h | #ifndef PROBLEM_H
#define PROBLEM_H
#include <iostream>
#include <vector>
class Problem
{
public:
Problem(std::vector< std::vector<int> > Grid, int n, int zeroRow, int zeroCol);
void printGrid() const; // couts grid to the screen
std::vector< <std::vector<int> > Move(); // Checks for legal moves, then generates child problems for those legal moves
private:
Grid state; // Grid object representing the game state
int n; // side-length of tile grid
int zeroRow; // Row coordinate of blank tile
int zeroCol; // Column coordinate of blank tile
};
#endif
| [
"SurlySilverback@github.com"
] | SurlySilverback@github.com |
6a286403ebca747127d2d03e5e4242ac93a78832 | f84be0d4ad35fa61627591344ebd0a18d24189dc | /Cpp/MPL/mpl__metafunc_dimensions_1/include/measures.h | 91b9a2168cafb49ab0b14b1f58bb93bf26ca65f3 | [] | no_license | rhexo/app-lib | 8602fd17aee208e4713572d2238a7b826bf6dc38 | 51f0deaf41b467d18028f18982e312f32f207574 | refs/heads/master | 2020-05-20T08:37:41.149116 | 2017-01-21T19:24:19 | 2017-01-21T19:24:19 | 44,518,075 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,237 | h | /** implementing measures system in C++ */
#include <iostream>
#include <boost/mpl/vector_c.hpp>
#include <boost/mpl/transform.hpp>
#include <boost/mpl/equal.hpp>
#include <boost/mpl/plus.hpp>
#include <boost/mpl/minus.hpp>
#include <boost/mpl/placeholders.hpp>
#include <boost/static_assert.hpp>
namespace measures{
using namespace boost;
using namespace std;
using namespace boost::mpl::placeholders;
// define dimentions
typedef mpl::vector_c<int,1,0,0,0,0,0,0> mass;
typedef mpl::vector_c<int,0,1,0,0,0,0,0> length;
typedef mpl::vector_c<int,0,0,1,0,0,0,0> time;
typedef mpl::vector_c<int,0,0,0,1,0,0,0> charge;
typedef mpl::vector_c<int,0,0,0,0,1,0,0> temperature;
typedef mpl::vector_c<int,0,0,0,0,0,1,0> intensity;
typedef mpl::vector_c<int,0,0,0,0,0,0,1> angle;
typedef mpl::vector_c<int,0,0,0,0,0,0,0> scalar;
// composite dimentions
typedef mpl::vector_c<int,0,1,-1,0,0,0,0> velocity;
typedef mpl::vector_c<int,0,1,-2,0,0,0,0> acceleration;
typedef mpl::vector_c<int,1,1,-1,0,0,0,0> momentum;
typedef mpl::vector_c<int,1,1,-2,0,0,0,0> force;
// quantity base class
template <class T, class Dimension>
struct quantity
{
explicit quantity(T x) : m_value(x) {}
// converting constructor
template <class OtherDimension>
quantity(const quantity<T,OtherDimension>& rhs)
: m_value(rhs.value())
{
BOOST_STATIC_ASSERT((mpl::equal<Dimension,OtherDimension>::type::value));
}
T value() const {return m_value;}
private:
T m_value;
};
/** implementing +, valid for operation with the same types operands */
template <class T, class D>
quantity<T,D> operator+(quantity<T,D> x, quantity<T,D> y)
{
return quantity<T, D>(x.value() + y.value());
};
/** implementing -, valid for operation with the same types operands*/
template <class T, class D>
quantity<T,D> operator-(quantity<T,D> x, quantity<T,D> y)
{
return quantity<T, D>(x.value() - y.value());
};
// cout overloading
template <class T, class D>
ostream& operator<<( ostream& cout, const quantity<T,D>& q)
{
return cout << q.value();
};
// metafunction class
struct plus_f
{
template<class T1, class T2>
struct apply
{
typedef typename mpl::plus<T1,T2>::type type;
};
};
// example of metafunction forwarding
// inheriting base class minus, inheriting typedef typename mpl::plus<T1,T2>::type type.
struct minus_f
{
template <class T1, class T2>
struct apply :
mpl::minus<T1,T2> {};
};
// overloading multiplity
template <class T, class D1, class D2>
quantity<T, typename mpl::transform<D1,D2,plus_f>::type> // new dimensions of result
operator*( quantity<T,D1> x, quantity<T,D2> y)
{
typedef typename mpl::transform<D1,D2,plus_f>::type dim;
return quantity<T, dim>( x.value() * y.value() );
};
// overloading division
// using placegolders expression
template <class T, class D1, class D2>
quantity<T, typename mpl::transform<D1, D2, mpl::minus<_1,_2> >::type >
operator/(quantity<T,D1> x, quantity<T,D2> y)
{
typedef typename mpl::transform<D1, D2, mpl::minus<_1, _2>>::type dim;
return quantity<T, dim>(x.value() / y.value());
}
};
| [
"mmusolov@gmail.com"
] | mmusolov@gmail.com |
bc60dd7136a64f25d04f333960089a05e806a0e6 | 45bebb1cf4e951d673755e5700a9e30b27b1c3ae | /Testing/Operations/mafOpConnectivitySurfaceTest.cpp | b64cd75ce53ad7e04e2b49c1ba3781bec55a0f6d | [] | no_license | besoft/MAF2 | 1a26bfbb4bedb036741941a43b135162448bbf33 | b576955f4f6b954467021f12baedfebcaf79a382 | refs/heads/master | 2020-04-13T13:58:44.609511 | 2019-07-31T13:56:54 | 2019-07-31T13:56:54 | 31,658,947 | 1 | 3 | null | 2015-03-04T13:41:48 | 2015-03-04T13:41:48 | null | UTF-8 | C++ | false | false | 2,507 | cpp | /*=========================================================================
Program: MAF2
Module: mafOpConnectivitySurfaceTest
Authors: Daniele Giunchi - Matteo Giacomoni
Copyright (c) B3C
All rights reserved. See Copyright.txt or
http://www.scsitaly.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.
=========================================================================*/
#include "mafDefines.h"
//----------------------------------------------------------------------------
// NOTE: Every CPP file in the MAF must include "mafDefines.h" as first.
// This force to include Window,wxWidgets and VTK exactly in this order.
// Failing in doing this will result in a run-time error saying:
// "Failure#0: The value of ESP was not properly saved across a function call"
//----------------------------------------------------------------------------
#include <cppunit/config/SourcePrefix.h>
#include "mafOpConnectivitySurfaceTest.h"
#include "mafOpConnectivitySurface.h"
#include "mafOpImporterSTL.h"
#include "mafVMEStorage.h"
#include "mafVMERoot.h"
#include "mafVMESurface.h"
#include "vtkPolyData.h"
//-----------------------------------------------------------
void mafOpConnectivitySurfaceTest::Test()
//-----------------------------------------------------------
{
//Create storage
mafVMEStorage *storage = mafVMEStorage::New();
storage->GetRoot()->SetName("root");
storage->GetRoot()->Initialize();
//Create operation
mafOpImporterSTL *Importer=new mafOpImporterSTL("importer");
mafString filename=MAF_DATA_ROOT;
filename<<"/STL/GenericSTL.stl";
Importer->TestModeOn();
Importer->SetFileName(filename);
Importer->SetInput(storage->GetRoot());
Importer->OpRun();
std::vector<mafVMESurface*> importedSTL;
Importer->GetImportedSTL(importedSTL);
mafVMESurface *Data = importedSTL[0];
Data->GetOutput()->GetVTKData()->Update();
Data->Update();
mafOpConnectivitySurface *connectSurface = new mafOpConnectivitySurface;
connectSurface->TestModeOn();
connectSurface->SetInput(Data);
connectSurface->OpRun();
connectSurface->SetThresold(20.0);
connectSurface->OnVtkConnect();
Data->Update();
mafString response = connectSurface->GetNumberOfExtractedSurfaces();
CPPUNIT_ASSERT(response == mafString("2"));
mafDEL(connectSurface);
mafDEL(Importer);
mafDEL(storage);
}
| [
"s.perticoni@scsitaly.com"
] | s.perticoni@scsitaly.com |
db9e49aca029e00bf18c22e95c5b483fda421ba9 | 277c6b1cd2fd3f6b40ca15f63e27e6cb06d5bf64 | /Movies Database/movieList.hpp | 43e3d7e7cba66ae322058edd261fc3614e8a87fd | [] | no_license | PriyaPilla4/Cplusplus | 4260843b1a4d7938908b81eedc8c13dfb89fc1e2 | 1d47eddccf3e1c2d087bf79bfc796f1e8472e81f | refs/heads/master | 2023-03-26T02:03:38.090824 | 2021-03-26T05:47:19 | 2021-03-26T05:47:19 | 289,357,332 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 661 | hpp | //
// MovieList.hpp
// ProjectThree
//
// Created by Priya Pilla on 3/20/20.
// Copyright © 2020 Priya Pilla. All rights reserved.
//
#ifndef movieList_hpp
#define movieList_hpp
#include <stdio.h>
#include "movie.hpp"
#include <vector>
class MovieList{
private:
Movie* head;
public:
MovieList();
void Insert(std::string title, std::string leadActorActress, std::string description, int year);
void Insert(Movie* movie);
bool Delete(std::string title);
Movie* Search(std::string title);
Movie* DetachAndGetFirst();
std::vector<Movie> GetElements();
void PrintList();
};
#endif /* movieList_hpp */
| [
"noreply@github.com"
] | noreply@github.com |
d97cd0536b75cf4248a8b67c7f59cf21015ac69b | 44495bcab3ab021ec3b21b9ecbd35074600d5493 | /GameProgramming2/Intermediate/Build/Win64/UE4Editor/Inc/GameProgramming2/GameProgramming2GameMode.generated.h | b36e3ff9d1ef733bc7ac0d2db1e571e01b456a02 | [] | no_license | FancyKetchup96/GameProgramming2 | e801b695bfe596da2001968c705a8e0b1b1e198b | 8f1db8f5296c30b55fe9a09dbaacca65cbbd0e82 | refs/heads/master | 2021-04-28T02:25:30.642997 | 2018-02-20T05:28:20 | 2018-02-20T05:28:20 | 122,112,872 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,757 | h | // Copyright 1998-2017 Epic Games, Inc. All Rights Reserved.
/*===========================================================================
Generated code exported from UnrealHeaderTool.
DO NOT modify this manually! Edit the corresponding .h files instead!
===========================================================================*/
#include "ObjectMacros.h"
#include "ScriptMacros.h"
PRAGMA_DISABLE_DEPRECATION_WARNINGS
#ifdef GAMEPROGRAMMING2_GameProgramming2GameMode_generated_h
#error "GameProgramming2GameMode.generated.h already included, missing '#pragma once' in GameProgramming2GameMode.h"
#endif
#define GAMEPROGRAMMING2_GameProgramming2GameMode_generated_h
#define GameProgramming2_Source_GameProgramming2_GameProgramming2GameMode_h_12_RPC_WRAPPERS
#define GameProgramming2_Source_GameProgramming2_GameProgramming2GameMode_h_12_RPC_WRAPPERS_NO_PURE_DECLS
#define GameProgramming2_Source_GameProgramming2_GameProgramming2GameMode_h_12_INCLASS_NO_PURE_DECLS \
private: \
static void StaticRegisterNativesAGameProgramming2GameMode(); \
friend GAMEPROGRAMMING2_API class UClass* Z_Construct_UClass_AGameProgramming2GameMode(); \
public: \
DECLARE_CLASS(AGameProgramming2GameMode, AGameModeBase, COMPILED_IN_FLAGS(0 | CLASS_Transient), 0, TEXT("/Script/GameProgramming2"), GAMEPROGRAMMING2_API) \
DECLARE_SERIALIZER(AGameProgramming2GameMode) \
enum {IsIntrinsic=COMPILED_IN_INTRINSIC};
#define GameProgramming2_Source_GameProgramming2_GameProgramming2GameMode_h_12_INCLASS \
private: \
static void StaticRegisterNativesAGameProgramming2GameMode(); \
friend GAMEPROGRAMMING2_API class UClass* Z_Construct_UClass_AGameProgramming2GameMode(); \
public: \
DECLARE_CLASS(AGameProgramming2GameMode, AGameModeBase, COMPILED_IN_FLAGS(0 | CLASS_Transient), 0, TEXT("/Script/GameProgramming2"), GAMEPROGRAMMING2_API) \
DECLARE_SERIALIZER(AGameProgramming2GameMode) \
enum {IsIntrinsic=COMPILED_IN_INTRINSIC};
#define GameProgramming2_Source_GameProgramming2_GameProgramming2GameMode_h_12_STANDARD_CONSTRUCTORS \
/** Standard constructor, called after all reflected properties have been initialized */ \
GAMEPROGRAMMING2_API AGameProgramming2GameMode(const FObjectInitializer& ObjectInitializer); \
DEFINE_DEFAULT_OBJECT_INITIALIZER_CONSTRUCTOR_CALL(AGameProgramming2GameMode) \
DECLARE_VTABLE_PTR_HELPER_CTOR(GAMEPROGRAMMING2_API, AGameProgramming2GameMode); \
DEFINE_VTABLE_PTR_HELPER_CTOR_CALLER(AGameProgramming2GameMode); \
private: \
/** Private move- and copy-constructors, should never be used */ \
GAMEPROGRAMMING2_API AGameProgramming2GameMode(AGameProgramming2GameMode&&); \
GAMEPROGRAMMING2_API AGameProgramming2GameMode(const AGameProgramming2GameMode&); \
public:
#define GameProgramming2_Source_GameProgramming2_GameProgramming2GameMode_h_12_ENHANCED_CONSTRUCTORS \
private: \
/** Private move- and copy-constructors, should never be used */ \
GAMEPROGRAMMING2_API AGameProgramming2GameMode(AGameProgramming2GameMode&&); \
GAMEPROGRAMMING2_API AGameProgramming2GameMode(const AGameProgramming2GameMode&); \
public: \
DECLARE_VTABLE_PTR_HELPER_CTOR(GAMEPROGRAMMING2_API, AGameProgramming2GameMode); \
DEFINE_VTABLE_PTR_HELPER_CTOR_CALLER(AGameProgramming2GameMode); \
DEFINE_DEFAULT_CONSTRUCTOR_CALL(AGameProgramming2GameMode)
#define GameProgramming2_Source_GameProgramming2_GameProgramming2GameMode_h_12_PRIVATE_PROPERTY_OFFSET
#define GameProgramming2_Source_GameProgramming2_GameProgramming2GameMode_h_9_PROLOG
#define GameProgramming2_Source_GameProgramming2_GameProgramming2GameMode_h_12_GENERATED_BODY_LEGACY \
PRAGMA_DISABLE_DEPRECATION_WARNINGS \
public: \
GameProgramming2_Source_GameProgramming2_GameProgramming2GameMode_h_12_PRIVATE_PROPERTY_OFFSET \
GameProgramming2_Source_GameProgramming2_GameProgramming2GameMode_h_12_RPC_WRAPPERS \
GameProgramming2_Source_GameProgramming2_GameProgramming2GameMode_h_12_INCLASS \
GameProgramming2_Source_GameProgramming2_GameProgramming2GameMode_h_12_STANDARD_CONSTRUCTORS \
public: \
PRAGMA_ENABLE_DEPRECATION_WARNINGS
#define GameProgramming2_Source_GameProgramming2_GameProgramming2GameMode_h_12_GENERATED_BODY \
PRAGMA_DISABLE_DEPRECATION_WARNINGS \
public: \
GameProgramming2_Source_GameProgramming2_GameProgramming2GameMode_h_12_PRIVATE_PROPERTY_OFFSET \
GameProgramming2_Source_GameProgramming2_GameProgramming2GameMode_h_12_RPC_WRAPPERS_NO_PURE_DECLS \
GameProgramming2_Source_GameProgramming2_GameProgramming2GameMode_h_12_INCLASS_NO_PURE_DECLS \
GameProgramming2_Source_GameProgramming2_GameProgramming2GameMode_h_12_ENHANCED_CONSTRUCTORS \
private: \
PRAGMA_ENABLE_DEPRECATION_WARNINGS
#undef CURRENT_FILE_ID
#define CURRENT_FILE_ID GameProgramming2_Source_GameProgramming2_GameProgramming2GameMode_h
PRAGMA_ENABLE_DEPRECATION_WARNINGS
| [
"36519171+FancyKetchup96@users.noreply.github.com"
] | 36519171+FancyKetchup96@users.noreply.github.com |
f7edf244aa7bb479df47b0f78b7d290885e54d8a | 8fe22721304ad10a40474592fb9fac31f2067ca5 | /WindowsVisualStudio/CppConsole/CppConsole/Inflator.h | 0a2a5f65db43773e21dfee5cf1d9bd034dcfbe89 | [] | no_license | luckynwj7/ProgrammersAlgorithm | 630e576af76559c1974b5b0091cd3cb93c4c3c9e | ad8026ec7e390b498dc7d7aac38f18d1bf4b02dc | refs/heads/master | 2023-08-03T00:05:55.854350 | 2021-10-06T14:31:19 | 2021-10-06T14:37:28 | 273,201,165 | 0 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 279 | h | //
// Inflator.hpp
// testConsole
//
// Created by ³ë¿øÁ¾ on 2021/09/20.
//
#ifndef Inflator_h
#define Inflator_h
#include <iostream>
#include <vector>
class Inflator {
public:
virtual ~Inflator() {}
virtual void ShowResult() = 0;
};
#endif /* Inflator_h */
| [
"44963879+luckynwj7@users.noreply.github.com"
] | 44963879+luckynwj7@users.noreply.github.com |
80ae6498408926f5f609265bde94a911bf54b613 | 6f05f7d5a67b6bb87956a22b988067ec772ba966 | /data/train/cpp/c5a47d37a825a19cf2d12e0ac36a6ceafdaf8ae1onsetdetection.h | c5a47d37a825a19cf2d12e0ac36a6ceafdaf8ae1 | [
"MIT"
] | permissive | harshp8l/deep-learning-lang-detection | 93b6d24a38081597c610ecf9b1f3b92c7d669be5 | 2a54293181c1c2b1a2b840ddee4d4d80177efb33 | refs/heads/master | 2020-04-07T18:07:00.697994 | 2018-11-29T23:21:23 | 2018-11-29T23:21:23 | 158,597,498 | 0 | 0 | MIT | 2018-11-21T19:36:42 | 2018-11-21T19:36:41 | null | UTF-8 | C++ | false | false | 704 | h | #ifndef _ONSETDETECTION_H
#define _ONSETDETECTION_H
#include <string.h>
typedef double sample;
sample mean(sample arr[], int n);
sample median(sample arr[], int n);
class RTOnsetDetection {
private:
int n_prev_values;
sample* prev_values;
sample* prev_values_copy; // needed to compute median as input array is modified
sample threshold;
sample mean_weight;
sample median_weight;
int median_window;
sample largest_peak;
sample noise_ratio;
sample max_threshold;
public:
RTOnsetDetection();
~RTOnsetDetection();
bool is_onset(sample odf_value);
sample max_odf_value;
};
#endif
| [
"aliostad+github@gmail.com"
] | aliostad+github@gmail.com |
8e702e90923e67af2d21a389f14af60d4a02d30c | ad1ce910ab5d9382a87bebd2480f73ecca4c37a5 | /bvp2d.cpp | 03d7ea027066da046cd32e81ed4e93c9effc0b0f | [
"MIT"
] | permissive | grenkin/joker-fdm | 33fee3fff4aa948bd4ba82c7016227a84b3cc5d8 | 21d60479ca0dd7f2deb0d8ce000f79a7c53f3202 | refs/heads/master | 2020-04-09T04:14:21.820983 | 2018-09-21T02:04:35 | 2018-09-21T02:04:35 | 68,077,571 | 4 | 0 | null | 2016-10-14T21:30:28 | 2016-09-13T05:35:13 | Matlab | UTF-8 | C++ | false | false | 9,250 | cpp | #include <boost/numeric/mtl/mtl.hpp>
#include <boost/numeric/itl/itl.hpp>
#include <cmath>
#include "bvp2d.h"
#include "var_expr.h"
inline int nindex (const Data2D& data, int i, int jX, int jY, int nX, int nY)
{
return i * data.grid.total_number_of_nodes + data.grid.index(jX, jY, nX, nY);
}
VarExpr U (const Data2D& data, int i, int jX, int jY, int nX, int nY)
{
VarExpr ve;
ve.num = 1;
ve.ind.push_back(nindex(data, i, jX, jY, nX, nY));
ve.val.push_back(1);
ve.rhs = 0;
return ve;
}
VarExpr DifferenceOperator2D_1D (const Data2D& data, var_t var,
int i, int jX, int jY, int nX, int nY)
// except the case of Dirichlet BC
{
std::array<int, 2> j = {jX, jY}, n = {nX, nY};
if (j[var] == 0 && n[var] == 0 || j[var] == data.grid.M[var] - 1
&& n[var] == data.grid.K[var][j[var]])
{
// boundary node
var_t var1 = (var_t)(1 - var);
std::array<int, 2> n1 = n;
double b0, w0;
if (n[var] == 0) {
// left or bottom boundary node
n1[var] = n[var] + 1;
b0 = data.b[i](var, 0, j[var1], n[var1]);
w0 = data.w[i](var, 0, j[var1], n[var1]);
}
else { // n[var] == data.grid.K[var][j[var]]
// right or top boundary node
n1[var] = n[var] - 1;
b0 = data.b[i](var, 1, j[var1], n[var1]);
w0 = data.w[i](var, 1, j[var1], n[var1]);
}
if (std::isinf(b0)) {
// Dirichlet BC
throw;
}
else {
return 2 * data.a[i][jX][jY] / pow(data.grid.h[var][j[var]], 2)
* (U(data, i, jX, jY, nX, nY) - U(data, i, jX, jY, n1[VAR_X], n1[VAR_Y]))
+ 2 / data.grid.h[var][j[var]] * (b0 * U(data, i, jX, jY, nX, nY) - w0);
}
}
else if (n[var] == data.grid.K[var][j[var]]) {
// rightmost or topmost node of the j-th domain
if (std::isinf(data.G[i][var][jX][jY])) {
// perfect contact conjugation conditions
// TODO; choose a large G instead of infinity
throw;
}
else {
// imperfect contact conjugation conditions
std::array<int, 2> n1 = n, j2 = j, n2 = n;
n1[var] = n[var] - 1;
j2[var] = j[var] + 1;
n2[var] = 0;
return 2 * data.a[i][jX][jY] / pow(data.grid.h[var][j[var]], 2)
* (U(data, i, jX, jY, nX, nY) - U(data, i, jX, jY, n1[VAR_X], n1[VAR_Y]))
+ 2 * data.G[i][var][jX][jY] / data.grid.h[var][j[var]]
* (U(data, i, jX, jY, nX, nY)
- U(data, i, j2[VAR_X], j2[VAR_Y], n2[VAR_X], n2[VAR_Y]));
}
}
else if (n[var] == 0) {
// leftmost or bottommost node of the j-th domain
std::array<int, 2> j2 = j;
j2[var] = j[var] - 1;
if (std::isinf(data.G[i][var][j2[VAR_X]][j2[VAR_Y]])) {
// perfect contact conjugation conditions
// TODO; choose a large G instead of infinity
throw;
}
else {
// imperfect contact conjugation conditions
std::array<int, 2> n1 = n, n2 = n;
n1[var] = n[var] + 1;
n2[var] = data.grid.K[var][j2[var]];
return 2 * data.a[i][jX][jY] / pow(data.grid.h[var][j[var]], 2)
* (U(data, i, jX, jY, nX, nY) - U(data, i, jX, jY, n1[VAR_X], n1[VAR_Y]))
+ 2 * data.G[i][var][j2[VAR_X]][j2[VAR_Y]] / data.grid.h[var][j[var]]
* (U(data, i, jX, jY, nX, nY)
- U(data, i, j2[VAR_X], j2[VAR_Y], n2[VAR_X], n2[VAR_Y]));
}
}
else {
// internal node
std::array<int, 2> n1 = n, n2 = n;
n1[var] = n[var] - 1;
n2[var] = n[var] + 1;
return - data.a[i][jX][jY] / pow(data.grid.h[var][j[var]], 2)
* (U(data, i, jX, jY, n1[VAR_X], n1[VAR_Y])
- 2 * U(data, i, jX, jY, nX, nY)
+ U(data, i, jX, jY, n2[VAR_X], n2[VAR_Y]));
}
}
bool equal(double a, double b)
{
return abs(a - b) < 1e-12;
}
bool is_Dirichlet (const Data2D& data, int i, int jX, int jY, int nX, int nY, double& w0)
{
// Note: equal nodes in conjugation conditions are not checked
std::array<int, 2> j = {jX, jY}, n = {nX, nY};
bool w0_set = false;
for (int var_index = 0; var_index < 2; ++var_index) {
var_t var = (var_t)var_index;
if (j[var] == 0 && n[var] == 0 || j[var] == data.grid.M[var] - 1
&& n[var] == data.grid.K[var][j[var]])
{
var_t var1 = (var_t)(1 - var_index);
double b1, w1;
if (n[var] == 0) {
// left or bottom boundary node
b1 = data.b[i](var, 0, j[var1], n[var1]);
w1 = data.w[i](var, 0, j[var1], n[var1]);
}
else { // n[var] == data.grid.K[var][j[var]]
// right or top boundary node
b1 = data.b[i](var, 1, j[var1], n[var1]);
w1 = data.w[i](var, 1, j[var1], n[var1]);
}
if (std::isinf(b1)) {
if (w0_set) {
if (!equal(w0, w1))
throw ENotConsistentDirichletBC(i, jX, jY, nX, nY);
}
else {
w0 = w1;
w0_set = true;
}
}
}
}
return w0_set;
}
VarExpr DifferenceOperator2D (const Data2D& data, int i, int jX, int jY, int nX, int nY)
{
double w0;
if (is_Dirichlet(data, i, jX, jY, nX, nY, w0))
return U(data, i, jX, jY, nX, nY) - w0;
else {
return DifferenceOperator2D_1D(data, VAR_X, i, jX, jY, nX, nY)
+ DifferenceOperator2D_1D(data, VAR_Y, i, jX, jY, nX, nY);
}
}
VarExpr NonlinearOperator2D (const Data2D& data, int i, int jX, int jY,
int nX, int nY, const mtl::dense_vector<double>& x_old)
{
double w0;
if (is_Dirichlet(data, i, jX, jY, nX, nY, w0))
return 0;
VarExpr ve = - data.g[i](jX, jY, nX, nY);
for (int k = 0; k < data.N; ++k) {
int ind = nindex(data, k, jX, jY, nX, nY);
ve += data.f[i][jX][jY][k](x_old[ind]) +
data.df[i][jX][jY][k](x_old[ind]) * (U(data, k, jX, jY, nX, nY) - x_old[ind]);
}
return ve;
}
void SolveBVP2D (const Data2D& data, const Parameters2D& param,
std::vector<GridFunction2D>& sol)
{
int unknowns = data.N * data.grid.total_number_of_nodes;
mtl::compressed2D<double> A(unknowns, unknowns);
mtl::dense_vector<double> b(unknowns), x(unknowns), x_old(unknowns);
int elements_per_row = 4 + data.N; // parameter of the inserter
// Set the initial guess
for (int i = 0; i < data.N; ++i) {
for (int jX = 0; jX < data.grid.M[VAR_X]; ++jX) {
for (int nX = 0; nX <= data.grid.K[VAR_X][jX]; ++nX) {
for (int jY = 0; jY < data.grid.M[VAR_Y]; ++jY) {
for (int nY = 0; nY <= data.grid.K[VAR_Y][jY]; ++nY)
x[nindex(data, i, jX, jY, nX, nY)] = sol[i](jX, jY, nX, nY);
}
}
}
}
// Apply Newton's method
int num_iterations = 0;
do {
A = 0;
x_old = x;
{ // additional block for applying the inserter
mtl::mat::inserter<mtl::compressed2D<double>,
mtl::update_plus<double> > ins(A, elements_per_row);
for (int i = 0; i < data.N; ++i) {
for (int jX = 0; jX < data.grid.M[VAR_X]; ++jX) {
for (int nX = 0; nX <= data.grid.K[VAR_X][jX]; ++nX) {
for (int jY = 0; jY < data.grid.M[VAR_Y]; ++jY) {
for (int nY = 0; nY <= data.grid.K[VAR_Y][jY]; ++nY) {
VarExpr ve = DifferenceOperator2D(data, i, jX, jY, nX, nY)
+ NonlinearOperator2D(data, i, jX, jY, nX, nY, x_old);
int row = nindex(data, i, jX, jY, nX, nY);
b[row] = ve.rhs;
for (int s = 0; s < ve.num; ++s)
ins(row, ve.ind[s]) << ve.val[s];
}
}
}
}
}
}
// Solve the linear system
itl::pc::ilu_0<mtl::compressed2D<double> > P(A);
itl::basic_iteration<double> iter(b, param.max_linear_sys_iterations,
param.linear_sys_tol);
// x is equal to the previous guess
bicgstab(A, x, b, P, iter);
++num_iterations;
} while (!(mtl::infinity_norm(x - x_old) < param.Newton_tol ||
num_iterations >= param.max_Newton_iterations));
// Set the solution
for (int i = 0; i < data.N; ++i) {
for (int jX = 0; jX < data.grid.M[VAR_X]; ++jX) {
for (int nX = 0; nX <= data.grid.K[VAR_X][jX]; ++nX) {
for (int jY = 0; jY < data.grid.M[VAR_Y]; ++jY) {
for (int nY = 0; nY <= data.grid.K[VAR_Y][jY]; ++nY)
sol[i](jX, jY, nX, nY) = x[nindex(data, i, jX, jY, nX, nY)];
}
}
}
}
}
| [
"glebgrenkin@gmail.com"
] | glebgrenkin@gmail.com |
bf2de1852b8103872ff63bdc0912af90a97675d2 | 15831ecccf14b2ad7f3e599bcc4ddd196b58eece | /SOLVE/uva solved/10678 - The Grazing Cow.cpp | 46bc61969bb4666b795c3003502c92437eac662d | [] | no_license | Sujit34/Problem-Solving | 542ac2b1ad67c7cfa353c23c74c5ec2b6ec195c4 | 5045d430b12971f09a74ee1bdb4dbb411b404aa9 | refs/heads/master | 2023-08-31T04:36:44.690454 | 2023-08-30T14:14:29 | 2023-08-30T14:14:29 | 162,864,398 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 493 | cpp | #include<cstdio>
#include<iostream>
#include<algorithm>
#include<cmath>
#include<cstring>
#include<cstdlib>
#define LLI long long int
#define ULL unsigned long long
#define PI acos(-1.0)
#define EPS 1e-9
#define CLR(a) memset(a,0,sizeof(a))
using namespace std;
int main()
{
double n,d,l,result,a,b;
cin>>n;
while(n--)
{
cin>>d>>l;
a=l/2;
b=sqrt(((l/2)*(l/2))-((d/2)*(d/2)));
result=PI*a*b;
printf("%.3lf\n",result);
}
}
| [
"sujitcsecuet@gmail.com"
] | sujitcsecuet@gmail.com |
a29f874247ba5e39b8fe49cc5dc45422fa9528f6 | 4b8296335e4fa1a38264fef02f430d3b57884cce | /chrome/browser/ui/views/frame/tab_strip_region_view.h | 406d59268581297f534bf03c62e85074517e79e7 | [
"BSD-3-Clause"
] | permissive | coxchris502/chromium | 07ad6d930123bbf6e1754fe1820505f21d719fcd | f786352782a89d148a10d7bdd8ef3d0a86497926 | refs/heads/master | 2022-11-06T23:54:53.001812 | 2020-07-03T14:54:27 | 2020-07-03T14:54:27 | 276,935,925 | 1 | 0 | BSD-3-Clause | 2020-07-03T15:49:58 | 2020-07-03T15:49:57 | null | UTF-8 | C++ | false | false | 1,223 | h | // Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CHROME_BROWSER_UI_VIEWS_FRAME_TAB_STRIP_REGION_VIEW_H_
#define CHROME_BROWSER_UI_VIEWS_FRAME_TAB_STRIP_REGION_VIEW_H_
#include "chrome/browser/ui/views/tabs/tab_strip.h"
#include "ui/views/view.h"
// Container for the tabstrip, new tab button, and reserved grab handle space.
// TODO (https://crbug.com/949660) Under construction.
class TabStripRegionView final : public views::View {
public:
TabStripRegionView();
~TabStripRegionView() override;
// Takes ownership of the tabstrip.
TabStrip* AddTabStrip(std::unique_ptr<TabStrip> tab_strip);
// views::View overrides:
const char* GetClassName() const override;
void ChildPreferredSizeChanged(views::View* child) override;
gfx::Size GetMinimumSize() const override;
// TODO(958173): Override OnBoundsChanged to cancel tabstrip animations.
private:
DISALLOW_COPY_AND_ASSIGN(TabStripRegionView);
int CalculateTabStripAvailableWidth();
views::View* tab_strip_container_;
views::View* tab_strip_;
};
#endif // CHROME_BROWSER_UI_VIEWS_FRAME_TAB_STRIP_REGION_VIEW_H_
| [
"commit-bot@chromium.org"
] | commit-bot@chromium.org |
f4b91f6ba51b11af35bbc0501abea0182e7b6129 | 032ceb96c84d2b2a88c15b5e1b8e90fc492776c7 | /Engine/AModule.cpp | aa2c387f8af0cc4777148f9be87e9eff17d20263 | [] | no_license | antiqe/RType | ae8859cfe589cfcfbd5ba8c0fc82480bfcd759d5 | 6165ad1dd11c179c82946d8be07c862db82483b4 | refs/heads/master | 2016-09-06T09:31:13.177842 | 2013-12-04T09:59:40 | 2013-12-04T09:59:40 | 14,722,487 | 1 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 910 | cpp | #include "AModule.hpp"
namespace Engine
{
std::string const AModule::EVENT = "event";
std::string const AModule::SOUND = "sound";
std::string const AModule::RENDER = "render";
std::string const AModule::STATE = "state";
std::string const AModule::DATA = "data";
std::string const AModule::SOURCE = "source";
std::string const AModule::NETWORK = "network";
std::string const AModule::FACTORY = "factory";
AModule::Compare::Compare(std::string const& id)
: _id(id)
{
}
bool AModule::Compare::operator()(AModule* const& module) const
{
return (this->_id == module->getID());
}
AModule::AModule(size_t frame)
: _owner(0), _frame(frame)
{
}
AModule::~AModule()
{
}
bool AModule::isImportant() const
{
return ((int)this->_frame == -1);
}
void AModule::setFrame(size_t frame)
{
this->_frame = frame;
}
size_t AModule::getFrame() const
{
return (this->_frame);
}
} | [
"alexis.leprovost@epitech.eu"
] | alexis.leprovost@epitech.eu |
d6d4a32e67c80eb5ef312c672efaffe4f797d19f | 76187296b12b09d94d0f983292c266bd347e2f3b | /codes/general/branch/ifElse.cc | 6a5387296db14d05dd82dfb1eedd29311fd0d0af | [] | no_license | SPLURGE831/practice | 0d6caa6abb8f9869946ed2ee54489d79edffdc74 | 5a86e5ca536b55235de6082f2cd095baaea5cfe2 | refs/heads/master | 2021-01-15T12:42:04.112067 | 2013-05-25T09:33:08 | 2013-05-25T09:33:08 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 98 | cc | //
int main()
{
int i=0;
int j = 1;
if (i && j)
i++;
else
i--;
return i;
}
| [
"junius.zhou@gmail.com"
] | junius.zhou@gmail.com |
95e4b9e932d79ca96a88840790054cb63aac292f | 8d7e9afd84f1e4dd6f95770287b8bee012d85c16 | /cc_sept_algomaniac/5.cpp | ec35ea5580de687df7ed192aa0c4f541db71ebbb | [] | no_license | amritshukla001/CodeChef-Solution | fae18b3675933dea5f8d281cb4d38b211de8386f | 4766c2a8b3a1c0df091a41d1f3099ec5b61d386b | refs/heads/master | 2023-08-11T12:33:24.423521 | 2021-10-09T19:41:11 | 2021-10-09T19:41:11 | 415,405,885 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,880 | cpp | #include <bits/stdc++.h>
#include <unordered_map>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef long double lld;
#define int long long
#define IOS \
ios_base::sync_with_stdio(false); \
cin.tie(NULL);
#define testcase \
long long testn; \
cin >> testn; \
while (testn--)
#define wi(x) cout << #x << " = " << x << endl;
#define wi2(x, y) cout << #x << " = " << x << " and " << #y << " = " << y << endl;
#define fo(i, l, r) for (int i = l; i < r; i++)
#define fo1(i, l, r) for (int i = l; i <= r; i++)
#define fore(i, l, r) for (int i = l; i > r; i--)
#define fore1(i, l, r) for (int i = l; i >= r; i--)
#define mp make_pair
#define fr first
#define sc second
#define pb push_back
#define mem1(ar) memset(ar,-1,sizeof(a))
#define mem0(ar) memset(ar,0,sizeof(a))
#define inp(v) for (auto &x : v) cin >> x;
#define disp(v) \
for(const auto &x:v) cout << x << "\t"; \
cout << "\n";
#define all(v) v.begin(),v.end()
#define uniq(v) (v).erase(unique(all(v)),(v).end())
template<typename T, typename T1>T amax(T &a, T1 b) {if (b > a)a = b; return a;}
template<typename T, typename T1>T amin(T &a, T1 b) {if (b < a)a = b; return a;}
const ll m = 1e9 + 7;
#ifndef ONLINE_JUDGE
#define debug(x) cerr << #x <<" "; _print(x); cerr << endl;
#else
#define debug(x);
#endif
/*---------------------------------------------------------------------------------------------------------------------------*/
void _print(int t) {cerr << t;}
void _print(string t) {cerr << t;}
void _print(char t) {cerr << t;}
void _print(lld t) {cerr << t;}
void _print(double t) {cerr << t;}
void _print(ull t) {cerr << t;}
template <class T, class V> void _print(pair <T, V> p);
template <class T> void _print(vector <T> v);
template <class T> void _print(set <T> v);
template <class T, class V> void _print(map <T, V> v);
template <class T> void _print(multiset <T> v);
template <class T, class V> void _print(pair <T, V> p) {cerr << "{"; _print(p.fr); cerr << ","; _print(p.sc); cerr << "}";}
template <class T> void _print(vector <T> v) {cerr << "[ "; for (T i : v) {_print(i); cerr << " ";} cerr << "]";}
template <class T> void _print(set <T> v) {cerr << "[ "; for (T i : v) {_print(i); cerr << " ";} cerr << "]";}
template <class T> void _print(multiset <T> v) {cerr << "[ "; for (T i : v) {_print(i); cerr << " ";} cerr << "]";}
template <class T, class V> void _print(map <T, V> v) {cerr << "[ "; for (auto i : v) {_print(i); cerr << " ";} cerr << "]";}
/*---------------------------------------------------------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------------------------------------------------------*/
ll gcd(ll a, ll b) {if (b > a) {return gcd(b, a);} if (b == 0) {return a;} return gcd(b, a % b);}
ll expo(ll a, ll b, ll mod) {ll res = 1; while (b > 0) {if (b & 1)res = (res * a) % mod; a = (a * a) % mod; b >>= 1;} return res;}
bool revsort(ll a, ll b) {return a > b;}
void swap(int &x, int &y) {int temp = x; x = y; y = temp;}
/*---------------------------------------------------------------------------------------------------------------------------*/
void solve() {
int n, k, s;
cin >> n >> k >> s;
vector<int> ai(n);
vector<vector<int>> c(n, vector<int>(k));
inp(ai);
fo(i, 0, n) {
vector<int> temp(k);
inp(temp);
c[i] = temp;
}
vector<int> dis(n, 1);
dis[s - 1] = 0;
fo(i, 0, n) if (ai[i] == ai[s - 1]) dis[i] = 0;
debug(dis);
debug(mp(ai, c));
}
int32_t main() {
IOS;
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
freopen("output.txt", "w" , stdout);
freopen("Error.txt", "w", stderr);
#endif
//clock_t tStart=clock();
solve();
//printf("Time taken: %.2fs\n", (double)(clock() - tStart)/CLOCKS_PER_SEC);
return 0;
} | [
"syeadmaazahmed@fmail.com"
] | syeadmaazahmed@fmail.com |
a76b6afb6ee2b8ed1a2f1e5562fac8e283f6eb06 | 4e3c4f30415062da425ad3058a0c1fed167e961e | /1004.cpp | 5fd7ed8774d2a616f6e59955c5cbcf3ed98b5a79 | [] | no_license | jing-ge/Jing-leetcode | 7f423d94d3983076630f33e7205c0ef6d54c20d8 | ae428bd3da52bb5658f3a25fbbd395b24552a735 | refs/heads/main | 2023-08-22T12:19:12.861091 | 2021-09-29T03:15:24 | 2021-09-29T03:15:24 | 321,316,029 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,764 | cpp | // 1004. Max Consecutive Ones III
// Given an array A of 0s and 1s, we may change up to K values from 0 to 1.
// Return the length of the longest (contiguous) subarray that contains only 1s.
// Example 1:
// Input: A = [1,1,1,0,0,0,1,1,1,1,0], K = 2
// Output: 6
// Explanation:
// [1,1,1,0,0,1,1,1,1,1,1]
// Bolded numbers were flipped from 0 to 1. The longest subarray is underlined.
// Example 2:
// Input: A = [0,0,1,1,0,0,1,1,1,0,1,1,0,0,0,1,1,1,1], K = 3
// Output: 10
// Explanation:
// [0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1]
// Bolded numbers were flipped from 0 to 1. The longest subarray is underlined.
// Note:
// 1 <= A.length <= 20000
// 0 <= K <= A.length
// A[i] is 0 or 1
// 通过次数28,047提交次数47,331
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
int longestOnes1(vector<int>& A, int K) {
int res = 0,k = 0,left = 0,right = 0;
while(right<A.size()){
while(k<K&&right<A.size()){
if(A[right]==0){
k++;
}
right++;
}
while(right<A.size()&&A[right])right++;
// cout<<left<<","<<right<<","<<k<<endl;
res = max(res,right-left);
if(k>0&&A[left]==0)k--;
left++;
if(left>right)right = left;
}
return res;
}
int longestOnes(vector<int>& A, int K) {
int left = 0, right = 0;
while(right<A.size()){
if(A[right++]==0)K--;
if(K<0&&A[left++]==0)K++;
}
return right-left;
}
};
int main(){
vector<int> A = {0,0,1,1,0,0};
int K = 0;
Solution s;
int res = s.longestOnes(A,K);
cout<<res<<endl;
return 0;
} | [
"675324370@qq.com"
] | 675324370@qq.com |
4f3c7eb9f194b39e2086461e2abc827994d6c7c7 | 6b2985d7ea8b289badbeade95efe45f02409cf1b | /bom.h | b4a8bfcc889a0847549bbee99e7bb7328c89ace3 | [] | no_license | feengg/SanTang | e92a3f7cca8766fe047739501d558bab3c326087 | 83577a464b251c96f26f75e13e7a557aa477a0ed | refs/heads/master | 2021-05-18T00:18:29.374704 | 2020-05-03T15:02:10 | 2020-05-03T15:02:10 | 251,019,653 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,668 | h | #ifndef BOM_H
#define BOM_H
#include <QWidget>
#include <QMouseEvent>
//#include <QAxObject>
#include <QFileDialog>
//#include "qexcel.h"
#include <QDebug>
#include <QMessageBox>
#include <QVariantList>
#include "widget.h"
#include "cgsq.h"
namespace Ui {
class Bom;
}
class Bom : public QWidget
{
Q_OBJECT
public:
explicit Bom(QWidget *parent = 0);
~Bom();
void mousePressEvent(QMouseEvent * event);
void mouseMoveEvent(QMouseEvent * event);
void mouseReleaseEvent(QMouseEvent *event);
QVariant static getCellValue(QAxObject * axObject,int row,int col);
int static getUsedRowsCount(QAxObject * workSheet);
void static setCellString(QAxObject * workSheet,int row, int column, const QVariant& value);
void static setCellValue(QAxObject * m_word,int row,int col,QString value);
bool static insertTable(QAxObject * m_document,QAxObject * m_word,int row,int column);
void static setRowAlignment(QAxObject * m_document,int row,int flag);
void static setColumnWidth(QAxObject * m_word,int column, int width);
void static setCellFontBold(QAxObject * m_document,int row,int column);
void static removeListSame(QStringList * list);
signals:
void emitToCGSQToFlushStreamListSig(QString type);
private slots:
void on_toolButton_clicked();
void on_pushButton_loadBom_clicked();
void on_pushButton_ok_clicked();
void on_pushButton_cgqd_clicked();
void on_pushButton_mxb_clicked();
void on_pushButton_cgsq_clicked();
void getCGSQSigSlot(QString type);
private:
Ui::Bom *ui;
bool dragWindow;
QPoint position;
QString bomFilePath = NULL;
};
#endif // BOM_H
| [
"feengg@163.com"
] | feengg@163.com |
c38ede1b179ce87825d54cadd4e9d6eccb1a11b0 | 0a62988d753fccb92e7fddfcf416e84819ce12d1 | /GEDDVASVF/Source/CommonFunctions.h | 2353a9377f95180e79d93f8bc8679f4f7e766d40 | [
"LicenseRef-scancode-warranty-disclaimer"
] | no_license | hgeddon/GEDD_JUCE_PUBLIC | 89e92011e1b47a19b59d9ba1aa7ff5af2f34ff4f | a3d9ef81433187a84ff1d5e5c64ee6041f9915a6 | refs/heads/main | 2023-06-23T23:58:17.796136 | 2021-08-02T15:08:29 | 2021-08-02T15:08:29 | 391,396,481 | 5 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,230 | h | /*
==============================================================================
CommonFunctions.h
Created: 31 Jul 2021 4:25:36pm
Author: GEDD
==============================================================================
*/
#pragma once
#include <JuceHeader.h>
namespace gedd
{
// Beginning index for each custom component's ColourIDs
namespace ComponentColourID
{
constexpr auto FrequencyDecibelGridOverlay = 0x8800000;
constexpr auto VASVFTraceComponent = 0x8800100;
}
// Create a NormalisableRange of template type with frequency scaling
template <typename Type = float>
static juce::NormalisableRange<Type> createFrequencyRange(Type min, Type max, Type interval = static_cast<Type>(0))
{
// have to create it and move it if we want to set the 'interval' parameter
auto x = juce::NormalisableRange<Type>(min, max,
[](Type start, Type end, Type value) mutable // from 0 to 1
{
const auto startLog = std::log(start);
const auto endLog = std::log(end);
return std::exp((value) * (endLog - startLog) + startLog);
},
[](Type start, Type end, Type value) mutable // to 0 to 1
{
const auto startLog = std::log(start);
const auto endLog = std::log(end);
return (std::log(value) - startLog) / (endLog - startLog);
});
x.interval = interval;
return std::move(x);
}
// Basic float to text / text to float conversion methods
static juce::String floatValueToTextFunction(float x) { return juce::String(x, 2); }
static float floatTextToValueFunction(const juce::String& str) { return str.getFloatValue(); }
// Math Constants
template <typename FloatType>
struct MathConstants
{
/** A predefined value for 1 / pi */
static constexpr FloatType reciprocalPi = static_cast<FloatType>(1 / 3.141592653589793238L);
/** A predefined value for 1 / twopi */
static constexpr FloatType reciprocalTwopi = static_cast<FloatType>(1 / (2 * 3.141592653589793238L));
/** A predefined value for 1 / halfpi */
static constexpr FloatType reciprocalHalfpi = static_cast<FloatType>(1 / (3.141592653589793238L / 2));
/** A predefined value for 1 / euler's number */
static constexpr FloatType reciprocalEuler = static_cast<FloatType>(1 / (2.71828182845904523536L));
/** A predefined value for 1 / sqrt(2) */
static constexpr FloatType reciprocalSqrt2 = static_cast<FloatType> (0.70710678118654752440L);
};
// gets the previous power of 2 to compliment juce::nextPowerOfTwo
inline int lastPowerOfTwo(int n) noexcept
{
n |= (n >> 1);
n |= (n >> 2);
n |= (n >> 4);
n |= (n >> 8);
n |= (n >> 16);
return n - (n >> 1);
}
/* Integer modulo for negative values */
static int reverseModulo(int x, int y)
{
jassert(x < 0); // why use it if not negative?
auto z = y - ((0 - x) % y);
if (z == y) z = 0;
return z;
}
} // namespace gedd | [
"harmergeddontv@gmail.com"
] | harmergeddontv@gmail.com |
6daf960896360783568c90721acb79b1d0c8b363 | 47a765a596da856d749b98cc671562484f98ac06 | /include/OMXCore.h | 8ba5fabd59dd6ad9083f255bc4f455c83aa15166 | [] | no_license | dlxqlig/xmbc_audio_engine | 34807acb016afe0d2bffdac614d60d091ac16263 | c4bcae9a52fd56afa5e0bed0989a9f0fae16f5b7 | refs/heads/master | 2021-01-20T00:56:38.175305 | 2014-01-28T12:28:58 | 2014-01-28T12:28:58 | 16,304,718 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 7,214 | h | /*
Copyright (C) 2007-2009 STMicroelectronics
Copyright (C) 2007-2009 Nokia Corporation and/or its subsidiary(-ies)
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.1 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, write to the Free Software Foundation, Inc.,
51 Franklin St, Fifth Floor, Boston, MA
02110-1301 USA
$Date: 2009-10-09 14:34:15 +0200 (Fri, 09 Oct 2009) $
Revision $Rev: 875 $
Author $Author: gsent $
You can also contact with mail(gangx.li@intel.com)
*/
#pragma once
#include <string>
#include <queue>
#include <string.h>
#ifndef OMX_SKIP64BIT
#define OMX_SKIP64BIT
#endif
#include <semaphore.h>
#include "OMX_Core.h"
#include "OMX_Component.h"
#include "OMX_Index.h"
#include "OMX_Image.h"
#include "OMX_Video.h"
#if 0
#define OMX_DEBUG_VERBOSE
#define OMX_DEBUG_EVENTHANDLER
#endif
#if 0
#define OMX_INIT_STRUCTURE(a) \
memset(&(a), 0, sizeof(a)); \
(a).nSize = sizeof(a); \
(a).nVersion.s.nVersionMajor = OMX_VERSION_MAJOR; \
(a).nVersion.s.nVersionMinor = OMX_VERSION_MINOR; \
(a).nVersion.s.nRevision = OMX_VERSION_REVISION; \
(a).nVersion.s.nStep = OMX_VERSION_STEP
#else
#define OMX_INIT_STRUCTURE(a) \
memset(&(a), 0, sizeof(a)); \
(a).nSize = sizeof(a); \
(a).nVersion.s.nVersionMajor = 1; \
(a).nVersion.s.nVersionMinor = 1; \
(a).nVersion.s.nRevision = 0; \
(a).nVersion.s.nStep = 0
#endif
#define OMX_MAX_PORTS 10
typedef struct omx_event {
OMX_EVENTTYPE eEvent;
OMX_U32 nData1;
OMX_U32 nData2;
} omx_event;
class COMXCore;
class COMXCoreComponent;
class COMXCoreComponent
{
public:
COMXCoreComponent();
~COMXCoreComponent();
OMX_HANDLETYPE GetComponent() { return m_handle; };
unsigned int GetInputPort() { return m_input_port; };
unsigned int GetOutputPort() { return m_output_port; };
std::string GetName() { return m_componentName; };
OMX_ERRORTYPE DisableAllPorts();
void RemoveEvent(OMX_EVENTTYPE eEvent, OMX_U32 nData1, OMX_U32 nData2);
OMX_ERRORTYPE AddEvent(OMX_EVENTTYPE eEvent, OMX_U32 nData1, OMX_U32 nData2);
OMX_ERRORTYPE WaitForEvent(OMX_EVENTTYPE event, long timeout = 300);
OMX_ERRORTYPE WaitForCommand(OMX_U32 command, OMX_U32 nData2, long timeout = 2000);
OMX_ERRORTYPE SetStateForComponent(OMX_STATETYPE state);
OMX_STATETYPE GetState();
OMX_ERRORTYPE SetParameter(OMX_INDEXTYPE paramIndex, OMX_PTR paramStruct);
OMX_ERRORTYPE GetParameter(OMX_INDEXTYPE paramIndex, OMX_PTR paramStruct);
OMX_ERRORTYPE SetConfig(OMX_INDEXTYPE configIndex, OMX_PTR configStruct);
OMX_ERRORTYPE GetConfig(OMX_INDEXTYPE configIndex, OMX_PTR configStruct);
OMX_ERRORTYPE SendCommand(OMX_COMMANDTYPE cmd, OMX_U32 cmdParam, OMX_PTR cmdParamData);
OMX_ERRORTYPE EnablePort(unsigned int port, bool wait = true);
OMX_ERRORTYPE DisablePort(unsigned int port, bool wait = true);
OMX_ERRORTYPE UseEGLImage(OMX_BUFFERHEADERTYPE** ppBufferHdr, OMX_U32 nPortIndex, OMX_PTR pAppPrivate, void* eglImage);
bool Initialize( const std::string &component_name, OMX_INDEXTYPE index);
bool IsInitialized();
bool Deinitialize(bool free_component = false);
// OMXCore Decoder delegate callback routines.
static OMX_ERRORTYPE DecoderEventHandlerCallback(OMX_HANDLETYPE hComponent, OMX_PTR pAppData,
OMX_EVENTTYPE eEvent, OMX_U32 nData1, OMX_U32 nData2, OMX_PTR pEventData);
static OMX_ERRORTYPE DecoderEmptyBufferDoneCallback(
OMX_HANDLETYPE hComponent, OMX_PTR pAppData, OMX_BUFFERHEADERTYPE* pBuffer);
static OMX_ERRORTYPE DecoderFillBufferDoneCallback(
OMX_HANDLETYPE hComponent, OMX_PTR pAppData, OMX_BUFFERHEADERTYPE* pBufferHeader);
// OMXCore decoder callback routines.
OMX_ERRORTYPE DecoderEventHandler(OMX_HANDLETYPE hComponent, OMX_PTR pAppData,
OMX_EVENTTYPE eEvent, OMX_U32 nData1, OMX_U32 nData2, OMX_PTR pEventData);
OMX_ERRORTYPE DecoderEmptyBufferDone(
OMX_HANDLETYPE hComponent, OMX_PTR pAppData, OMX_BUFFERHEADERTYPE* pBuffer);
OMX_ERRORTYPE DecoderFillBufferDone(
OMX_HANDLETYPE hComponent, OMX_PTR pAppData, OMX_BUFFERHEADERTYPE* pBuffer);
void TransitionToStateLoaded();
OMX_ERRORTYPE EmptyThisBuffer(OMX_BUFFERHEADERTYPE *omx_buffer);
OMX_ERRORTYPE FillThisBuffer(OMX_BUFFERHEADERTYPE *omx_buffer);
OMX_ERRORTYPE FreeOutputBuffer(OMX_BUFFERHEADERTYPE *omx_buffer);
unsigned int GetInputBufferSize();
unsigned int GetOutputBufferSize();
unsigned int GetInputBufferSpace();
unsigned int GetOutputBufferSpace();
void FlushAll();
void FlushInput();
void FlushOutput();
OMX_BUFFERHEADERTYPE *GetInputBuffer(long timeout=200);
OMX_BUFFERHEADERTYPE *GetOutputBuffer();
OMX_ERRORTYPE AllocInputBuffers(bool use_buffers = false);
OMX_ERRORTYPE AllocOutputBuffers(bool use_buffers = false);
OMX_ERRORTYPE FreeInputBuffers();
OMX_ERRORTYPE FreeOutputBuffers();
bool IsEOS() { return m_eos; };
bool BadState() { return m_resource_error; };
void ResetEos();
private:
OMX_HANDLETYPE m_handle;
unsigned int m_input_port;
unsigned int m_output_port;
std::string m_componentName;
pthread_mutex_t m_omx_event_mutex;
pthread_mutex_t m_omx_eos_mutex;
pthread_mutex_t m_lock;
std::vector<omx_event> m_omx_events;
OMX_CALLBACKTYPE m_callbacks;
// OMXCore input buffers (demuxer packets)
pthread_mutex_t m_omx_input_mutex;
std::queue<OMX_BUFFERHEADERTYPE*> m_omx_input_avaliable;
std::vector<OMX_BUFFERHEADERTYPE*> m_omx_input_buffers;
unsigned int m_input_alignment;
unsigned int m_input_buffer_size;
unsigned int m_input_buffer_count;
bool m_omx_input_use_buffers;
// OMXCore output buffers (video frames)
pthread_mutex_t m_omx_output_mutex;
std::queue<OMX_BUFFERHEADERTYPE*> m_omx_output_available;
std::vector<OMX_BUFFERHEADERTYPE*> m_omx_output_buffers;
unsigned int m_output_alignment;
unsigned int m_output_buffer_size;
unsigned int m_output_buffer_count;
bool m_omx_output_use_buffers;
bool m_exit;
bool m_DllOMXOpen;
pthread_cond_t m_input_buffer_cond;
pthread_cond_t m_output_buffer_cond;
pthread_cond_t m_omx_event_cond;
bool m_eos;
bool m_flush_input;
bool m_flush_output;
bool m_resource_error;
void Lock();
void UnLock();
};
class COMXCore
{
public:
COMXCore();
~COMXCore();
bool Initialize();
void Deinitialize();
protected:
bool m_is_open;
bool m_Initialized;
};
| [
"dlxqlig@gmail.com"
] | dlxqlig@gmail.com |
8f79c8e63a421075ac0e25d640a1888178d5abe3 | 39bcafc5f6b1672f31f0f6ea9c8d6047ee432950 | /src/include/duckdb/common/enums/set_type.hpp | 0b5eedd2000f2d06a325d0ac435b72a407b15c94 | [
"MIT"
] | permissive | duckdb/duckdb | 315270af6b198d26eb41a20fc7a0eda04aeef294 | f89ccfe0ec01eb613af9c8ac7c264a5ef86d7c3a | refs/heads/main | 2023-09-05T08:14:21.278345 | 2023-09-05T07:28:59 | 2023-09-05T07:28:59 | 138,754,790 | 8,964 | 986 | MIT | 2023-09-14T18:42:49 | 2018-06-26T15:04:45 | C++ | UTF-8 | C++ | false | false | 392 | hpp | //===----------------------------------------------------------------------===//
// DuckDB
//
// duckdb/common/enums/set_type.hpp
//
//
//===----------------------------------------------------------------------===//
#pragma once
#include "duckdb/common/constants.hpp"
namespace duckdb {
enum class SetType : uint8_t { SET = 0, RESET = 1 };
} // namespace duckdb
| [
"t_b@live.nl"
] | t_b@live.nl |
c86b6ce6e2f79863369b578e81ffa0f1ded7faef | d16985a72e39109c30b1e975007cc1cabe8a6ac8 | /Common/Packets/GWCommand.cpp | 2185d4a868b60f61766ea21cdcc6a15eda138a9e | [] | no_license | uvbs/wx2Server | e878c3c5c27715a0a1044f6b3229960d36eff4b4 | 78a4b693ac018a4ae82e7919f6e29c97b92554ab | refs/heads/master | 2021-01-18T00:06:34.770227 | 2013-12-13T09:18:54 | 2013-12-13T09:18:54 | 43,288,843 | 2 | 3 | null | 2015-09-28T08:24:45 | 2015-09-28T08:24:44 | null | UTF-8 | C++ | false | false | 767 | cpp |
#include "stdafx.h"
#include "GWCommand.h"
BOOL GWCommand::Read( SocketInputStream& iStream )
{
__ENTER_FUNCTION
iStream.Read( (CHAR*)(&m_PlayerID), sizeof(PlayerID_t) ) ;
iStream.Read( (CHAR*)(&m_Command), sizeof(SERVER_COMMAND) ) ;
return TRUE ;
__LEAVE_FUNCTION
return FALSE ;
}
BOOL GWCommand::Write( SocketOutputStream& oStream )const
{
__ENTER_FUNCTION
oStream.Write( (CHAR*)(&m_PlayerID), sizeof(PlayerID_t) ) ;
oStream.Write( (CHAR*)(&m_Command), sizeof(SERVER_COMMAND) ) ;
return TRUE ;
__LEAVE_FUNCTION
return FALSE ;
}
UINT GWCommand::Execute( Player* pPlayer )
{
__ENTER_FUNCTION
return GWCommandHandler::Execute( this, pPlayer ) ;
__LEAVE_FUNCTION
return FALSE ;
}
| [
"tangming032@outlook.com"
] | tangming032@outlook.com |
309653f5829c95f878bc3893bb43fc34c4c635b4 | 2284a82990a36f5459cb8f26cfeb555a1c053272 | /anonssplitter/stringcontainer/CharClasses.cpp | 3a5740592d3de064a5b21c4257881b455427087f | [] | no_license | Artmozaec/Artprogramm | fbcf9f91015705fc25c64cd0b02986fc7be380ea | 673a427e5930db3b99db70c16b68d7873ec11dcc | refs/heads/master | 2021-05-26T22:56:32.925842 | 2020-06-06T14:34:14 | 2020-06-06T14:34:14 | 254,181,824 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 200 | cpp | #ifndef CharClassesH
#define CharClassesH
enum CharClass{
DIRECTION,
SYMBOLS,
DIGITS,
RUSSIAN_UPPERCASE,
RUSSIAN_LOWERCASE,
ENGLISH_UPPERCASE,
ENGLISH_LOWERCASE,
};
#endif | [
"artmozaec@gmail.com"
] | artmozaec@gmail.com |
920e6fe7d95ab04daf171f90507109e949666bc4 | c588186250b1af54a276dbba2efc8bb78ca14125 | /luogu/1056.cpp | 130b73fa1a869c46a7ae42943c816cca9ba01aa8 | [] | no_license | Meng-Lan/Lan | 380fdedd8ed7b0c1e5ffdabdc0c2ce48344927df | fc12199919028335d6ddb12c8a0aa0537a07b851 | refs/heads/master | 2021-06-28T11:59:50.201500 | 2020-07-11T09:05:53 | 2020-07-11T09:05:53 | 93,761,541 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 1,503 | cpp | #include<iostream>
#include<cstdio>
#include<string>
#include<cstring>
#include<vector>
#include<map>
#include<set>
#include<utility>
#include<queue>
#include<stack>
#include<algorithm>
#include<cstdlib>
using namespace std;
typedef long long ll;
typedef pair<int, int> P;
typedef pair<P, P> PP;
#define mp make_pair
const int maxd = 2000 + 5;
//此题输出是个坑,要求输出的从小到大排列
PP D[maxd];
P r[maxd], c[maxd];
bool cmp(const P &t, const P &s) {
return t.first > s.first || t.first == s.first&&t.second < s.second;
}
int main() {
int m, n, k, l, d;
scanf("%d%d%d%d%d", &m, &n, &k, &l, &d);
for (int i = 0; i < d; i++)
scanf("%d%d%d%d", &D[i].first.first, &D[i].first.second, &D[i].second.first, &D[i].second.second);
int len = max(m, n);
for (int i = 1; i <= len; i++)
r[i].second = c[i].second = i;
for (int i = 0; i < d; i++)
if (D[i].first.first != D[i].second.first)
r[min(D[i].first.first, D[i].second.first)].first++;
else
c[min(D[i].first.second, D[i].second.second)].first++;
sort(r, r + len + 1, cmp);
sort(c, c + len + 1, cmp);
vector<int> ans;
for (int i = 0; i < k; i++) ans.push_back(r[i].second);
sort(ans.begin(), ans.end());
for (int i = 0; i < k; i++) {
if (i) putchar(' ');
printf("%d", ans[i]);
}
putchar('\n');
ans.clear();
for (int i = 0; i < l; i++) ans.push_back(c[i].second);
sort(ans.begin(), ans.end());
for (int i = 0; i < l; i++) {
if (i) putchar(' ');
printf("%d",ans[i]);
}
putchar('\n');
return 0;
} | [
"779379402@qq.com"
] | 779379402@qq.com |
93df552199598f7ca4fbc1280a092dda917f2ad6 | fd57bcbc5eb0253f8388895f20f2452f28d6f650 | /src/CalcManager/CalculatorVector.h | 5ddf5300d08a0ae283f59dba4ed488ea689f6d2d | [
"MIT",
"LGPL-2.1-or-later"
] | permissive | rhalp10/calculator-1 | 97e983541c347ff241693c96240b77912505f6fc | 8b58cee02cb88e05c073c1dbf4d17e66a0d5ac36 | refs/heads/master | 2020-04-27T11:43:24.402214 | 2020-02-15T06:56:31 | 2020-02-15T06:56:31 | 174,305,598 | 0 | 0 | MIT | 2020-02-15T06:56:32 | 2019-03-07T08:42:55 | C++ | UTF-8 | C++ | false | false | 3,327 | h | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
#pragma once
template <typename TType>
class CalculatorVector
{
public:
HRESULT GetAt(_In_opt_ unsigned int index, _Out_ TType *item)
{
HRESULT hr = S_OK;
try
{
*item = m_vector.at(index);
}
catch (std::out_of_range /*ex*/)
{
hr = E_BOUNDS;
}
return hr;
}
HRESULT GetSize(_Out_ unsigned int *size)
{
*size = static_cast<unsigned>(m_vector.size());
return S_OK;
}
HRESULT SetAt(_In_ unsigned int index, _In_opt_ TType item)
{
HRESULT hr = S_OK;
try
{
m_vector[index] = item;
}
catch (std::out_of_range /*ex*/)
{
hr = E_BOUNDS;
}
return hr;
}
HRESULT RemoveAt(_In_ unsigned int index)
{
HRESULT hr = S_OK;
if (index < m_vector.size())
{
m_vector.erase(m_vector.begin() + index);
}
else
{
hr = E_BOUNDS;
}
return hr;
}
HRESULT InsertAt(_In_ unsigned int index, _In_ TType item)
{
HRESULT hr = S_OK;
try
{
auto iter = m_vector.begin() + index;
m_vector.insert(iter, item);
}
catch (std::bad_alloc /*ex*/)
{
hr = E_OUTOFMEMORY;
}
return hr;
}
HRESULT Truncate(_In_ unsigned int index)
{
HRESULT hr = S_OK;
if (index < m_vector.size())
{
auto startIter = m_vector.begin() + index;
m_vector.erase(startIter, m_vector.end());
}
else
{
hr = E_BOUNDS;
}
return hr;
}
HRESULT Append(_In_opt_ TType item)
{
HRESULT hr = S_OK;
try
{
m_vector.push_back(item);
}
catch (std::bad_alloc /*ex*/)
{
hr = E_OUTOFMEMORY;
}
return hr;
}
HRESULT RemoveAtEnd()
{
m_vector.erase(--(m_vector.end()));
return S_OK;
}
HRESULT Clear()
{
m_vector.clear();
return S_OK;
}
HRESULT GetString(_Out_ std::wstring* expression)
{
HRESULT hr = S_OK;
unsigned int nTokens = 0;
std::pair <std::wstring, int> currentPair;
hr = this->GetSize(&nTokens);
if (SUCCEEDED(hr))
{
for (unsigned int i = 0; i < nTokens; i++)
{
hr = this->GetAt(i, ¤tPair);
if (SUCCEEDED(hr))
{
expression->append(currentPair.first);
if (i != (nTokens - 1))
{
expression->append(L" ");
}
}
}
std::wstring expressionSuffix{};
hr = GetExpressionSuffix(&expressionSuffix);
if (SUCCEEDED(hr))
{
expression->append(expressionSuffix);
}
}
return hr;
}
HRESULT GetExpressionSuffix(_Out_ std::wstring* suffix)
{
*suffix = L" =";
return S_OK;
}
private:
std::vector<TType> m_vector;
};
| [
"HowardWolosky@users.noreply.github.com"
] | HowardWolosky@users.noreply.github.com |
8241fc70a67bdd572c5556b4b6997d895dab71cd | 0b5a0b18704cb94cf7d987f0a23f942391860ee1 | /src/core/ws/TextInputDispatcher.h | abadf2f6b7a753f5a091f53b221df30951a44ee3 | [
"BSD-2-Clause"
] | permissive | kaust-vislab/DisplayCluster | ea14764c9581d2ab3d9f6f982f18720bd1565711 | a87057e6992ec016ed82734a7e9cda8b4634ff5a | refs/heads/master | 2022-10-21T05:16:58.379552 | 2015-10-26T07:23:47 | 2015-10-26T07:23:47 | 12,727,480 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,602 | h | /*********************************************************************/
/* Copyright (c) 2014, EPFL/Blue Brain Project */
/* Raphael Dumusc <raphael.dumusc@epfl.ch> */
/* All rights reserved. */
/* */
/* Redistribution and use in source and binary forms, with or */
/* without modification, are permitted provided that the following */
/* conditions are met: */
/* */
/* 1. Redistributions of source code must retain the above */
/* copyright notice, this list of conditions and the following */
/* disclaimer. */
/* */
/* 2. Redistributions in binary form must reproduce the above */
/* copyright notice, this list of conditions and the following */
/* disclaimer in the documentation and/or other materials */
/* provided with the distribution. */
/* */
/* THIS SOFTWARE IS PROVIDED BY THE UNIVERSITY OF TEXAS AT */
/* AUSTIN ``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 UNIVERSITY OF TEXAS AT */
/* AUSTIN 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. */
/* */
/* The views and conclusions contained in the software and */
/* documentation are those of the authors and should not be */
/* interpreted as representing official policies, either expressed */
/* or implied, of The University of Texas at Austin. */
/*********************************************************************/
#ifndef TEXTINPUTDISPATCHER_H
#define TEXTINPUTDISPATCHER_H
#include <QObject>
#include "types.h"
#include "AsciiToQtKeyCodeMapper.h"
/**
* Dispatch text input from the WebServiceServer thread to the active ContentWindow.
*/
class TextInputDispatcher : public QObject
{
Q_OBJECT
public:
/**
* Constructor.
* @param displayGroup The DisplayGroup which holds the target ContentWindow.
* @param parentObject An optional parent QObject
*/
TextInputDispatcher(DisplayGroupPtr displayGroup, QObject *parentObject = 0);
public slots:
/**
* Send the given key event to the active (frontmost) window
* @param key The key code to send
*/
void sendKeyEventToActiveWindow(const char key) const;
private:
DisplayGroupPtr displayGroup_;
AsciiToQtKeyCodeMapper keyMapper_;
};
#endif // TEXTINPUTDISPATCHER_H
| [
"raphael.dumusc@epfl.ch"
] | raphael.dumusc@epfl.ch |
28cbdd535448be6c06bdc4bdfdc458832541def9 | 4051fbe4641bcc557d731a9c131affd7566fe47e | /VisualizationDirectX/Direct3D11/D3D11HullShaderPipelineStage.h | a1a906342643050d807271cf4379eb7c75a07415 | [] | no_license | sulerzh/directx | 1bef849a2a72aae68e2efe62fa693b9e75f7df26 | 225479355babdd31ff256eb37a237dccada23945 | refs/heads/master | 2020-05-20T03:13:22.857348 | 2015-05-25T05:47:23 | 2015-05-25T05:47:23 | 29,289,661 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,200 | h | //Copyright (c) Microsoft Corporation. All rights reserved.
#pragma once
#include "D3D11PipelineStage.h"
#include "D3D11ShaderAndClasses.h"
namespace Microsoft { namespace Data { namespace Visualization { namespace DirectX { namespace Direct3D11 {
/// <summary>
/// Hull Shader pipeline stage.
/// </summary>
public ref class HullShaderPipelineStage : PipelineStage
{
public:
/// <summary>
/// Get the constant buffers used by the hull-shader stage.
/// <para>(Also see DirectX SDK: ID3D11DeviceContext::HSGetConstantBuffers)</para>
/// </summary>
/// <param name="startSlot">Index into the device's zero-based array to begin retrieving constant buffers from (ranges from 0 to D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT - 1).</param>
/// <param name="bufferCount">Number of buffers to retrieve (ranges from 0 to D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT - startSlot).</param>
/// <returns>Collection of constant buffer objects (see <see cref="D3DBuffer"/>)<seealso cref="D3DBuffer"/> to be returned by the method.</returns>
ReadOnlyCollection<D3DBuffer^>^ GetConstantBuffers(UInt32 startSlot, UInt32 bufferCount);
/// <summary>
/// Get an array of sampler state objects from the hull-shader stage.
/// <para>(Also see DirectX SDK: ID3D11DeviceContext::HSGetSamplers)</para>
/// </summary>
/// <param name="startSlot">Index into a zero-based array to begin getting samplers from (ranges from 0 to D3D11_COMMONSHADER_SAMPLER_SLOT_COUNT - 1).</param>
/// <param name="samplerCount">Number of samplers to get from a device context. Each pipeline stage has a total of 16 sampler slots available (ranges from 0 to D3D11_COMMONSHADER_SAMPLER_SLOT_COUNT - startSlot).</param>
/// <returns>A collection of sampler-state objects (see <see cref="SamplerState"/>)<seealso cref="SamplerState"/>.</returns>
ReadOnlyCollection<SamplerState^>^ GetSamplers(UInt32 startSlot, UInt32 samplerCount);
/// <summary>
/// Get the hull shader currently set on the device.
/// <para>(Also see DirectX SDK: ID3D11DeviceContext::HSGetShader)</para>
/// </summary>
/// <param name="classInstanceCount">The number of class-instance elements requested.</param>
/// <returns>
/// A HullShader object and its classes (see <see cref="HullShader" />, <see cref="ShaderAndClasses" />)
/// <seealso cref="HullShader" />, <seealso cref="ShaderAndClasses" />.
/// </returns>
ShaderAndClasses<HullShader^> GetShaderAndClasses(UInt32 classInstanceCount);
/// <summary>
/// Gets or sets the hull shader currently set on the device. (See <see cref="GeometryShader"/>)<seealso cref="GeometryShader"/>
/// <para>(Also see DirectX SDK: ID3D11DeviceContext::HSGetShader, ID3D11DeviceContext::HSSetShader)</para>
/// Setting this property to null disables the shader for this pipeline stage.
/// </summary>
property HullShader^ Shader
{
HullShader^ get(void);
void set(HullShader^ shader);
}
/// <summary>
/// Get the hull-shader resources.
/// <para>(Also see DirectX SDK: ID3D11DeviceContext::HSGetShaderResources)</para>
/// </summary>
/// <param name="startSlot">Index into the device's zero-based array to begin getting shader resources from (ranges from 0 to D3D11_COMMONSHADER_INPUT_RESOURCE_SLOT_COUNT - 1).</param>
/// <param name="viewCount">The number of resources to get from the device. Up to a maximum of 128 slots are available for shader resources (ranges from 0 to D3D11_COMMONSHADER_INPUT_RESOURCE_SLOT_COUNT - startSlot).</param>
/// <returns>Collection of shader resource view objects to be returned by the device.</returns>
ReadOnlyCollection<ShaderResourceView^>^ GetShaderResources(UInt32 startSlot, UInt32 viewCount);
/// <summary>
/// Set the constant buffers used by the hull-shader stage.
/// <para>(Also see DirectX SDK: ID3D11DeviceContext::HSSetConstantBuffers)</para>
/// </summary>
/// <param name="startSlot">Index into the device's zero-based array to begin setting constant buffers to (ranges from 0 to D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT - 1).</param>
/// <param name="constantBuffers">Collection of constant buffers (see <see cref="D3DBuffer"/>)<seealso cref="D3DBuffer"/> being given to the device.</param>
void SetConstantBuffers(UInt32 startSlot, IEnumerable<D3DBuffer^>^ constantBuffers);
/// <summary>
/// Set an array of sampler states to the hull-shader stage.
/// <para>(Also see DirectX SDK: ID3D11DeviceContext::HSSetSamplers)</para>
/// </summary>
/// <param name="startSlot">Index into the zero-based array to begin setting samplers to (ranges from 0 to D3D11_COMMONSHADER_SAMPLER_SLOT_COUNT - 1).</param>
/// <param name="samplers">A collection of sampler-state objects (see <see cref="SamplerState"/>)<seealso cref="SamplerState"/>. See Remarks.</param>
void SetSamplers(UInt32 startSlot, IEnumerable<SamplerState^>^ samplers);
/// <summary>
/// Set a hull shader to the device.
/// <para>(Also see DirectX SDK: ID3D11DeviceContext::HSSetShader)</para>
/// </summary>
/// <param name="shader">A hull shader (see <see cref="HullShader"/>)<seealso cref="HullShader"/>.
/// Passing in null disables the shader for this pipeline stage.</param>
/// <param name="classInstances">A collection of class-instance objects (see <see cref="ClassInstance"/>)<seealso cref="ClassInstance"/>.
/// Each interface used by a shader must have a corresponding class instance or the shader will get disabled. Set to null if the shader does not use any interfaces.</param>
void SetShader(HullShader^ shader, IEnumerable<ClassInstance^>^ classInstances);
/// <summary>
/// Set a hull shader to the device.
/// <para>(Also see DirectX SDK: ID3D11DeviceContext::HSSetShader)</para>
/// </summary>
/// <param name="shaderAndClasses">
/// A HullShader object and its classes (see <see cref="HullShader" />, <see cref="ShaderAndClasses" />)
/// <seealso cref="HullShader" />, <seealso cref="ShaderAndClasses" />.
/// Passing in null for the shader disables the shader for this pipeline stage.
/// </param>
void SetShader(ShaderAndClasses<HullShader^> shaderAndClasses);
/// <summary>
/// Bind an array of shader resources to the hull-shader stage.
/// <para>(Also see DirectX SDK: ID3D11DeviceContext::HSSetShaderResources)</para>
/// </summary>
/// <param name="startSlot">Index into the device's zero-based array to begin setting shader resources to (ranges from 0 to D3D11_COMMONSHADER_INPUT_RESOURCE_SLOT_COUNT - 1).</param>
/// <param name="shaderResourceViews">Collection of shader resource view objects to set to the device.
/// Up to a maximum of 128 slots are available for shader resources(ranges from 0 to D3D11_COMMONSHADER_INPUT_RESOURCE_SLOT_COUNT - startSlot).</param>
void SetShaderResources(UInt32 startSlot, IEnumerable<ShaderResourceView^>^ shaderResourceViews);
protected:
HullShaderPipelineStage() { }
internal:
HullShaderPipelineStage(DeviceContext^ parent) : PipelineStage(parent) { }
};
} } } } }
| [
"sulerzh@sina.com"
] | sulerzh@sina.com |
e911dfa0d23deec805fc98f7322abaeb391a6e60 | ce6e89e41e9a498e837e5b215b9e0398ac172bf1 | /Parte 2/cutsphere.h | 90835d09bc5a0e9f896577af5e81fc2a4a20f1e8 | [] | no_license | martamaira/Projeto-Escultor-3D | eb1e69d8648ca7ceb5d359fd4552e05dce1b263b | 2928b3791bceb6a9fec17eb4bad8f605e0c6a4a5 | refs/heads/main | 2023-07-11T01:52:33.831250 | 2021-08-16T02:52:51 | 2021-08-16T02:52:51 | 388,477,233 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 339 | h | #ifndef CUTSPHERE_H
#define CUTSPHERE_H
#include "sculptor.h"
#include "figurageometrica.h"
class cutSphere : public figuraGeometrica
{
int xcenter, ycenter, zcenter, radius;
public:
cutSphere(int xcenter, int ycenter, int zcenter, float radius);
~cutSphere(){
};
void draw(Sculptor &s);
};
#endif // CUTSPHERE_H
| [
"noreply@github.com"
] | noreply@github.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.