blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 3
264
| content_id
stringlengths 40
40
| detected_licenses
sequencelengths 0
85
| license_type
stringclasses 2
values | repo_name
stringlengths 5
140
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringclasses 986
values | visit_date
timestamp[us] | revision_date
timestamp[us] | committer_date
timestamp[us] | github_id
int64 3.89k
681M
⌀ | star_events_count
int64 0
209k
| fork_events_count
int64 0
110k
| gha_license_id
stringclasses 23
values | gha_event_created_at
timestamp[us] | gha_created_at
timestamp[us] | gha_language
stringclasses 145
values | src_encoding
stringclasses 34
values | language
stringclasses 1
value | is_vendor
bool 1
class | is_generated
bool 2
classes | length_bytes
int64 3
10.4M
| extension
stringclasses 122
values | content
stringlengths 3
10.4M
| authors
sequencelengths 1
1
| author_id
stringlengths 0
158
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
bab79ca9935598c0d5582f4c76d7f8c63fa390e7 | 0084166695a3bea4f4285eadd57d03607314c149 | /TouchGFX/target/generated/TouchGFXGeneratedHAL.cpp | ae76144669a0671e69c7eb5f250a13bce5357755 | [] | no_license | Zhangzhicheng001/Magnetic_shielding_system | 142556f79ada0e9f1b4addcbeaf69441a0f515b6 | 7714e14758de2a30c920ab9ad74ec9dc1e094820 | refs/heads/main | 2023-07-08T11:18:05.720893 | 2021-08-09T10:25:02 | 2021-08-09T10:25:02 | 391,795,760 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,986 | cpp | /**
******************************************************************************
* File Name : TouchGFXGeneratedHAL.cpp
******************************************************************************
* @attention
*
* <h2><center>© Copyright (c) 2021 STMicroelectronics.
* All rights reserved.</center></h2>
*
* This software component is licensed by ST under Ultimate Liberty license
* SLA0044, the "License"; You may not use this file except in compliance with
* the License. You may obtain a copy of the License at:
* www.st.com/SLA0044
*
******************************************************************************
*/
#include <TouchGFXGeneratedHAL.hpp>
#include <touchgfx/hal/OSWrappers.hpp>
#include <gui/common/FrontendHeap.hpp>
#include <touchgfx/hal/GPIO.hpp>
#include "stm32h7xx.h"
#include "stm32h7xx_hal_ltdc.h"
using namespace touchgfx;
namespace
{
static uint16_t lcd_int_active_line;
static uint16_t lcd_int_porch_line;
}
void TouchGFXGeneratedHAL::initialize()
{
HAL::initialize();
registerEventListener(*(Application::getInstance()));
setFrameBufferStartAddresses((void*)0xC0000000, (void*)0xC0119400, (void*)0);
}
void TouchGFXGeneratedHAL::configureInterrupts()
{
NVIC_SetPriority(DMA2D_IRQn, 9);
NVIC_SetPriority(LTDC_IRQn, 9);
}
void TouchGFXGeneratedHAL::enableInterrupts()
{
NVIC_EnableIRQ(DMA2D_IRQn);
NVIC_EnableIRQ(LTDC_IRQn);
}
void TouchGFXGeneratedHAL::disableInterrupts()
{
NVIC_DisableIRQ(DMA2D_IRQn);
NVIC_DisableIRQ(LTDC_IRQn);
}
void TouchGFXGeneratedHAL::enableLCDControllerInterrupt()
{
lcd_int_active_line = (LTDC->BPCR & 0x7FF) - 1;
lcd_int_porch_line = (LTDC->AWCR & 0x7FF) - 1;
/* Sets the Line Interrupt position */
LTDC->LIPCR = lcd_int_active_line;
/* Line Interrupt Enable */
LTDC->IER |= LTDC_IER_LIE;
}
bool TouchGFXGeneratedHAL::beginFrame()
{
return HAL::beginFrame();
}
void TouchGFXGeneratedHAL::endFrame()
{
HAL::endFrame();
}
uint16_t* TouchGFXGeneratedHAL::getTFTFrameBuffer() const
{
return (uint16_t*)LTDC_Layer1->CFBAR;
}
void TouchGFXGeneratedHAL::setTFTFrameBuffer(uint16_t* adr)
{
LTDC_Layer1->CFBAR = (uint32_t)adr;
/* Reload immediate */
LTDC->SRCR = (uint32_t)LTDC_SRCR_IMR;
}
void TouchGFXGeneratedHAL::flushFrameBuffer(const touchgfx::Rect& rect)
{
HAL::flushFrameBuffer(rect);
// If the framebuffer is placed in Write Through cached memory (e.g. SRAM) then
// the DCache must be flushed prior to DMA2D accessing it. That's done
// using the function SCB_CleanInvalidateDCache(). Remember to enable "CPU Cache" in the
// "System Core" settings for "Cortex M7" in CubeMX in order for this function call to work.
if (SCB->CCR & SCB_CCR_DC_Msk)
{
SCB_CleanInvalidateDCache();
}
}
bool TouchGFXGeneratedHAL::blockCopy(void* RESTRICT dest, const void* RESTRICT src, uint32_t numBytes)
{
return HAL::blockCopy(dest, src, numBytes);
}
void TouchGFXGeneratedHAL::InvalidateCache()
{
// If the framebuffer is placed in Write Through cached memory (e.g. SRAM) then
// the DCache must be flushed prior to DMA2D accessing it. That's done
// using the function SCB_CleanInvalidateDCache(). Remember to enable "CPU Cache" in the
// "System Core" settings for "Cortex M7" in CubeMX in order for this function call to work.
if (SCB->CCR & SCB_CCR_DC_Msk)
{
SCB_CleanInvalidateDCache();
}
}
void TouchGFXGeneratedHAL::FlushCache()
{
// If the framebuffer is placed in Write Through cached memory (e.g. SRAM) then
// the DCache must be flushed prior to DMA2D accessing it. That's done
// using the function SCB_CleanInvalidateDCache(). Remember to enable "CPU Cache" in the
// "System Core" settings for "Cortex M7" in CubeMX in order for this function call to work.
if (SCB->CCR & SCB_CCR_DC_Msk)
{
SCB_CleanInvalidateDCache();
}
}
extern "C"
{
void HAL_LTDC_LineEventCallback(LTDC_HandleTypeDef* hltdc)
{
if (LTDC->LIPCR == lcd_int_active_line)
{
//entering active area
HAL_LTDC_ProgramLineEvent(hltdc, lcd_int_porch_line);
HAL::getInstance()->vSync();
OSWrappers::signalVSync();
// Swap frame buffers immediately instead of waiting for the task to be scheduled in.
// Note: task will also swap when it wakes up, but that operation is guarded and will not have
// any effect if already swapped.
HAL::getInstance()->swapFrameBuffers();
GPIO::set(GPIO::VSYNC_FREQ);
}
else
{
//exiting active area
HAL_LTDC_ProgramLineEvent(hltdc, lcd_int_active_line);
GPIO::clear(GPIO::VSYNC_FREQ);
HAL::getInstance()->frontPorchEntered();
}
}
}
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
| [
"[email protected]"
] | |
160beafcd0375ee1abc289f6df9dc822b8749eb5 | 4b0a3fffa69840fac4fa77ba40f3aed8ae51442c | /FinalProject/workingfolder/Erin's Updates/bouncingcube/BouncingCube.h | a06731fe152c89b5848227598c4d455e34849b77 | [] | no_license | hoffm386/graphics-final-project | 732633bf55482051730e0087c025ab1d6e5253e7 | 584a16eda13572d6a92bad690da6b4a903eef084 | refs/heads/master | 2021-01-10T20:14:04.415740 | 2014-04-30T02:50:22 | 2014-04-30T02:50:22 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 725 | h |
// BouncingCube.h : main header file for the BouncingCube application
//
#pragma once
#ifndef __AFXWIN_H__
#error "include 'stdafx.h' before including this file for PCH"
#endif
#include "resource.h" // main symbols
// CBouncingCubeApp:
// See BouncingCube.cpp for the implementation of this class
//
class CBouncingCubeApp : public CWinAppEx
{
public:
CBouncingCubeApp();
// Overrides
public:
virtual BOOL InitInstance();
virtual int ExitInstance();
// Implementation
public:
UINT m_nAppLook;
BOOL m_bHiColorIcons;
virtual void PreLoadState();
virtual void LoadCustomState();
virtual void SaveCustomState();
afx_msg void OnAppAbout();
DECLARE_MESSAGE_MAP()
};
extern CBouncingCubeApp theApp;
| [
"[email protected]"
] | |
6a5800c8150e8c9144d23429c10f35136b06e222 | 578ceec075394968a5ac0ef3ed5961697d8cd826 | /daemon/DekdCommand.h | 7a1648ba3f971ea0a278f233a006d43f4fa34003 | [] | no_license | olicmoon/dekd | 3938a6f76cdb8b0a9ef915b273f94ac8fa9276d9 | c5a88ec8330a67ce952351970bf5657813977eae | refs/heads/master | 2021-01-19T06:24:54.282288 | 2015-08-31T21:17:06 | 2015-09-01T00:40:38 | 40,740,525 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 365 | h | /*
* DekdCommand.h
*
* Created on: Aug 17, 2015
* Author: olic
*/
#ifndef DEKDCOMMAND_H_
#define DEKDCOMMAND_H_
#include <FrameworkCommand.h>
class DekdCommand : public FrameworkCommand {
public:
DekdCommand(const char *cmd);
virtual ~DekdCommand() {}
int runCommand(SocketClient *c, int argc, char **argv);
};
#endif /* DEKDCOMMAND_H_ */
| [
"[email protected]"
] | |
9c3fa67cf4ece508073c0b6822db284debea7229 | 70fe255d0a301952a023be5e1c1fefd062d1e804 | /LintCode/37.cpp | f1154a8fa46ae6f897c35bd74ec803f12ec70812 | [
"MIT"
] | permissive | LauZyHou/Algorithm-To-Practice | 524d4318032467a975cf548d0c824098d63cca59 | 66c047fe68409c73a077eae561cf82b081cf8e45 | refs/heads/master | 2021-06-18T01:48:43.378355 | 2021-01-27T14:44:14 | 2021-01-27T14:44:14 | 147,997,740 | 8 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 255 | cpp | class Solution {
public:
/**
* @param number: A 3-digit number.
* @return: Reversed number.
*/
int reverseInteger(int number) {
int a = number%10;
int b = number/10%10;
int c = number/100;
return a*100+b*10+c;
}
}; | [
"[email protected]"
] | |
55d577d1a75a9ab17fa7b5d2dfee420f67de653e | c4d0cc1b8f7a0c4eefb405e105ac9727e1a98aad | /FlashCards/src/StringWordSplitter.cpp | fdab3206d76415785a84cd483dcc64795aae68ce | [] | no_license | KNITcpp/FlashCards | 513ed1f7fb2829692538636e0e6b65847bad8da9 | 7ac1c359d6a6f0aa5639bb64a39696b2f5eb63e2 | refs/heads/master | 2020-03-07T14:15:49.733326 | 2018-05-28T09:43:41 | 2018-05-28T09:43:41 | 127,522,390 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 505 | cpp |
#include "StringWordSplitter.h"
#include <string>
#include <vector>
StringWordSplitter::StringWordSplitter(std::wstring strToBeSplitted)
{
std::wstring singleWord;
for(int i=0; i<strToBeSplitted.length(); ++i)
{
if(strToBeSplitted[i] == L' ')
{
if(singleWord.size()!=0)
{
words.push_back(singleWord);
singleWord.clear();
}
}
else
singleWord.push_back(strToBeSplitted[i]);
}
if(singleWord.size()!=0) //something left to push after loop
words.push_back(singleWord);
}
| [
"[email protected]"
] | |
71b57f5243d516e395976e4bdf4e9b22391da34d | 46de5c99419f112b4507fd386f398769626ad328 | /thinkbig2.cpp | 16cfc1eba8eed89495a53e3254d4d0856bad3cb9 | [] | no_license | sanu11/Codes | 20a7903d95d600078db8b0bf0e12a3731615c3c1 | dd58a5577b51ade54f95c96003fc2c99609c15eb | refs/heads/master | 2021-01-21T04:50:36.855876 | 2019-07-09T05:12:56 | 2019-07-09T05:12:56 | 48,174,017 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 768 | cpp |
#include<bits/stdc++.h>
using namespace std;
int main()
{
int n,m;
cin>>n;
int arr[n];
int x,y;
map<int,int>a;
map<int,int>::iterator p;
for(int i=0;i<n;i++)
{
cin>>arr[i];
cin>>x;
for(int j=0;j<x;j++)
{
cin>>y;
p=a.find(y);
if(p==a.end())
a.insert(make_pair(y,1));
}
}
p=a.begin();
for(int i=0;i<n;i++)
{
p=a.begin();
while(p!=a.end())
{
// cout<<arr[i]<<" "<<p->first<<endl;
if(arr[i]==p->first)
p->second--;
p++;
}
}
p=a.begin();
int sum=0;
while(p!=a.end())
{
//cout<<p->first<<" "<<p->second<<endl;
sum+=p->second;
p++;
}
cout<<sum<<endl;
return 0;
}
| [
"[email protected]"
] | |
757766d5b9534a8341b7e39db49c029319f6bd2b | c78f931e0a7298b20f722b6351bb8b2566ec462b | /Centyry from year.cpp | 7083f588cb751c5ce7335f3457914027b569a925 | [] | no_license | tdutybqs/Practice | e37d125609c9b0d50ebc430e926a155814458675 | 8cdbac7080be9e6529d379fe98e919d91add215f | refs/heads/main | 2023-07-20T14:28:28.652383 | 2021-08-31T09:08:49 | 2021-08-31T09:08:49 | 381,703,801 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 442 | cpp | /*
Introduction
The first century spans from the year 1 up to and including the year 100, The second - from the year 101 up to and including the year 200, etc.
Task :
Given a year, return the century it is in.
Input , Output Examples :
1705 --> 18
1900 --> 19
1601 --> 17
2000 --> 20
Hope you enjoy it .. Awaiting for Best Practice Codes
Enjoy Learning !!!
*/
int centuryFromYear(int year) {
return year / 100 + int(year % 100 != 0);
}
| [
"[email protected]"
] | |
39cc31371670480b292396298ed339ab29cd2e67 | 3dc0034f54360349734e5b133f169e39cdff3ce5 | /BUGLIFE-12867964-src.cpp | 412ba3f82f97ff515730e433b6f57995f2dd67c2 | [] | no_license | anshul1927/SPOJ-Solutions | 6c8022d11b3097b8ef3af2c17983375e01b8eb56 | 07c1d4dcc5b29c4b3a0c61cc8bc7d7e10307822a | refs/heads/master | 2021-03-30T21:20:19.514777 | 2015-08-19T15:49:04 | 2015-08-19T15:49:04 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,558 | cpp | #include <iostream>
#include<queue>
#include<cstring>
#include<cstdio>
#define comp(c) (c==1)?2:1
#define gc getchar_unlocked
using namespace std;
bool sus;
int idx[2000];
bool done[2000];
int bugs[2000];
int inter[2000][2000];
int n,in;
void scanint(int &x)
{
register int c = gc();
x = 0;
for(;(c<48 || c>57);c = gc());
for(;c>47 && c<58;c = gc()) {x = (x<<1) + (x<<3) + c - 48;}
}
void bfs(){
for(int p=0;p<n;p++){
if(!done[p]){
queue<int> Q;
bugs[p]=1;
done[p]=true;
Q.push(p);
while(!Q.empty()){
int curr=Q.front();
Q.pop();
for(int i=0;i<idx[curr];i++){
if(!done[inter[curr][i]]){
bugs[inter[curr][i]]=comp(bugs[curr]);
Q.push(inter[curr][i]);
done[inter[curr][i]]=true;
}
else{
if(bugs[inter[curr][i]]==bugs[curr]){
sus=true;
return;
}
}
}
}
}
}
}
int main()
{
long long t;
cin>>t;
for(long long j=1;j<=t;j++){
scanint(n);
scanint(in);
memset(idx,0,sizeof idx);
for(int i=0;i<in;i++){
int x,y;
scanint(x);
scanint(y);
x=x-1;
y=y-1;
inter[x][idx[x]]=y;idx[x]++;
inter[y][idx[y]]=x;idx[y]++;
}
sus=false;
memset(bugs,0,sizeof bugs);
memset(done,false,sizeof bugs);
bfs();
cout<<"Scenario #"<<j<<":"<<endl;
if(sus)printf("Suspicious bugs found!\n");
else printf("No suspicious bugs found!\n");
}
return 0;
}
| [
"[email protected]"
] | |
f46de1bd281fa3736931ddc5c85eb5849f2b7ee0 | 723b67f6a8b202dc5bb009427f60ffd9f185dba8 | /devel/include/ros_arduino_msgs/ServoWriteResponse.h | ef1a29d38d970bae98cdea4932c90d41f162ce62 | [] | no_license | Dhawgupta/catkin_ws | 15edced50d3d69bf78851315658646cd671eb911 | edab645f1a94c83925836b36d38ecf2ad8f42abc | refs/heads/master | 2021-01-19T10:56:09.954495 | 2017-04-11T09:52:20 | 2017-04-11T09:52:20 | 87,917,514 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,028 | h | // Generated by gencpp from file ros_arduino_msgs/ServoWriteResponse.msg
// DO NOT EDIT!
#ifndef ROS_ARDUINO_MSGS_MESSAGE_SERVOWRITERESPONSE_H
#define ROS_ARDUINO_MSGS_MESSAGE_SERVOWRITERESPONSE_H
#include <string>
#include <vector>
#include <map>
#include <ros/types.h>
#include <ros/serialization.h>
#include <ros/builtin_message_traits.h>
#include <ros/message_operations.h>
namespace ros_arduino_msgs
{
template <class ContainerAllocator>
struct ServoWriteResponse_
{
typedef ServoWriteResponse_<ContainerAllocator> Type;
ServoWriteResponse_()
{
}
ServoWriteResponse_(const ContainerAllocator& _alloc)
{
(void)_alloc;
}
typedef boost::shared_ptr< ::ros_arduino_msgs::ServoWriteResponse_<ContainerAllocator> > Ptr;
typedef boost::shared_ptr< ::ros_arduino_msgs::ServoWriteResponse_<ContainerAllocator> const> ConstPtr;
}; // struct ServoWriteResponse_
typedef ::ros_arduino_msgs::ServoWriteResponse_<std::allocator<void> > ServoWriteResponse;
typedef boost::shared_ptr< ::ros_arduino_msgs::ServoWriteResponse > ServoWriteResponsePtr;
typedef boost::shared_ptr< ::ros_arduino_msgs::ServoWriteResponse const> ServoWriteResponseConstPtr;
// constants requiring out of line definition
template<typename ContainerAllocator>
std::ostream& operator<<(std::ostream& s, const ::ros_arduino_msgs::ServoWriteResponse_<ContainerAllocator> & v)
{
ros::message_operations::Printer< ::ros_arduino_msgs::ServoWriteResponse_<ContainerAllocator> >::stream(s, "", v);
return s;
}
} // namespace ros_arduino_msgs
namespace ros
{
namespace message_traits
{
// BOOLTRAITS {'IsFixedSize': True, 'IsMessage': True, 'HasHeader': False}
// {'std_msgs': ['/opt/ros/kinetic/share/std_msgs/cmake/../msg'], 'ros_arduino_msgs': ['/home/dawg/catkin_ws/src/ros_arduino_bridge/ros_arduino_msgs/msg']}
// !!!!!!!!!!! ['__class__', '__delattr__', '__dict__', '__doc__', '__eq__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_parsed_fields', 'constants', 'fields', 'full_name', 'has_header', 'header_present', 'names', 'package', 'parsed_fields', 'short_name', 'text', 'types']
template <class ContainerAllocator>
struct IsFixedSize< ::ros_arduino_msgs::ServoWriteResponse_<ContainerAllocator> >
: TrueType
{ };
template <class ContainerAllocator>
struct IsFixedSize< ::ros_arduino_msgs::ServoWriteResponse_<ContainerAllocator> const>
: TrueType
{ };
template <class ContainerAllocator>
struct IsMessage< ::ros_arduino_msgs::ServoWriteResponse_<ContainerAllocator> >
: TrueType
{ };
template <class ContainerAllocator>
struct IsMessage< ::ros_arduino_msgs::ServoWriteResponse_<ContainerAllocator> const>
: TrueType
{ };
template <class ContainerAllocator>
struct HasHeader< ::ros_arduino_msgs::ServoWriteResponse_<ContainerAllocator> >
: FalseType
{ };
template <class ContainerAllocator>
struct HasHeader< ::ros_arduino_msgs::ServoWriteResponse_<ContainerAllocator> const>
: FalseType
{ };
template<class ContainerAllocator>
struct MD5Sum< ::ros_arduino_msgs::ServoWriteResponse_<ContainerAllocator> >
{
static const char* value()
{
return "d41d8cd98f00b204e9800998ecf8427e";
}
static const char* value(const ::ros_arduino_msgs::ServoWriteResponse_<ContainerAllocator>&) { return value(); }
static const uint64_t static_value1 = 0xd41d8cd98f00b204ULL;
static const uint64_t static_value2 = 0xe9800998ecf8427eULL;
};
template<class ContainerAllocator>
struct DataType< ::ros_arduino_msgs::ServoWriteResponse_<ContainerAllocator> >
{
static const char* value()
{
return "ros_arduino_msgs/ServoWriteResponse";
}
static const char* value(const ::ros_arduino_msgs::ServoWriteResponse_<ContainerAllocator>&) { return value(); }
};
template<class ContainerAllocator>
struct Definition< ::ros_arduino_msgs::ServoWriteResponse_<ContainerAllocator> >
{
static const char* value()
{
return "\n\
";
}
static const char* value(const ::ros_arduino_msgs::ServoWriteResponse_<ContainerAllocator>&) { return value(); }
};
} // namespace message_traits
} // namespace ros
namespace ros
{
namespace serialization
{
template<class ContainerAllocator> struct Serializer< ::ros_arduino_msgs::ServoWriteResponse_<ContainerAllocator> >
{
template<typename Stream, typename T> inline static void allInOne(Stream&, T)
{}
ROS_DECLARE_ALLINONE_SERIALIZER
}; // struct ServoWriteResponse_
} // namespace serialization
} // namespace ros
namespace ros
{
namespace message_operations
{
template<class ContainerAllocator>
struct Printer< ::ros_arduino_msgs::ServoWriteResponse_<ContainerAllocator> >
{
template<typename Stream> static void stream(Stream&, const std::string&, const ::ros_arduino_msgs::ServoWriteResponse_<ContainerAllocator>&)
{}
};
} // namespace message_operations
} // namespace ros
#endif // ROS_ARDUINO_MSGS_MESSAGE_SERVOWRITERESPONSE_H
| [
"[email protected]"
] | |
6f9e2a1251e0d80527ebef9b1764f62a60cc7984 | c26e9d3f92d95f7ce9d0fd5ef2c18dd95ec209a5 | /hackerrank/graph/murderer.cpp | 1fb9dd65652537e7209bab94ed2d7f66c6acb818 | [] | no_license | crystal95/Competetive-Programming-at-different-platforms | c9ad1684f6258539309d07960ed6abfa7d1a16d0 | 92d283171b0ae0307e9ded473c6eea16f62cb60e | refs/heads/master | 2021-01-09T21:44:28.175506 | 2016-03-27T21:26:26 | 2016-03-27T21:26:26 | 54,848,617 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,083 | cpp | using namespace std;
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <vector>
#include <iostream>
#include <queue>
#include <algorithm>
#include <unordered_set>
typedef long long int ll;
typedef pair<int,int> ii;
void bfs(vector<vector<int> > &adj,int s,vector<int> &dis,int n)
{
int i ;
unordered_set<int> unvisited;
for(i=1;i<=n;i++)
unvisited.insert(i);
queue<int> q;
q.push(s);
unvisited.erase(s);
while(!q.empty())
{
int tmp=q.front();
q.pop();
for(auto it=unvisited.begin();it!=unvisited.end();++it)
{
if(find(adj[tmp].begin(),adj[tmp].end(),*it)==adj[tmp].end())
{
q.push(*it);
dis[*it]=dis[tmp]+1;
unvisited.erase(*it);
}
}
}
}
int main()
{
int T;
cin>>T;
while(T--)
{
int i,n,m,u,v,s,w,start;
cin>>n>>m;
vector<vector<int > > adj(n+1);
vector<int> dis(n+1,0);
for(i=0;i<m;i++)
{
cin>>u>>v;
adj[u].push_back(v);
adj[v].push_back(u);
}
cin>>start;
bfs(adj,start,dis,n);
for(i=1;i<=n;i++)
{
if(start!=i)
cout<<dis[i]<<" ";
}
cout<<endl;
}
return 0;
}
| [
"[email protected]"
] | |
4bf7445e62392551dbda48960e850b648fa4164c | 0863a85756b0385a36605f6da18550d74df417ea | /insertDeletBinarySearchTree/main.cpp | 06dc38bff06ee3a609f252482761aa820f13f3d0 | [] | no_license | tianjingyu1/cProject | f759fb538538d689b14e38995c00afd5b70d1283 | b5c01517b8f9f654f175161de1c0967cbe43f557 | refs/heads/master | 2021-02-27T15:39:22.998819 | 2020-05-29T00:13:41 | 2020-05-29T00:13:41 | 245,616,533 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 1,967 | cpp | #include <iostream>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
BinTree Insert( BinTree BST, ElementType X )
{
if( !BST ){ /* 若原树为空,生成并返回一个结点的二叉搜索树 */
BST = (BinTree)malloc(sizeof(struct TNode));
BST->Data = X;
BST->Left = BST->Right = NULL;
}
else { /* 开始找要插入元素的位置 */
if( X < BST->Data )
BST->Left = Insert( BST->Left, X ); /*递归插入左子树*/
else if( X > BST->Data )
BST->Right = Insert( BST->Right, X ); /*递归插入右子树*/
/* else X已经存在,什么都不做 */
}
return BST;
}
BinTree Delete( BinTree BST, ElementType X )
{
Position Tmp;
if( !BST )
printf("要删除的元素未找到");
else {
if( X < BST->Data )
BST->Left = Delete( BST->Left, X ); /* 从左子树递归删除 */
else if( X > BST->Data )
BST->Right = Delete( BST->Right, X ); /* 从右子树递归删除 */
else { /* BST就是要删除的结点 */
/* 如果被删除结点有左右两个子结点 */
if( BST->Left && BST->Right ) {
/* 从右子树中找最小的元素填充删除结点 */
Tmp = FindMin( BST->Right );
BST->Data = Tmp->Data;
/* 从右子树中删除最小元素 */
BST->Right = Delete( BST->Right, BST->Data );
}
else { /* 被删除结点有一个或无子结点 */
Tmp = BST;
if( !BST->Left ) /* 只有右孩子或无子结点 */
BST = BST->Right;
else /* 只有左孩子 */
BST = BST->Left;
free( Tmp );
}
}
}
return BST;
}
int main(int argc, char** argv) {
return 0;
}
| [
"[email protected]"
] | |
24db047e3e13fafc5ddd4547fc9e46520a696d7f | b301ab714ad4d4625d4a79005a1bda6456a283ec | /UVa/334.cpp | f025069dbdd616fd733ba2408d048555a145a5a6 | [] | no_license | askeySnip/OJ_records | 220fd83d406709328e8450df0f6da98ae57eb2d9 | 4b77e3bb5cf19b98572fa6583dff390e03ff1a7c | refs/heads/master | 2022-06-26T02:14:34.957580 | 2022-06-11T13:56:33 | 2022-06-11T13:56:33 | 117,955,514 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,302 | cpp | /*
ID: leezhen
TASK: practice
LANG: C++11
*/
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <set>
#include <map>
#include <stack>
#include <queue>
#include <cmath>
#include <bitset>
using namespace std;
typedef vector<int> vi;
typedef pair<int, int> ii;
typedef vector<pair<int, int> > vii;
// struct
#define inf 1e6
// data
int nc, ne, nm;
int dist[404][404];
char e[2][10];
vector<string> vstr;
map<string, int> mpsi;
int main() {
int kase = 0;
while(scanf("%d", &nc), nc) {
mpsi.clear();
vstr.clear();
for(int i=0; i<404; i++) {
for(int j=0; j<404; j++) {
if(i == j) dist[i][j] = 0;
else dist[i][j] = inf;
}
}
for(int i=0; i<nc; i++) {
scanf("%d", &ne);
scanf("%s", e[0]);
if(mpsi.find(e[0]) == mpsi.end()) {
vstr.push_back(e[0]);
mpsi[e[0]] = vstr.size()-1;
}
int last = 0;
for(int j=1; j<ne; j++) {
scanf("%s", e[1-last]);
if(mpsi.find(e[1-last]) == mpsi.end()) {
mpsi[e[1-last]] = vstr.size();
vstr.push_back(e[1-last]);
}
dist[mpsi[e[last]]][mpsi[e[1-last]]] = 1;
last = 1-last;
}
}
scanf("%d", &nm);
for(int i=0; i<nm; i++) {
scanf("%s %s", e[0], e[1]);
dist[mpsi[e[0]]][mpsi[e[1]]] = 1;
}
int n = vstr.size();
for(int k=0; k<n; k++) {
for(int i=0; i<n; i++) {
for(int j=0; j<n; j++) {
if(dist[i][j] > dist[i][k] + dist[k][j]) {
dist[i][j] = dist[i][k] + dist[k][j];
}
}
}
}
vii ans;
for(int i=0; i<n; i++) {
for(int j=i+1; j<n; j++) {
if(dist[i][j] == inf && dist[j][i] == inf) ans.push_back(ii(i, j));
}
}
if(ans.empty())printf("Case %d, no concurrent events.\n", ++kase);
else {
printf("Case %d, %d concurrent events:\n", ++kase, (int)ans.size());
if((int)ans.size() == 1) {
printf("(%s,%s) \n", vstr[ans[0].first].c_str(), vstr[ans[0].second].c_str());
}
else {
printf("(%s,%s) (%s,%s) \n", vstr[ans[0].first].c_str(), vstr[ans[0].second].c_str(), vstr[ans[1].first].c_str(), vstr[ans[1].second].c_str());
}
}
}
return 0;
}
| [
"[email protected]"
] | |
6ac48384b37ee2583609e4478de1a2f61b0ef09a | a7ec77cc491d24998e00a68a203c54b9e121ef79 | /SDK/include/SoT_Interaction_enums.hpp | b48b3df2a125a4b79427c6855e7e76f7316ab0bd | [] | no_license | EO-Zanzo/zSoT-DLL | a213547ca63a884a009991b9a5c49f7c08ecffcb | 3b241befbb47062cda3cebc3ac0cf12e740ddfd7 | refs/heads/master | 2020-12-26T21:21:14.909021 | 2020-02-01T17:39:43 | 2020-02-01T17:39:43 | 237,647,839 | 4 | 1 | null | 2020-02-01T17:05:08 | 2020-02-01T17:05:08 | null | UTF-8 | C++ | false | false | 866 | hpp | #pragma once
// Sea of Thieves (2.0) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
namespace SDK
{
//---------------------------------------------------------------------------
//Enums
//---------------------------------------------------------------------------
// Enum Interaction.EInteractionBlockReason
enum class EInteractionBlockReason : uint8_t
{
EInteractionBlockReason__None = 0,
EInteractionBlockReason__Radial = 1,
EInteractionBlockReason__Other = 2,
EInteractionBlockReason__EInteractionBlockReason_MAX = 3
};
// Enum Interaction.EInteractionObject
enum class EInteractionObject : uint8_t
{
EInteractionObject__None = 0,
EInteractionObject__Shop = 1,
EInteractionObject__Chest = 2,
EInteractionObject__Barrel = 3,
EInteractionObject__EInteractionObject_MAX = 4
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"[email protected]"
] | |
aaa8f706eca185ad9f7dd72dda3930415ee4cc22 | e4f29494a0ecb0a19b231a17e51127a7ddbfe387 | /TcpDebug.ino | 4c4d7c9df0d7cf9d84c51667ee552e72d3a97973 | [] | no_license | EvertDekker/Nixieclock3V1 | de9fb41a14decd21a2a86ba4914bc6c5b1839414 | 67a97d38f1895dbb285c541efe6988dcb04496fc | refs/heads/master | 2020-05-29T15:43:43.041005 | 2019-05-29T13:26:52 | 2019-05-29T13:26:52 | 189,228,943 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 436 | ino | void init_telnet_debug(){
#ifdef TELNET
if (MDNS.begin(hostn)) {
Serial.println("* MDNS responder started. Hostname -> ");
Serial.println(hostn);
}
MDNS.addService("telnet", "tcp", 23); // Initialize the telnet server of RemoteDebug
Debug.begin(hostn); // Initiaze the telnet server
Debug.setResetCmdEnabled(true); // Enable the reset command
//Debug.showTime(true); // To show time
#endif
}
| [
"[email protected]"
] | |
510031590fb18ee868c9ac88fb8da30c2ec3e09a | b056684eb040d7f14f3d1bd5a5ae26d33bd18481 | /src/file_trans/include/file_trans.grpc.pb.h | 87036594527e453e37245aeeeaa4e6ddcda5ffe1 | [] | no_license | amyxu1/webpack-mdns | 5f1fbba65452d7475e5cc7a2548805ddf1c74859 | 516a44825d200ca495afe18f59411ae2cecec28e | refs/heads/master | 2023-06-02T21:17:44.070368 | 2021-06-15T16:52:22 | 2021-06-15T16:52:22 | 294,596,101 | 1 | 1 | null | 2020-11-06T07:05:55 | 2020-09-11T04:43:30 | Makefile | UTF-8 | C++ | false | true | 14,845 | h | // Generated by the gRPC C++ plugin.
// If you make any local change, they will be lost.
// source: file_trans.proto
#ifndef GRPC_file_5ftrans_2eproto__INCLUDED
#define GRPC_file_5ftrans_2eproto__INCLUDED
#include "file_trans.pb.h"
#include <functional>
#include <grpc/impl/codegen/port_platform.h>
#include <grpcpp/impl/codegen/async_generic_service.h>
#include <grpcpp/impl/codegen/async_stream.h>
#include <grpcpp/impl/codegen/async_unary_call.h>
#include <grpcpp/impl/codegen/client_callback.h>
#include <grpcpp/impl/codegen/client_context.h>
#include <grpcpp/impl/codegen/completion_queue.h>
#include <grpcpp/impl/codegen/message_allocator.h>
#include <grpcpp/impl/codegen/method_handler.h>
#include <grpcpp/impl/codegen/proto_utils.h>
#include <grpcpp/impl/codegen/rpc_method.h>
#include <grpcpp/impl/codegen/server_callback.h>
#include <grpcpp/impl/codegen/server_callback_handlers.h>
#include <grpcpp/impl/codegen/server_context.h>
#include <grpcpp/impl/codegen/service_type.h>
#include <grpcpp/impl/codegen/status.h>
#include <grpcpp/impl/codegen/stub_options.h>
#include <grpcpp/impl/codegen/sync_stream.h>
namespace file_trans {
class WebpackServer final {
public:
static constexpr char const* service_full_name() {
return "file_trans.WebpackServer";
}
class StubInterface {
public:
virtual ~StubInterface() {}
std::unique_ptr< ::grpc::ClientReaderInterface< ::file_trans::FileChunk>> SendFile(::grpc::ClientContext* context, const ::file_trans::Request& request) {
return std::unique_ptr< ::grpc::ClientReaderInterface< ::file_trans::FileChunk>>(SendFileRaw(context, request));
}
std::unique_ptr< ::grpc::ClientAsyncReaderInterface< ::file_trans::FileChunk>> AsyncSendFile(::grpc::ClientContext* context, const ::file_trans::Request& request, ::grpc::CompletionQueue* cq, void* tag) {
return std::unique_ptr< ::grpc::ClientAsyncReaderInterface< ::file_trans::FileChunk>>(AsyncSendFileRaw(context, request, cq, tag));
}
std::unique_ptr< ::grpc::ClientAsyncReaderInterface< ::file_trans::FileChunk>> PrepareAsyncSendFile(::grpc::ClientContext* context, const ::file_trans::Request& request, ::grpc::CompletionQueue* cq) {
return std::unique_ptr< ::grpc::ClientAsyncReaderInterface< ::file_trans::FileChunk>>(PrepareAsyncSendFileRaw(context, request, cq));
}
class experimental_async_interface {
public:
virtual ~experimental_async_interface() {}
#ifdef GRPC_CALLBACK_API_NONEXPERIMENTAL
virtual void SendFile(::grpc::ClientContext* context, ::file_trans::Request* request, ::grpc::ClientReadReactor< ::file_trans::FileChunk>* reactor) = 0;
#else
virtual void SendFile(::grpc::ClientContext* context, ::file_trans::Request* request, ::grpc::experimental::ClientReadReactor< ::file_trans::FileChunk>* reactor) = 0;
#endif
};
#ifdef GRPC_CALLBACK_API_NONEXPERIMENTAL
typedef class experimental_async_interface async_interface;
#endif
#ifdef GRPC_CALLBACK_API_NONEXPERIMENTAL
async_interface* async() { return experimental_async(); }
#endif
virtual class experimental_async_interface* experimental_async() { return nullptr; }
private:
virtual ::grpc::ClientReaderInterface< ::file_trans::FileChunk>* SendFileRaw(::grpc::ClientContext* context, const ::file_trans::Request& request) = 0;
virtual ::grpc::ClientAsyncReaderInterface< ::file_trans::FileChunk>* AsyncSendFileRaw(::grpc::ClientContext* context, const ::file_trans::Request& request, ::grpc::CompletionQueue* cq, void* tag) = 0;
virtual ::grpc::ClientAsyncReaderInterface< ::file_trans::FileChunk>* PrepareAsyncSendFileRaw(::grpc::ClientContext* context, const ::file_trans::Request& request, ::grpc::CompletionQueue* cq) = 0;
};
class Stub final : public StubInterface {
public:
Stub(const std::shared_ptr< ::grpc::ChannelInterface>& channel);
std::unique_ptr< ::grpc::ClientReader< ::file_trans::FileChunk>> SendFile(::grpc::ClientContext* context, const ::file_trans::Request& request) {
return std::unique_ptr< ::grpc::ClientReader< ::file_trans::FileChunk>>(SendFileRaw(context, request));
}
std::unique_ptr< ::grpc::ClientAsyncReader< ::file_trans::FileChunk>> AsyncSendFile(::grpc::ClientContext* context, const ::file_trans::Request& request, ::grpc::CompletionQueue* cq, void* tag) {
return std::unique_ptr< ::grpc::ClientAsyncReader< ::file_trans::FileChunk>>(AsyncSendFileRaw(context, request, cq, tag));
}
std::unique_ptr< ::grpc::ClientAsyncReader< ::file_trans::FileChunk>> PrepareAsyncSendFile(::grpc::ClientContext* context, const ::file_trans::Request& request, ::grpc::CompletionQueue* cq) {
return std::unique_ptr< ::grpc::ClientAsyncReader< ::file_trans::FileChunk>>(PrepareAsyncSendFileRaw(context, request, cq));
}
class experimental_async final :
public StubInterface::experimental_async_interface {
public:
#ifdef GRPC_CALLBACK_API_NONEXPERIMENTAL
void SendFile(::grpc::ClientContext* context, ::file_trans::Request* request, ::grpc::ClientReadReactor< ::file_trans::FileChunk>* reactor) override;
#else
void SendFile(::grpc::ClientContext* context, ::file_trans::Request* request, ::grpc::experimental::ClientReadReactor< ::file_trans::FileChunk>* reactor) override;
#endif
private:
friend class Stub;
explicit experimental_async(Stub* stub): stub_(stub) { }
Stub* stub() { return stub_; }
Stub* stub_;
};
class experimental_async_interface* experimental_async() override { return &async_stub_; }
private:
std::shared_ptr< ::grpc::ChannelInterface> channel_;
class experimental_async async_stub_{this};
::grpc::ClientReader< ::file_trans::FileChunk>* SendFileRaw(::grpc::ClientContext* context, const ::file_trans::Request& request) override;
::grpc::ClientAsyncReader< ::file_trans::FileChunk>* AsyncSendFileRaw(::grpc::ClientContext* context, const ::file_trans::Request& request, ::grpc::CompletionQueue* cq, void* tag) override;
::grpc::ClientAsyncReader< ::file_trans::FileChunk>* PrepareAsyncSendFileRaw(::grpc::ClientContext* context, const ::file_trans::Request& request, ::grpc::CompletionQueue* cq) override;
const ::grpc::internal::RpcMethod rpcmethod_SendFile_;
};
static std::unique_ptr<Stub> NewStub(const std::shared_ptr< ::grpc::ChannelInterface>& channel, const ::grpc::StubOptions& options = ::grpc::StubOptions());
class Service : public ::grpc::Service {
public:
Service();
virtual ~Service();
virtual ::grpc::Status SendFile(::grpc::ServerContext* context, const ::file_trans::Request* request, ::grpc::ServerWriter< ::file_trans::FileChunk>* writer);
};
template <class BaseClass>
class WithAsyncMethod_SendFile : public BaseClass {
private:
void BaseClassMustBeDerivedFromService(const Service* /*service*/) {}
public:
WithAsyncMethod_SendFile() {
::grpc::Service::MarkMethodAsync(0);
}
~WithAsyncMethod_SendFile() override {
BaseClassMustBeDerivedFromService(this);
}
// disable synchronous version of this method
::grpc::Status SendFile(::grpc::ServerContext* /*context*/, const ::file_trans::Request* /*request*/, ::grpc::ServerWriter< ::file_trans::FileChunk>* /*writer*/) override {
abort();
return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, "");
}
void RequestSendFile(::grpc::ServerContext* context, ::file_trans::Request* request, ::grpc::ServerAsyncWriter< ::file_trans::FileChunk>* writer, ::grpc::CompletionQueue* new_call_cq, ::grpc::ServerCompletionQueue* notification_cq, void *tag) {
::grpc::Service::RequestAsyncServerStreaming(0, context, request, writer, new_call_cq, notification_cq, tag);
}
};
typedef WithAsyncMethod_SendFile<Service > AsyncService;
template <class BaseClass>
class ExperimentalWithCallbackMethod_SendFile : public BaseClass {
private:
void BaseClassMustBeDerivedFromService(const Service* /*service*/) {}
public:
ExperimentalWithCallbackMethod_SendFile() {
#ifdef GRPC_CALLBACK_API_NONEXPERIMENTAL
::grpc::Service::
#else
::grpc::Service::experimental().
#endif
MarkMethodCallback(0,
new ::grpc_impl::internal::CallbackServerStreamingHandler< ::file_trans::Request, ::file_trans::FileChunk>(
[this](
#ifdef GRPC_CALLBACK_API_NONEXPERIMENTAL
::grpc::CallbackServerContext*
#else
::grpc::experimental::CallbackServerContext*
#endif
context, const ::file_trans::Request* request) { return this->SendFile(context, request); }));
}
~ExperimentalWithCallbackMethod_SendFile() override {
BaseClassMustBeDerivedFromService(this);
}
// disable synchronous version of this method
::grpc::Status SendFile(::grpc::ServerContext* /*context*/, const ::file_trans::Request* /*request*/, ::grpc::ServerWriter< ::file_trans::FileChunk>* /*writer*/) override {
abort();
return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, "");
}
#ifdef GRPC_CALLBACK_API_NONEXPERIMENTAL
virtual ::grpc::ServerWriteReactor< ::file_trans::FileChunk>* SendFile(
::grpc::CallbackServerContext* /*context*/, const ::file_trans::Request* /*request*/)
#else
virtual ::grpc::experimental::ServerWriteReactor< ::file_trans::FileChunk>* SendFile(
::grpc::experimental::CallbackServerContext* /*context*/, const ::file_trans::Request* /*request*/)
#endif
{ return nullptr; }
};
#ifdef GRPC_CALLBACK_API_NONEXPERIMENTAL
typedef ExperimentalWithCallbackMethod_SendFile<Service > CallbackService;
#endif
typedef ExperimentalWithCallbackMethod_SendFile<Service > ExperimentalCallbackService;
template <class BaseClass>
class WithGenericMethod_SendFile : public BaseClass {
private:
void BaseClassMustBeDerivedFromService(const Service* /*service*/) {}
public:
WithGenericMethod_SendFile() {
::grpc::Service::MarkMethodGeneric(0);
}
~WithGenericMethod_SendFile() override {
BaseClassMustBeDerivedFromService(this);
}
// disable synchronous version of this method
::grpc::Status SendFile(::grpc::ServerContext* /*context*/, const ::file_trans::Request* /*request*/, ::grpc::ServerWriter< ::file_trans::FileChunk>* /*writer*/) override {
abort();
return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, "");
}
};
template <class BaseClass>
class WithRawMethod_SendFile : public BaseClass {
private:
void BaseClassMustBeDerivedFromService(const Service* /*service*/) {}
public:
WithRawMethod_SendFile() {
::grpc::Service::MarkMethodRaw(0);
}
~WithRawMethod_SendFile() override {
BaseClassMustBeDerivedFromService(this);
}
// disable synchronous version of this method
::grpc::Status SendFile(::grpc::ServerContext* /*context*/, const ::file_trans::Request* /*request*/, ::grpc::ServerWriter< ::file_trans::FileChunk>* /*writer*/) override {
abort();
return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, "");
}
void RequestSendFile(::grpc::ServerContext* context, ::grpc::ByteBuffer* request, ::grpc::ServerAsyncWriter< ::grpc::ByteBuffer>* writer, ::grpc::CompletionQueue* new_call_cq, ::grpc::ServerCompletionQueue* notification_cq, void *tag) {
::grpc::Service::RequestAsyncServerStreaming(0, context, request, writer, new_call_cq, notification_cq, tag);
}
};
template <class BaseClass>
class ExperimentalWithRawCallbackMethod_SendFile : public BaseClass {
private:
void BaseClassMustBeDerivedFromService(const Service* /*service*/) {}
public:
ExperimentalWithRawCallbackMethod_SendFile() {
#ifdef GRPC_CALLBACK_API_NONEXPERIMENTAL
::grpc::Service::
#else
::grpc::Service::experimental().
#endif
MarkMethodRawCallback(0,
new ::grpc_impl::internal::CallbackServerStreamingHandler< ::grpc::ByteBuffer, ::grpc::ByteBuffer>(
[this](
#ifdef GRPC_CALLBACK_API_NONEXPERIMENTAL
::grpc::CallbackServerContext*
#else
::grpc::experimental::CallbackServerContext*
#endif
context, const::grpc::ByteBuffer* request) { return this->SendFile(context, request); }));
}
~ExperimentalWithRawCallbackMethod_SendFile() override {
BaseClassMustBeDerivedFromService(this);
}
// disable synchronous version of this method
::grpc::Status SendFile(::grpc::ServerContext* /*context*/, const ::file_trans::Request* /*request*/, ::grpc::ServerWriter< ::file_trans::FileChunk>* /*writer*/) override {
abort();
return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, "");
}
#ifdef GRPC_CALLBACK_API_NONEXPERIMENTAL
virtual ::grpc::ServerWriteReactor< ::grpc::ByteBuffer>* SendFile(
::grpc::CallbackServerContext* /*context*/, const ::grpc::ByteBuffer* /*request*/)
#else
virtual ::grpc::experimental::ServerWriteReactor< ::grpc::ByteBuffer>* SendFile(
::grpc::experimental::CallbackServerContext* /*context*/, const ::grpc::ByteBuffer* /*request*/)
#endif
{ return nullptr; }
};
typedef Service StreamedUnaryService;
template <class BaseClass>
class WithSplitStreamingMethod_SendFile : public BaseClass {
private:
void BaseClassMustBeDerivedFromService(const Service* /*service*/) {}
public:
WithSplitStreamingMethod_SendFile() {
::grpc::Service::MarkMethodStreamed(0,
new ::grpc::internal::SplitServerStreamingHandler<
::file_trans::Request, ::file_trans::FileChunk>(
[this](::grpc_impl::ServerContext* context,
::grpc_impl::ServerSplitStreamer<
::file_trans::Request, ::file_trans::FileChunk>* streamer) {
return this->StreamedSendFile(context,
streamer);
}));
}
~WithSplitStreamingMethod_SendFile() override {
BaseClassMustBeDerivedFromService(this);
}
// disable regular version of this method
::grpc::Status SendFile(::grpc::ServerContext* /*context*/, const ::file_trans::Request* /*request*/, ::grpc::ServerWriter< ::file_trans::FileChunk>* /*writer*/) override {
abort();
return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, "");
}
// replace default version of method with split streamed
virtual ::grpc::Status StreamedSendFile(::grpc::ServerContext* context, ::grpc::ServerSplitStreamer< ::file_trans::Request,::file_trans::FileChunk>* server_split_streamer) = 0;
};
typedef WithSplitStreamingMethod_SendFile<Service > SplitStreamedService;
typedef WithSplitStreamingMethod_SendFile<Service > StreamedService;
};
} // namespace file_trans
#endif // GRPC_file_5ftrans_2eproto__INCLUDED
| [
"[email protected]"
] | |
ca132ef2e0abab744552b5d3569fea6189f708df | 9407b552787d3e872d8cdcfae5f86cd056042dfa | /dfs2.cpp | 802f9dd49b7db9f78140d4c167793fdfe7ce8a5a | [] | no_license | themechanicalcoder/Data-Structure-And-Algorithms | 7077c30cecdd42c8291c07b39089252d6cd672e3 | 3dc49f9926de10b2645e0b1c022ddbce932e208c | refs/heads/master | 2021-06-19T21:12:35.973712 | 2020-12-18T10:58:03 | 2020-12-18T10:58:03 | 134,423,943 | 0 | 1 | null | 2020-03-22T11:18:56 | 2018-05-22T14:02:38 | C++ | UTF-8 | C++ | false | false | 574 | cpp | #include<bits/stdc++.h>
using namespace std;
vector<list<int> >g;
vector<int>v;
vector<int>d;
void dfs(int u){
if(!v[u]){
v[u]=1;
cout<<u<<" ";
for(auto it=g[u].begin();it!=g[u].end();it++){
if(!v[*it]){
d[*it]=d[u]+1;
dfs(*it);
}
}
}}
int main(){
int n,m,a,b;
cin>>n>>m;
d.assign(n+1,0);
v.assign(n+1,0);
g.assign(n+1,list<int>());
for(int i=0;i<m;i++){
cin>>a>>b;
g[a].push_back(b);
g[b].push_back(a);
}
for(int i=1;i<=n;i++){
if(!v[i]){
dfs(i);
}
}
for(int i=1;i<=n;i++){
cout<<d[i];
}
return 0;
}
| [
"[email protected]"
] | |
a35449fec2af60cbb23f7da0b8bae35a4ce64aef | 1dc05c3cb3a57aea5f64052f329eaf458f73c832 | /topic/LeetCode/0807maxIncreaseKeepingSkyline.cpp | 603cf6950b266ec0a72ef42137f69d3f137e23ee | [] | no_license | ITShadow/practiceCode | 0b1fcbb6b150a1ee91283e8ac7a8d928b4751eda | 4b407ad98e3abc0be5eadc97ff32165f9f367104 | refs/heads/master | 2023-04-08T05:53:21.734166 | 2021-04-26T03:45:46 | 2021-04-26T03:45:46 | 295,429,631 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,203 | cpp | /* 在二维数组grid中,grid[i][j]代表位于某处的建筑物的高度。 我们被允许增加任何数量(不同建筑物的数量可能不同)的建筑物的高度。 高度 0 也被认为是建筑物。
最后,从新数组的所有四个方向(即顶部,底部,左侧和右侧)观看的“天际线”必须与原始数组的天际线相同。 城市的天际线是从远处观看时,由所有建筑物形成的矩形的外部轮廓。 请看下面的例子。
建筑物高度可以增加的最大总和是多少?
例子:
输入: grid = [[3,0,8,4],[2,4,5,7],[9,2,6,3],[0,3,1,0]]
输出: 35
解释:
The grid is:
[ [3, 0, 8, 4],
[2, 4, 5, 7],
[9, 2, 6, 3],
[0, 3, 1, 0] ]
从数组竖直方向(即顶部,底部)看“天际线”是:[9, 4, 8, 7]
从水平水平方向(即左侧,右侧)看“天际线”是:[8, 7, 9, 3]
在不影响天际线的情况下对建筑物进行增高后,新数组如下:
gridNew = [ [8, 4, 8, 7],
[7, 4, 7, 7],
[9, 4, 8, 7],
[3, 3, 3, 3] ]
说明:
1 < grid.length = grid[0].length <= 50。
grid[i][j] 的高度范围是: [0, 100]。
一座建筑物占据一个grid[i][j]:换言之,它们是 1 x 1 x grid[i][j] 的长方体。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/max-increase-to-keep-city-skyline
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
class Solution {
public:
int maxIncreaseKeepingSkyline(vector<vector<int>>& grid) {
if (grid.empty()) return 0;
int R = grid.size();
int C = grid[0].size();
vector<int> row_max(R, 0);
vector<int> col_max(C, 0);
for (int i = 0; i < R; ++i) {
for (int j = 0; j < C; ++j) {
row_max[i] = max(row_max[i], grid[i][j]);
col_max[j] = max(col_max[j], grid[i][j]);
}
}
int res = 0;
for (int i = 0; i < R; ++i) {
for (int j = 0; j < C; ++j) {
res += min(row_max[i], col_max[j]) - grid[i][j];
}
}
return res;
}
}; */
/* 就是找行列最大 */ | [
"[email protected]"
] | |
22b4b85995b27b9bf5a3b2c844bcb56c4ab65e55 | 090243cf699213f32f870baf2902eb4211f825d6 | /cf/621/D.cpp | 27cba968aae8be25270c8a561e72debc59131184 | [] | no_license | zhu-he/ACM-Source | 0d4d0ac0668b569846b12297e7ed4abbb1c16571 | 02e3322e50336063d0d2dad37b2761ecb3d4e380 | refs/heads/master | 2021-06-07T18:27:19.702607 | 2016-07-10T09:20:48 | 2016-07-10T09:20:48 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 625 | cpp | #include <cstdio>
#include <cmath>
const char s[12][10] = {"x^y^z", "x^z^y", "(x^y)^z", "(x^z)^y", "y^x^z", "y^z^x", "(y^x)^z", "(y^z)^x", "z^x^y", "z^y^x", "(z^x)^y", "(z^y)^x"};
double d[12];
int main()
{
double x, y, z;
scanf("%lf %lf %lf", &x, &y, &z);
d[0] = pow(y, z) * log(x);
d[1] = pow(z, y) * log(x);
d[2] = d[3] = y * z * log(x);
d[4] = pow(x, z) * log(y);
d[5] = pow(z, x) * log(y);
d[6] = d[7] = x * z * log(y);
d[8] = pow(x, y) * log(z);
d[9] = pow(y, x) * log(z);
d[10] = d[11] = x * y * log(z);
int mx = 0;
for (int i = 1; i < 12; ++i)
if (d[i] > d[mx])
mx = i;
puts(s[mx]);
return 0;
}
| [
"[email protected]"
] | |
4b1a2ff69ea1c73dca9f8d22448ade38d373b8e1 | 84df2566bbce86ad087ec0465eaed091737b8e69 | /66. Trojki liczb/66.3/main.cpp | 925fdf6fbfb5a04c38f48df0aa157c12d0745e0b | [] | no_license | matura-inf/cpp | 5d6ea1bd12395042551f9e55fc3a88375a0aa911 | f1a9cb6930b536acb5fb1632773abd411daa0c3d | refs/heads/main | 2023-03-01T04:03:05.107390 | 2021-02-10T21:40:32 | 2021-02-10T21:40:32 | 309,538,910 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,325 | cpp | #include <iostream>
#include <fstream>
#include <cmath>
using namespace std;
int main()
{
ifstream in("../trojki.txt");
ofstream out("../wyniki_trojki.txt", ofstream::app);
long long pierwsza, druga, trzecia, nr_linii = 0;
long long pierwsza_p = 1, druga_p = 2, trzecia_p = 3;
long long pierwsza_n = 1, druga_n = 2, trzecia_n = 3;
out << endl
<< "Zad3" << endl
<< endl;
while (in >> pierwsza >> druga >> trzecia)
{
if (nr_linii % 2 == 0)
{
pierwsza_p = pierwsza;
druga_p = druga;
trzecia_p = trzecia;
}
if (nr_linii % 2 == 1)
{
pierwsza_n = pierwsza;
druga_n = druga;
trzecia_n = trzecia;
}
if (((pow(pierwsza_p, 2) + pow(druga_p, 2) == pow(trzecia_p, 2)) || (pow(pierwsza_p, 2) + pow(trzecia_p, 2) == pow(druga_p, 2)) || (pow(trzecia_p, 2) + pow(druga_p, 2) == pow(pierwsza_p, 2))) && ((pow(pierwsza_n, 2) + pow(druga_n, 2) == pow(trzecia_n, 2)) || (pow(pierwsza_n, 2) + pow(trzecia_n, 2) == pow(druga_n, 2)) || (pow(trzecia_n, 2) + pow(druga_n, 2) == pow(pierwsza_n, 2))))
{
out << pierwsza_n << " " << druga_n << " " << trzecia_n << endl;
out << pierwsza_p << " " << druga_p << " " << trzecia_p << endl
<< endl;
}
nr_linii++;
}
in.close();
out.close();
system("pause");
return 0;
} | [
"[email protected]"
] | |
fb140c6343d8cb845bec30e15d68b2741357c692 | 5668d876245e982c842409466b39e6660e5fc740 | /servo_brazo_potenciometros_guardaposicion.ino | 3ef4e592616b58aabc9c2a86ef50a4ec55730403 | [] | no_license | RiquiMora/Brazo-Robotico-4DOF | 5dea34ff7115e9e5e126d5e292b84d92cfcb2d4b | a472bd7ea25e75f91f6079aa184c3a1e47ec18b2 | refs/heads/master | 2020-03-19T02:04:27.984336 | 2018-05-31T15:05:30 | 2018-05-31T15:05:30 | 135,596,748 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,326 | ino | #include <Servo.h>
Servo hombro, brazo, base, garra;
int potpi = 0;
int pot = 1;
int potp = 2;
int po = 3;
int val; // variable to read the value from the analog pin
int val1;
int val2;
int val3;
const int max_root = 180;
char valores;
String codigo = "";
boolean mode = true;
void setup() {
Serial.begin(9600);
base.attach(11);
brazo.attach(10);
hombro.attach(9);
garra.attach(8);
}
void loop() {
val = analogRead(potpi); // reads the value of the potentiometer (value between 0 and 1023)
val = map(val, 0, 1023, 0, 180); // scale it to use it with the servo (value between 0 and 180)
hombro.write(val); // sets the servo position according to the scaled value
delay(15); // waits for the servo to get there
val1 = analogRead(pot); // reads the value of the potentiometer (value between 0 and 1023)
val1 = map(val1, 0, 1023, 0, 180); // scale it to use it with the servo (value between 0 and 180)
brazo.write(val1); // sets the servo position according to the scaled value
delay(15); // waits for the servo to get there
val2 = analogRead(potp); // reads the value of the potentiometer (value between 0 and 1023)
val2 = map(val2, 0, 1023, 0, 180); // scale it to use it with the servo (value between 0 and 180)
base.write(val2); // sets the servo position according to the scaled value
delay(15); // waits for the servo to get there
val3 = analogRead(po); // reads the value of the potentiometer (value between 0 and 1023)
val3 = map(val3, 0, 1023, 0, 180); // scale it to use it with the servo (value between 0 and 180)
garra.write(val3); // sets the servo position according to the scaled value
delay(15); // waits for the servo to get there
String metodo="",init = ""; boolean tipo = false;
int posicion = 0;
base.write(60);
brazo.write(60);
hombro.write(60);
garra.write(60);
if(Serial.available() > 0)
{
codigo = "";
while(Serial.available() > 0)
{
valores = Decimal_to_ASCII(Serial.read());
Serial.print(valores);
codigo = codigo + valores;
}
delay(2000);
}
Serial.println(codigo);
delay(2000);
for( int i=0; i < codigo.length(); i++)
{
if(tipo == false)
{
if(codigo.charAt(i) == '(')
{
tipo = true;
continue;
}
metodo = metodo + codigo.charAt(i);
} else
{
init = init + codigo.charAt(i);
if(codigo.charAt(i) == ')')
{
continue;
}else if(codigo.charAt(i) == ';'){
delay(2000);
posicion = init.toInt();
if(metodo == "brazo")
{
posicion < 180 ? brazo.write(posicion) : brazo.write(180);
Serial.println("brazo");
delay(2000);
}else if(metodo == "base")
{
posicion < max_root ? base.write(posicion) : base.write(180);
Serial.println("base");
delay(2000);
}else if(metodo == "hombro")
{
posicion < max_root ? hombro.write(posicion) : hombro.write(180);
Serial.println("hombro");
delay(2000);
}else if(metodo == "garra")
{
posicion < max_root ? garra.write(posicion) : garra.write(180);
Serial.println("garra");
delay(2000);
}
metodo = "";
tipo = false;
init = "";
}
}
}
}
char Decimal_to_ASCII(int entrada){
char salida=' ';
switch(entrada){
case 32:
salida=' ';
break;
case 33:
salida='!';
break;
case 34:
salida='"';
break;
case 35:
salida='#';
break;
case 36:
salida='$';
break;
case 37:
salida='%';
break;
case 38:
salida='&';
break;
case 39:
salida=' ';
break;
case 40:
salida='(';
break;
case 41:
salida=')';
break;
case 42:
salida='*';
break;
case 43:
salida='+';
break;
case 44:
salida=',';
break;
case 45:
salida='-';
break;
case 46:
salida='.';
break;
case 47:
salida='/';
break;
case 48:
salida='0';
break;
case 49:
salida='1';
break;
case 50:
salida='2';
break;
case 51:
salida='3';
break;
case 52:
salida='4';
break;
case 53:
salida='5';
break;
case 54:
salida='6';
break;
case 55:
salida='7';
break;
case 56:
salida='8';
break;
case 57:
salida='9';
break;
case 58:
salida=':';
break;
case 59:
salida=';';
break;
case 60:
salida='<';
break;
case 61:
salida='=';
break;
case 62:
salida='>';
break;
case 63:
salida='?';
break;
case 64:
salida='@';
break;
case 65:
salida='A';
break;
case 66:
salida='B';
break;
case 67:
salida='C';
break;
case 68:
salida='D';
break;
case 69:
salida='E';
break;
case 70:
salida='F';
break;
case 71:
salida='G';
break;
case 72:
salida='H';
break;
case 73:
salida='I';
break;
case 74:
salida='J';
break;
case 75:
salida='K';
break;
case 76:
salida='L';
break;
case 77:
salida='M';
break;
case 78:
salida='N';
break;
case 79:
salida='O';
break;
case 80:
salida='P';
break;
case 81:
salida='Q';
break;
case 82:
salida='R';
break;
case 83:
salida='S';
break;
case 84:
salida='T';
break;
case 85:
salida='U';
break;
case 86:
salida='V';
break;
case 87:
salida='W';
break;
case 88:
salida='X';
break;
case 89:
salida='Y';
break;
case 90:
salida='Z';
break;
case 91:
salida='[';
break;
case 92:
salida=' ';
break;
case 93:
salida=']';
break;
case 94:
salida='^';
break;
case 95:
salida='_';
break;
case 96:
salida='`';
break;
case 97:
salida='a';
break;
case 98:
salida='b';
break;
case 99:
salida='c';
break;
case 100:
salida='d';
break;
case 101:
salida='e';
break;
case 102:
salida='f';
break;
case 103:
salida='g';
break;
case 104:
salida='h';
break;
case 105:
salida='i';
break;
case 106:
salida='j';
break;
case 107:
salida='k';
break;
case 108:
salida='l';
break;
case 109:
salida='m';
break;
case 110:
salida='n';
break;
case 111:
salida='o';
break;
case 112:
salida='p';
break;
case 113:
salida='q';
break;
case 114:
salida='r';
break;
case 115:
salida='s';
break;
case 116:
salida='t';
break;
case 117:
salida='u';
break;
case 118:
salida='v';
break;
case 119:
salida='w';
break;
case 120:
salida='x';
break;
case 121:
salida='y';
break;
case 122:
salida='z';
break;
case 123:
salida='{';
break;
case 124:
salida='|';
break;
case 125:
salida='}';
break;
case 126:
salida='~';
break;
}
return salida;
}
| [
"[email protected]"
] | |
a8d17ef93bf42f1113f7e8f7b8af41d62d7166d6 | 2b1a79a1fd6ebe6ebeb3b58d6b8144bf8ccd8c0d | /Games/Rong/Export/cpp/windows/obj/src/StringTools.cpp | 7cd4329bc5960408e432ca980ec5fefd8315e61a | [] | no_license | spoozbe/Portfolio | 18ba48bad5981e21901d2ef2b5595584b2451c19 | 4818a58eb50cbec949854456af6bbd49d6f37716 | refs/heads/master | 2021-01-02T08:45:38.660402 | 2014-11-02T04:49:25 | 2014-11-02T04:49:25 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,029 | cpp | #include <hxcpp.h>
#ifndef INCLUDED_StringTools
#include <StringTools.h>
#endif
Void StringTools_obj::__construct()
{
return null();
}
StringTools_obj::~StringTools_obj() { }
Dynamic StringTools_obj::__CreateEmpty() { return new StringTools_obj; }
hx::ObjectPtr< StringTools_obj > StringTools_obj::__new()
{ hx::ObjectPtr< StringTools_obj > result = new StringTools_obj();
result->__construct();
return result;}
Dynamic StringTools_obj::__Create(hx::DynamicArray inArgs)
{ hx::ObjectPtr< StringTools_obj > result = new StringTools_obj();
result->__construct();
return result;}
::String StringTools_obj::urlEncode( ::String s){
HX_STACK_PUSH("StringTools::urlEncode","C:\\Motion-Twin\\haxe/std/StringTools.hx",41);
HX_STACK_ARG(s,"s");
HX_STACK_LINE(41)
return s.__URLEncode();
}
STATIC_HX_DEFINE_DYNAMIC_FUNC1(StringTools_obj,urlEncode,return )
::String StringTools_obj::urlDecode( ::String s){
HX_STACK_PUSH("StringTools::urlDecode","C:\\Motion-Twin\\haxe/std/StringTools.hx",68);
HX_STACK_ARG(s,"s");
HX_STACK_LINE(68)
return s.__URLDecode();
}
STATIC_HX_DEFINE_DYNAMIC_FUNC1(StringTools_obj,urlDecode,return )
::String StringTools_obj::htmlEscape( ::String s){
HX_STACK_PUSH("StringTools::htmlEscape","C:\\Motion-Twin\\haxe/std/StringTools.hx",95);
HX_STACK_ARG(s,"s");
HX_STACK_LINE(95)
return s.split(HX_CSTRING("&"))->join(HX_CSTRING("&")).split(HX_CSTRING("<"))->join(HX_CSTRING("<")).split(HX_CSTRING(">"))->join(HX_CSTRING(">"));
}
STATIC_HX_DEFINE_DYNAMIC_FUNC1(StringTools_obj,htmlEscape,return )
::String StringTools_obj::htmlUnescape( ::String s){
HX_STACK_PUSH("StringTools::htmlUnescape","C:\\Motion-Twin\\haxe/std/StringTools.hx",102);
HX_STACK_ARG(s,"s");
HX_STACK_LINE(102)
return s.split(HX_CSTRING(">"))->join(HX_CSTRING(">")).split(HX_CSTRING("<"))->join(HX_CSTRING("<")).split(HX_CSTRING("&"))->join(HX_CSTRING("&"));
}
STATIC_HX_DEFINE_DYNAMIC_FUNC1(StringTools_obj,htmlUnescape,return )
bool StringTools_obj::startsWith( ::String s,::String start){
HX_STACK_PUSH("StringTools::startsWith","C:\\Motion-Twin\\haxe/std/StringTools.hx",113);
HX_STACK_ARG(s,"s");
HX_STACK_ARG(start,"start");
HX_STACK_LINE(113)
return (bool((s.length >= start.length)) && bool((s.substr((int)0,start.length) == start)));
}
STATIC_HX_DEFINE_DYNAMIC_FUNC2(StringTools_obj,startsWith,return )
bool StringTools_obj::endsWith( ::String s,::String end){
HX_STACK_PUSH("StringTools::endsWith","C:\\Motion-Twin\\haxe/std/StringTools.hx",126);
HX_STACK_ARG(s,"s");
HX_STACK_ARG(end,"end");
HX_STACK_LINE(132)
int elen = end.length; HX_STACK_VAR(elen,"elen");
HX_STACK_LINE(133)
int slen = s.length; HX_STACK_VAR(slen,"slen");
HX_STACK_LINE(134)
return (bool((slen >= elen)) && bool((s.substr((slen - elen),elen) == end)));
}
STATIC_HX_DEFINE_DYNAMIC_FUNC2(StringTools_obj,endsWith,return )
bool StringTools_obj::isSpace( ::String s,int pos){
HX_STACK_PUSH("StringTools::isSpace","C:\\Motion-Twin\\haxe/std/StringTools.hx",141);
HX_STACK_ARG(s,"s");
HX_STACK_ARG(pos,"pos");
HX_STACK_LINE(142)
Dynamic c = s.charCodeAt(pos); HX_STACK_VAR(c,"c");
HX_STACK_LINE(143)
return (bool((bool((c >= (int)9)) && bool((c <= (int)13)))) || bool((c == (int)32)));
}
STATIC_HX_DEFINE_DYNAMIC_FUNC2(StringTools_obj,isSpace,return )
::String StringTools_obj::ltrim( ::String s){
HX_STACK_PUSH("StringTools::ltrim","C:\\Motion-Twin\\haxe/std/StringTools.hx",149);
HX_STACK_ARG(s,"s");
HX_STACK_LINE(155)
int l = s.length; HX_STACK_VAR(l,"l");
HX_STACK_LINE(156)
int r = (int)0; HX_STACK_VAR(r,"r");
HX_STACK_LINE(157)
while(((bool((r < l)) && bool(::StringTools_obj::isSpace(s,r))))){
HX_STACK_LINE(157)
(r)++;
}
HX_STACK_LINE(160)
if (((r > (int)0))){
HX_STACK_LINE(161)
return s.substr(r,(l - r));
}
else{
HX_STACK_LINE(163)
return s;
}
HX_STACK_LINE(160)
return null();
}
STATIC_HX_DEFINE_DYNAMIC_FUNC1(StringTools_obj,ltrim,return )
::String StringTools_obj::rtrim( ::String s){
HX_STACK_PUSH("StringTools::rtrim","C:\\Motion-Twin\\haxe/std/StringTools.hx",170);
HX_STACK_ARG(s,"s");
HX_STACK_LINE(176)
int l = s.length; HX_STACK_VAR(l,"l");
HX_STACK_LINE(177)
int r = (int)0; HX_STACK_VAR(r,"r");
HX_STACK_LINE(178)
while(((bool((r < l)) && bool(::StringTools_obj::isSpace(s,((l - r) - (int)1)))))){
HX_STACK_LINE(178)
(r)++;
}
HX_STACK_LINE(181)
if (((r > (int)0))){
HX_STACK_LINE(181)
return s.substr((int)0,(l - r));
}
else{
HX_STACK_LINE(183)
return s;
}
HX_STACK_LINE(181)
return null();
}
STATIC_HX_DEFINE_DYNAMIC_FUNC1(StringTools_obj,rtrim,return )
::String StringTools_obj::trim( ::String s){
HX_STACK_PUSH("StringTools::trim","C:\\Motion-Twin\\haxe/std/StringTools.hx",192);
HX_STACK_ARG(s,"s");
HX_STACK_LINE(192)
return ::StringTools_obj::ltrim(::StringTools_obj::rtrim(s));
}
STATIC_HX_DEFINE_DYNAMIC_FUNC1(StringTools_obj,trim,return )
::String StringTools_obj::rpad( ::String s,::String c,int l){
HX_STACK_PUSH("StringTools::rpad","C:\\Motion-Twin\\haxe/std/StringTools.hx",207);
HX_STACK_ARG(s,"s");
HX_STACK_ARG(c,"c");
HX_STACK_ARG(l,"l");
HX_STACK_LINE(211)
int sl = s.length; HX_STACK_VAR(sl,"sl");
HX_STACK_LINE(212)
int cl = c.length; HX_STACK_VAR(cl,"cl");
HX_STACK_LINE(213)
while(((sl < l))){
HX_STACK_LINE(213)
if ((((l - sl) < cl))){
HX_STACK_LINE(215)
hx::AddEq(s,c.substr((int)0,(l - sl)));
HX_STACK_LINE(216)
sl = l;
}
else{
HX_STACK_LINE(218)
hx::AddEq(s,c);
HX_STACK_LINE(219)
hx::AddEq(sl,cl);
}
}
HX_STACK_LINE(222)
return s;
}
STATIC_HX_DEFINE_DYNAMIC_FUNC3(StringTools_obj,rpad,return )
::String StringTools_obj::lpad( ::String s,::String c,int l){
HX_STACK_PUSH("StringTools::lpad","C:\\Motion-Twin\\haxe/std/StringTools.hx",229);
HX_STACK_ARG(s,"s");
HX_STACK_ARG(c,"c");
HX_STACK_ARG(l,"l");
HX_STACK_LINE(233)
::String ns = HX_CSTRING(""); HX_STACK_VAR(ns,"ns");
HX_STACK_LINE(234)
int sl = s.length; HX_STACK_VAR(sl,"sl");
HX_STACK_LINE(235)
if (((sl >= l))){
HX_STACK_LINE(235)
return s;
}
HX_STACK_LINE(237)
int cl = c.length; HX_STACK_VAR(cl,"cl");
HX_STACK_LINE(238)
while(((sl < l))){
HX_STACK_LINE(238)
if ((((l - sl) < cl))){
HX_STACK_LINE(240)
hx::AddEq(ns,c.substr((int)0,(l - sl)));
HX_STACK_LINE(241)
sl = l;
}
else{
HX_STACK_LINE(243)
hx::AddEq(ns,c);
HX_STACK_LINE(244)
hx::AddEq(sl,cl);
}
}
HX_STACK_LINE(247)
return (ns + s);
}
STATIC_HX_DEFINE_DYNAMIC_FUNC3(StringTools_obj,lpad,return )
::String StringTools_obj::replace( ::String s,::String sub,::String by){
HX_STACK_PUSH("StringTools::replace","C:\\Motion-Twin\\haxe/std/StringTools.hx",254);
HX_STACK_ARG(s,"s");
HX_STACK_ARG(sub,"sub");
HX_STACK_ARG(by,"by");
HX_STACK_LINE(254)
return s.split(sub)->join(by);
}
STATIC_HX_DEFINE_DYNAMIC_FUNC3(StringTools_obj,replace,return )
::String StringTools_obj::hex( int n,Dynamic digits){
HX_STACK_PUSH("StringTools::hex","C:\\Motion-Twin\\haxe/std/StringTools.hx",269);
HX_STACK_ARG(n,"n");
HX_STACK_ARG(digits,"digits");
HX_STACK_LINE(275)
::String s = HX_CSTRING(""); HX_STACK_VAR(s,"s");
HX_STACK_LINE(276)
::String hexChars = HX_CSTRING("0123456789ABCDEF"); HX_STACK_VAR(hexChars,"hexChars");
HX_STACK_LINE(277)
do{
HX_STACK_LINE(278)
s = (hexChars.charAt((int(n) & int((int)15))) + s);
HX_STACK_LINE(279)
hx::UShrEq(n,(int)4);
}
while(((n > (int)0)));
HX_STACK_LINE(282)
if (((digits != null()))){
HX_STACK_LINE(283)
while(((s.length < digits))){
HX_STACK_LINE(284)
s = (HX_CSTRING("0") + s);
}
}
HX_STACK_LINE(285)
return s;
}
STATIC_HX_DEFINE_DYNAMIC_FUNC2(StringTools_obj,hex,return )
int StringTools_obj::fastCodeAt( ::String s,int index){
HX_STACK_PUSH("StringTools::fastCodeAt","C:\\Motion-Twin\\haxe/std/StringTools.hx",292);
HX_STACK_ARG(s,"s");
HX_STACK_ARG(index,"index");
HX_STACK_LINE(292)
return s.cca(index);
}
STATIC_HX_DEFINE_DYNAMIC_FUNC2(StringTools_obj,fastCodeAt,return )
bool StringTools_obj::isEOF( int c){
HX_STACK_PUSH("StringTools::isEOF","C:\\Motion-Twin\\haxe/std/StringTools.hx",322);
HX_STACK_ARG(c,"c");
HX_STACK_LINE(322)
return (c == (int)0);
}
STATIC_HX_DEFINE_DYNAMIC_FUNC1(StringTools_obj,isEOF,return )
StringTools_obj::StringTools_obj()
{
}
void StringTools_obj::__Mark(HX_MARK_PARAMS)
{
HX_MARK_BEGIN_CLASS(StringTools);
HX_MARK_END_CLASS();
}
void StringTools_obj::__Visit(HX_VISIT_PARAMS)
{
}
Dynamic StringTools_obj::__Field(const ::String &inName,bool inCallProp)
{
switch(inName.length) {
case 3:
if (HX_FIELD_EQ(inName,"hex") ) { return hex_dyn(); }
break;
case 4:
if (HX_FIELD_EQ(inName,"trim") ) { return trim_dyn(); }
if (HX_FIELD_EQ(inName,"rpad") ) { return rpad_dyn(); }
if (HX_FIELD_EQ(inName,"lpad") ) { return lpad_dyn(); }
break;
case 5:
if (HX_FIELD_EQ(inName,"ltrim") ) { return ltrim_dyn(); }
if (HX_FIELD_EQ(inName,"rtrim") ) { return rtrim_dyn(); }
if (HX_FIELD_EQ(inName,"isEOF") ) { return isEOF_dyn(); }
break;
case 7:
if (HX_FIELD_EQ(inName,"isSpace") ) { return isSpace_dyn(); }
if (HX_FIELD_EQ(inName,"replace") ) { return replace_dyn(); }
break;
case 8:
if (HX_FIELD_EQ(inName,"endsWith") ) { return endsWith_dyn(); }
break;
case 9:
if (HX_FIELD_EQ(inName,"urlEncode") ) { return urlEncode_dyn(); }
if (HX_FIELD_EQ(inName,"urlDecode") ) { return urlDecode_dyn(); }
break;
case 10:
if (HX_FIELD_EQ(inName,"htmlEscape") ) { return htmlEscape_dyn(); }
if (HX_FIELD_EQ(inName,"startsWith") ) { return startsWith_dyn(); }
if (HX_FIELD_EQ(inName,"fastCodeAt") ) { return fastCodeAt_dyn(); }
break;
case 12:
if (HX_FIELD_EQ(inName,"htmlUnescape") ) { return htmlUnescape_dyn(); }
}
return super::__Field(inName,inCallProp);
}
Dynamic StringTools_obj::__SetField(const ::String &inName,const Dynamic &inValue,bool inCallProp)
{
return super::__SetField(inName,inValue,inCallProp);
}
void StringTools_obj::__GetFields(Array< ::String> &outFields)
{
super::__GetFields(outFields);
};
static ::String sStaticFields[] = {
HX_CSTRING("urlEncode"),
HX_CSTRING("urlDecode"),
HX_CSTRING("htmlEscape"),
HX_CSTRING("htmlUnescape"),
HX_CSTRING("startsWith"),
HX_CSTRING("endsWith"),
HX_CSTRING("isSpace"),
HX_CSTRING("ltrim"),
HX_CSTRING("rtrim"),
HX_CSTRING("trim"),
HX_CSTRING("rpad"),
HX_CSTRING("lpad"),
HX_CSTRING("replace"),
HX_CSTRING("hex"),
HX_CSTRING("fastCodeAt"),
HX_CSTRING("isEOF"),
String(null()) };
static ::String sMemberFields[] = {
String(null()) };
static void sMarkStatics(HX_MARK_PARAMS) {
HX_MARK_MEMBER_NAME(StringTools_obj::__mClass,"__mClass");
};
static void sVisitStatics(HX_VISIT_PARAMS) {
HX_VISIT_MEMBER_NAME(StringTools_obj::__mClass,"__mClass");
};
Class StringTools_obj::__mClass;
void StringTools_obj::__register()
{
Static(__mClass) = hx::RegisterClass(HX_CSTRING("StringTools"), hx::TCanCast< StringTools_obj> ,sStaticFields,sMemberFields,
&__CreateEmpty, &__Create,
&super::__SGetClass(), 0, sMarkStatics, sVisitStatics);
}
void StringTools_obj::__boot()
{
}
| [
"[email protected]"
] | |
2b17e47589ce2b7bb6579f599aad8e4a664896b5 | b8487f927d9fb3fa5529ad3686535714c687dd50 | /include/hermes/VM/JIT/DenseUInt64.h | 7cb45f61cba99d132ac4e42fc17f6b4a3b55cbc0 | [
"MIT"
] | permissive | hoangtuanhedspi/hermes | 4a1399f05924f0592c36a9d4b3fd1f804f383c14 | 02dbf3c796da4d09ec096ae1d5808dcb1b6062bf | refs/heads/master | 2020-07-12T21:21:53.781167 | 2019-08-27T22:58:17 | 2019-08-27T22:59:55 | 204,908,743 | 1 | 0 | MIT | 2019-08-28T17:44:49 | 2019-08-28T10:44:49 | null | UTF-8 | C++ | false | false | 2,568 | h | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the LICENSE
* file in the root directory of this source tree.
*/
#ifndef HERMES_VM_JIT_DENSEUINT64_H
#define HERMES_VM_JIT_DENSEUINT64_H
#include "hermes/VM/HermesValue.h"
#include "llvm/ADT/DenseMapInfo.h"
namespace hermes {
namespace vm {
/// A wrapper for using uint64_t with llvm::DenseMap/Set.
class DenseUInt64 {
public:
/// Enum to differentiate between LLVM's empty/tombstone and normal values.
enum class MapKeyType {
empty,
tombstone,
valid,
};
DenseUInt64(uint64_t cval) : keyType_(MapKeyType::valid), rawValue_(cval) {}
DenseUInt64(void *addr)
: keyType_(MapKeyType::valid), rawValue_((uint64_t)addr) {}
DenseUInt64(HermesValue hv)
: keyType_(MapKeyType::valid), rawValue_(hv.getRaw()) {}
DenseUInt64(double v) : DenseUInt64(HermesValue::encodeDoubleValue(v)) {}
DenseUInt64(MapKeyType keyType) : keyType_(keyType), rawValue_(0) {
assert(keyType_ != MapKeyType::valid && "valid entries must have a value");
}
bool operator==(const DenseUInt64 &other) const {
return keyType_ == other.keyType_ && rawValue_ == other.rawValue_;
}
HermesValue valueAsHV() const {
assert(
keyType_ == MapKeyType::valid &&
"attempting to get the value of tombstone/empty entry");
return HermesValue(rawValue_);
}
void *valueAsAddr() const {
assert(
keyType_ == MapKeyType::valid &&
"attempting to get the value of tombstone/empty entry");
return (void *)rawValue_;
}
uint64_t rawValue() const {
return rawValue_;
}
private:
/// The type of value we have: empty/tombstone/normal.
MapKeyType keyType_;
/// A raw uint64_t: it could be a HermesValue or an address
uint64_t rawValue_;
};
} // namespace vm
} // namespace hermes
namespace llvm {
/// Traits to enable using UInt64Constant with llvm::DenseSet/Map.
template <>
struct DenseMapInfo<hermes::vm::DenseUInt64> {
using UInt64Constant = hermes::vm::DenseUInt64;
using MapKeyType = UInt64Constant::MapKeyType;
static inline UInt64Constant getEmptyKey() {
return MapKeyType::empty;
}
static inline UInt64Constant getTombstoneKey() {
return MapKeyType::tombstone;
}
static inline unsigned getHashValue(UInt64Constant x) {
return DenseMapInfo<uint64_t>::getHashValue(x.rawValue());
}
static inline bool isEqual(UInt64Constant a, UInt64Constant b) {
return a == b;
}
};
} // namespace llvm
#endif // HERMES_VM_JIT_DENSEUINT64_H
| [
"[email protected]"
] | |
ec71eee9144a294508e930330ca1e438fb3fc919 | 32b88f828b33279cfe33420c2ed969131a7df987 | /Code/Core/Mem/MemTracker.cpp | 777a97039b84548fb8dbfdacb216b93ff26a076f | [
"LicenseRef-scancode-other-permissive",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | punitchandra/fastbuild | 53b51f001350104629e71434bb5e521a1bb63cae | 8a445d77343bc4881b33a5ebcf31a2ec8777ae2d | refs/heads/master | 2021-01-15T13:23:26.995800 | 2017-08-21T15:05:32 | 2017-08-21T15:05:32 | 38,138,811 | 0 | 0 | null | 2015-06-26T23:30:24 | 2015-06-26T23:30:23 | null | UTF-8 | C++ | false | false | 7,281 | cpp | // MemTracker.cpp
//------------------------------------------------------------------------------
// Includes
//------------------------------------------------------------------------------
#include "Core/PrecompiledHeader.h"
#include "MemTracker.h"
//------------------------------------------------------------------------------
#if defined( MEMTRACKER_ENABLED )
// Includes
//------------------------------------------------------------------------------
#include "Core/Mem/MemPoolBlock.h"
#include "Core/Process/Atomic.h"
#include "Core/Process/Thread.h"
#include "Core/Tracing/Tracing.h"
// system
#include <memory.h> // for memset
// Static Data
//------------------------------------------------------------------------------
/*static*/ uint32_t MemTracker::s_Id( 0 );
/*static*/ bool MemTracker::s_Enabled( true );
/*static*/ bool MemTracker::s_Initialized( false );
/*static*/ uint32_t MemTracker::s_AllocationCount( 0 );
/*static*/ uint64_t MemTracker::s_Mutex[];
/*static*/ MemTracker::Allocation ** MemTracker::s_AllocationHashTable = nullptr;
/*static*/ MemPoolBlock * MemTracker::s_Allocations( nullptr );
// Thread-Local Data
//------------------------------------------------------------------------------
THREAD_LOCAL uint32_t g_MemTrackerDisabledOnThisThread( 0 );
// Defines
#define ALLOCATION_MINIMUM_ALIGN ( 0x4 ) // assume at least 4 byte alignment
#define ALLOCATION_HASH_SHIFT ( 0x2 ) // shift off lower bits
#define ALLOCATION_HASH_SIZE ( 0x100000 ) // one megabyte
#define ALLOCATION_HASH_MASK ( 0x0FFFFF ) // mask off upper bits
// Alloc
//------------------------------------------------------------------------------
/*static*/ void MemTracker::Alloc( void * ptr, size_t size, const char * file, int line )
{
if ( !s_Enabled )
{
return;
}
// handle allocations during initialization
if ( g_MemTrackerDisabledOnThisThread )
{
return;
}
++g_MemTrackerDisabledOnThisThread;
if ( !s_Initialized )
{
Init();
}
const size_t hashIndex = ( ( (size_t)ptr >> ALLOCATION_HASH_SHIFT ) & ALLOCATION_HASH_MASK );
{
MutexHolder mh( GetMutex() );
Allocation * a = (Allocation *)s_Allocations->Alloc( sizeof( Allocation ) );
++s_AllocationCount;
a->m_Id = ++s_Id;
a->m_Ptr = ptr;
a->m_Size = size;
a->m_Next = s_AllocationHashTable[ hashIndex ];
a->m_File = file;
a->m_Line = line;
static size_t breakOnSize = (size_t)-1;
static uint32_t breakOnId = 0;
if ( ( size == breakOnSize ) || ( a->m_Id == breakOnId ) )
{
BREAK_IN_DEBUGGER;
}
s_AllocationHashTable[ hashIndex ] = a;
}
--g_MemTrackerDisabledOnThisThread;
}
// Free
//------------------------------------------------------------------------------
/*static*/ void MemTracker::Free( void * ptr )
{
if ( !s_Enabled )
{
return;
}
if ( !s_Initialized )
{
return;
}
if ( g_MemTrackerDisabledOnThisThread )
{
return;
}
const size_t hashIndex = ( ( (size_t)ptr >> ALLOCATION_HASH_SHIFT ) & ALLOCATION_HASH_MASK );
MutexHolder mh( GetMutex() );
Allocation * a = s_AllocationHashTable[ hashIndex ];
Allocation * prev = nullptr;
while ( a )
{
if ( a->m_Ptr == ptr )
{
if ( prev == nullptr )
{
s_AllocationHashTable[ hashIndex ] = a->m_Next;
}
else
{
prev->m_Next = a->m_Next;
}
++g_MemTrackerDisabledOnThisThread;
s_Allocations->Free( a );
--s_AllocationCount;
--g_MemTrackerDisabledOnThisThread;
break;
}
prev = a;
a = a->m_Next;
}
}
// DumpAllocations
//------------------------------------------------------------------------------
/*static*/ void MemTracker::DumpAllocations()
{
if ( s_Enabled == false )
{
OUTPUT( "DumpAllocations failed - MemTracker not enabled\n" );
return;
}
if ( s_Initialized == false )
{
OUTPUT( "DumpAllocations : No allocations\n" );
return;
}
MutexHolder mh( GetMutex() );
if ( s_AllocationCount == 0 )
{
OUTPUT( "DumpAllocations : No allocations\n" );
return;
}
uint64_t total = 0;
uint64_t numAllocs = 0;
// for each leak, we'll print a view of the memory
unsigned char displayChar[256];
memset( displayChar, '.', sizeof( displayChar ) );
const unsigned char * okChars = (const unsigned char *)"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ~`1234567890-=!@#$^&*()_+[]{};:'\",<>/?|\\";
const unsigned char * ok = okChars;
for ( ;; ) { unsigned char c = *ok; if ( c == 0 ) break; displayChar[ c ] = c; ++ok; }
char memView[ 32 ] = { 0 };
OUTPUT( "--- DumpAllocations ------------------------------------------------\n" );
for ( size_t i=0; i<ALLOCATION_HASH_SIZE; ++i )
{
Allocation * a = s_AllocationHashTable[ i ];
while ( a )
{
uint32_t id = a->m_Id;
uint64_t addr = (size_t)a->m_Ptr;
uint64_t size = a->m_Size;
// format a view of the memory contents
const char * src = (const char *)addr;
char * dst = memView;
const size_t num = Math::Min< size_t >( (size_t)size, 31 );
for ( uint32_t j=0; j<num; ++j )
{
unsigned char c = *src;
*dst = displayChar[ c ];
++src;
++dst;
}
*dst = 0;
OUTPUT( "%s(%u): Id %u : %u bytes @ 0x%016llx (Mem: %s)\n", a->m_File, a->m_Line, id, size, addr, memView );
++numAllocs;
total += size;
a = a->m_Next;
}
}
OUTPUT( "--------------------------------------------------------------------\n" );
OUTPUT( "Total: %llu bytes in %llu allocs\n", total, numAllocs );
OUTPUT( "--------------------------------------------------------------------\n" );
}
// Reset
//------------------------------------------------------------------------------
/*static*/ void MemTracker::Reset()
{
MutexHolder mh( GetMutex() );
++g_MemTrackerDisabledOnThisThread;
// free all allocation tracking
for ( size_t i=0; i<ALLOCATION_HASH_SIZE; ++i )
{
Allocation * a = s_AllocationHashTable[ i ];
while ( a )
{
s_Allocations->Free( a );
--s_AllocationCount;
a = a->m_Next;
}
s_AllocationHashTable[ i ] = nullptr;
}
ASSERT( s_AllocationCount == 0 );
s_Id = 0;
--g_MemTrackerDisabledOnThisThread;
}
// Init
//------------------------------------------------------------------------------
/*static*/ void MemTracker::Init()
{
CTASSERT( sizeof( MemTracker::s_Mutex ) == sizeof( Mutex ) );
ASSERT( g_MemTrackerDisabledOnThisThread );
// first caller does init
static uint32_t threadSafeGuard( 0 );
if ( AtomicIncU32( &threadSafeGuard ) != 1 )
{
// subsequent callers wait for init
while ( !s_Initialized ) {}
return;
}
// construct primary mutex in-place
INPLACE_NEW ( &GetMutex() ) Mutex;
// init hash table
s_AllocationHashTable = new Allocation*[ ALLOCATION_HASH_SIZE ];
memset( s_AllocationHashTable, 0, ALLOCATION_HASH_SIZE * sizeof( Allocation * ) );
// init pool for allocation structures
s_Allocations = new MemPoolBlock( sizeof( Allocation ), __alignof( Allocation ) );
MemoryBarrier();
s_Initialized = true;
}
//------------------------------------------------------------------------------
#endif // MEMTRACKER_ENABLED
//------------------------------------------------------------------------------
| [
"[email protected]"
] | |
583d34be535e307cea59286df8c350b922d68244 | 4dabe3dca7a679a5ba7c79cd4e0384657657dec2 | /views/console/proposedCombinationView.cpp | 71f0f78cfcc080d0bf61444707db3121b212baf5 | [] | no_license | carlosv5/MasterMind | 47285e4a3b191294bc07650873fb13e46459e42d | b45c61a264c936191e8db23f27234b91943e7638 | refs/heads/master | 2020-04-20T12:26:51.642639 | 2019-05-11T19:05:23 | 2019-05-11T19:05:23 | 150,888,071 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,741 | cpp | #include <assert.h>
#include <iostream>
#include "proposedCombinationView.hpp"
#include "../../controllers/colocateController.hpp"
#include "../../models/proposedCombination.hpp"
using namespace std;
ProposedCombinationView::ProposedCombinationView(){};
ProposedCombination ProposedCombinationView::readProposedCombination(ProposedCombination proposedCombination, int SIZE_COMBINATION){
showColorOptions();
std::cout << "--Insert your colors (XXXX)--" << std::endl;
std::string combinationString;
getline(std::cin, combinationString);
char * combination = proposedCombination.getCombination();
for (int i = 0; i < SIZE_COMBINATION; i++)
{
char *colorArray = new char[Color::numberOfColors];
Color::values(colorArray);
bool isAColor = false;
for (int j = 0; j < Color::numberOfColors; j++)
{
if (combinationString[i] == colorArray[j])
{
isAColor = true;
}
}
assert(isAColor);
char colorToInsert = combinationString[i];
combination[i] = colorToInsert;
}
return proposedCombination;
}
void ProposedCombinationView::showColorOptions()
{
std::cout << "You can use these colors:" << std::endl;
char *colorArray = new char[Color::numberOfColors];
Color::values(colorArray);
for (int i = 0; i < Color::numberOfColors; i++)
{
std::cout << colorArray[i] << " ";
}
std::cout << std::endl;
delete (colorArray);
}
void ProposedCombinationView::printResults(ProposedCombination * proposedCombinations, int turn)
{
std::cout << "Results:" << std::endl;
for (int i = 0; i < turn + 1; i++){
for (int j = 0; j < proposedCombinations[0].getSize(); j++)
{
std::cout << "|" << proposedCombinations[i].getCombination()[j] << "|"
<< " ";
}
std::cout << "Results:|" << proposedCombinations[i].getResults()[INDEX_BLACK_RESULT] << " Blacks|" << proposedCombinations[i].getResults()[INDEX_WHITE_RESULT] << "Whites|"
<< " " << std::endl;
}
}
void ProposedCombinationView::printPreviewCombinations(ProposedCombination * proposedCombinations, int turn)
{
std::cout << "The board is:" << std::endl;
for (int i = 0; i < turn; i++){
for (int j = 0; j < proposedCombinations[0].getSize(); j++)
{
std::cout << "|" << proposedCombinations[i].getCombination()[j] << "|"
<< " ";
}
std::cout << "Results:|" << proposedCombinations[i].getResults()[INDEX_BLACK_RESULT] << " Blacks|" << proposedCombinations[i].getResults()[INDEX_WHITE_RESULT] << "Whites|"
<< " " << std::endl;
}
} | [
"[email protected]"
] | |
28ccee844626dc8f532b974e14b830d2f77d8276 | fce00ed7da745340691c8c6cf47905ba4fe5a08e | /UchClient/FrmMain.cpp | 632d7a2b262d04091ced8c1a66af203405b47a34 | [
"Unlicense"
] | permissive | EAirPeter/Uch | bc9bae801721a9241afbfe8add293cf5dcf7a322 | 193ee52fb98d2d224cd22483b2523caf02805cfe | refs/heads/master | 2021-07-24T15:06:17.555444 | 2017-11-05T14:25:50 | 2017-11-05T14:25:50 | 109,581,211 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,153 | cpp | #include "Common.hpp"
#include "FrmFileRecv.hpp"
#include "FrmFileSend.hpp"
#include "FrmMain.hpp"
#include "Ucl.hpp"
#include <nana/gui/filebox.hpp>
using namespace nana;
FrmMain::FrmMain() :
form(nullptr, {768, 480}, appear::decorate<
appear::taskbar, appear::minimize, appear::maximize, appear::sizable
>())
{
caption(Title(L"Client"));
events().destroy(std::bind(&FrmMain::X_OnDestroy, this, std::placeholders::_1));
events().user(std::bind(&FrmMain::X_OnUser, this, std::placeholders::_1));
events().unload([this] (const arg_unload &e) {
msgbox mbx {nullptr, TitleU8(L"Exit"), msgbox::yes_no};
mbx.icon(msgbox::icon_question);
mbx << L"Are you sure to exit Uch?";
if (mbx() != mbx.pick_yes)
e.cancel = true;
});
x_btnSend.caption(L"Send");
x_btnSend.events().click(std::bind(&FrmMain::X_OnSend, this));
x_btnSend.events().key_press([this] (const arg_keyboard &e) {
if (e.key == keyboard::enter)
X_OnSend();
});
x_btnFile.caption(L"Send File");
x_btnFile.events().click(std::bind(&FrmMain::X_OnFile, this));
x_btnFile.events().key_press([this] (const arg_keyboard &e) {
if (e.key == keyboard::enter)
X_OnFile();
});
x_btnExit.caption(L"Exit");
x_btnExit.events().click(std::bind(&FrmMain::close, this));
x_btnExit.events().key_press([this] (const arg_keyboard &e) {
if (e.key == keyboard::enter)
close();
});
x_txtMessage.multi_lines(false).tip_string(u8"Message:");
x_txtMessage.events().focus([this] (const arg_focus &e) {
x_txtMessage.select(e.getting);
});
x_txtMessage.events().key_press([this] (const arg_keyboard &e) {
if (e.key == keyboard::enter)
X_OnSend();
});
x_lbxUsers.enable_single(true, false);
x_lbxUsers.append_header(L"Who", 110);
x_lbxUsers.append({L"Online", L"Offline"});
x_lbxMessages.sortable(false);
x_lbxMessages.append_header(L"When", 80);
x_lbxMessages.append_header(L"How", 180);
x_lbxMessages.append_header(L"What", 310);
x_pl.div(
"margin=[14,16]"
" <weight=120 List> <weight=8>"
" <vert"
" <Msgs> <weight=7>"
" <weight=25 Imsg> <weight=7>"
" <weight=25 <> <weight=259 gap=8 Btns>>"
" >"
);
x_pl["List"] << x_lbxUsers;
x_pl["Msgs"] << x_lbxMessages;
x_pl["Imsg"] << x_txtMessage;
x_pl["Btns"] << x_btnExit << x_btnFile << x_btnSend;
x_pl.collocate();
Ucl::Bus().Register(*this);
}
void FrmMain::OnEvent(event::EvMessage &e) noexcept {
constexpr static auto kszFmt = L"(%s) %s => %s";
x_lbxMessages.at(0).append({
FormattedTime(),
FormatString(L"(%s) %s => %s", e.sCat.c_str(), e.sFrom.c_str(), e.sTo.c_str()),
e.sWhat
});
x_lbxMessages.scroll(true);
}
void FrmMain::OnEvent(event::EvListUon &e) noexcept {
x_lbxUsers.at(1).model<std::recursive_mutex>(
e.vecUon,
[] (auto &c) {
return AsWideString(c.front().text);
},
[] (auto &s) {
return std::vector<listbox::cell> {AsUtf8String(s)};
}
);
}
void FrmMain::OnEvent(event::EvListUff &e) noexcept {
x_lbxUsers.at(2).model<std::recursive_mutex>(
e.vecUff,
[] (auto &c) {
return AsWideString(c.front().text);
},
[] (auto &s) {
return std::vector<listbox::cell> {AsUtf8String(s)};
}
);
}
void FrmMain::OnEvent(event::EvFileReq &e) noexcept {
user(std::make_unique<event::EvFileReq>(e).release());
}
void FrmMain::X_OnSend() {
auto vec = x_lbxUsers.selected();
if (vec.empty()) {
msgbox mbx {nullptr, TitleU8(L"Send message"), msgbox::ok};
mbx.icon(msgbox::icon_error);
mbx << L"Please select a recipient";
mbx();
return;
}
auto &idx = vec.front();
auto sUser = AsWideString(x_lbxUsers.at(idx.cat).at(idx.item).text(0));
switch (idx.cat) {
case 1:
// Online
X_AddMessage({kszCatChat, kszSelf, sUser, x_txtMessage.caption_wstring()});
(*Ucl::Pmg())[sUser].PostPacket(protocol::EvpMessage {
x_txtMessage.caption_wstring()
});
break;
case 2:
// Offline
X_AddMessage({kszCatFmsg, kszSelf, sUser, x_txtMessage.caption_wstring()});
Ucl::Con()->PostPacket(protocol::EvcMessageTo {
sUser, x_txtMessage.caption_wstring()
});
break;
default:
throw ExnIllegalState {};
}
x_txtMessage.caption(String {});
}
void FrmMain::X_OnFile() {
auto vec = x_lbxUsers.selected();
if (vec.empty()) {
msgbox mbx {TitleU8(L"Send file")};
mbx.icon(msgbox::icon_error);
mbx << L"Please select a recipient";
mbx();
return;
}
auto &idx = vec.front();
if (idx.cat != 1) {
msgbox mbx {TitleU8(L"Send file")};
mbx.icon(msgbox::icon_error);
mbx << L"Please select an online user";
mbx();
return;
}
auto sUser = AsWideString(x_lbxUsers.at(idx.cat).at(idx.item).text(0));
filebox fbx {nullptr, true};
if (!fbx())
return;
auto sPath = AsWideString(fbx.file());
UccPipl *pPipl;
try {
pPipl = &(*Ucl::Pmg())[sUser];
}
catch (std::out_of_range) {
msgbox mbx {TitleU8(L"Send file")};
mbx << L"The user if offline";
mbx();
return;
}
form_loader<FrmFileSend>() (*this, pPipl, sPath).show();
}
void FrmMain::X_OnDestroy(const nana::arg_destroy &e) {
Ucl::Con()->PostPacket(protocol::EvcExit {Ucl::Usr()});
Ucl::Con()->Shutdown();
Ucl::Pmg()->Shutdown();
Ucl::Bus().Unregister(*this);
}
void FrmMain::X_OnUser(const nana::arg_user &e) {
std::unique_ptr<event::EvFileReq> up {
reinterpret_cast<event::EvFileReq *>(e.param)
};
try {
form_loader<FrmFileRecv>() (*this, up->pPipl, up->eReq).show();
}
catch (ExnIllegalState) {}
}
void FrmMain::X_AddMessage(event::EvMessage &&e) noexcept {
OnEvent(e);
}
| [
"[email protected]"
] | |
0097d92533baaeb7b0f9a69817088336a809c56e | e9c9efaa1f19a28a5154c19312b2871cc4449f92 | /src/fsw/FCCode/ADCSBoxController.hpp | d57a42f104cc371266e2b4a71bca2c39e6067346 | [
"MIT"
] | permissive | Vsj986/FlightSoftware | 52bc663d00786e6866a4cbaf2c04282cacf4ad97 | c8ae3504a1685d05556a0c9253b147f9d24c03b6 | refs/heads/master | 2022-04-24T23:48:34.531495 | 2020-04-28T08:07:32 | 2020-04-28T08:07:32 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,690 | hpp | #ifndef ADCS_BOX_CONTROLLER_HPP_
#define ADCS_BOX_CONTROLLER_HPP_
#include "Drivers/ADCS.hpp"
#include "TimedControlTask.hpp"
/**
* @brief Takes input command statefields and commands the ADCS Box.
*
* Note this CT doesn't do any computing, just actuation
* This CT is inteded to only do hardware calls
*/
class ADCSBoxController : public TimedControlTask<void>
{
public:
/**
* @brief Construct a new ADCSBoxController control task
*
* @param registry input StateField registry
* @param offset control task offset
* @param _adcs the input adcs system
*/
ADCSBoxController(StateFieldRegistry ®istry, unsigned int offset, Devices::ADCS &_adcs);
/** ADCS Driver. **/
Devices::ADCS& adcs_system;
/**
* @brief Given the command statefields, use the ADCS driver to execute
*/
void execute() override;
protected:
/**
* @brief Command to get from mission_manager
*
*/
const WritableStateField<unsigned char>* adcs_state_fp;
/**
* @brief RWA command fields
*
*/
const WritableStateField<unsigned char>* rwa_mode_fp;
const WritableStateField<f_vector_t>* rwa_speed_cmd_fp;
const WritableStateField<f_vector_t>* rwa_torque_cmd_fp;
const WritableStateField<float>* rwa_speed_filter_fp;
const WritableStateField<float>* rwa_ramp_filter_fp;
/**
* @brief MTR command fields
*
*/
const WritableStateField<unsigned char>* mtr_mode_fp;
const WritableStateField<f_vector_t>* mtr_cmd_fp;
const WritableStateField<float>* mtr_limit_fp;
/**
* @brief SSA command fields
*
*/
const ReadableStateField<unsigned char>* ssa_mode_fp;
const WritableStateField<float>* ssa_voltage_filter_fp;
/**
* @brief IMU command fields
*
*/
const WritableStateField<unsigned char>* mag1_mode_fp;
const WritableStateField<unsigned char>* mag2_mode_fp;
const WritableStateField<float>* imu_mag_filter_fp;
const WritableStateField<float>* imu_gyr_filter_fp;
const WritableStateField<float>* imu_gyr_temp_filter_fp;
const WritableStateField<float>* imu_gyr_temp_kp_fp;
const WritableStateField<float>* imu_gyr_temp_ki_fp;
const WritableStateField<float>* imu_gyr_temp_kd_fp;
const WritableStateField<float>* imu_gyr_temp_desired_fp;
/**
* @brief HAVT command tables, a vector of pointers to bool state fields
*
*/
std::vector<WritableStateField<bool>*> havt_cmd_reset_vector_fp;
std::vector<WritableStateField<bool>*> havt_cmd_disable_vector_fp;
};
#endif
| [
"[email protected]"
] | |
b54f8af3b8d91ec3312f1936cc121941612c52f9 | 33c05858242f026297d97a902656ee8f066683a8 | /satellite_sniffer_BoTFSM/src/Canvas.cpp | ad8ababfa55c65250d872cc2f5187e0f6e6b207d | [] | no_license | CodecoolBP20171/cpp-satellite-sniffer-botfsm | d8bcb902da2c4f3e2d7b827da0558343022687c3 | b29818ae7dc1d2f7f3967c278a3d01c447786df8 | refs/heads/master | 2021-06-01T16:43:46.978984 | 2018-09-30T13:10:56 | 2018-09-30T13:10:56 | 113,032,533 | 4 | 2 | null | 2018-09-30T13:10:57 | 2017-12-04T11:09:09 | C | UTF-8 | C++ | false | false | 883 | cpp | #include "stdafx.h"
#include "Canvas.h"
#include "Resources.h"
#include <SDL.h>
Canvas::Canvas(const int width, const int height)
{
this->height = height;
this->width = width;
texture = SDL_CreateTexture(Resources::getInstance()->getRenderer(), SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, width, height);
SDL_SetTextureBlendMode(texture, SDL_BLENDMODE_BLEND);
}
void Canvas::resize(const int width, const int height)
{
if (texture) SDL_DestroyTexture(texture);
this->height = height;
this->width = width;
texture = SDL_CreateTexture(Resources::getInstance()->getRenderer(), SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, width, height);
SDL_SetTextureBlendMode(texture, SDL_BLENDMODE_BLEND);
}
void Canvas::setAsRenderTarget()
{
SDL_SetRenderTarget(Resources::getInstance()->getRenderer(), texture);
}
Canvas::~Canvas()
{
}
| [
"[email protected]"
] | |
85ea4dd8d55151bc08e835ee9c71d1a426ef6ce3 | 13c402c37ff65709039cb190f9079667429fd31d | /dll/StatisticsClass.cpp | 2b0c76776a165c45531775a642a1473fe7a1e2c5 | [] | no_license | DarkGL/TrackerUI | 7146689298e1b44386b4575d06c96c4c5b461463 | 3de5fb05c662ba1bb06673d815062de2448ff22b | refs/heads/master | 2023-03-17T04:39:45.409222 | 2023-03-15T06:48:49 | 2023-03-15T06:48:49 | 41,966,780 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,308 | cpp | #include "StatisticsClass.h"
const char * StatisticsClass::urlNewClient = "http://csiks.pl/pliki/stats/newClient.php";
const char * StatisticsClass::urlPingClient = "http://csiks.pl/pliki/stats/pingClient.php";
char StatisticsClass::token[] = "";
bool StatisticsClass::clientConnected = false;
void StatisticsClass::newClient(){
if( this -> getClientConnected() ){
return ;
}
HINTERNET connectHandle = InternetOpen( "HL" ,0,NULL, NULL, 0);
if( !connectHandle ){
return;
}
char connectUrl[ 512 ];
snprintf( connectUrl , sizeof( connectUrl ) , "%s?version=%s" , StatisticsClass::urlNewClient , currentVersion );
HINTERNET openAddress = InternetOpenUrl( connectHandle , connectUrl , NULL , 0, INTERNET_FLAG_PRAGMA_NOCACHE , 0);
if ( !openAddress ){
InternetCloseHandle( connectHandle );
return;
}
char bufferRead[ 64 ];
DWORD NumberOfBytesRead = 0;
InternetReadFile( openAddress , bufferRead , sizeof bufferRead , &NumberOfBytesRead );
if( NumberOfBytesRead <= 0 ){
InternetCloseHandle( openAddress );
InternetCloseHandle( connectHandle );
return;
}
InternetCloseHandle( openAddress );
InternetCloseHandle( connectHandle );
this -> setToken( bufferRead );
this -> setClientConnected( true );
}
void StatisticsClass::pingClient(){
if( !this -> getClientConnected() ){
return ;
}
char bufferUrl[ 2048 ];
snprintf( bufferUrl , sizeof( bufferUrl ) / sizeof( char ) , "%s?token=%s&version=%s" , StatisticsClass::urlPingClient , this -> getToken() , currentVersion );
HINTERNET connectHandle = InternetOpen( "HL" ,0,NULL, NULL, 0);
if( !connectHandle ){
return;
}
HINTERNET openAddress = InternetOpenUrl( connectHandle , bufferUrl , NULL , 0, INTERNET_FLAG_PRAGMA_NOCACHE , 0);
if ( !openAddress ){
InternetCloseHandle( connectHandle );
return;
}
InternetCloseHandle( openAddress );
InternetCloseHandle( connectHandle );
}
bool StatisticsClass::getClientConnected(){
return StatisticsClass::clientConnected;
}
void StatisticsClass::setClientConnected( bool value ){
StatisticsClass::clientConnected = value;
}
const char * StatisticsClass::getToken(){
return StatisticsClass::token;
}
void StatisticsClass::setToken( char * tokenSet ){
strcpy( StatisticsClass::token , tokenSet );
}
| [
"[email protected]"
] | |
31c05ddd07b9d79686913c8c08a00eaf1395abbb | 6fdd703d48a01bb73bf658c8d3aac0d98f965967 | /src_cpp/elfgames/go/train/data_loader.h | 472fb3d536934f874a4ab6fd4147fce6d3ed1d0d | [
"BSD-3-Clause"
] | permissive | roughsoft/ELF | 27f762aad66f4946411f2fdae71a45fabd028730 | 751eb1cf85aac15e3c3c792a47afa1ac64ea810c | refs/heads/master | 2020-03-25T19:54:55.579846 | 2018-08-08T21:34:11 | 2018-08-08T21:34:11 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,596 | h | /**
* Copyright (c) 2018-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
#pragma once
#include "../common/record.h"
#include "elf/distributed/shared_reader.h"
#include "elf/distributed/shared_rw_buffer2.h"
struct Stats {
std::atomic<int> client_size;
std::atomic<int> buffer_size;
std::atomic<int> failed_count;
std::atomic<int> msg_count;
std::atomic<uint64_t> total_msg_size;
Stats()
: client_size(0),
buffer_size(0),
failed_count(0),
msg_count(0),
total_msg_size(0) {}
std::string info() const {
std::stringstream ss;
ss << "#msg: " << buffer_size << " #client: " << client_size << ", ";
ss << "Msg count: " << msg_count
<< ", avg msg size: " << (float)(total_msg_size) / msg_count
<< ", failed count: " << failed_count;
return ss.str();
}
void feed(const elf::shared::InsertInfo& insert_info) {
if (!insert_info.success) {
failed_count++;
} else {
buffer_size += insert_info.delta;
msg_count++;
total_msg_size += insert_info.msg_size;
}
}
};
class DataInterface {
public:
virtual void OnStart() {}
virtual elf::shared::InsertInfo OnReceive(
const std::string& identity,
const std::string& msg) = 0;
virtual bool OnReply(const std::string& identity, std::string* msg) = 0;
};
class DataOnlineLoader {
public:
DataOnlineLoader(const elf::shared::Options& net_options)
: logger_(elf::logging::getLogger("DataOnlineLoader-", "")) {
auto curr_timestamp = time(NULL);
const std::string database_name =
"data-" + std::to_string(curr_timestamp) + ".db";
reader_.reset(new elf::shared::Reader(database_name, net_options));
std::cout << reader_->info() << std::endl;
}
void start(DataInterface* interface) {
auto proc_func = [&, interface](
elf::shared::Reader* reader,
const std::string& identity,
const std::string& msg) -> bool {
(void)reader;
try {
auto info = interface->OnReceive(identity, msg);
stats_.feed(info);
/*
if (options_.verbose) {
std::cout << "Content from " << identity
<< ", msg_size: " << msg.size() << ", " << stats_.info()
<< std::endl;
}
*/
if (stats_.msg_count % 1000 == 0) {
std::cout << elf_utils::now() << ", last_identity: " << identity
<< ", " << stats_.info() << std::endl;
}
return info.success;
} catch (...) {
logger_->error("Data malformed! String is {}", msg);
return false;
}
};
auto replier_func = [&, interface](
elf::shared::Reader* reader,
const std::string& identity,
std::string* msg) -> bool {
(void)reader;
interface->OnReply(identity, msg);
if (logger_->should_log(spdlog::level::level_enum::debug)) {
logger_->debug(
"Replier: about to send: recipient {}; msg {}; reader {}",
identity,
*msg,
reader_->info());
}
return true;
};
reader_->startReceiving(
proc_func, replier_func, [interface]() { interface->OnStart(); });
}
~DataOnlineLoader() {}
private:
std::unique_ptr<elf::shared::Reader> reader_;
Stats stats_;
std::shared_ptr<spdlog::logger> logger_;
};
| [
"[email protected]"
] | |
18296b24c1a4c774d930261e017e37a0cf8d04fa | d0601b28a3060105e82c2a839d435c4329fe82a9 | /OpenGL_Material/build-OpenGL_Material-Desktop_Qt_5_8_0_MSVC2015_64bit-Debug/debug/moc_mainwindow.cpp | 51b68186ab06892d4bfefdfe122cf57267d5fcdf | [] | no_license | guoerba/opengl | 9458b1b3827e24884bcd0a1b91d122ab6a252f8e | 103da63ada1703a3f450cfde19f41b04e922187e | refs/heads/master | 2020-07-10T15:40:49.828059 | 2019-08-25T13:52:58 | 2019-08-25T13:52:58 | 204,300,456 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,706 | cpp | /****************************************************************************
** Meta object code from reading C++ file 'mainwindow.h'
**
** Created by: The Qt Meta Object Compiler version 67 (Qt 5.8.0)
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/
#include "../../OpenGL_Material/mainwindow.h"
#include <QtCore/qbytearray.h>
#include <QtCore/qmetatype.h>
#if !defined(Q_MOC_OUTPUT_REVISION)
#error "The header file 'mainwindow.h' doesn't include <QObject>."
#elif Q_MOC_OUTPUT_REVISION != 67
#error "This file was generated using the moc from 5.8.0. 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
QT_WARNING_PUSH
QT_WARNING_DISABLE_DEPRECATED
struct qt_meta_stringdata_MainWindow_t {
QByteArrayData data[1];
char stringdata0[11];
};
#define QT_MOC_LITERAL(idx, ofs, len) \
Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \
qptrdiff(offsetof(qt_meta_stringdata_MainWindow_t, stringdata0) + ofs \
- idx * sizeof(QByteArrayData)) \
)
static const qt_meta_stringdata_MainWindow_t qt_meta_stringdata_MainWindow = {
{
QT_MOC_LITERAL(0, 0, 10) // "MainWindow"
},
"MainWindow"
};
#undef QT_MOC_LITERAL
static const uint qt_meta_data_MainWindow[] = {
// content:
7, // 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
};
void MainWindow::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 QMetaObject MainWindow::staticMetaObject = {
{ &QMainWindow::staticMetaObject, qt_meta_stringdata_MainWindow.data,
qt_meta_data_MainWindow, qt_static_metacall, Q_NULLPTR, Q_NULLPTR}
};
const QMetaObject *MainWindow::metaObject() const
{
return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject;
}
void *MainWindow::qt_metacast(const char *_clname)
{
if (!_clname) return Q_NULLPTR;
if (!strcmp(_clname, qt_meta_stringdata_MainWindow.stringdata0))
return static_cast<void*>(const_cast< MainWindow*>(this));
return QMainWindow::qt_metacast(_clname);
}
int MainWindow::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QMainWindow::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
return _id;
}
QT_WARNING_POP
QT_END_MOC_NAMESPACE
| [
"[email protected]"
] | |
759a015ca9170f3456ab0ac5f3a1626efca68ad7 | 483428f23277dc3fd2fad6588de334fc9b8355d2 | /hpp/iOSDevice32/Release/uTPLb_MemoryStreamPool.hpp | bee8378fa9718a035cca20b9ad1bd10f11e6c5d4 | [] | no_license | gzwplato/LockBox3-1 | 7084932d329beaaa8169b94729c4b05c420ebe44 | 89e300b47f8c1393aefbec01ffb89ddf96306c55 | refs/heads/master | 2021-05-10T18:41:18.748523 | 2015-07-04T09:48:06 | 2015-07-04T09:48:06 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,375 | hpp | // CodeGear C++Builder
// Copyright (c) 1995, 2015 by Embarcadero Technologies, Inc.
// All rights reserved
// (DO NOT EDIT: machine generated header) 'uTPLb_MemoryStreamPool.pas' rev: 29.00 (iOS)
#ifndef Utplb_memorystreampoolHPP
#define Utplb_memorystreampoolHPP
#pragma delphiheader begin
#pragma option push
#pragma option -w- // All warnings off
#pragma option -Vx // Zero-length empty class member
#pragma pack(push,8)
#include <System.hpp>
#include <SysInit.hpp>
#include <System.Classes.hpp>
//-- user supplied -----------------------------------------------------------
namespace Utplb_memorystreampool
{
//-- forward type declarations -----------------------------------------------
__interface IMemoryStreamPool;
typedef System::DelphiInterface<IMemoryStreamPool> _di_IMemoryStreamPool;
class DELPHICLASS TPooledMemoryStream;
//-- type declarations -------------------------------------------------------
__interface INTERFACE_UUID("{ADB2D4BA-40F6-4249-923E-201D4719609B}") IMemoryStreamPool : public System::IInterface
{
virtual int __fastcall BayCount(void) = 0 ;
virtual void __fastcall GetUsage(int Size, int &Current, int &Peak) = 0 ;
virtual int __fastcall GetSize(int Idx) = 0 ;
virtual System::Classes::TMemoryStream* __fastcall NewMemoryStream(int InitSize) = 0 ;
};
#pragma pack(push,4)
class PASCALIMPLEMENTATION TPooledMemoryStream : public System::Classes::TMemoryStream
{
typedef System::Classes::TMemoryStream inherited;
protected:
_di_IMemoryStreamPool FPool;
int FCoVector;
virtual void * __fastcall Realloc(int &NewCapacity);
public:
__fastcall TPooledMemoryStream(const _di_IMemoryStreamPool Pool1);
public:
/* TMemoryStream.Destroy */ inline __fastcall virtual ~TPooledMemoryStream(void) { }
};
#pragma pack(pop)
//-- var, const, procedure ---------------------------------------------------
extern DELPHI_PACKAGE _di_IMemoryStreamPool __fastcall NewPool(void);
} /* namespace Utplb_memorystreampool */
#if !defined(DELPHIHEADER_NO_IMPLICIT_NAMESPACE_USE) && !defined(NO_USING_NAMESPACE_UTPLB_MEMORYSTREAMPOOL)
using namespace Utplb_memorystreampool;
#endif
#pragma pack(pop)
#pragma option pop
#pragma delphiheader end.
//-- end unit ----------------------------------------------------------------
#endif // Utplb_memorystreampoolHPP
| [
"[email protected]"
] | |
579829351084c1173b9154fd34d518856cd45da2 | 829869a01da6da0f17dcc173bb5ddd640fd8ba2c | /src/server/test/pegasus_write_service_impl_test.cpp | f3ee0a89b6f99cdf004fb08a169bca7d8300c1f6 | [
"Apache-2.0"
] | permissive | SunnyShow/incubator-pegasus | fff92fa95354c7e44de6c82eb6bb4e6181b8f86d | c02e055e803dab479a31d3cac31739b75542f804 | refs/heads/master | 2022-12-21T00:30:26.747514 | 2020-09-28T16:03:42 | 2020-09-28T16:03:42 | 299,217,109 | 0 | 0 | Apache-2.0 | 2020-09-28T06:57:47 | 2020-09-28T06:57:47 | null | UTF-8 | C++ | false | false | 8,058 | cpp | // Copyright (c) 2017, Xiaomi, Inc. All rights reserved.
// This source code is licensed under the Apache License Version 2.0, which
// can be found in the LICENSE file in the root directory of this source tree.
#include "pegasus_server_test_base.h"
#include "server/pegasus_server_write.h"
#include "server/pegasus_write_service_impl.h"
#include "message_utils.h"
#include <dsn/utility/defer.h>
namespace pegasus {
namespace server {
class pegasus_write_service_impl_test : public pegasus_server_test_base
{
protected:
std::unique_ptr<pegasus_server_write> _server_write;
pegasus_write_service::impl *_write_impl{nullptr};
public:
void SetUp() override
{
start();
_server_write = dsn::make_unique<pegasus_server_write>(_server.get(), true);
_write_impl = _server_write->_write_svc->_impl.get();
}
uint64_t read_timestamp_from(dsn::string_view raw_key)
{
std::string raw_value;
rocksdb::Status s = _write_impl->_db->Get(
_write_impl->_rd_opts, utils::to_rocksdb_slice(raw_key), &raw_value);
uint64_t local_timetag =
pegasus_extract_timetag(_write_impl->_pegasus_data_version, raw_value);
return extract_timestamp_from_timetag(local_timetag);
}
// start with duplicating.
void set_app_duplicating()
{
_server->stop(false);
dsn::replication::destroy_replica(_replica);
dsn::app_info app_info;
app_info.app_type = "pegasus";
app_info.duplicating = true;
_replica =
dsn::replication::create_test_replica(_replica_stub, _gpid, app_info, "./", false);
_server = dsn::make_unique<pegasus_server_impl>(_replica);
SetUp();
}
int db_get(dsn::string_view raw_key, db_get_context *get_ctx)
{
return _write_impl->db_get(raw_key, get_ctx);
}
void single_set(dsn::blob raw_key, dsn::blob user_value)
{
dsn::apps::update_request put;
put.key = raw_key;
put.value = user_value;
db_write_context write_ctx;
dsn::apps::update_response put_resp;
_write_impl->batch_put(write_ctx, put, put_resp);
ASSERT_EQ(_write_impl->batch_commit(0), 0);
}
};
TEST_F(pegasus_write_service_impl_test, put_verify_timetag)
{
set_app_duplicating();
dsn::blob raw_key;
pegasus::pegasus_generate_key(
raw_key, dsn::string_view("hash_key"), dsn::string_view("sort_key"));
std::string value = "value";
int64_t decree = 10;
/// insert timestamp 10
uint64_t timestamp = 10;
auto ctx = db_write_context::create(decree, timestamp);
ASSERT_EQ(0, _write_impl->db_write_batch_put_ctx(ctx, raw_key, value, 0));
ASSERT_EQ(0, _write_impl->db_write(ctx.decree));
_write_impl->clear_up_batch_states(decree, 0);
ASSERT_EQ(read_timestamp_from(raw_key), timestamp);
/// insert timestamp 15, which overwrites the previous record
timestamp = 15;
ctx = db_write_context::create(decree, timestamp);
ASSERT_EQ(0, _write_impl->db_write_batch_put_ctx(ctx, raw_key, value, 0));
ASSERT_EQ(0, _write_impl->db_write(ctx.decree));
_write_impl->clear_up_batch_states(decree, 0);
ASSERT_EQ(read_timestamp_from(raw_key), timestamp);
/// insert timestamp 15 from remote, which will overwrite the previous record,
/// since its cluster id is larger (current cluster_id=1)
timestamp = 15;
ctx.remote_timetag = pegasus::generate_timetag(timestamp, 2, false);
ctx.verify_timetag = true;
ASSERT_EQ(0, _write_impl->db_write_batch_put_ctx(ctx, raw_key, value + "_new", 0));
ASSERT_EQ(0, _write_impl->db_write(ctx.decree));
_write_impl->clear_up_batch_states(decree, 0);
ASSERT_EQ(read_timestamp_from(raw_key), timestamp);
std::string raw_value;
dsn::blob user_value;
rocksdb::Status s =
_write_impl->_db->Get(_write_impl->_rd_opts, utils::to_rocksdb_slice(raw_key), &raw_value);
pegasus_extract_user_data(_write_impl->_pegasus_data_version, std::move(raw_value), user_value);
ASSERT_EQ(user_value.to_string(), "value_new");
// write retry
ASSERT_EQ(0, _write_impl->db_write_batch_put_ctx(ctx, raw_key, value + "_new", 0));
ASSERT_EQ(0, _write_impl->db_write(ctx.decree));
_write_impl->clear_up_batch_states(decree, 0);
/// insert timestamp 16 from local, which will overwrite the remote record,
/// since its timestamp is larger
timestamp = 16;
ctx = db_write_context::create(decree, timestamp);
ASSERT_EQ(0, _write_impl->db_write_batch_put_ctx(ctx, raw_key, value, 0));
ASSERT_EQ(0, _write_impl->db_write(ctx.decree));
_write_impl->clear_up_batch_states(decree, 0);
ASSERT_EQ(read_timestamp_from(raw_key), timestamp);
// write retry
ASSERT_EQ(0, _write_impl->db_write_batch_put_ctx(ctx, raw_key, value, 0));
ASSERT_EQ(0, _write_impl->db_write(ctx.decree));
_write_impl->clear_up_batch_states(decree, 0);
}
// verify timetag on data version v0
TEST_F(pegasus_write_service_impl_test, verify_timetag_compatible_with_version_0)
{
dsn::fail::setup();
dsn::fail::cfg("db_get", "100%1*return()");
// if db_write_batch_put_ctx invokes db_get, this test must fail.
const_cast<uint32_t &>(_write_impl->_pegasus_data_version) = 0; // old version
dsn::blob raw_key;
pegasus::pegasus_generate_key(
raw_key, dsn::string_view("hash_key"), dsn::string_view("sort_key"));
std::string value = "value";
int64_t decree = 10;
uint64_t timestamp = 10;
auto ctx = db_write_context::create_duplicate(decree, timestamp, true);
ASSERT_EQ(0, _write_impl->db_write_batch_put_ctx(ctx, raw_key, value, 0));
ASSERT_EQ(0, _write_impl->db_write(ctx.decree));
_write_impl->clear_up_batch_states(decree, 0);
dsn::fail::teardown();
}
class incr_test : public pegasus_write_service_impl_test
{
public:
void SetUp() override
{
pegasus_write_service_impl_test::SetUp();
pegasus::pegasus_generate_key(
req.key, dsn::string_view("hash_key"), dsn::string_view("sort_key"));
}
dsn::apps::incr_request req;
dsn::apps::incr_response resp;
};
TEST_F(incr_test, incr_on_absent_record)
{
// ensure key is absent
db_get_context get_ctx;
db_get(req.key, &get_ctx);
ASSERT_FALSE(get_ctx.found);
req.increment = 100;
_write_impl->incr(0, req, resp);
ASSERT_EQ(resp.new_value, 100);
db_get(req.key, &get_ctx);
ASSERT_TRUE(get_ctx.found);
}
TEST_F(incr_test, negative_incr_and_zero_incr)
{
req.increment = -100;
ASSERT_EQ(0, _write_impl->incr(0, req, resp));
ASSERT_EQ(resp.new_value, -100);
req.increment = -1;
ASSERT_EQ(0, _write_impl->incr(0, req, resp));
ASSERT_EQ(resp.new_value, -101);
req.increment = 0;
ASSERT_EQ(0, _write_impl->incr(0, req, resp));
ASSERT_EQ(resp.new_value, -101);
}
TEST_F(incr_test, invalid_incr)
{
single_set(req.key, dsn::blob::create_from_bytes("abc"));
req.increment = 10;
_write_impl->incr(1, req, resp);
ASSERT_EQ(resp.error, rocksdb::Status::kInvalidArgument);
ASSERT_EQ(resp.new_value, 0);
single_set(req.key, dsn::blob::create_from_bytes("100"));
req.increment = std::numeric_limits<int64_t>::max();
_write_impl->incr(1, req, resp);
ASSERT_EQ(resp.error, rocksdb::Status::kInvalidArgument);
ASSERT_EQ(resp.new_value, 100);
}
TEST_F(incr_test, fail_on_get)
{
dsn::fail::setup();
dsn::fail::cfg("db_get", "100%1*return()");
// when db_get failed, incr should return an error.
req.increment = 10;
_write_impl->incr(1, req, resp);
ASSERT_EQ(resp.error, FAIL_DB_GET);
dsn::fail::teardown();
}
TEST_F(incr_test, fail_on_put)
{
dsn::fail::setup();
dsn::fail::cfg("db_write_batch_put", "100%1*return()");
// when rocksdb put failed, incr should return an error.
req.increment = 10;
_write_impl->incr(1, req, resp);
ASSERT_EQ(resp.error, FAIL_DB_WRITE_BATCH_PUT);
dsn::fail::teardown();
}
} // namespace server
} // namespace pegasus
| [
"[email protected]"
] | |
6dab7827ababfb8c432c08e1e9a9dc6eff7e91be | 866948421e7f22480da2bdf699c54220734e3a4b | /C/permutation.cpp | 1de35f518bc8136f4d30d264ac7ce768cd0b7ed8 | [] | no_license | QinShelly/workspace | f0f5aba1280a1a112cf7df316b7857454338fb2d | 4734ec9e561c64bcbdb11e321163048c1c140f58 | refs/heads/master | 2020-07-06T21:49:25.249134 | 2020-02-08T07:34:34 | 2020-02-08T07:34:34 | 67,876,658 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 530 | cpp | #include <iostream>
int a[10],book[10],n;
void dfs(int step){
int i;
if (step == n + 1) {
for (i=1; i<=n; i++) {
printf(" %d",a[i]);
}
printf("\n");
}
for (i = 1; i <= n; i++) {
if (book[i] == 0 ) {
a[step] = i;
book[i] = 1;
dfs(step + 1);
book[i] = 0;
}
}
return;
}
int main(int argc, const char * argv[]) {
scanf("%d",&n);
dfs(1);
getchar();
return 0;
}
| [
"[email protected]"
] | |
f2fd573fb8ac9dde4919620147f9c6d1cc0536a0 | d47ad8721876e05cc92a48ea772981dd2541d27c | /FPMLib/lib/bfc/autores.h | 78620a35bff0d40b0b1f790be9dc42de2b418042 | [] | no_license | cjld/ANNO-video | 5ac5f604d43e00a3ee8b2a40050413ffd8334c3e | e8ad4f1d617f8b2393db5241a40f98c156127e52 | refs/heads/master | 2021-01-25T06:45:24.164963 | 2017-06-12T15:54:19 | 2017-06-12T15:54:19 | 93,606,386 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,150 | h |
#ifndef _FF_BFC_AUTORES_H
#define _FF_BFC_AUTORES_H
#include <utility>
#include <iterator>
#include"ffdef.h"
_FF_BEG
//To help implement reference-counter in @AutoRes.
template<typename ValT>
class ReferenceCounter
{
typedef std::pair<int,ValT> _CounterT;
private:
_CounterT *_pdata;
void _inc() const
{
++_pdata->first;
}
void _dec() const
{
--_pdata->first;
}
public:
ReferenceCounter()
:_pdata(new _CounterT(1,ValT()))
{
}
ReferenceCounter(const ValT& val)
:_pdata(new _CounterT(1,val))
{
}
ReferenceCounter(const ReferenceCounter& right)
:_pdata(right._pdata)
{
this->_inc();
}
ReferenceCounter& operator=(const ReferenceCounter& right)
{
if(_pdata!=right._pdata)
{
if(this->IsLast())
delete _pdata;
else
this->_dec();
_pdata=right._pdata;
right._inc();
}
return *this;
}
//whether current reference is the last one.
bool IsLast() const
{
return _pdata->first==1;
}
//get the value stored with the counter.
const ValT& Value() const
{
return _pdata->second;
}
ValT& Value()
{
return _pdata->second;
}
//swap two counters.
void Swap(ReferenceCounter& right)
{
std::swap(this->_pdata,right._pdata);
}
~ReferenceCounter()
{
if(this->IsLast())
delete _pdata;
else
this->_dec();
}
};
//auto-resource, which is the base to implement AutoPtr,AutoArrayPtr and AutoComPtr.
template<typename PtrT,typename RetPtrT,typename ReleaseOpT>
class AutoRes
{
enum{_F_DETACHED=0x01};
struct _ValT
{
PtrT ptr;
ReleaseOpT rel_op;
int flag;
public:
_ValT()
:ptr(PtrT()),flag(0)
{
}
_ValT(const PtrT & _ptr,const ReleaseOpT & _rel_op, int _flag=0)
:ptr(_ptr),rel_op(_rel_op),flag(_flag)
{
}
void release()
{
if((flag&_F_DETACHED)==0)
rel_op(ptr);
}
};
typedef ReferenceCounter<_ValT> _CounterT;
protected:
_CounterT _counter;
void _release()
{ //release the referenced object with the stored operator.
_counter.Value().release();
}
public:
AutoRes()
{
}
explicit AutoRes(PtrT ptr,const ReleaseOpT& op=ReleaseOpT())
:_counter(_ValT(ptr,op))
{
}
AutoRes& operator=(const AutoRes& right)
{
if(this!=&right)
{
if(_counter.IsLast())
this->_release();
_counter=right._counter;
}
return *this;
}
RetPtrT operator->() const
{
return &*_counter.Value().ptr;
}
typename std::iterator_traits<RetPtrT>::reference operator*() const
{
return *_counter.Value().ptr;
}
void Swap(AutoRes& right)
{
_counter.Swap(right._counter);
}
//detach the referenced object from @*this.
RetPtrT Detach()
{
_counter.Value().flag|=_F_DETACHED;
return &*_counter.Value().ptr;
}
operator PtrT()
{
return _counter.Value().ptr;
}
~AutoRes() throw()
{
if(_counter.IsLast())
this->_release();
}
};
//operator to delete a single object.
class DeleteObj
{
public:
template<typename _PtrT>
void operator()(_PtrT ptr)
{
delete ptr;
}
};
template<typename _ObjT>
class AutoPtr
:public AutoRes<_ObjT*,_ObjT*,DeleteObj>
{
public:
explicit AutoPtr(_ObjT* ptr=NULL)
:AutoRes<_ObjT*,_ObjT*,DeleteObj>(ptr)
{
}
};
//operator to delete array of objects.
class DeleteArray
{
public:
template<typename _PtrT>
void operator()(_PtrT ptr)
{
delete[]ptr;
}
};
template<typename _ObjT>
class AutoArrayPtr
:public AutoRes<_ObjT*,_ObjT*,DeleteArray>
{
public:
explicit AutoArrayPtr(_ObjT* ptr=NULL)
:AutoRes<_ObjT*,_ObjT*,DeleteArray>(ptr)
{
}
//_ObjT& operator[](int i) const
//{
// return this->_counter.Value().ptr[i];
//}
};
class OpCloseFile
{
public:
void operator()(const FILE *fp)
{
if(fp)
fclose((FILE*)fp);
}
};
class AutoFilePtr
:public AutoRes<FILE*,FILE*,OpCloseFile>
{
public:
explicit AutoFilePtr(FILE *fp=NULL)
:AutoRes<FILE*,FILE*,OpCloseFile>(fp)
{
}
};
//operator to release COM object.
class ReleaseObj
{
public:
template<typename _PtrT>
void operator()(_PtrT ptr)
{
if(ptr)
ptr->Release();
}
};
template<typename _ObjT>
class AutoComPtr
:public AutoRes<_ObjT*,_ObjT*,ReleaseObj>
{
public:
explicit AutoComPtr(_ObjT* ptr=NULL)
:AutoRes<_ObjT*,_ObjT*,ReleaseObj>(ptr)
{
}
};
class DestroyObj
{
public:
template<typename _PtrT>
void operator()(_PtrT ptr)
{
if(ptr)
ptr->Destroy();
}
};
template<typename _ObjT>
class AutoDestroyPtr
:public AutoRes<_ObjT*,_ObjT*,DestroyObj>
{
public:
explicit AutoDestroyPtr(_ObjT* ptr=NULL)
:AutoRes<_ObjT*,_ObjT*,DestroyObj>(ptr)
{
}
};
template<typename _ServerPtrT>
class ReleaseClientOp
{
private:
_ServerPtrT m_pServer;
public:
ReleaseClientOp(_ServerPtrT pServer=_ServerPtrT())
:m_pServer(pServer)
{
}
template<typename _ClientPtrT>
void operator()(_ClientPtrT ptr)
{
if(m_pServer)
m_pServer->ReleaseClient(ptr);
}
};
template<typename _ServerPtrT,typename _ClientPtrT>
class AutoClientPtr
:public AutoRes<_ClientPtrT,_ClientPtrT,ReleaseClientOp<_ServerPtrT> >
{
typedef AutoRes<_ClientPtrT,_ClientPtrT,ReleaseClientOp<_ServerPtrT> > _MyBaseT;
public:
explicit AutoClientPtr(_ServerPtrT pServer=_ServerPtrT(),_ClientPtrT pClient=_ClientPtrT())
:_MyBaseT(pClient,ReleaseClientOp<_ServerPtrT>(pServer))
{
}
};
_FF_END
#endif
| [
"[email protected]"
] | |
fc66a1678930bf9093bd076f90dd380635b60366 | ceeddddcf3e99e909c4af5ff2b9fad4a8ecaeb2a | /branches/releases/1.3.NET/source/Irrlicht/CGUIColorSelectDialog.h | fed63371d4d75b6f6d20e164aab8c2e8f2527655 | [
"Zlib",
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-other-permissive"
] | permissive | jivibounty/irrlicht | d9d6993bd0aee00dce2397a887b7f547ade74fbb | c5c80cde40b6d14fe5661440638d36a16b41d7ab | refs/heads/master | 2021-01-18T02:56:08.844268 | 2015-07-21T08:02:25 | 2015-07-21T08:02:25 | 39,405,895 | 0 | 0 | null | 2015-07-20T20:07:06 | 2015-07-20T20:07:06 | null | UTF-8 | C++ | false | false | 1,684 | h | // Copyright (C) 2002-2007 Nikolaus Gebhardt
// This file is part of the "Irrlicht Engine".
// For conditions of distribution and use, see copyright notice in irrlicht.h
#ifndef __C_GUI_COLOR_SELECT_DIALOG_H_INCLUDED__
#define __C_GUI_COLOR_SELECT_DIALOG_H_INCLUDED__
#include "IGUIColorSelectDialog.h"
#include "IGUIButton.h"
#include "IGUIEditBox.h"
#include "IGUIScrollBar.h"
#include "IGUIImage.h"
#include "irrArray.h"
namespace irr
{
namespace gui
{
class CGUIColorSelectDialog : public IGUIColorSelectDialog
{
public:
//! constructor
CGUIColorSelectDialog(const wchar_t* title, IGUIEnvironment* environment, IGUIElement* parent, s32 id);
//! destructor
virtual ~CGUIColorSelectDialog();
//! called if an event happened.
virtual bool OnEvent(SEvent event);
//! draws the element and its children
virtual void draw();
private:
//! sends the event that the file has been selected.
void sendSelectedEvent();
//! sends the event that the file choose process has been canceld
void sendCancelEvent();
core::position2d<s32> DragStart;
bool Dragging;
IGUIButton* CloseButton;
IGUIButton* OKButton;
IGUIButton* CancelButton;
struct SBatteryItem
{
f32 Incoming;
f32 Outgoing;
IGUIEditBox * Edit;
IGUIScrollBar *Scrollbar;
};
core::array< SBatteryItem > Battery;
struct SColorCircle
{
IGUIImage * Control;
video::ITexture * Texture;
};
SColorCircle ColorRing;
void buildColorRing( const core::dimension2d<s32> & dim, s32 supersample, const u32 borderColor );
};
} // end namespace gui
} // end namespace irr
#endif
| [
"hybrid@dfc29bdd-3216-0410-991c-e03cc46cb475"
] | hybrid@dfc29bdd-3216-0410-991c-e03cc46cb475 |
06cfb9ca96a61137a348fc2045f8693d23f03832 | d160bb839227b14bb25e6b1b70c8dffb8d270274 | /MCMS/Main/Processes/Resource/ResourceLib/ConfResources.cpp | 6a1729f5225cd051689ecd1184f8de8e5b900429 | [] | no_license | somesh-ballia/mcms | 62a58baffee123a2af427b21fa7979beb1e39dd3 | 41aaa87d5f3b38bc186749861140fef464ddadd4 | refs/heads/master | 2020-12-02T22:04:46.442309 | 2017-07-03T06:02:21 | 2017-07-03T06:02:21 | 96,075,113 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 38,433 | cpp | #include "ConfResources.h"
#include "StatusesGeneral.h"
#include "ProcessBase.h"
#include "TraceStream.h"
#include "ResourceManager.h"
#include "WrappersResource.h"
#include "HelperFuncs.h"
#include "VideoApiDefinitionsStrings.h"
#include <algorithm>
#include <functional>
////////////////////////////////////////////////////////////////////////////
// CUdpRsrcDesc
////////////////////////////////////////////////////////////////////////////
CUdpRsrcDesc::CUdpRsrcDesc(WORD rsrcPartyId, WORD servId, WORD subServId, WORD PQMid)
{
m_rsrcPartyId = rsrcPartyId;
m_servId = servId;
m_PQMid = PQMid;
m_subServId = subServId;
memset(&m_udp, 0, sizeof(UdpAddresses));
for (int i = 0; i < MAX_NUM_OF_ALLOCATED_PARTY_UDP_PORTS; i++)
{
m_rtp_channels[i] = 0;
m_rtcp_channels[i] = 0;
}
}
////////////////////////////////////////////////////////////////////////////
CUdpRsrcDesc::~CUdpRsrcDesc()
{
}
////////////////////////////////////////////////////////////////////////////
bool operator==(const CUdpRsrcDesc& lhs,const CUdpRsrcDesc& rhs)
{
return ((lhs.m_rsrcPartyId == rhs.m_rsrcPartyId) && (lhs.m_type == rhs.m_type ));
}
////////////////////////////////////////////////////////////////////////////
bool operator<(const CUdpRsrcDesc& lhs,const CUdpRsrcDesc& rhs)
{
if (lhs.m_rsrcPartyId != rhs.m_rsrcPartyId)
return (lhs.m_rsrcPartyId < rhs.m_rsrcPartyId);
return (lhs.m_type < rhs.m_type);
}
////////////////////////////////////////////////////////////////////////////
void CUdpRsrcDesc::SetIpAddresses(ipAddressV4If ipAddressV4, const ipv6AddressArray& ipAddressV6)
{
CIPV4Wrapper v4wrapper(m_udp.IpV4Addr);
v4wrapper.CopyData(ipAddressV4);
CIPV6AraryWrapper v6wrapper(m_udp.IpV6AddrArray);
v6wrapper.CopyData(ipAddressV6);
}
////////////////////////////////////////////////////////////////////////////
// CRsrcDesc
////////////////////////////////////////////////////////////////////////////
CRsrcDesc::CRsrcDesc(DWORD connectionId, eLogicalResourceTypes type, DWORD rsrcConfId, WORD rsrcPartyId,
WORD boxId , WORD bId, WORD subBid, WORD uid, WORD acceleratorId, WORD firstPortId, ECntrlType cntrl,
WORD channelId, BOOL bIsUpdated /*= FALSE*/ )
{
m_connectionId = connectionId;
m_type = type;
m_rsrcConfId = rsrcConfId;
m_rsrcPartyId = rsrcPartyId;
m_boxId = boxId;
m_boardId = bId;
m_subBoardId = subBid;
m_unitId = uid;
m_acceleratorId = acceleratorId;
m_firstPortId = firstPortId;
m_numPorts = 1;
m_cntrl = cntrl;
m_channelId = channelId;
m_bIsUpdated = bIsUpdated;
memset(&m_IpV4Addr, 0, sizeof(m_IpV4Addr));
}
////////////////////////////////////////////////////////////////////////////
CRsrcDesc::~CRsrcDesc()
{
}
////////////////////////////////////////////////////////////////////////////
bool operator==(const CRsrcDesc& lhs,const CRsrcDesc& rhs)
{
//net ports can be the same except for the board, portid, unit_id (=span id) and accelerator_id, so check this
if (lhs.m_type == eLogical_net && rhs.m_type == eLogical_net)
if (lhs.m_firstPortId != rhs.m_firstPortId || lhs.m_unitId != rhs.m_unitId || lhs.m_acceleratorId != rhs.m_acceleratorId || lhs.m_boardId != rhs.m_boardId)
return FALSE;
return ((lhs.m_rsrcPartyId == rhs.m_rsrcPartyId) &&
(lhs.m_type == rhs.m_type ) && (lhs.m_cntrl == rhs.m_cntrl));
}
////////////////////////////////////////////////////////////////////////////
bool operator<(const CRsrcDesc& lhs,const CRsrcDesc& rhs)
{
if (lhs.m_rsrcPartyId != rhs.m_rsrcPartyId)
return (lhs.m_rsrcPartyId < rhs.m_rsrcPartyId);
else if (lhs.m_type != rhs.m_type)
return (lhs.m_type < rhs.m_type);
else if (lhs.m_type != eLogical_net)
return (lhs.m_cntrl < rhs.m_cntrl);
else //if it's net type
{
if (lhs.m_firstPortId != rhs.m_firstPortId)
return (lhs.m_firstPortId < rhs.m_firstPortId);
else if (lhs.m_acceleratorId != rhs.m_acceleratorId)
return (lhs.m_acceleratorId < rhs.m_acceleratorId);
else if (lhs.m_unitId != rhs.m_unitId)
return (lhs.m_unitId < rhs.m_unitId);
else
return (lhs.m_boardId < rhs.m_boardId);
}
}
////////////////////////////////////////////////////////////////////////////
void CRsrcDesc::SetIpAddresses(ipAddressV4If ipAddressV4)
{
CIPV4Wrapper v4wrapper(m_IpV4Addr);
v4wrapper.CopyData(ipAddressV4);
}
////////////////////////////////////////////////////////////////////////////
eResourceTypes CRsrcDesc::GetPhysicalType() const
{
switch (m_type)
{
case eLogical_audio_encoder:
return ePhysical_art;
case eLogical_audio_decoder:
return ePhysical_art;
case eLogical_audio_controller:
return ePhysical_audio_controller;
case eLogical_video_encoder:
case eLogical_video_encoder_content:
case eLogical_COP_CIF_encoder:
case eLogical_COP_VSW_encoder:
case eLogical_COP_PCM_encoder:
case eLogical_COP_HD720_encoder:
case eLogical_COP_HD1080_encoder:
case eLogical_COP_4CIF_encoder:
return ePhysical_video_encoder;
case eLogical_video_decoder:
case eLogical_COP_Dynamic_decoder:
case eLogical_COP_VSW_decoder:
case eLogical_COP_LM_decoder:
return ePhysical_video_decoder;
case eLogical_rtp:
return ePhysical_art;
/*Not in use for now
case eLogical_ip_signaling:
return ePhysical_res_none;
*/
case eLogical_net:
return ePhysical_rtm;
case eLogical_ivr_controller:
return ePhysical_ivr_controller;
case eLogical_mux:
return ePhysical_art;
// OLGA - Soft MCU
case eLogical_relay_rtp:
case eLogical_relay_svc_to_avc_rtp:
case eLogical_relay_video_encoder:
return ePhysical_mrmp;
case eLogical_relay_audio_encoder:
case eLogical_relay_audio_decoder:
case eLogical_legacy_to_SAC_audio_encoder:
case eLogical_relay_avc_to_svc_rtp:
case eLogical_relay_avc_to_svc_rtp_with_audio_encoder:
return ePhysical_art;
case eLogical_relay_avc_to_svc_video_encoder_1:
case eLogical_relay_avc_to_svc_video_encoder_2:
return ePhysical_video_encoder;
default:
return ePhysical_res_none;
}
}
////////////////////////////////////////////////////////////////////////////
std::ostream& operator<<(std::ostream& os, CRsrcDesc& obj)
{
os
<< "\n ConnectionId :" << obj.m_connectionId
<< "\n ResourceType :" << obj.m_type
<< "\n ConfId :" << obj.m_rsrcConfId
<< "\n PartyId :" << obj.m_rsrcPartyId
<< "\n BoxId :" << obj.m_boxId
<< "\n BoardId :" << obj.m_boardId
<< "\n SubBoardId :" << obj.m_subBoardId
<< "\n UnitId :" << obj.m_unitId
<< "\n AcceleratorId :" << obj.m_acceleratorId
<< "\n FirstPortId :" << obj.m_firstPortId;
return os;
}
////////////////////////////////////////////////////////////////////////////
// CConfRsrc
////////////////////////////////////////////////////////////////////////////
CConfRsrc::CConfRsrc(DWORD monitorConfId, eSessionType sessionType, eLogicalResourceTypes encoderLogicalType, eConfMediaType confMediaType)
{
m_monitorConfId = monitorConfId;
m_sessionType = sessionType;
m_rsrcConfId = 0; //0 - not allocated.
m_num_Parties = 0;
m_pUdpRsrcDescList = new std::set<CUdpRsrcDesc>;
m_encoderTypeCOP = encoderLogicalType;
m_confMediaState = eMediaStateEmpty;
m_confMediaType = confMediaType;
m_mrcMcuId = 1;
}
////////////////////////////////////////////////////////////////////////////
CConfRsrc::CConfRsrc(const CConfRsrc& other) : CPObject(other), m_pUdpRsrcDescList(new std::set<CUdpRsrcDesc>(*(other.m_pUdpRsrcDescList)))
{
m_monitorConfId = other.m_monitorConfId;
m_sessionType = other.m_sessionType;
m_bondingPhones = other.m_bondingPhones;
m_parties = other.m_parties;
m_rsrcConfId = other.m_rsrcConfId; //0 - not allocated.
m_num_Parties = other.m_num_Parties;
m_encoderTypeCOP = other.m_encoderTypeCOP;
m_confMediaState = other.m_confMediaState;
m_confMediaType = other.m_confMediaType;
m_mrcMcuId = other.m_mrcMcuId;
m_pRsrcDescList = other.m_pRsrcDescList;
}
////////////////////////////////////////////////////////////////////////////
CConfRsrc::~CConfRsrc()
{
m_pUdpRsrcDescList->clear();
PDELETE( m_pUdpRsrcDescList);
m_pUdpRsrcDescList = 0 ;
}
////////////////////////////////////////////////////////////////////////////
WORD operator==(const CConfRsrc& lhs,const CConfRsrc& rhs)
{
return (lhs.m_monitorConfId == rhs.m_monitorConfId);
}
////////////////////////////////////////////////////////////////////////////
bool operator<(const CConfRsrc& lhs,const CConfRsrc& rhs)
{
return (lhs.m_monitorConfId < rhs.m_monitorConfId);
}
////////////////////////////////////////////////////////////////////////////
STATUS CConfRsrc::AddUdpDesc(CUdpRsrcDesc* pUdpRsrcDesc)
{
PASSERT_AND_RETURN_VALUE(!pUdpRsrcDesc, STATUS_FAIL);
std::set<CUdpRsrcDesc>::iterator _itr = m_pUdpRsrcDescList->find(*pUdpRsrcDesc);
PASSERT_AND_RETURN_VALUE(_itr != m_pUdpRsrcDescList->end(), STATUS_FAIL);
m_pUdpRsrcDescList->insert(*pUdpRsrcDesc);
return STATUS_OK;
}
////////////////////////////////////////////////////////////////////////////
// The function only updates existing desc, not adding new one, if not found
STATUS CConfRsrc::UpdateUdpDesc(WORD rsrcpartyId, CUdpRsrcDesc* pUdpRsrcDesc)
{
PASSERT_AND_RETURN_VALUE(!pUdpRsrcDesc, STATUS_FAIL);
CUdpRsrcDesc desc(rsrcpartyId);
std::set<CUdpRsrcDesc>::iterator _itr = m_pUdpRsrcDescList->find(desc);
PASSERT_AND_RETURN_VALUE(_itr == m_pUdpRsrcDescList->end(), STATUS_FAIL);
m_pUdpRsrcDescList->erase(_itr);
m_pUdpRsrcDescList->insert(*pUdpRsrcDesc);
return STATUS_OK;
}
////////////////////////////////////////////////////////////////////////////
STATUS CConfRsrc::RemoveUdpDesc(WORD rsrcpartyId)
{
std::set<CUdpRsrcDesc>::iterator i;
CUdpRsrcDesc desc(rsrcpartyId);
i = m_pUdpRsrcDescList->find(desc);
if (i == m_pUdpRsrcDescList->end())//not exists
{
PASSERT(1);
return STATUS_FAIL;
}
m_pUdpRsrcDescList->erase(i);
return STATUS_OK;
}
////////////////////////////////////////////////////////////////////////////
const CUdpRsrcDesc* CConfRsrc::GetUdpDesc(WORD rsrcpartyId)const
{
std::set<CUdpRsrcDesc>::iterator i;
CUdpRsrcDesc desc(rsrcpartyId);
i = m_pUdpRsrcDescList->find(desc);
if (i == m_pUdpRsrcDescList->end())//not exists
{
PASSERT(1);
return NULL;
}
return (&(*i));
}
////////////////////////////////////////////////////////////////////////////
STATUS CConfRsrc::AddDesc(CRsrcDesc* pRsrcDesc)
{
if (!pRsrcDesc || pRsrcDesc->GetRsrcConfId() != m_rsrcConfId)
{
DBGPASSERT(1);
if (pRsrcDesc)
TRACEINTOLVLERR << "ERROR: m_rsrcConfId = " << m_rsrcConfId << ", GetRsrcConfId()=" << pRsrcDesc->GetRsrcConfId();
return STATUS_FAIL;
}
if (m_pRsrcDescList.find(*pRsrcDesc) != m_pRsrcDescList.end())
{//desc already exists
TRACEINTOLVLERR << "Failed, descriptor already exists" << *pRsrcDesc;
PASSERT_AND_RETURN_VALUE(1, STATUS_FAIL);
}
m_pRsrcDescList.insert(*pRsrcDesc);
return STATUS_OK;
}
////////////////////////////////////////////////////////////////////////////
STATUS CConfRsrc::RemoveDesc(WORD rsrcpartyId, eLogicalResourceTypes type, ECntrlType cntrl, WORD portId, WORD unitId, WORD acceleratorId, WORD boardId)
{
CRsrcDesc desc(0, type, 0, rsrcpartyId, 0, boardId, 0, unitId, acceleratorId, portId, cntrl);
RSRC_DESC_MULTISET_ITR itr = m_pRsrcDescList.find(desc);
if (itr == m_pRsrcDescList.end()) // not exists
{
TRACEINTOLVLERR << "Failed, descriptor not exist" << desc;
PASSERT_AND_RETURN_VALUE(1, STATUS_FAIL);
}
m_pRsrcDescList.erase(itr);
return STATUS_OK;
}
////////////////////////////////////////////////////////////////////////////
CRsrcDesc* CConfRsrc::GetDescFromConnectionId(DWORD connectionId)
{
RSRC_DESC_MULTISET_ITR itr;
for (itr = m_pRsrcDescList.begin(); itr != m_pRsrcDescList.end(); itr++)
{
if ((itr->GetConnId() == connectionId))
{
return ((CRsrcDesc*)(&(*itr)));
}
}
return NULL;
}
////////////////////////////////////////////////////////////////////////////
const CRsrcDesc* CConfRsrc::GetDesc(WORD rsrcpartyId, eLogicalResourceTypes type, ECntrlType cntrl, WORD portId, WORD unitId, WORD acceleratorId, WORD boardId)
{
CRsrcDesc desc(0, type, 0, rsrcpartyId, 0, boardId, 0, unitId, acceleratorId, portId, cntrl);
RSRC_DESC_MULTISET_ITR i = m_pRsrcDescList.find(desc);
if (i == m_pRsrcDescList.end()) // not exists
{
// PASSERT(1);
return NULL;
}
return (&(*i));
}
////////////////////////////////////////////////////////////////////////////
const CRsrcDesc* CConfRsrc::GetDescByType(eLogicalResourceTypes type, ECntrlType cntrl)
{
RSRC_DESC_MULTISET_ITR itr;
for (itr = m_pRsrcDescList.begin(); itr != m_pRsrcDescList.end(); itr++)
{
if (itr->GetType() == type && itr->GetCntrlType() == cntrl)
{
return ((CRsrcDesc*)(&(*itr)));
}
}
return NULL;
}
////////////////////////////////////////////////////////////////////////////
int CConfRsrc::GetDescArray( CRsrcDesc**& pRsrcDescArray)
{
int arrSize = m_pRsrcDescList.size();
if( 0 == arrSize )
return 0;
pRsrcDescArray = new CRsrcDesc*[arrSize];
RSRC_DESC_MULTISET_ITR itr;
int i = 0;
for (itr = m_pRsrcDescList.begin(); itr != m_pRsrcDescList.end(); itr++)
{
pRsrcDescArray[i] = (CRsrcDesc*)&(*itr);
i++;
}
return i;
}
////////////////////////////////////////////////////////////////////////////
// Need to receive in pRsrcDescList memory of MAX_NUM_ALLOCATED_RSRCS_NET pointers (CRsrcDesc*) allocated for the output (and initialized to all NULLs)
// Returns number of RsrcDescs found.
WORD CConfRsrc::GetDescArrayPerResourceTypeByRsrcId(WORD rsrcpartyId,eLogicalResourceTypes type, CRsrcDesc** pRsrcDescArray, BYTE arrSize) const
{
RSRC_DESC_MULTISET_ITR itr;
int i = 0;
for (itr = m_pRsrcDescList.begin(); itr != m_pRsrcDescList.end(); itr++)
{
if ((itr->GetRsrcPartyId() == rsrcpartyId ) && ( (itr->GetType() == type) || (eLogical_res_none == type)))
{
if (i < arrSize) // For protection
{
pRsrcDescArray[i] = (CRsrcDesc*)&(*itr);
i++;
}
else
PASSERTMSG(1, "CConfRsrc::GetDescArrayPerResourceTypeByRsrcId - error in call to function");
}
}
return i;
}
////////////////////////////////////////////////////////////////////////////
const CPartyRsrc* CConfRsrc::GetPartyRsrcByRsrcPartyId(PartyRsrcID partyId) const
{
PARTIES::iterator _iiEnd = m_parties.end();
for (PARTIES::iterator _ii = m_parties.begin(); _ii != _iiEnd; ++_ii)
{
if (_ii->GetRsrcPartyId() == partyId)
return &(*_ii);
}
return NULL;
}
////////////////////////////////////////////////////////////////////////////
WORD CConfRsrc::GetNumVideoPartiesPerBoard(WORD boardId)
{
WORD numVideoParties = 0;
PARTIES::iterator _iiEnd = m_parties.end();
for (PARTIES::iterator _ii = m_parties.begin(); _ii != _iiEnd; ++_ii)
{
PartyRsrcID partyId = _ii->GetRsrcPartyId();
CPartyRsrc* pParty = const_cast<CPartyRsrc*>(GetPartyRsrcByRsrcPartyId(partyId));
if (pParty)
{
eVideoPartyType videoPartyType = pParty->GetVideoPartyType();
if (eVideo_party_type_none != videoPartyType)
{
CRsrcDesc* pDecDesc = const_cast<CRsrcDesc*>(GetDesc(partyId, eLogical_video_decoder));
if (pDecDesc)
{
if (boardId == pDecDesc->GetBoardId())
numVideoParties++;
}
}
}
}
return numVideoParties;
}
////////////////////////////////////////////////////////////////////////////
// CPartyRsrc
////////////////////////////////////////////////////////////////////////////
CPartyRsrc::CPartyRsrc(PartyMonitorID monitorPartyId, eNetworkPartyType networkPartyType, eVideoPartyType videoPartyType, WORD ARTChannels, ePartyRole partyRole,eHdVswTypesInMixAvcSvc hdVswTypeInMixAvcSvcMode)
{
m_monitorPartyId = monitorPartyId;
m_networkPartyType = networkPartyType;
m_videoPartyType = videoPartyType;
m_resourcePartyType = e_Audio;
m_partyRole = partyRole;
m_rsrcPartyId = 0; //0 - not allocated.
m_CSconnId = 0;
#ifdef MS_LYNC_AVMCU_LINK
// MS Lync
m_partySigOrganizerConnId = 0;
m_partySigFocusConnId = 0;
m_partySigEventPackConnId = 0;
#endif
m_DialInReservedPorts = 0;
m_ARTChannels = ARTChannels;
m_roomPartyId = 0; //TIP Cisco
m_tipPartyType = eTipNone;
m_countPartyAsICEinMFW = FALSE;
m_ssrcAudio = 0;
m_tipNumOfScreens = 0;
m_HdVswTypeInMixAvcSvcMode = hdVswTypeInMixAvcSvcMode;
memset(m_ssrcContent, 0, sizeof(m_ssrcContent));
memset(m_ssrcVideo, 0, sizeof(m_ssrcVideo));
}
////////////////////////////////////////////////////////////////////////////
CPartyRsrc::CPartyRsrc(const CPartyRsrc& other) : CPObject(other),
m_monitorPartyId(other.m_monitorPartyId),
m_rsrcPartyId(other.m_rsrcPartyId),
m_roomPartyId(other.m_roomPartyId),
m_tipPartyType(other.m_tipPartyType),
m_tipNumOfScreens(other.m_tipNumOfScreens),
m_networkPartyType(other.m_networkPartyType),
m_videoPartyType(other.m_videoPartyType),
m_resourcePartyType(other.m_resourcePartyType),
m_partyRole(other.m_partyRole),
m_ARTChannels(other.m_ARTChannels),
m_CSconnId(other.m_CSconnId),
#ifdef MS_LYNC_AVMCU_LINK
// MS Lync
m_partySigOrganizerConnId(other.m_partySigOrganizerConnId),
m_partySigFocusConnId(other.m_partySigFocusConnId),
m_partySigEventPackConnId(other.m_partySigEventPackConnId),
#endif
m_DialInReservedPorts(other.m_DialInReservedPorts),
m_countPartyAsICEinMFW(other.m_countPartyAsICEinMFW),
m_HdVswTypeInMixAvcSvcMode(other.m_HdVswTypeInMixAvcSvcMode)
{
m_ssrcAudio = other.m_ssrcAudio;
for(WORD i=0;i<MAX_NUM_RECV_STREAMS_FOR_CONTENT;i++)
m_ssrcContent[i] = other.m_ssrcContent[i];
for(WORD i=0;i<MAX_NUM_RECV_STREAMS_FOR_VIDEO;i++)
m_ssrcVideo[i] = other.m_ssrcVideo[i];
}
////////////////////////////////////////////////////////////////////////////
CPartyRsrc::~CPartyRsrc()
{
}
////////////////////////////////////////////////////////////////////////////
void CPartyRsrc::SetARTChannels(WORD ARTChannels)
{
m_ARTChannels = ARTChannels;
// bridge-809: assert only not in soft MCU - in soft MCU ARTChannels set to 0, not to limit soft ART capacity
CSystemResources* pSyst = CHelperFuncs::GetSystemResources();
if (pSyst && !CHelperFuncs::IsSoftMCU(pSyst->GetProductType()))
{
DBGPASSERT(0 == ARTChannels);
}
}
////////////////////////////////////////////////////////////////////////////
WORD operator==(const CPartyRsrc& lhs,const CPartyRsrc& rhs)
{
return (lhs.m_monitorPartyId == rhs.m_monitorPartyId);
}
////////////////////////////////////////////////////////////////////////////
bool operator<(const CPartyRsrc& lhs,const CPartyRsrc& rhs)
{
return (lhs.m_monitorPartyId < rhs.m_monitorPartyId);
}
////////////////////////////////////////////////////////////////////////////
STATUS CConfRsrc::AddParty(CPartyRsrc& party)
{
PASSERTSTREAM_AND_RETURN_VALUE(m_parties.find(party) != m_parties.end(), "MonitorPartyId:" << party.GetMonitorPartyId() << " - Already exist", STATUS_FAIL);
TRACEINTO << "MonitorPartyId:" << party.GetMonitorPartyId() << ", PartyLogicalType:" << party.GetPartyResourceType();
m_parties.insert(party);
m_num_Parties++;
UpdateConfMediaStateByPartiesList();
return STATUS_OK;
}
////////////////////////////////////////////////////////////////////////////
BOOL CConfRsrc::CheckIfOneMorePartyCanBeAddedToConf2C(eVideoPartyType videoPartyType)
{
CSystemResources *pSystemResources = CHelperFuncs::GetSystemResources();
eSystemCardsMode systemCardsMode = pSystemResources ? pSystemResources->GetSystemCardsMode() : eSystemCardsMode_illegal;
if (eVSW_video_party_type == videoPartyType)
{
if((eVSW_28_session == m_sessionType && m_num_Parties > MAX_PARTIES_IN_CONF_2C_VSW28) ||
(eVSW_56_session == m_sessionType && m_num_Parties > MAX_PARTIES_IN_CONF_2C_VSW56))
{
return FALSE;
}
else if (eVSW_Auto_session == m_sessionType)
{
if ((eSystemCardsMode_breeze == systemCardsMode && m_num_Parties > 180))
return FALSE;
}
}
else if (eCOP_party_type == videoPartyType)
{
DWORD max_cop_parties = 160; //on breeze
CReservator* pReservator = CHelperFuncs::GetReservator();
if (pReservator)
max_cop_parties = pReservator->GetDongleRestriction();
TRACEINTO << " CConfRsrc::CheckIfOneMorePartyCanBeAddedToConf2C : max_cop_parties = " << max_cop_parties;
if ((eCOP_HD1080_session == m_sessionType || eCOP_HD720_50_session == m_sessionType) && m_num_Parties >= max_cop_parties)//192
return FALSE;
}
return TRUE;
}
////////////////////////////////////////////////////////////////////////////
WORD CConfRsrc::RemoveAllParties(BYTE force_kill_all_ports)
{
CResourceManager* pRsrcMngr = (CResourceManager*)(CProcessBase::GetProcess()->GetCurrentTask());
if (!pRsrcMngr)
{
PASSERT(1); return 0;
}
DEALLOC_PARTY_REQ_PARAMS_S* pdeallocateParams = new DEALLOC_PARTY_REQ_PARAMS_S;
memset(pdeallocateParams, 0, sizeof(DEALLOC_PARTY_REQ_PARAMS_S));
DEALLOC_PARTY_IND_PARAMS_S* pResult = new DEALLOC_PARTY_IND_PARAMS_S;
pdeallocateParams->numOfRsrcsWithProblems = 0;
pdeallocateParams->monitor_conf_id = m_monitorConfId;
pdeallocateParams->force_kill_all_ports = force_kill_all_ports;
// make a copy of parties container
PARTIES PartyRsrcList = m_parties;
PARTIES::iterator itr = PartyRsrcList.begin();
DWORD monitorPartyId = 0;
WORD numOfRemovedParties = 0;
for (itr = PartyRsrcList.begin(); itr != PartyRsrcList.end(); itr++)
{
monitorPartyId = ((CPartyRsrc*)(&(*itr)))->GetMonitorPartyId();
TRACEINTO << "monitorPartyId=" << monitorPartyId;
memset(pResult, 0, sizeof(DEALLOC_PARTY_IND_PARAMS_S));
pdeallocateParams->monitor_party_id = monitorPartyId;
pRsrcMngr->DeAlloc(pdeallocateParams, pResult);
if (pResult->status == STATUS_OK)
++numOfRemovedParties;
}
delete pdeallocateParams;
delete pResult;
return numOfRemovedParties;
}
////////////////////////////////////////////////////////////////////////////
STATUS CConfRsrc::RemoveParty(PartyMonitorID monitorPartyId)
{
CPartyRsrc party(monitorPartyId);
PARTIES::iterator itr = m_parties.find(party);
PASSERTSTREAM_AND_RETURN_VALUE(itr == m_parties.end(), "MonitorPartyId:" << monitorPartyId << " - Party not exist", STATUS_FAIL);
m_parties.erase(itr);
m_num_Parties--;
UpdateConfMediaStateByPartiesList();
return STATUS_OK;
}
////////////////////////////////////////////////////////////////////////////
const CPartyRsrc* CConfRsrc::GetParty(PartyMonitorID monitorPartyId) const
{
CPartyRsrc party(monitorPartyId);
PARTIES::iterator itr = m_parties.find(party);
TRACECOND_AND_RETURN_VALUE(itr == m_parties.end(), "MonitorPartyId:" << monitorPartyId << " - Party not exist", NULL);
return &(*itr);
}
////////////////////////////////////////////////////////////////////////////
STATUS CConfRsrc::AddTempBondingPhoneNumber(PartyRsrcID partyId, Phone* pPhone)
{
PASSERT_AND_RETURN_VALUE(!pPhone, STATUS_FAIL);
Phone* phone = new Phone;
strcpy_safe(phone->phone_number, pPhone->phone_number);
m_bondingPhones.insert(BONDING_PHONES::value_type(partyId, phone));
return STATUS_OK;
}
////////////////////////////////////////////////////////////////////////////
STATUS CConfRsrc::RemoveTempBondingPhoneNumber(PartyRsrcID partyId)
{
BONDING_PHONES::iterator itr = m_bondingPhones.find(partyId);
if (itr == m_bondingPhones.end())
return STATUS_FAIL;
delete itr->second;
m_bondingPhones.erase(itr);
return STATUS_OK;
}
////////////////////////////////////////////////////////////////////////////
Phone* CConfRsrc::GetTempBondingPhoneNumberByRsrcPartyId(PartyRsrcID partyId) const
{
BONDING_PHONES::const_iterator itr = m_bondingPhones.find(partyId);
if (itr == m_bondingPhones.end())
return NULL;
return itr->second;
}
////////////////////////////////////////////////////////////////////////////
WORD CConfRsrc::IsBoardIdAllocatedToConf(WORD boardId)
{
//if board allocated o conf -
// there is have to be at least on RsrcDesc of this board.
//WORD bId = 2;
RSRC_DESC_MULTISET_ITR itr;
for (itr = m_pRsrcDescList.begin(); itr != m_pRsrcDescList.end(); itr++)
{
if (itr->GetBoardId() == boardId)
return TRUE;
}
return FALSE;
}
////////////////////////////////////////////////////////////////////////////
void CConfRsrc::AddListOfPartiesDescriptorsOnBoard(WORD boardId, WORD subBoardId, std::map<std::string,CONF_PARTY_ID_S*>* listOfConfIdPartyIdPair) const
{
RSRC_DESC_MULTISET_ITR itr;
CRsrcDesc rsrcdesc;
std::string strKey;
CONF_PARTY_ID_S* pConf_party_id_s = NULL;
for (itr = m_pRsrcDescList.begin(); itr != m_pRsrcDescList.end(); itr++)
{
rsrcdesc = ((CRsrcDesc)(*itr));
if (rsrcdesc.GetBoardId() == boardId)
{
//if subboard is 1 (MFA), this means that the whole card will be taken out, including the RTM
//so it doesn't matter on which subboard it is
if (subBoardId == MFA_SUBBOARD_ID || rsrcdesc.GetSubBoardId() == subBoardId)
{
strKey = GetPartyKey(rsrcdesc.GetRsrcConfId() ,rsrcdesc.GetRsrcPartyId());
if (listOfConfIdPartyIdPair->find(strKey) == listOfConfIdPartyIdPair->end())
{
pConf_party_id_s = new CONF_PARTY_ID_S();
pConf_party_id_s->monitor_conf_id = GetMonitorConfId();
CPartyRsrc* pParty = (CPartyRsrc*)(GetPartyRsrcByRsrcPartyId(rsrcdesc.GetRsrcPartyId()));
if (pParty == NULL)
{
POBJDELETE(pConf_party_id_s);
PASSERT(1);
continue;
}
else
{
pConf_party_id_s->monitor_party_id = pParty->GetMonitorPartyId();
}
(*listOfConfIdPartyIdPair)[strKey] = pConf_party_id_s;
}
}
}
}
}
////////////////////////////////////////////////////////////////////////////
std::string CConfRsrc::GetPartyKey(DWORD rsrcConfId, DWORD rsrcPartyId) const
{
std::ostringstream o;
o << rsrcConfId << "_" << rsrcPartyId;
return o.str();
}
////////////////////////////////////////////////////////////////////////////
STATUS CConfRsrc::GetFreeVideoRsrcVSW(CRsrcDesc*& pEncDesc, CRsrcDesc*& pDecDesc)
{
WORD rsrcId = 0, enc_found = 0, dec_found = 0;
RSRC_DESC_MULTISET_ITR itr;
for (itr = m_pRsrcDescList.begin(); itr != m_pRsrcDescList.end(); itr++)
{
CRsrcDesc* pRsrcDesc = (CRsrcDesc*)&(*itr);
BOOL isDecType = CHelperFuncs::IsLogicalVideoDecoderType( pRsrcDesc->GetType());
BOOL isEncType = CHelperFuncs::IsLogicalVideoEncoderType( pRsrcDesc->GetType());
if (pRsrcDesc->GetIsUpdated() || (!isDecType && !isEncType) ||
(isDecType && dec_found) || (isEncType && enc_found))
continue;
rsrcId = pRsrcDesc->GetRsrcPartyId();
if (isDecType)
{
dec_found = rsrcId;
pDecDesc = pRsrcDesc;
}
else
{
enc_found = rsrcId;
pEncDesc = pRsrcDesc;
}
if (dec_found && enc_found && dec_found == enc_found)
break;
}
if (!pEncDesc || !pDecDesc)
return STATUS_FAIL;
return STATUS_OK;
}
////////////////////////////////////////////////////////////////////////////
STATUS CConfRsrc::GetBoardUnitIdByRoomIdTIP(DWORD room_id, WORD& boardIdTIP, WORD& unitIdTIP) //TIP Cisco
{
PARTIES::iterator _iiEnd = m_parties.end();
for (PARTIES::iterator _ii = m_parties.begin(); _ii != _iiEnd; ++_ii)
{
if (_ii->GetRoomPartyId() == room_id)
{
const CRsrcDesc* pAudEncDesc = GetDesc(_ii->GetRsrcPartyId(), eLogical_audio_encoder);
if (pAudEncDesc)
{
boardIdTIP = pAudEncDesc->GetBoardId();
unitIdTIP = pAudEncDesc->GetUnitId();
return STATUS_OK;
}
}
}
return STATUS_FAIL;
}
////////////////////////////////////////////////////////////////////////////
WORD CConfRsrc::GetBoardIdForRelayParty() //olga
{
PARTIES::iterator _it = std::find_if(m_parties.begin(), m_parties.end(), compareVideoPartyFunc());
if (_it != m_parties.end())
{
const CRsrcDesc* pRtpDesc = GetDesc(_it->GetRsrcPartyId(), eLogical_rtp);
if (pRtpDesc)
return pRtpDesc->GetBoardId();
}
TRACEINTO << "Relay party is not allocated on any board";
return 0;
}
////////////////////////////////////////////////////////////////////////////
bool CConfRsrc::CheckIfThereAreRelayParty() const
{
PARTIES::iterator _it = std::find_if(m_parties.begin(), m_parties.end(), compareVideoPartyFunc());
return (_it != m_parties.end());
}
////////////////////////////////////////////////////////////////////////////
bool CConfRsrc::CheckIfThereAreNotRelayParty() const
{
PARTIES::iterator _it = std::find_if(m_parties.begin(), m_parties.end(), not1(compareVideoPartyFunc()));
return (_it != m_parties.end());
}
////////////////////////////////////////////////////////////////////////////
STATUS CConfRsrc::GetBoardUnitIdByAvMcuLinkMain(PartyRsrcID mainPartyRsrcID, WORD& boardId, WORD& unitId)
{
const CRsrcDesc* pRtpDesc = GetDesc(mainPartyRsrcID, eLogical_rtp);
if (pRtpDesc)
{
boardId = pRtpDesc->GetBoardId();
unitId = pRtpDesc->GetUnitId();
return STATUS_OK;
}
return STATUS_FAIL;
}
////////////////////////////////////////////////////////////////////////////
void CConfRsrc::CountAvcSvcParties(WORD& numAvc, WORD& numSvc) const
{
numAvc = 0;
numSvc = 0;
PARTIES::iterator _iiEnd = m_parties.end();
for (PARTIES::iterator _ii = m_parties.begin(); _ii != _iiEnd; ++_ii)
{
if (CHelperFuncs::IsVideoRelayParty(_ii->GetVideoPartyType()))
numSvc++;
else
numAvc++;
}
}
////////////////////////////////////////////////////////////////////////////
// Need to receive in pRsrcDescList memory of MAX_NUM_ALLOCATED_RSRCS_NET pointers (CRsrcDesc*) allocated for the output (and initialized to all NULLs)
// Returns number of RsrcDescs found.
WORD CConfRsrc::GetPartyRcrsDescArrayByRsrcId(DWORD rsrcpartyId, CRsrcDesc** pRsrcDescArray, WORD arrSize)
{
RSRC_DESC_MULTISET_ITR itr;
int num_party_resources = 0;
for (itr = m_pRsrcDescList.begin(); itr != m_pRsrcDescList.end(); itr++)
{
if (itr->GetRsrcPartyId() == rsrcpartyId)
{
if (num_party_resources < arrSize) // For protection
{
pRsrcDescArray[num_party_resources] = (CRsrcDesc*)&(*itr);
num_party_resources++;
}
else{
PASSERTMSG(num_party_resources, "CConfRsrc::GetDescArrayPerResourceTypeByRsrcId - error in call to function");
}
}
}
return num_party_resources;
}
////////////////////////////////////////////////////////////////////////////
WORD CConfRsrc::GetPartyRTPDescArrayByRsrcId(DWORD rsrcpartyId, CRsrcDesc** pRsrcDescArray, WORD arrSize)
{
RSRC_DESC_MULTISET_ITR itr;
int num_party_resources = 0;
for (itr = m_pRsrcDescList.begin(); itr != m_pRsrcDescList.end(); itr++)
{
if (itr->GetRsrcPartyId() == rsrcpartyId && CHelperFuncs::IsLogicalRTPtype(itr->GetType()))
{
if (num_party_resources < arrSize) // For protection
{
pRsrcDescArray[num_party_resources] = (CRsrcDesc*)&(*itr);
num_party_resources++;
}
else{
PASSERTMSG(num_party_resources, "CConfRsrc::GetDescArrayPerResourceTypeByRsrcId - error in call to function");
}
}
}
return num_party_resources;
}
////////////////////////////////////////////////////////////////////////////
void CConfRsrc::UpdateConfMediaStateByPartiesList()
{
bool hasRelayParties = CheckIfThereAreRelayParty();
bool hasNotRelayParties = CheckIfThereAreNotRelayParty();
if (eMediaStateMixAvcSvc == m_confMediaState)
{
// since we don't support downgrade - we don't change ConfMediaState after it already in mixed
return;
}
if (!hasRelayParties && !hasNotRelayParties)
{
SetConfMediaState(eMediaStateEmpty);
}
else if (hasRelayParties && !hasNotRelayParties)
{
SetConfMediaState(eMediaStateSvcOnly);
}
else if (!hasRelayParties && hasNotRelayParties)
{
SetConfMediaState(eMediaStateAvcOnly);
}
}
////////////////////////////////////////////////////////////////////////////
// CConfRsrcDB
////////////////////////////////////////////////////////////////////////////
CConfRsrcDB::CConfRsrcDB()
{
m_numConfRsrcs = 0;
}
////////////////////////////////////////////////////////////////////////////
CConfRsrcDB::~CConfRsrcDB()
{
m_numConfRsrcs = 0;
}
////////////////////////////////////////////////////////////////////////////
STATUS CConfRsrcDB::AddConfRsrc(CConfRsrc* pConfRsrc)
{
PASSERT_AND_RETURN_VALUE(!pConfRsrc, STATUS_FAIL);
PASSERT_AND_RETURN_VALUE(m_confList.find(*pConfRsrc) != m_confList.end(), STATUS_FAIL);
m_confList.insert(*pConfRsrc);
ConfRsrcID id = pConfRsrc->GetRsrcConfId();
if (STANDALONE_CONF_ID != id)
m_numConfRsrcs++;
TRACEINTO << "ConfId:" << id << ", NumOngoingConf:" << m_numConfRsrcs;
return STATUS_OK;
}
////////////////////////////////////////////////////////////////////////////
STATUS CConfRsrcDB::RemoveConfRsrc(ConfMonitorID confId)
{
CConfRsrc conf(confId);
RSRC_CONF_LIST::iterator _itr = m_confList.find(conf);
if (_itr == m_confList.end())
return STATUS_FAIL;
ConfRsrcID id = _itr->GetRsrcConfId();
if (STANDALONE_CONF_ID != id)
{
if (m_numConfRsrcs > 0)
m_numConfRsrcs--;
else
PASSERT(1);
}
m_confList.erase(_itr);
TRACEINTO << "ConfId:" << id << ", NumOngoingConf:" << m_numConfRsrcs;
return STATUS_OK;
}
////////////////////////////////////////////////////////////////////////////
CConfRsrc* CConfRsrcDB::GetConfRsrc(ConfMonitorID confId)
{
CConfRsrc conf(confId);
RSRC_CONF_LIST::iterator _itr = m_confList.find(conf);
if (_itr != m_confList.end())
return (CConfRsrc*)(&(*_itr));
return NULL;
}
////////////////////////////////////////////////////////////////////////////
CConfRsrc* CConfRsrcDB::GetConfRsrcByRsrcConfId(ConfRsrcID confId)
{
RSRC_CONF_LIST::iterator _end = m_confList.end();
for (RSRC_CONF_LIST::iterator _itr = m_confList.begin(); _itr != _end; ++_itr)
{
if (_itr->GetRsrcConfId() == confId)
return (CConfRsrc*)(&(*_itr));
}
return NULL;
}
////////////////////////////////////////////////////////////////////////////
STATUS CConfRsrcDB::GetMonitorIdsRsrcIds(ConfRsrcID confId, PartyRsrcID partyId, ConfMonitorID& monitorConfId, PartyMonitorID& monitorPartyId)
{
monitorConfId = 0xFFFFFFFF;
monitorPartyId = 0xFFFFFFFF;
RSRC_CONF_LIST::iterator _end = m_confList.end();
for (RSRC_CONF_LIST::iterator _itr = m_confList.begin(); _itr != _end; ++_itr)
{
if (_itr->GetRsrcConfId() == confId)
{
monitorConfId = _itr->GetMonitorConfId();
const CPartyRsrc* pParty = _itr->GetPartyRsrcByRsrcPartyId(partyId);
if (pParty)
{
monitorPartyId = pParty->GetMonitorPartyId();
return STATUS_OK;
}
}
}
return STATUS_FAIL;
}
////////////////////////////////////////////////////////////////////////////
bool CConfRsrcDB::IsExitingConf(ConfMonitorID confId)
{
const CConfRsrc* pConfRsrc = GetConfRsrc(confId);
return (pConfRsrc == NULL)? false : true;
}
////////////////////////////////////////////////////////////////////////////
bool CConfRsrcDB::IsEmptyConf(ConfMonitorID confId)
{
CConfRsrc* pConfRsrc = GetConfRsrc(confId);
PASSERT_AND_RETURN_VALUE(!pConfRsrc, true);
return pConfRsrc->GetNumParties() ? false : true;
}
////////////////////////////////////////////////////////////////////////////
ConfRsrcID CConfRsrcDB::MonitorToRsrcConfId(ConfMonitorID confId)
{
CConfRsrc* pConfRsrc = GetConfRsrc(confId);
return pConfRsrc ? pConfRsrc->GetRsrcConfId() : 0;
}
////////////////////////////////////////////////////////////////////////////
void CConfRsrcDB::GetAllPartiesOnBoard(WORD boardId, WORD subBoardId, std::map<std::string, CONF_PARTY_ID_S*>* listOfConfIdPartyIdPair)
{
RSRC_CONF_LIST::iterator _end = m_confList.end();
for (RSRC_CONF_LIST::iterator _itr = m_confList.begin(); _itr != _end; ++_itr)
_itr->AddListOfPartiesDescriptorsOnBoard(boardId, subBoardId, listOfConfIdPartyIdPair);
}
////////////////////////////////////////////////////////////////////////////
void CConfRsrcDB::FillISDNServiceName(ConfMonitorID confId, PartyMonitorID partyId, char serviceName[GENERAL_SERVICE_PROVIDER_NAME_LEN])
{
CSystemResources* pSystemResources = CHelperFuncs::GetSystemResources();
PASSERT_AND_RETURN(!pSystemResources);
const CConfRsrc* pConfRsrc = GetConfRsrc(confId);
TRACECOND_AND_RETURN(!pConfRsrc, "MonitorConfId:" << confId << " - Failed, conference not found");
const CPartyRsrc* pPartyRsrc = pConfRsrc->GetParty(partyId);
TRACECOND_AND_RETURN(!pPartyRsrc, "MonitorPartyId:" << partyId << " - Failed, participant not found");
CRsrcDesc** pRsrcDescArray = new CRsrcDesc*[MAX_NUM_ALLOCATED_RSRCS_NET];
for (int i = 0 ; i < MAX_NUM_ALLOCATED_RSRCS_NET ; i++)
pRsrcDescArray[i] = NULL;
// Get all resource descriptors of RTM per a given party
pConfRsrc->GetDescArrayPerResourceTypeByRsrcId(pPartyRsrc->GetRsrcPartyId(), eLogical_net, pRsrcDescArray);
if (pRsrcDescArray[0] == NULL)
{
TRACEINTO << "MonitorPartyId:" << partyId << " - Failed, RTMs not found for party";
delete []pRsrcDescArray;
return;
}
WORD boardId = pRsrcDescArray[0]->GetBoardId();
WORD unitId = pRsrcDescArray[0]->GetUnitId();
delete []pRsrcDescArray;
CBoard* pBoard = pSystemResources->GetBoard(boardId);
PASSERT_AND_RETURN(!pBoard);
const CSpanRTM* pSpan = pBoard->GetRTM(unitId);
PASSERT_AND_RETURN(!pSpan);
const char* serviceNameFromSpan = pSpan->GetSpanServiceName();
if (serviceNameFromSpan)
strcpy_safe(serviceName, sizeof(serviceName), serviceNameFromSpan);
}
////////////////////////////////////////////////////////////////////////////
PartyRsrcID CConfRsrcDB::MonitorToRsrcPartyId(ConfMonitorID confId, PartyMonitorID partyId)
{
const CConfRsrc* pConfRsrc = GetConfRsrc(confId);
if (pConfRsrc)
{
const CPartyRsrc* pPartyRsrc = pConfRsrc->GetParty(partyId);
if (pPartyRsrc)
return pPartyRsrc->GetRsrcPartyId();
}
return 0;
}
////////////////////////////////////////////////////////////////////////////
bool CConfRsrcDB::GetPartyType(ConfMonitorID confId, PartyMonitorID partyId,
eNetworkPartyType& networkPartyType,
eVideoPartyType& videoPartyType,
ePartyRole& partyRole,
WORD& artChannels,
eSessionType& sessionType)
{
const CConfRsrc* pConfRsrc = GetConfRsrc(confId);
TRACECOND_AND_RETURN_VALUE(!pConfRsrc, "MonitorConfId:" << confId << " - Failed, conference not found", false);
const CPartyRsrc* pPartyRsrc = pConfRsrc->GetParty(partyId);
TRACECOND_AND_RETURN_VALUE(!pPartyRsrc, "MonitorPartyId:" << partyId << " - Failed, participant not found", false);
networkPartyType = pPartyRsrc->GetNetworkPartyType();
videoPartyType = pPartyRsrc->GetVideoPartyType();
partyRole = pPartyRsrc->GetPartyRole();
artChannels = pPartyRsrc->GetARTChannels();
sessionType = pConfRsrc->GetSessionType();
return true;
}
| [
"[email protected]"
] | |
95f7befcf665c6bd7d6cf9cdcc561666e56f2e88 | cf88c1e3d9587f2bdc8cf40397bca3f0b5f11e7c | /Arrays/Array_Rearrangement/MaxLengthBitonicSubsequence.cpp | fb2e5de210006b85afeb4f3b2d78fe1f36e1b413 | [] | no_license | shaival141/Practice_Old | f6193b4ae2365548d70c047180de429f9a9fdc1d | f02d55faf1c0a861093bf0e094747c64bdd81b34 | refs/heads/master | 2022-01-05T12:54:54.863035 | 2018-05-18T18:05:06 | 2018-05-18T18:05:06 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,321 | cpp | /* Dynamic Programming implementation of longest bitonic subsequence problem */
#include<stdio.h>
#include<stdlib.h>
/* lbs() returns the length of the Longest Bitonic Subsequence in
arr[] of size n. The function mainly creates two temporary arrays
lis[] and lds[] and returns the maximum lis[i] + lds[i] - 1.
lis[i] ==> Longest Increasing subsequence ending with arr[i]
lds[i] ==> Longest decreasing subsequence starting with arr[i]
*/
int lbs( int arr[], int n )
{
int i,j;
int lis[n];
int lds[n];
for(i=0;i<n;i++)
lis[i]=1;
for(i=0;i<n;i++)
lds[i]=1;
for(i=1;i<n;i++)
{
for(j=0;j<i;j++)
{
if(arr[j]<arr[i] && lis[i]<lis[j]+1)
lis[i]=lis[j]+1;
}
}
for(i=n-1;i>=0;i--)
{
for(j=n-1;j>i;j--)
{
if(arr[j]<arr[i] && lds[i]<lds[j]+1)
lds[i]=lds[j]+1;
}
}
int max=0;
for(i=0;i<n;i++)
{
if(lis[i]+lds[i]-1>max)
{
max =lis[i] + lds[i] - 1;
}
}
return max;
}
/* Driver program to test above function */
int main()
{
int arr[] = {0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5,
13, 3, 11, 7, 15};
int n = sizeof(arr)/sizeof(arr[0]);
printf("Length of LBS is %d\n", lbs( arr, n ) );
return 0;
} | [
"[email protected]"
] | |
d59c5f726c85c0426fe1f464a529f7fc97a16b65 | a6f1cd042e91b17f72bcc7872a47cc022f2cf21e | /DFS/140. Word Break II.cpp | f0c3e25853d36e6953d7c4095b60ae93953c6b90 | [] | no_license | sammiiT/leetcode | bc1b8fa107c15bbdd803e6f5e4f86a179904a988 | 8e882f4a6fb05ba645bd1ff8355d3b8f14654fb0 | refs/heads/master | 2023-09-06T04:43:54.582944 | 2023-09-04T15:19:00 | 2023-09-04T15:19:00 | 219,103,778 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,104 | cpp | //===類似題===
139. Word Break
472. Concatenated Words
//=== 思路====
(*) DFS算法
- 陣列中的每一個節點都可以當作root節點, 每一個節點都是上一層的child節點
- 此題的陣列是vector<string> wordDict
- 因為陣列元素可以reused,所以每進入下一層, loop迴圈都從i=0開始
0. segment 是要連續,不能中間斷掉, 左半部和右半部連接
1.宣告 string& out, 紀錄每一個滿足條件的string
2.宣告 vector<string>& res, 紀錄滿足最後條件的string
3.每一次substring都要從string[0]開始,
- 取從0開始的substr, 判斷此substr是否等於wordDict[i]
--不等於就continue
4.每一次都要記錄(append)新的string; out.append(wordDict[i]+" ")
跳回上一層要把append刪除; out = out.substr(0,size);//size維之前out的長度
5.最回傳res
(*)
cout<<str.substr(pos, str.size()-pos)<<endl;
//str.size()是1-index, pos是0-index 相減??????
(*)思路重構
1.以wordDict為依據, 遍歷wordDict並與string做比較
2.wordDict[i]不同的排列方式, 可以滿足string的segmentation => 所以用DFS
for(int i=0; i<wordDict.size(); ++i){...}
3.每一次判斷string segement, 都把此segment從string中刪除, 並將剩下的string放到下一層DFS中做運算
//=====
void helper(string s ,vector<string>& wordDict, string& out, vector<string>& res){
if(s.size()==0){
out.pop_back();//將space 字元移除
res.push_back(out);
return;
}
for(int i=0; i<wordDict.size(); ++i){
int len = wordDict[i].size();
if(s.substr(0,len)!=wordDict[i]) continue;//不同排列順序
string tmp = s.substr(len,s.size()-len);//剩下的String
int size = out.size();
out.append(wordDict[i]+" ");
helper(tmp,wordDict,out,res);
out = out.substr(0,size);//沒有辦法pop_back() string,所以用之前紀錄的substriing size
}
}
vector<string> wordBreak(string s, vector<string>& wordDict) {
vector<string> res;
string out;
helper(s,wordDict,out,res);
return res;
}
| [
"[email protected]"
] | |
c35c2d62a156829d22448cc6b0d87e80e60d5a76 | c27a1b7e258b9fa30653a9aa6dd36dcd1df15810 | /arduino_code_outer.ino | a27b32227a2881ae73337661e4ccde0c8c8668c9 | [] | no_license | Emmanuel-Edidiong/Automatic-Wireless-Weather-Station-with-Arduino | 1b0b97d20a742c1dfb98d8b97966ee2560e86c00 | 8268b1b4dbe8bbb79386ecaf867eea141e34610b | refs/heads/master | 2020-09-13T13:51:21.347427 | 2019-11-19T23:08:11 | 2019-11-19T23:08:11 | 222,806,119 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,116 | ino | /*
Outdoor unit - Transmitter
*/
#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>
#include <dht.h>
#include <LowPower.h>
#define dataPin 8 // DHT22 data pina
dht DHT; // Creates a DHT object
RF24 radio(10, 9); // CE, CSN
const byte address[6] = "00001";
char thChar[32] = "";
String thString = "";
void setup() {
Serial.begin(115200);
radio.begin();
radio.openWritingPipe(address);
radio.setPALevel(RF24_PA_MIN);
radio.stopListening();
}
void loop() {
int readData = DHT.read22(dataPin); // Reads the data from the sensor
int t = DHT.temperature; // Gets the values of the temperature
int h = DHT.humidity; // Gets the values of the humidity
thString = String(t) + String(h);
thString.toCharArray(thChar, 12);
Serial.println(thChar);
// Sent the data wirelessly to the indoor unit
for (int i = 0; i <= 3; i++) { // Send the data 3 times
radio.write(&thChar, sizeof(thChar));
delay(50);
}
// Sleep for 2 minutes, 15*8 = 120s
for (int sleepCounter = 15; sleepCounter > 0; sleepCounter--)
{
LowPower.powerDown(SLEEP_8S, ADC_OFF, BOD_OFF);
}
}
| [
"[email protected]"
] | |
1cd2b7ce9a506eb8b775389be6d61a36481bfe5c | 3c1dbc0532ec129a34dfc5eb6b663d7eaf31a1f8 | /limak_house.cpp | ac80f9d7ee246671c9cd11ac2355035eae409fcd | [] | no_license | fredybotas/Spoj | c79702b163627f3f83461fb2ccb923c544ae7a16 | 5a99e0d15b8fcbbb093dc1c694cdd56c2f83f0c4 | refs/heads/master | 2021-01-19T20:34:56.636668 | 2017-02-27T00:03:39 | 2017-02-27T00:03:39 | 81,080,973 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,865 | cpp | #include <stdio.h>
#include <string.h>
int main(){
//najdi spodok
char buffer[20];
int curr, i, low = 0, high = 1000;
while(low < high){
curr = (low + high) / 2;
printf("? %d %d\n", curr, 0);
fflush(stdout);
scanf("%s", buffer);
if(!strcmp(buffer, "YES"))
low = curr + 1;
else
high = curr;
}
for(i = curr - 3; i < curr + 4; i++){
if(i == 1000){
curr = 1000;
break;
}
printf("? %d %d\n", i, 0);
fflush(stdout);
scanf("%s", buffer);
if(!strcmp(buffer, "YES"))
continue;
else{
curr = i - 1;
break;
}
}
int x_square = curr*2;
//trojuholnik
low = x_square/2;
high = 1000;
while(low < high){
curr = (low + high) / 2;
printf("? %d %d\n", curr, x_square);
fflush(stdout);
scanf("%s", buffer);
if(!strcmp(buffer, "YES"))
low = curr + 1;
else
high = curr;
}
for(i = curr - 3; i < curr + 4; i++){
if(i == 1000){
curr = 1000;
break;
}
printf("? %d %d\n", i, x_square);
fflush(stdout);
scanf("%s", buffer);
if(!strcmp(buffer, "YES"))
continue;
else{
curr = i - 1;
break;
}
}
int x_triangle = curr*2;
low = x_square;
high = 1000;
while(low < high){
curr = (low + high) / 2;
printf("? %d %d\n", 0, curr);
fflush(stdout);
scanf("%s", buffer);
if(!strcmp(buffer, "YES"))
low = curr + 1;
else
high = curr;
}
for(i = curr - 3; i < curr + 4; i++){
if(i == 1000){
curr = 1000;
break;
}
printf("? %d %d\n", 0, i);
fflush(stdout);
scanf("%s", buffer);
if(!strcmp(buffer, "YES"))
continue;
else{
curr = i - 1;
break;
}
}
int height = curr;
printf("! %d\n", x_square*x_square + x_triangle*(height - x_square)/2);
fflush(stdout);
return 0;
}
| [
"[email protected]"
] | |
38f7c8a3cad67c635c35e49aa86561033dd5059e | b2b9e4d616a6d1909f845e15b6eaa878faa9605a | /Genemardon/20150726浙大月赛/H.cpp | a21dd35a335cc1f9d08f48963c32541c661122f1 | [] | no_license | JinbaoWeb/ACM | db2a852816d2f4e395086b2b7f2fdebbb4b56837 | 021b0c8d9c96c1bc6e10374ea98d0706d7b509e1 | refs/heads/master | 2021-01-18T22:32:50.894840 | 2016-06-14T07:07:51 | 2016-06-14T07:07:51 | 55,882,694 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 737 | cpp | #include <stdio.h>
#include <string.h>
#include <algorithm>
#include <vector>
using namespace std;
vector<int>tab[50010];
int n,m,q;
int ans[50010];
int main(int argc, char const *argv[])
{
while (scanf("%d%d%d",&n,&m,&q) != EOF)
{
memset(ans,0,sizeof(ans));
for (int i=1;i<=n;i++) tab[i].clear();
for (int i=0;i<m;i++)
{
int u,v;
scanf("%d%d",&u,&v);
if (v<u)
tab[u].push_back(v);
}
int m1=n,m2=n;
for (int i=n;i>1;i--)
{
for (int j=0;j<tab[i].size();j++) if (tab[i][j]<m1)
{
m2=m1;
m1=tab[i][j];
}
else if (tab[i][j]<m2)
{
m2=tab[i][j];
}
ans[i]=max(i-m2,0);
}
int ask;
for (int i=0;i<q;i++)
{
scanf("%d",&ask);
printf("%d\n", ans[ask]);
}
}
return 0;
} | [
"[email protected]"
] | |
288230e9c8d07e65f331be84dae3541bd8429c30 | c26b2d68eab6ce8a7bcabaa61a0edcf067362aea | /vz03/src/herbivora.h | bb867b5ce4aa6e64988ea2e29cc49c33f213e8af | [] | no_license | reiva5/oop | b810f4c75f209eef631c2cf2cd26dfad284cd236 | 465c6075f2d2f16221c482bae9dbb4117c4a6398 | refs/heads/master | 2020-12-10T04:28:46.077254 | 2017-03-15T06:36:02 | 2017-03-15T06:36:02 | 83,626,249 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 419 | h | #ifndef HERBIVORA_H
#define HREBIVORA_H
#include "pemakan.h"
/** @class Herbivora
* Kelas Herbivora menyimpan informasi makanan berupa tumbuhan
*/
class Herbivora: public Pemakan {
public:
/** @brief Setter tumbuhan
* @param n Jumlah tumbuhan yang diinginkan
*/
void SetAmount(int n);
/** @brief Getter tumbuhan
* @return tumbuhan
*/
int GetAmount();
protected:
int tumbuhan;
};
#endif | [
"[email protected]"
] | |
4369c661485646300e4388170f7303ad261fce8b | 70dc2b3a7418bb0b5b8092b037bb3eeeea1ed4a0 | /gui-kde/unitselector.h | 638588de4f3f8c94b3295bf57eabc8f9ffb756fe | [] | no_license | jusirkka/freeciv-kde | 829bc62643876b1491bbf8e3b3f8274383aedf3a | 417c80d46b53f0a7fe75f3ffd5200041f1a58d57 | refs/heads/master | 2020-04-20T01:55:45.980679 | 2019-04-28T03:28:24 | 2019-04-28T03:28:24 | 168,558,596 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 999 | h | #ifndef UNITSELECTOR_H
#define UNITSELECTOR_H
#include <QWidget>
#include <QTimer>
struct tile;
struct unit;
namespace KV {
class UnitSelector: public QWidget
{
Q_OBJECT
public:
explicit UnitSelector(tile* t, QWidget *parent = nullptr);
protected:
void paintEvent(QPaintEvent *event) override;
void mousePressEvent(QMouseEvent *event) override;
void keyPressEvent(QKeyEvent *event) override;
void mouseMoveEvent(QMouseEvent *event) override;
void wheelEvent(QWheelEvent *event) override;
void closeEvent(QCloseEvent *event) override;
void enterEvent(QEvent *event) override;
void leaveEvent(QEvent *event) override;
private slots:
void updateUnits();
private:
void updateUnitList();
void createPixmap();
private:
QPixmap m_pix;
QPixmap m_pixHigh;
QSize m_itemSize;
QList<unit*> m_unitList;
QFont m_font;
QFont m_infoFont;
int m_indexHigh;
int m_unitOffset;
tile *m_tile;
QTimer m_delay;
bool m_first;
};
}
#endif // UNITSELECTOR_H
| [
"[email protected]"
] | |
9db88d488c6ffd2b10d44ee4753ddf7f6822594e | 81bb77804b2481a92c0d48ad2f76e5b79d29e9ec | /src/base58.h | 458f045ad5289379066b5ccc631231dae4dcac16 | [
"MIT"
] | permissive | AndrewJEON/qtum | a5216a67c25e818b11266366f37d0b7bcf5a573f | 5373115c4550a9dbd99f360dd50cc4f67722dc91 | refs/heads/master | 2021-06-11T16:50:00.126511 | 2017-03-14T17:12:40 | 2017-03-14T17:12:40 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,741 | h | // Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2015 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
/**
* Why base-58 instead of standard base-64 encoding?
* - Don't want 0OIl characters that look the same in some fonts and
* could be used to create visually identical looking data.
* - A string with non-alphanumeric characters is not as easily accepted as input.
* - E-mail usually won't line-break if there's no punctuation to break at.
* - Double-clicking selects the whole string as one word if it's all alphanumeric.
*/
#ifndef QUANTUM_BASE58_H
#define QUANTUM_BASE58_H
#include "chainparams.h"
#include "key.h"
#include "pubkey.h"
#include "script/script.h"
#include "script/standard.h"
#include "support/allocators/zeroafterfree.h"
#include <string>
#include <vector>
/**
* Encode a byte sequence as a base58-encoded string.
* pbegin and pend cannot be NULL, unless both are.
*/
std::string EncodeBase58(const unsigned char* pbegin, const unsigned char* pend);
/**
* Encode a byte vector as a base58-encoded string
*/
std::string EncodeBase58(const std::vector<unsigned char>& vch);
/**
* Decode a base58-encoded string (psz) into a byte vector (vchRet).
* return true if decoding is successful.
* psz cannot be NULL.
*/
bool DecodeBase58(const char* psz, std::vector<unsigned char>& vchRet);
/**
* Decode a base58-encoded string (str) into a byte vector (vchRet).
* return true if decoding is successful.
*/
bool DecodeBase58(const std::string& str, std::vector<unsigned char>& vchRet);
/**
* Encode a byte vector into a base58-encoded string, including checksum
*/
std::string EncodeBase58Check(const std::vector<unsigned char>& vchIn);
/**
* Decode a base58-encoded string (psz) that includes a checksum into a byte
* vector (vchRet), return true if decoding is successful
*/
inline bool DecodeBase58Check(const char* psz, std::vector<unsigned char>& vchRet);
/**
* Decode a base58-encoded string (str) that includes a checksum into a byte
* vector (vchRet), return true if decoding is successful
*/
inline bool DecodeBase58Check(const std::string& str, std::vector<unsigned char>& vchRet);
/**
* Base class for all base58-encoded data
*/
class CBase58Data
{
protected:
//! the version byte(s)
std::vector<unsigned char> vchVersion;
//! the actually encoded data
typedef std::vector<unsigned char, zero_after_free_allocator<unsigned char> > vector_uchar;
vector_uchar vchData;
CBase58Data();
void SetData(const std::vector<unsigned char> &vchVersionIn, const void* pdata, size_t nSize);
void SetData(const std::vector<unsigned char> &vchVersionIn, const unsigned char *pbegin, const unsigned char *pend);
public:
bool SetString(const char* psz, unsigned int nVersionBytes = 1);
bool SetString(const std::string& str);
std::string ToString() const;
int CompareTo(const CBase58Data& b58) const;
bool operator==(const CBase58Data& b58) const { return CompareTo(b58) == 0; }
bool operator<=(const CBase58Data& b58) const { return CompareTo(b58) <= 0; }
bool operator>=(const CBase58Data& b58) const { return CompareTo(b58) >= 0; }
bool operator< (const CBase58Data& b58) const { return CompareTo(b58) < 0; }
bool operator> (const CBase58Data& b58) const { return CompareTo(b58) > 0; }
};
/** base58-encoded Quantum addresses.
* Public-key-hash-addresses have version 0 (or 111 testnet).
* The data vector contains RIPEMD160(SHA256(pubkey)), where pubkey is the serialized public key.
* Script-hash-addresses have version 5 (or 196 testnet).
* The data vector contains RIPEMD160(SHA256(cscript)), where cscript is the serialized redemption script.
*/
class CQuantumAddress : public CBase58Data {
public:
bool Set(const CKeyID &id);
bool Set(const CScriptID &id);
bool Set(const CTxDestination &dest);
bool IsValid() const;
bool IsValid(const CChainParams ¶ms) const;
CQuantumAddress() {}
CQuantumAddress(const CTxDestination &dest) { Set(dest); }
CQuantumAddress(const std::string& strAddress) { SetString(strAddress); }
CQuantumAddress(const char* pszAddress) { SetString(pszAddress); }
CTxDestination Get() const;
bool GetKeyID(CKeyID &keyID) const;
bool IsScript() const;
};
/**
* A base58-encoded secret key
*/
class CQuantumSecret : public CBase58Data
{
public:
void SetKey(const CKey& vchSecret);
CKey GetKey();
bool IsValid() const;
bool SetString(const char* pszSecret);
bool SetString(const std::string& strSecret);
CQuantumSecret(const CKey& vchSecret) { SetKey(vchSecret); }
CQuantumSecret() {}
};
template<typename K, int Size, CChainParams::Base58Type Type> class CQuantumExtKeyBase : public CBase58Data
{
public:
void SetKey(const K &key) {
unsigned char vch[Size];
key.Encode(vch);
SetData(Params().Base58Prefix(Type), vch, vch+Size);
}
K GetKey() {
K ret;
if (vchData.size() == Size) {
//if base58 encouded data not holds a ext key, return a !IsValid() key
ret.Decode(&vchData[0]);
}
return ret;
}
CQuantumExtKeyBase(const K &key) {
SetKey(key);
}
CQuantumExtKeyBase(const std::string& strBase58c) {
SetString(strBase58c.c_str(), Params().Base58Prefix(Type).size());
}
CQuantumExtKeyBase() {}
};
typedef CQuantumExtKeyBase<CExtKey, BIP32_EXTKEY_SIZE, CChainParams::EXT_SECRET_KEY> CQuantumExtKey;
typedef CQuantumExtKeyBase<CExtPubKey, BIP32_EXTKEY_SIZE, CChainParams::EXT_PUBLIC_KEY> CQuantumExtPubKey;
#endif // QUANTUM_BASE58_H
| [
"[email protected]"
] | |
3046cc516b94d3d61b5944e8e72cb324eb8e83b2 | 2f10f807d3307b83293a521da600c02623cdda82 | /deps/boost/win/debug/include/boost/hana/fwd/concept/sequence.hpp | 422e52578079c9edc98e149f855e4d4868c1d9cf | [] | no_license | xpierrohk/dpt-rp1-cpp | 2ca4e377628363c3e9d41f88c8cbccc0fc2f1a1e | 643d053983fce3e6b099e2d3c9ab8387d0ea5a75 | refs/heads/master | 2021-05-23T08:19:48.823198 | 2019-07-26T17:35:28 | 2019-07-26T17:35:28 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 129 | hpp | version https://git-lfs.github.com/spec/v1
oid sha256:2995f98908d109d3d0c6f3843c95855164d1b5d8229cdc1d99bcf3b7094d3655
size 7412
| [
"[email protected]"
] | |
e5da24000808179faf59b1240f2745fd73190189 | 129136fed2665b6554223cb95407b1bbb7c421e2 | /Programming/1-2_sem/Qsort_opt/Qsort_opt.cpp | 61fe73c950928a8237e6ccb996816d7ad125f5f5 | [] | no_license | PotapovaSofia/DIHT-MIPT | e28f62c3ef91137d86ee8585ad4daefb1930a890 | aef75ac5154d22ce0e424b3874bf15bae779fbf0 | refs/heads/master | 2016-09-05T16:44:46.501488 | 2016-02-20T21:46:23 | 2016-02-20T21:46:23 | 32,089,336 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,077 | cpp | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
void generation(int* Arr, int n)
{
int i;
srand(time(NULL));
for ( i=0;i<n;++i)
{
Arr[i] = rand()%100 - 50;
printf("%d ", Arr[i]);
}
printf("\n");
}
int cmp_(void* a, void* b){
return (*(int*)a - *(int*)b);
}
void swap(void* a, void* b, size_t size)
{
char* x = (char*)(malloc(size));
memcpy(x, a, size);
memcpy(a, b, size);
memcpy(b, x, size);
free(x);
}
void QuickSort ( void* Arr, int first, int last, size_t size, int(*cmp)(void*, void*))
{
if ((last - first) > 10)
{
int i, j;
i = first;
j = last;
int key = (rand() % last + first) % last;
char *buf = (char*)malloc(size);
memcpy(buf, (char*)Arr + key*size, size);
do {
while (cmp((char*)Arr + i*size, buf) < 0) i++;
while (cmp((char*)Arr + j*size, buf) > 0) j--;
if(i <= j) {
if (i < j) swap((char*)Arr + i*size, (char*)Arr + j*size, size);
i++;
j--;
}
} while (i <= j);
if (i < last)
QuickSort(Arr, i, last, size, cmp);
if (first < j)
QuickSort(Arr, first,j, size, cmp);
}
}
void InsertSort(void* a, int n, size_t size, int(*cmp)(void*, void*))
{
int i;
for (i = 1; i < n; ++i)
{
char* key = (char*)(malloc(size));
memcpy(key, (char*)a + i* size, size);
int j = i - 1;
while ((j >= 0) && (cmp((char*)a + j * size, key) > 0))
{
swap((char*)a + j*size, (char*)a + (j + 1) * size, size);
j--;
}
memcpy((char*)a + (j + 1) * size, key, size);
}
}
int main()
{
int i, n;
printf("Number: ");
scanf("%d", &n);
printf ("\n");
int* Arr = (int*)(malloc(sizeof(int)*n));
generation(Arr, n);
int(*p)(void*, void*);
p = cmp_;
QuickSort(Arr, 0, n - 1, sizeof(int), p);
InsertSort(Arr, n, sizeof(int), p);
for (i = 0; i < n; ++i)
{
printf("%d ", Arr[i]);
}
free(Arr);
return 0;
}
| [
"[email protected]"
] | |
37a17f5aada19a69bd57c79199f40ec689d1616f | 4ddb183621a8587f45c12216d0227d36dfb430ff | /MBDGeneralFW/MBDTechInfo.m/src/MBDNoteModifyDlg.cpp | a936ad957930efba2ddfc947cf25662e1c5142a8 | [] | no_license | 0000duck/good-idea | 7cdd05c55483faefb96ef9b2efaa7b7eb2f22512 | 876b9c8bb67fa4a7dc62d89683d4fd9d28a94cae | refs/heads/master | 2021-05-29T02:46:02.336920 | 2013-07-22T17:53:06 | 2013-07-22T17:53:06 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,085 | cpp | // COPYRIGHT Dassault Systemes 2010
//===================================================================
//
// MBDNoteModifyDlg.cpp
// The dialog : MBDNoteModifyDlg
//
//===================================================================
//
// Usage notes:
//
//===================================================================
//
// Mar 2010 Creation: Code generated by the CAA wizard ev5adm
//===================================================================
#include "MBDNoteModifyDlg.h"
#include "CATApplicationFrame.h"
#include "CATDlgGridConstraints.h"
#include "CATMsgCatalog.h"
#ifdef MBDNoteModifyDlg_ParameterEditorInclude
#include "CATIParameterEditorFactory.h"
#include "CATIParameterEditor.h"
#include "CATICkeParm.h"
#endif
//-------------------------------------------------------------------------
// Constructor
//-------------------------------------------------------------------------
MBDNoteModifyDlg::MBDNoteModifyDlg() :
CATDlgDialog ((CATApplicationFrame::GetApplicationFrame())->GetMainWindow(),
//CAA2 WIZARD CONSTRUCTOR DECLARATION SECTION
"MBDNoteModifyDlg",CATDlgWndModal|CATDlgWndPointerLocation|CATDlgWndBtnOKCancel|CATDlgGridLayout
//END CAA2 WIZARD CONSTRUCTOR DECLARATION SECTION
)
{
//CAA2 WIZARD CONSTRUCTOR INITIALIZATION SECTION
_MBDModifyNameEditor = NULL;
_MBDModifyValueEditor = NULL;
//END CAA2 WIZARD CONSTRUCTOR INITIALIZATION SECTION
}
//-------------------------------------------------------------------------
// Destructor
//-------------------------------------------------------------------------
MBDNoteModifyDlg::~MBDNoteModifyDlg()
{
// Do not delete the control elements of your dialog:
// this is done automatically
// --------------------------------------------------
//CAA2 WIZARD DESTRUCTOR DECLARATION SECTION
_MBDModifyNameEditor = NULL;
_MBDModifyValueEditor = NULL;
//END CAA2 WIZARD DESTRUCTOR DECLARATION SECTION
}
void MBDNoteModifyDlg::Build()
{
// TODO: This call builds your dialog from the layout declaration file
// -------------------------------------------------------------------
//CAA2 WIZARD WIDGET CONSTRUCTION SECTION
_MBDModifyNameEditor = new CATDlgEditor(this, "MBDModifyNameEditor", CATDlgEdtReadOnly);
_MBDModifyNameEditor -> SetVisibleTextWidth(5);
_MBDModifyNameEditor -> SetGridConstraints(0, 0, 1, 1, CATGRID_4SIDES);
_MBDModifyValueEditor = new CATDlgEditor(this, "MBDModifyValueEditor");
_MBDModifyValueEditor -> SetGridConstraints(0, 1, 1, 1, CATGRID_4SIDES);
//END CAA2 WIZARD WIDGET CONSTRUCTION SECTION
int oHeight = 0,oWidth = 0;
PrtService::GetWindowMaxSize(&oHeight,&oWidth );
_MBDModifyValueEditor -> SetVisibleTextWidth(int (0.065*oWidth));
//CAA2 WIZARD CALLBACK DECLARATION SECTION
//END CAA2 WIZARD CALLBACK DECLARATION SECTION
}
CATDlgEditor* MBDNoteModifyDlg::GetMBDNoteModifyNameEditor()
{
return _MBDModifyNameEditor;
}
CATDlgEditor* MBDNoteModifyDlg::GetMBDNoteModifyValueEditor()
{
return _MBDModifyValueEditor;
}
| [
"zhangwy0916@e6631ee2-bc36-6fc4-7263-08c298121e4e"
] | zhangwy0916@e6631ee2-bc36-6fc4-7263-08c298121e4e |
4a9133ddb6d9eb9f7a3eb47d157200415e748cd3 | 4b6db2bfec027acdd71e1d030829983bade67980 | /src/Draw/Text.h | ff67611214c68cec2ac1055830858cf152892386 | [] | no_license | AkiraSekine/CreaDXTKLib | 78b0980777814d6d2a4336cfdb779d1ab0007f7b | 9259ecd31a003c620dddc770e383173f5d3bcda7 | refs/heads/develop | 2020-03-30T23:07:33.919981 | 2019-02-15T06:02:02 | 2019-02-15T06:02:02 | 151,691,370 | 0 | 0 | null | 2019-02-15T06:02:03 | 2018-10-05T08:23:28 | HTML | SHIFT_JIS | C++ | false | false | 2,502 | h | #pragma once
#include "../Default/pch.h"
#include "../Utility/Singleton.h"
#include "../Math/Vector2.h"
#include <string>
#include <map>
namespace CreaDXTKLib
{
namespace Draw
{
/// <summary>
/// テキスト描画クラス
/// </summary>
class Text final : public Utility::Singleton<Text>
{
SINGLETON(Text)
public:
/// <summary>
/// フォントファイルの読み込み
/// </summary>
/// <param name="_key">ハンドル名</param>
/// <param name="_fileName">ファイル名</param>
void Load(const std::wstring& _key, const std::wstring& _fileName);
/// <summary>
/// テキストの描画
/// </summary>
/// <param name="_key">ハンドル名</param>
/// <param name="_position">描画座標</param>
/// <param name="_text">描画文字列(フォーマット)</param>
void Draw(const std::wstring& _key, const Math::Vector2& _position, const std::wstring _text, ...);
/// <summary>
/// テキストの描画
/// </summary>
/// <param name="_key">ハンドル名</param>
/// <param name="_position">描画座標</param>
/// <param name="_color">色</param>
/// <param name="_text">描画文字列(フォーマット)</param>
void Draw(const std::wstring& _key, const Math::Vector2& _position, const DirectX::XMVECTORF32& _color , const std::wstring _text, ...);
/// <summary>
/// テキストの描画
/// </summary>
/// <param name="_key">ハンドル名</param>
/// <param name="_position">描画座標</param>
/// <param name="_color">色</param>
/// <param name="_text">描画文字列(フォーマット)</param>
void Draw(const std::wstring& _key, const Math::Vector2& _position, const DirectX::FXMVECTOR& _color , const std::wstring _text, ...);
/// <summary>
/// 初期化処理
/// </summary>
void Initialize(Microsoft::WRL::ComPtr<ID3D11Device1> _device, Microsoft::WRL::ComPtr<ID3D11DeviceContext1> _context);
/// <summary>
/// 終了処理
/// </summary>
void OnEnd();
private:
Microsoft::WRL::ComPtr<ID3D11Device1> m_device;
std::unique_ptr<DirectX::SpriteBatch> m_spriteBatch;
std::map<std::wstring, DirectX::SpriteFont*> m_fonts = std::map<std::wstring, DirectX::SpriteFont*>();
};
} // Draw
} // CreaDXTKLib | [
"[email protected]"
] | |
da31735876bffe91848fabb58d01bca37453a174 | fcb11ed067ca203932f930facb608e4a07824112 | /series5.cpp | cb814ccf6b5cbbefc393b33f4d1027f8ca52fbf2 | [] | no_license | debjyotigorai/Cpp | 8891a7cdb813ae52a67667a04c80658f1374281f | 19f35c3e64b480471cac0658713cb32d9213aa04 | refs/heads/master | 2021-06-28T01:31:01.889120 | 2019-02-06T16:08:53 | 2019-02-06T16:08:53 | 100,121,539 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 455 | cpp | //1 - x^2 + x^3 - x^4 + ...
#include <iostream>
#include <math.h>
using namespace std;
int main()
{
long long int i, x, sum=1, n;
cout << "Enter the value of x : ";
cin >> x;
cout << "Enter the range : ";
cin >> n;
cout << "1";
for (i=2; i<=n; i++)
{
int z=pow(-1,i+1);
if (z<0)
cout << " - ";
else
cout << " + ";
if (i==n)
cout << x << "^5 ";
else
cout << x << "^" << i;
sum+=(z)*(pow(x,i));
}
cout << " = " << sum;
}
| [
"[email protected]"
] | |
a4b0f42c09efa2ae00be3b45fa8c4aee80eac3e7 | 575731c1155e321e7b22d8373ad5876b292b0b2f | /examples/native/ios/Pods/boost-for-react-native/boost/metaparse/v1/impl/push_back_c.hpp | c6868c0dc16cb49fd78c00b976ceed9edb14fad6 | [
"BSL-1.0",
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | Nozbe/zacs | 802a84ffd47413a1687a573edda519156ca317c7 | c3d455426bc7dfb83e09fdf20781c2632a205c04 | refs/heads/master | 2023-06-12T20:53:31.482746 | 2023-06-07T07:06:49 | 2023-06-07T07:06:49 | 201,777,469 | 432 | 10 | MIT | 2023-01-24T13:29:34 | 2019-08-11T14:47:50 | JavaScript | UTF-8 | C++ | false | false | 1,027 | hpp | #ifndef BOOST_METAPARSE_V1_PUSH_BACK_C_HPP
#define BOOST_METAPARSE_V1_PUSH_BACK_C_HPP
// Copyright Abel Sinkovics ([email protected]) 2013.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#include <boost/metaparse/config.hpp>
#include <boost/metaparse/v1/fwd/string.hpp>
#include <boost/metaparse/v1/impl/update_c.hpp>
#include <boost/metaparse/v1/impl/size.hpp>
namespace boost
{
namespace metaparse
{
namespace v1
{
namespace impl
{
template <class S, char C>
struct push_back_c;
#ifdef BOOST_METAPARSE_VARIADIC_STRING
template <char... Cs, char C>
struct push_back_c<string<Cs...>, C> : string<Cs..., C> {};
#else
template <class S, char C>
struct push_back_c :
update_c<typename S::type, size<typename S::type>::type::value, C>
{};
#endif
}
}
}
}
#endif
| [
"[email protected]"
] | |
72a8c8e1d5a24677d25f802676368885cde7f460 | c712c82341b30aad4678f6fbc758d6d20bd84c37 | /CAC_Source_1.7884/RecusalBookDialog.h | 43ecb8655aa472f0ac07fe40bdad7923e117ad1a | [] | no_license | governmentbg/EPEP_2019_d2 | ab547c729021e1d625181e264bdf287703dcb46c | 5e68240f15805c485505438b27de12bab56df91e | refs/heads/master | 2022-12-26T10:00:41.766991 | 2020-09-28T13:55:30 | 2020-09-28T13:55:30 | 292,803,726 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 358 | h | class TRecusalBookDialog : public TFloatDialog
{
public:
TRecusalBookDialog(TWindow* parent, TRecusalBookGroup *group, int resId = IDD_RECUSAL_BOOK);
protected:
TCharListFace *types;
TCharAutoListFace *compositions;
TDateFace *minDate;
TDateFace *maxDate;
TLongFace *autogen;
TCheckFace *filtered;
TCheckFace *recujed;
virtual bool IsValid();
};
| [
"[email protected]"
] | |
508d55d75ab154fe547faf8438d150f7652f0e14 | 52a3c93c38bef127eaee4420f36a89d929a321c5 | /SDK/SoT_BP_FishingFish_Wrecker_05_Colour_05_Moon_classes.hpp | 8be34a73802fcedf704075651af56099a98ab051 | [] | no_license | RDTCREW/SoT-SDK_2_0_7_reserv | 8e921275508d09e5f81b10f9a43e47597223cb35 | db6a5fc4cdb9348ddfda88121ebe809047aa404a | refs/heads/master | 2020-07-24T17:18:40.537329 | 2019-09-11T18:53:58 | 2019-09-11T18:53:58 | 207,991,316 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 883 | hpp | #pragma once
// Sea of Thieves (2.0) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
#include "SoT_BP_FishingFish_Wrecker_05_Colour_05_Moon_structs.hpp"
namespace SDK
{
//---------------------------------------------------------------------------
//Classes
//---------------------------------------------------------------------------
// BlueprintGeneratedClass BP_FishingFish_Wrecker_05_Colour_05_Moon.BP_FishingFish_Wrecker_05_Colour_05_Moon_C
// 0x0000 (0x0990 - 0x0990)
class ABP_FishingFish_Wrecker_05_Colour_05_Moon_C : public ABP_FishingFish_Wrecker_05_C
{
public:
static UClass* StaticClass()
{
static auto ptr = UObject::FindObject<UClass>(_xor_("BlueprintGeneratedClass BP_FishingFish_Wrecker_05_Colour_05_Moon.BP_FishingFish_Wrecker_05_Colour_05_Moon_C"));
return ptr;
}
void UserConstructionScript();
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"[email protected]"
] | |
9b83294b2fb573490cadd874fd3157c93a47fcac | c689037be8a029aa95bf5fe1c4aef2912f194f31 | /LaboratoryDevices/SelectDevicesWidget.h | 1278c022880d40441eb5570eadcee42586655303 | [] | no_license | oscilo/LabDev | b6933d65562af9d210f809e00a0cfcc09c37833b | 8ae22a5658f85f2854b30b47e6aebc75d1cb02e4 | refs/heads/master | 2020-05-31T03:27:28.118419 | 2017-03-15T22:44:28 | 2017-03-15T22:44:28 | 30,373,361 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,663 | h | #ifndef SELECTDEVICESWIDGET_H
#define SELECTDEVICESWIDGET_H
#include "globals.h"
#include "structures.h"
class CheckDeviceLayout : public QHBoxLayout {
Q_OBJECT
public:
CheckDeviceLayout(const DeviceInfo &di, QWidget *parent = 0) : QHBoxLayout(parent), curDI(di) {
check = new QCheckBox(di.name, parent);
spin = new QSpinBox(parent);
spin->setRange(1, 5);
spin->hide();
connect(check, SIGNAL(clicked(bool)), spin, SLOT(setVisible(bool)));
connect(check, SIGNAL(clicked(bool)), this, SLOT(OnOffSlot(bool)));
connect(spin, SIGNAL(valueChanged(int)), this, SLOT(CountChanged(int)));
this->addWidget(check, 1);
this->addWidget(spin);
}
~CheckDeviceLayout() {
}
QList<DeviceInfo>& GetDeviceList() {
return devices;
}
signals:
void UpdateDevices();
public slots:
void Clear() {
spin->setValue(1);
spin->hide();
check->setChecked(false);
}
void CheckSelectionList(const QList<DeviceInfo> &existingSelection) {
QList<DeviceInfo> newDevices;
foreach(DeviceInfo di, existingSelection) {
if(di.id == curDI.id) {
di.order = newDevices.size();
newDevices << di;
}
}
if(0 == newDevices.size())
Clear();
else {
check->setChecked(true);
spin->show();
spin->setValue(newDevices.size());
devices = newDevices;
}
}
private slots:
void OnOffSlot(bool action) {
if(action)
emit CountChanged(spin->value());
else
emit CountChanged(0);
}
void CountChanged(int count) {
int oldSize = devices.size();
if(oldSize == count)
return;
if(oldSize < count) {
int flag = count - oldSize;
while(flag) {
DeviceInfo di = curDI;
di.order = devices.size();
di.uuid = QUuid::createUuid();
devices << di;
flag--;
}
}
else {
int flag = oldSize - count;
while(flag) {
devices.removeLast();
flag--;
}
}
emit UpdateDevices();
}
private:
DeviceInfo curDI;
QList<DeviceInfo> devices;
QCheckBox *check;
QSpinBox *spin;
};
class SelectDevicesWidget : public QGroupBox {
Q_OBJECT
public:
SelectDevicesWidget(QWidget *parent = 0);
~SelectDevicesWidget();
void SetDevicesList(const QList<DeviceInfo>&);
DBRecordList GetSelectedDevices();
signals:
void SelectionUpdated(const QList<DeviceInfo>&);
void CheckSelectionList(const QList<DeviceInfo>&);
public slots:
void Clear();
void SetExistingSelection(const QList<DeviceInfo>&);
private slots:
void UpdateSelectedDevices();
private:
void FillWidget();
void AddCheckLayoutAtPosition(const DeviceInfo &, int row, int column);
QList<DeviceInfo> totalDevices;
QList<DeviceInfo> selectedDevices;
QList<CheckDeviceLayout*> checkLayouts;
QGridLayout *layout;
};
#endif | [
"[email protected]"
] | |
e96e3af0be76106444fb057262c722e6095061a3 | d4baaa6748dda226b88a1afb2fba2b6c6f54a3cc | /QuestionAnswer_1/source/user.h | a61b280ceaa5b68c731d18c6ba2624a705a5fe11 | [] | no_license | zhangjiuchao/ProgramDesign | 8343363e9ebd4ad8bc2beb051c36f450cda653fe | 175c286b2ed2eca3c386f7aaf7ec13404989a95f | refs/heads/master | 2020-06-30T18:34:16.947478 | 2016-08-26T15:20:53 | 2016-08-26T15:20:53 | 66,571,078 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,026 | h | #ifndef USER_H
#define USER_H
//#include <iostream>
#include <QString>
#include <QList>
#include "questinfor.h"
#include <QTextStream>
class user
{
public:
user(QString str1="",QString str2="",QString str3="");
bool AddFocus(QString focusID);
void AddQuest(QString title,QString content);
void AddAnswer(QString);
void eraseQuest(QString question_id);
void eraseFocus(QString eraseID);
bool changePassword(QString str1,QString str2,QString str3);
bool isFocus(QString id);
friend QTextStream& operator<<(QTextStream& os,const user* host);
friend QTextStream& operator>>(QTextStream& is,user* host);
QList<QString> getFocusList();
QList<QString> getMyQuestion();
QList<QString> get_question_my_anwser();
QString getID();
QString getName();
QString getPassword();
private:
QString ID;
QString userName;
QString Password;
QList<QString> focusList;
QList<QString> myQuestion;
QList<QString> question_my_answer;
};
#endif // USER_H
| [
"[email protected]"
] | |
b807966f3409def6e402e0f4154383a68f8e5e97 | b21b07fc237a764474eb9995783c1b714356bf5f | /src/Xyz/SimplexNoise.cpp | d605c33842509507b55cb3da1b68390f4969d9a0 | [
"BSD-2-Clause"
] | permissive | jebreimo/Xyz | a26b7d93fbb112ebf6c13369c16313db82b68550 | 2f3a6773345c28ad2925e24e89cab296561b42c5 | refs/heads/master | 2023-08-31T03:10:18.086392 | 2023-08-20T14:46:15 | 2023-08-20T14:46:15 | 48,961,224 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,995 | cpp | //****************************************************************************
// Copyright © 2022 Jan Erik Breimo. All rights reserved.
// Created by Jan Erik Breimo on 2022-05-07.
//
// This file is distributed under the BSD License.
// License text is included with the source distribution.
//****************************************************************************
#include "Xyz/SimplexNoise.hpp"
#include <algorithm>
// Copied (and slightly adapted)
// from https://gist.github.com/Flafla2/f0260a861be0ebdeef76
namespace
{
// Hash lookup table as defined by Ken SimplexNoise. This is a randomly
// arranged array of all numbers from 0-255 inclusive.
uint8_t PERMUTATION[256] = {
151, 160, 137, 91, 90, 15, 131, 13, 201, 95, 96, 53, 194, 233,
7, 225, 140, 36, 103, 30, 69, 142, 8, 99, 37, 240, 21, 10,
23, 190, 6, 148, 247, 120, 234, 75, 0, 26, 197, 62, 94, 252,
219, 203, 117, 35, 11, 32, 57, 177, 33, 88, 237, 149, 56, 87,
174, 20, 125, 136, 171, 168, 68, 175, 74, 165, 71, 134, 139, 48,
27, 166, 77, 146, 158, 231, 83, 111, 229, 122, 60, 211, 133, 230,
220, 105, 92, 41, 55, 46, 245, 40, 244, 102, 143, 54, 65, 25,
63, 161, 1, 216, 80, 73, 209, 76, 132, 187, 208, 89, 18, 169,
200, 196, 135, 130, 116, 188, 159, 86, 164, 100, 109, 198, 173, 186,
3, 64, 52, 217, 226, 250, 124, 123, 5, 202, 38, 147, 118, 126,
255, 82, 85, 212, 207, 206, 59, 227, 47, 16, 58, 17, 182, 189,
28, 42, 223, 183, 170, 213, 119, 248, 152, 2, 44, 154, 163, 70,
221, 153, 101, 155, 167, 43, 172, 9, 129, 22, 39, 253, 19, 98,
108, 110, 79, 113, 224, 232, 178, 185, 112, 104, 218, 246, 97, 228,
251, 34, 242, 193, 238, 210, 144, 12, 191, 179, 162, 241, 81, 51,
145, 235, 249, 14, 239, 107, 49, 192, 214, 31, 181, 199, 106, 157,
184, 84, 204, 176, 115, 121, 50, 45, 127, 4, 150, 254, 138, 236,
205, 93, 222, 114, 67, 29, 24, 72, 243, 141, 128, 195, 78, 66,
215, 61, 156, 180
};
double gradient(int hash, double x, double y, double z)
{
switch (hash & 0xF)
{
case 0x0: return x + y;
case 0x1: return -x + y;
case 0x2: return x - y;
case 0x3: return -x - y;
case 0x4: return x + z;
case 0x5: return -x + z;
case 0x6: return x - z;
case 0x7: return -x - z;
case 0x8: return y + z;
case 0x9: return -y + z;
case 0xA: return y - z;
case 0xB: return -y - z;
case 0xC: return y + x;
case 0xD: return -y + z;
case 0xE: return y - x;
case 0xF: return -y - z;
default: return 0;
}
}
double fade(double t)
{
// Fade function as defined by Ken SimplexNoise. This eases coordinate
// values so that they will "ease" towards integral values.
// This ends up smoothing the final output.
return t * t * t * (t * (t * 6 - 15) + 10); // 6t^5 - 15t^4 + 10t^3
}
double lerp(double a, double b, double x)
{
return a + x * (b - a);
}
}
SimplexNoise::SimplexNoise()
{
std::copy(std::begin(PERMUTATION), std::end(PERMUTATION),
permutation_);
std::copy(std::begin(PERMUTATION), std::end(PERMUTATION),
permutation_ + 256);
}
double SimplexNoise::simplex(double x, double y, double z)
{
// Calculate the "unit cube" that the point asked will be located in.
// The left bound is ( |_x_|,|_y_|,|_z_| ) and the right bound is that
// plus 1. Next we calculate the location (from 0.0 to 1.0) in that cube.
// We also fade the location to smooth the result.
int xi = int(x) & 255;
int yi = int(y) & 255;
int zi = int(z) & 255;
double xf = x - int(x);
double yf = y - int(y);
double zf = z - int(z);
double u = fade(xf);
double v = fade(yf);
double w = fade(zf);
int aaa, aba, aab, abb, baa, bba, bab, bbb;
aaa = permutation_[permutation_[permutation_[xi] + yi] + zi];
aba = permutation_[permutation_[permutation_[xi] + ++yi] + zi];
aab = permutation_[permutation_[permutation_[xi] + yi] + ++zi];
abb = permutation_[permutation_[permutation_[xi] + ++yi] + ++zi];
baa = permutation_[permutation_[permutation_[++xi] + yi] + zi];
bba = permutation_[permutation_[permutation_[++xi] + ++yi] + zi];
bab = permutation_[permutation_[permutation_[++xi] + yi] + ++zi];
bbb = permutation_[permutation_[permutation_[++xi] + ++yi] + ++zi];
double x1, x2, y1, y2;
// The gradient function calculates the dot product between a pseudorandom
// gradient vector and the vector from the input coordinate to the 8
// surrounding points in its unit cube.
x1 = lerp(gradient(aaa, xf, yf, zf),
gradient(baa, xf - 1, yf, zf),
u);
// This is all then lerped together as a sort of weighted average based on
// the faded (u,v,w) values we made earlier.
x2 = lerp(gradient(aba, xf, yf - 1, zf),
gradient(bba, xf - 1, yf - 1, zf),
u);
y1 = lerp(x1, x2, v);
x1 = lerp(gradient(aab, xf, yf, zf - 1),
gradient(bab, xf - 1, yf, zf - 1),
u);
x2 = lerp(gradient(abb, xf, yf - 1, zf - 1),
gradient(bbb, xf - 1, yf - 1, zf - 1),
u);
y2 = lerp(x1, x2, v);
// For convenience, we reduce it to 0 - 1 (theoretical min/max before
// is -1 - 1)
return (lerp(y1, y2, w) + 1) / 2;
}
double SimplexNoise::simplex(double x, double y, double z,
int octaves, double persistence)
{
double total = 0;
double frequency = 1;
double amplitude = 1;
double max_value = 0;
for (int i = 0; i < octaves; i++)
{
total += simplex(x * frequency, y * frequency, z * frequency)
* amplitude;
max_value += amplitude;
amplitude *= persistence;
frequency *= 2;
}
return total / max_value;
}
| [
"[email protected]"
] | |
3c562a4243e222e2a5d2afd6f33ac1002b5d77d5 | e49020bee62e9a7006b7a603588aff026ac19402 | /clang/lib/Basic/IdentifierTable.cpp | 621bcc265020d77a202936efaba490ba1a2832a7 | [
"NCSA"
] | permissive | angopher/llvm | 10d540f4d38fd184506d9096fb02a288af8a1aa1 | 163def217817c90fb982a6daf384744d8472b92b | refs/heads/master | 2020-06-10T09:59:52.274700 | 2018-05-10T23:14:40 | 2018-05-10T23:14:40 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 23,406 | cpp | //===- IdentifierTable.cpp - Hash table for identifier lookup -------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the IdentifierInfo, IdentifierVisitor, and
// IdentifierTable interfaces.
//
//===----------------------------------------------------------------------===//
#include "clang/Basic/IdentifierTable.h"
#include "clang/Basic/CharInfo.h"
#include "clang/Basic/LangOptions.h"
#include "clang/Basic/OperatorKinds.h"
#include "clang/Basic/Specifiers.h"
#include "clang/Basic/TokenKinds.h"
#include "llvm/ADT/DenseMapInfo.h"
#include "llvm/ADT/FoldingSet.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/StringMap.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/Support/Allocator.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/raw_ostream.h"
#include <cassert>
#include <cstdio>
#include <cstring>
#include <string>
using namespace clang;
//===----------------------------------------------------------------------===//
// IdentifierInfo Implementation
//===----------------------------------------------------------------------===//
IdentifierInfo::IdentifierInfo() {
TokenID = tok::identifier;
ObjCOrBuiltinID = 0;
HasMacro = false;
HadMacro = false;
IsExtension = false;
IsFutureCompatKeyword = false;
IsPoisoned = false;
IsCPPOperatorKeyword = false;
NeedsHandleIdentifier = false;
IsFromAST = false;
ChangedAfterLoad = false;
FEChangedAfterLoad = false;
RevertedTokenID = false;
OutOfDate = false;
IsModulesImport = false;
}
//===----------------------------------------------------------------------===//
// IdentifierTable Implementation
//===----------------------------------------------------------------------===//
IdentifierIterator::~IdentifierIterator() = default;
IdentifierInfoLookup::~IdentifierInfoLookup() = default;
namespace {
/// A simple identifier lookup iterator that represents an
/// empty sequence of identifiers.
class EmptyLookupIterator : public IdentifierIterator
{
public:
StringRef Next() override { return StringRef(); }
};
} // namespace
IdentifierIterator *IdentifierInfoLookup::getIdentifiers() {
return new EmptyLookupIterator();
}
IdentifierTable::IdentifierTable(IdentifierInfoLookup *ExternalLookup)
: HashTable(8192), // Start with space for 8K identifiers.
ExternalLookup(ExternalLookup) {}
IdentifierTable::IdentifierTable(const LangOptions &LangOpts,
IdentifierInfoLookup *ExternalLookup)
: IdentifierTable(ExternalLookup) {
// Populate the identifier table with info about keywords for the current
// language.
AddKeywords(LangOpts);
}
//===----------------------------------------------------------------------===//
// Language Keyword Implementation
//===----------------------------------------------------------------------===//
// Constants for TokenKinds.def
namespace {
enum {
KEYC99 = 0x1,
KEYCXX = 0x2,
KEYCXX11 = 0x4,
KEYGNU = 0x8,
KEYMS = 0x10,
BOOLSUPPORT = 0x20,
KEYALTIVEC = 0x40,
KEYNOCXX = 0x80,
KEYBORLAND = 0x100,
KEYOPENCL = 0x200,
KEYC11 = 0x400,
KEYARC = 0x800,
KEYNOMS18 = 0x01000,
KEYNOOPENCL = 0x02000,
WCHARSUPPORT = 0x04000,
HALFSUPPORT = 0x08000,
CHAR8SUPPORT = 0x10000,
KEYCONCEPTS = 0x20000,
KEYOBJC2 = 0x40000,
KEYZVECTOR = 0x80000,
KEYCOROUTINES = 0x100000,
KEYMODULES = 0x200000,
KEYCXX2A = 0x400000,
KEYALLCXX = KEYCXX | KEYCXX11 | KEYCXX2A,
KEYALL = (0x7fffff & ~KEYNOMS18 &
~KEYNOOPENCL) // KEYNOMS18 and KEYNOOPENCL are used to exclude.
};
/// How a keyword is treated in the selected standard.
enum KeywordStatus {
KS_Disabled, // Disabled
KS_Extension, // Is an extension
KS_Enabled, // Enabled
KS_Future // Is a keyword in future standard
};
} // namespace
/// Translates flags as specified in TokenKinds.def into keyword status
/// in the given language standard.
static KeywordStatus getKeywordStatus(const LangOptions &LangOpts,
unsigned Flags) {
if (Flags == KEYALL) return KS_Enabled;
if (LangOpts.CPlusPlus && (Flags & KEYCXX)) return KS_Enabled;
if (LangOpts.CPlusPlus11 && (Flags & KEYCXX11)) return KS_Enabled;
if (LangOpts.CPlusPlus2a && (Flags & KEYCXX2A)) return KS_Enabled;
if (LangOpts.C99 && (Flags & KEYC99)) return KS_Enabled;
if (LangOpts.GNUKeywords && (Flags & KEYGNU)) return KS_Extension;
if (LangOpts.MicrosoftExt && (Flags & KEYMS)) return KS_Extension;
if (LangOpts.Borland && (Flags & KEYBORLAND)) return KS_Extension;
if (LangOpts.Bool && (Flags & BOOLSUPPORT)) return KS_Enabled;
if (LangOpts.Half && (Flags & HALFSUPPORT)) return KS_Enabled;
if (LangOpts.WChar && (Flags & WCHARSUPPORT)) return KS_Enabled;
if (LangOpts.Char8 && (Flags & CHAR8SUPPORT)) return KS_Enabled;
if (LangOpts.AltiVec && (Flags & KEYALTIVEC)) return KS_Enabled;
if (LangOpts.OpenCL && (Flags & KEYOPENCL)) return KS_Enabled;
if (!LangOpts.CPlusPlus && (Flags & KEYNOCXX)) return KS_Enabled;
if (LangOpts.C11 && (Flags & KEYC11)) return KS_Enabled;
// We treat bridge casts as objective-C keywords so we can warn on them
// in non-arc mode.
if (LangOpts.ObjC2 && (Flags & KEYARC)) return KS_Enabled;
if (LangOpts.ObjC2 && (Flags & KEYOBJC2)) return KS_Enabled;
if (LangOpts.ConceptsTS && (Flags & KEYCONCEPTS)) return KS_Enabled;
if (LangOpts.CoroutinesTS && (Flags & KEYCOROUTINES)) return KS_Enabled;
if (LangOpts.ModulesTS && (Flags & KEYMODULES)) return KS_Enabled;
if (LangOpts.CPlusPlus && (Flags & KEYALLCXX)) return KS_Future;
return KS_Disabled;
}
/// AddKeyword - This method is used to associate a token ID with specific
/// identifiers because they are language keywords. This causes the lexer to
/// automatically map matching identifiers to specialized token codes.
static void AddKeyword(StringRef Keyword,
tok::TokenKind TokenCode, unsigned Flags,
const LangOptions &LangOpts, IdentifierTable &Table) {
KeywordStatus AddResult = getKeywordStatus(LangOpts, Flags);
// Don't add this keyword under MSVCCompat.
if (LangOpts.MSVCCompat && (Flags & KEYNOMS18) &&
!LangOpts.isCompatibleWithMSVC(LangOptions::MSVC2015))
return;
// Don't add this keyword under OpenCL.
if (LangOpts.OpenCL && (Flags & KEYNOOPENCL))
return;
// Don't add this keyword if disabled in this language.
if (AddResult == KS_Disabled) return;
IdentifierInfo &Info =
Table.get(Keyword, AddResult == KS_Future ? tok::identifier : TokenCode);
Info.setIsExtensionToken(AddResult == KS_Extension);
Info.setIsFutureCompatKeyword(AddResult == KS_Future);
}
/// AddCXXOperatorKeyword - Register a C++ operator keyword alternative
/// representations.
static void AddCXXOperatorKeyword(StringRef Keyword,
tok::TokenKind TokenCode,
IdentifierTable &Table) {
IdentifierInfo &Info = Table.get(Keyword, TokenCode);
Info.setIsCPlusPlusOperatorKeyword();
}
/// AddObjCKeyword - Register an Objective-C \@keyword like "class" "selector"
/// or "property".
static void AddObjCKeyword(StringRef Name,
tok::ObjCKeywordKind ObjCID,
IdentifierTable &Table) {
Table.get(Name).setObjCKeywordID(ObjCID);
}
/// AddKeywords - Add all keywords to the symbol table.
///
void IdentifierTable::AddKeywords(const LangOptions &LangOpts) {
// Add keywords and tokens for the current language.
#define KEYWORD(NAME, FLAGS) \
AddKeyword(StringRef(#NAME), tok::kw_ ## NAME, \
FLAGS, LangOpts, *this);
#define ALIAS(NAME, TOK, FLAGS) \
AddKeyword(StringRef(NAME), tok::kw_ ## TOK, \
FLAGS, LangOpts, *this);
#define CXX_KEYWORD_OPERATOR(NAME, ALIAS) \
if (LangOpts.CXXOperatorNames) \
AddCXXOperatorKeyword(StringRef(#NAME), tok::ALIAS, *this);
#define OBJC1_AT_KEYWORD(NAME) \
if (LangOpts.ObjC1) \
AddObjCKeyword(StringRef(#NAME), tok::objc_##NAME, *this);
#define OBJC2_AT_KEYWORD(NAME) \
if (LangOpts.ObjC2) \
AddObjCKeyword(StringRef(#NAME), tok::objc_##NAME, *this);
#define TESTING_KEYWORD(NAME, FLAGS)
#include "clang/Basic/TokenKinds.def"
if (LangOpts.ParseUnknownAnytype)
AddKeyword("__unknown_anytype", tok::kw___unknown_anytype, KEYALL,
LangOpts, *this);
if (LangOpts.DeclSpecKeyword)
AddKeyword("__declspec", tok::kw___declspec, KEYALL, LangOpts, *this);
// Add the '_experimental_modules_import' contextual keyword.
get("import").setModulesImport(true);
}
/// Checks if the specified token kind represents a keyword in the
/// specified language.
/// \returns Status of the keyword in the language.
static KeywordStatus getTokenKwStatus(const LangOptions &LangOpts,
tok::TokenKind K) {
switch (K) {
#define KEYWORD(NAME, FLAGS) \
case tok::kw_##NAME: return getKeywordStatus(LangOpts, FLAGS);
#include "clang/Basic/TokenKinds.def"
default: return KS_Disabled;
}
}
/// Returns true if the identifier represents a keyword in the
/// specified language.
bool IdentifierInfo::isKeyword(const LangOptions &LangOpts) const {
switch (getTokenKwStatus(LangOpts, getTokenID())) {
case KS_Enabled:
case KS_Extension:
return true;
default:
return false;
}
}
/// Returns true if the identifier represents a C++ keyword in the
/// specified language.
bool IdentifierInfo::isCPlusPlusKeyword(const LangOptions &LangOpts) const {
if (!LangOpts.CPlusPlus || !isKeyword(LangOpts))
return false;
// This is a C++ keyword if this identifier is not a keyword when checked
// using LangOptions without C++ support.
LangOptions LangOptsNoCPP = LangOpts;
LangOptsNoCPP.CPlusPlus = false;
LangOptsNoCPP.CPlusPlus11 = false;
LangOptsNoCPP.CPlusPlus2a = false;
return !isKeyword(LangOptsNoCPP);
}
tok::PPKeywordKind IdentifierInfo::getPPKeywordID() const {
// We use a perfect hash function here involving the length of the keyword,
// the first and third character. For preprocessor ID's there are no
// collisions (if there were, the switch below would complain about duplicate
// case values). Note that this depends on 'if' being null terminated.
#define HASH(LEN, FIRST, THIRD) \
(LEN << 5) + (((FIRST-'a') + (THIRD-'a')) & 31)
#define CASE(LEN, FIRST, THIRD, NAME) \
case HASH(LEN, FIRST, THIRD): \
return memcmp(Name, #NAME, LEN) ? tok::pp_not_keyword : tok::pp_ ## NAME
unsigned Len = getLength();
if (Len < 2) return tok::pp_not_keyword;
const char *Name = getNameStart();
switch (HASH(Len, Name[0], Name[2])) {
default: return tok::pp_not_keyword;
CASE( 2, 'i', '\0', if);
CASE( 4, 'e', 'i', elif);
CASE( 4, 'e', 's', else);
CASE( 4, 'l', 'n', line);
CASE( 4, 's', 'c', sccs);
CASE( 5, 'e', 'd', endif);
CASE( 5, 'e', 'r', error);
CASE( 5, 'i', 'e', ident);
CASE( 5, 'i', 'd', ifdef);
CASE( 5, 'u', 'd', undef);
CASE( 6, 'a', 's', assert);
CASE( 6, 'd', 'f', define);
CASE( 6, 'i', 'n', ifndef);
CASE( 6, 'i', 'p', import);
CASE( 6, 'p', 'a', pragma);
CASE( 7, 'd', 'f', defined);
CASE( 7, 'i', 'c', include);
CASE( 7, 'w', 'r', warning);
CASE( 8, 'u', 'a', unassert);
CASE(12, 'i', 'c', include_next);
CASE(14, '_', 'p', __public_macro);
CASE(15, '_', 'p', __private_macro);
CASE(16, '_', 'i', __include_macros);
#undef CASE
#undef HASH
}
}
//===----------------------------------------------------------------------===//
// Stats Implementation
//===----------------------------------------------------------------------===//
/// PrintStats - Print statistics about how well the identifier table is doing
/// at hashing identifiers.
void IdentifierTable::PrintStats() const {
unsigned NumBuckets = HashTable.getNumBuckets();
unsigned NumIdentifiers = HashTable.getNumItems();
unsigned NumEmptyBuckets = NumBuckets-NumIdentifiers;
unsigned AverageIdentifierSize = 0;
unsigned MaxIdentifierLength = 0;
// TODO: Figure out maximum times an identifier had to probe for -stats.
for (llvm::StringMap<IdentifierInfo*, llvm::BumpPtrAllocator>::const_iterator
I = HashTable.begin(), E = HashTable.end(); I != E; ++I) {
unsigned IdLen = I->getKeyLength();
AverageIdentifierSize += IdLen;
if (MaxIdentifierLength < IdLen)
MaxIdentifierLength = IdLen;
}
fprintf(stderr, "\n*** Identifier Table Stats:\n");
fprintf(stderr, "# Identifiers: %d\n", NumIdentifiers);
fprintf(stderr, "# Empty Buckets: %d\n", NumEmptyBuckets);
fprintf(stderr, "Hash density (#identifiers per bucket): %f\n",
NumIdentifiers/(double)NumBuckets);
fprintf(stderr, "Ave identifier length: %f\n",
(AverageIdentifierSize/(double)NumIdentifiers));
fprintf(stderr, "Max identifier length: %d\n", MaxIdentifierLength);
// Compute statistics about the memory allocated for identifiers.
HashTable.getAllocator().PrintStats();
}
//===----------------------------------------------------------------------===//
// SelectorTable Implementation
//===----------------------------------------------------------------------===//
unsigned llvm::DenseMapInfo<clang::Selector>::getHashValue(clang::Selector S) {
return DenseMapInfo<void*>::getHashValue(S.getAsOpaquePtr());
}
namespace clang {
/// MultiKeywordSelector - One of these variable length records is kept for each
/// selector containing more than one keyword. We use a folding set
/// to unique aggregate names (keyword selectors in ObjC parlance). Access to
/// this class is provided strictly through Selector.
class MultiKeywordSelector
: public DeclarationNameExtra, public llvm::FoldingSetNode {
MultiKeywordSelector(unsigned nKeys) {
ExtraKindOrNumArgs = NUM_EXTRA_KINDS + nKeys;
}
public:
// Constructor for keyword selectors.
MultiKeywordSelector(unsigned nKeys, IdentifierInfo **IIV) {
assert((nKeys > 1) && "not a multi-keyword selector");
ExtraKindOrNumArgs = NUM_EXTRA_KINDS + nKeys;
// Fill in the trailing keyword array.
IdentifierInfo **KeyInfo = reinterpret_cast<IdentifierInfo **>(this+1);
for (unsigned i = 0; i != nKeys; ++i)
KeyInfo[i] = IIV[i];
}
// getName - Derive the full selector name and return it.
std::string getName() const;
unsigned getNumArgs() const { return ExtraKindOrNumArgs - NUM_EXTRA_KINDS; }
using keyword_iterator = IdentifierInfo *const *;
keyword_iterator keyword_begin() const {
return reinterpret_cast<keyword_iterator>(this+1);
}
keyword_iterator keyword_end() const {
return keyword_begin()+getNumArgs();
}
IdentifierInfo *getIdentifierInfoForSlot(unsigned i) const {
assert(i < getNumArgs() && "getIdentifierInfoForSlot(): illegal index");
return keyword_begin()[i];
}
static void Profile(llvm::FoldingSetNodeID &ID,
keyword_iterator ArgTys, unsigned NumArgs) {
ID.AddInteger(NumArgs);
for (unsigned i = 0; i != NumArgs; ++i)
ID.AddPointer(ArgTys[i]);
}
void Profile(llvm::FoldingSetNodeID &ID) {
Profile(ID, keyword_begin(), getNumArgs());
}
};
} // namespace clang.
unsigned Selector::getNumArgs() const {
unsigned IIF = getIdentifierInfoFlag();
if (IIF <= ZeroArg)
return 0;
if (IIF == OneArg)
return 1;
// We point to a MultiKeywordSelector.
MultiKeywordSelector *SI = getMultiKeywordSelector();
return SI->getNumArgs();
}
IdentifierInfo *Selector::getIdentifierInfoForSlot(unsigned argIndex) const {
if (getIdentifierInfoFlag() < MultiArg) {
assert(argIndex == 0 && "illegal keyword index");
return getAsIdentifierInfo();
}
// We point to a MultiKeywordSelector.
MultiKeywordSelector *SI = getMultiKeywordSelector();
return SI->getIdentifierInfoForSlot(argIndex);
}
StringRef Selector::getNameForSlot(unsigned int argIndex) const {
IdentifierInfo *II = getIdentifierInfoForSlot(argIndex);
return II? II->getName() : StringRef();
}
std::string MultiKeywordSelector::getName() const {
SmallString<256> Str;
llvm::raw_svector_ostream OS(Str);
for (keyword_iterator I = keyword_begin(), E = keyword_end(); I != E; ++I) {
if (*I)
OS << (*I)->getName();
OS << ':';
}
return OS.str();
}
std::string Selector::getAsString() const {
if (InfoPtr == 0)
return "<null selector>";
if (getIdentifierInfoFlag() < MultiArg) {
IdentifierInfo *II = getAsIdentifierInfo();
if (getNumArgs() == 0) {
assert(II && "If the number of arguments is 0 then II is guaranteed to "
"not be null.");
return II->getName();
}
if (!II)
return ":";
return II->getName().str() + ":";
}
// We have a multiple keyword selector.
return getMultiKeywordSelector()->getName();
}
void Selector::print(llvm::raw_ostream &OS) const {
OS << getAsString();
}
/// Interpreting the given string using the normal CamelCase
/// conventions, determine whether the given string starts with the
/// given "word", which is assumed to end in a lowercase letter.
static bool startsWithWord(StringRef name, StringRef word) {
if (name.size() < word.size()) return false;
return ((name.size() == word.size() || !isLowercase(name[word.size()])) &&
name.startswith(word));
}
ObjCMethodFamily Selector::getMethodFamilyImpl(Selector sel) {
IdentifierInfo *first = sel.getIdentifierInfoForSlot(0);
if (!first) return OMF_None;
StringRef name = first->getName();
if (sel.isUnarySelector()) {
if (name == "autorelease") return OMF_autorelease;
if (name == "dealloc") return OMF_dealloc;
if (name == "finalize") return OMF_finalize;
if (name == "release") return OMF_release;
if (name == "retain") return OMF_retain;
if (name == "retainCount") return OMF_retainCount;
if (name == "self") return OMF_self;
if (name == "initialize") return OMF_initialize;
}
if (name == "performSelector" || name == "performSelectorInBackground" ||
name == "performSelectorOnMainThread")
return OMF_performSelector;
// The other method families may begin with a prefix of underscores.
while (!name.empty() && name.front() == '_')
name = name.substr(1);
if (name.empty()) return OMF_None;
switch (name.front()) {
case 'a':
if (startsWithWord(name, "alloc")) return OMF_alloc;
break;
case 'c':
if (startsWithWord(name, "copy")) return OMF_copy;
break;
case 'i':
if (startsWithWord(name, "init")) return OMF_init;
break;
case 'm':
if (startsWithWord(name, "mutableCopy")) return OMF_mutableCopy;
break;
case 'n':
if (startsWithWord(name, "new")) return OMF_new;
break;
default:
break;
}
return OMF_None;
}
ObjCInstanceTypeFamily Selector::getInstTypeMethodFamily(Selector sel) {
IdentifierInfo *first = sel.getIdentifierInfoForSlot(0);
if (!first) return OIT_None;
StringRef name = first->getName();
if (name.empty()) return OIT_None;
switch (name.front()) {
case 'a':
if (startsWithWord(name, "array")) return OIT_Array;
break;
case 'd':
if (startsWithWord(name, "default")) return OIT_ReturnsSelf;
if (startsWithWord(name, "dictionary")) return OIT_Dictionary;
break;
case 's':
if (startsWithWord(name, "shared")) return OIT_ReturnsSelf;
if (startsWithWord(name, "standard")) return OIT_Singleton;
break;
case 'i':
if (startsWithWord(name, "init")) return OIT_Init;
default:
break;
}
return OIT_None;
}
ObjCStringFormatFamily Selector::getStringFormatFamilyImpl(Selector sel) {
IdentifierInfo *first = sel.getIdentifierInfoForSlot(0);
if (!first) return SFF_None;
StringRef name = first->getName();
switch (name.front()) {
case 'a':
if (name == "appendFormat") return SFF_NSString;
break;
case 'i':
if (name == "initWithFormat") return SFF_NSString;
break;
case 'l':
if (name == "localizedStringWithFormat") return SFF_NSString;
break;
case 's':
if (name == "stringByAppendingFormat" ||
name == "stringWithFormat") return SFF_NSString;
break;
}
return SFF_None;
}
namespace {
struct SelectorTableImpl {
llvm::FoldingSet<MultiKeywordSelector> Table;
llvm::BumpPtrAllocator Allocator;
};
} // namespace
static SelectorTableImpl &getSelectorTableImpl(void *P) {
return *static_cast<SelectorTableImpl*>(P);
}
SmallString<64>
SelectorTable::constructSetterName(StringRef Name) {
SmallString<64> SetterName("set");
SetterName += Name;
SetterName[3] = toUppercase(SetterName[3]);
return SetterName;
}
Selector
SelectorTable::constructSetterSelector(IdentifierTable &Idents,
SelectorTable &SelTable,
const IdentifierInfo *Name) {
IdentifierInfo *SetterName =
&Idents.get(constructSetterName(Name->getName()));
return SelTable.getUnarySelector(SetterName);
}
size_t SelectorTable::getTotalMemory() const {
SelectorTableImpl &SelTabImpl = getSelectorTableImpl(Impl);
return SelTabImpl.Allocator.getTotalMemory();
}
Selector SelectorTable::getSelector(unsigned nKeys, IdentifierInfo **IIV) {
if (nKeys < 2)
return Selector(IIV[0], nKeys);
SelectorTableImpl &SelTabImpl = getSelectorTableImpl(Impl);
// Unique selector, to guarantee there is one per name.
llvm::FoldingSetNodeID ID;
MultiKeywordSelector::Profile(ID, IIV, nKeys);
void *InsertPos = nullptr;
if (MultiKeywordSelector *SI =
SelTabImpl.Table.FindNodeOrInsertPos(ID, InsertPos))
return Selector(SI);
// MultiKeywordSelector objects are not allocated with new because they have a
// variable size array (for parameter types) at the end of them.
unsigned Size = sizeof(MultiKeywordSelector) + nKeys*sizeof(IdentifierInfo *);
MultiKeywordSelector *SI =
(MultiKeywordSelector *)SelTabImpl.Allocator.Allocate(
Size, alignof(MultiKeywordSelector));
new (SI) MultiKeywordSelector(nKeys, IIV);
SelTabImpl.Table.InsertNode(SI, InsertPos);
return Selector(SI);
}
SelectorTable::SelectorTable() {
Impl = new SelectorTableImpl();
}
SelectorTable::~SelectorTable() {
delete &getSelectorTableImpl(Impl);
}
const char *clang::getOperatorSpelling(OverloadedOperatorKind Operator) {
switch (Operator) {
case OO_None:
case NUM_OVERLOADED_OPERATORS:
return nullptr;
#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
case OO_##Name: return Spelling;
#include "clang/Basic/OperatorKinds.def"
}
llvm_unreachable("Invalid OverloadedOperatorKind!");
}
StringRef clang::getNullabilitySpelling(NullabilityKind kind,
bool isContextSensitive) {
switch (kind) {
case NullabilityKind::NonNull:
return isContextSensitive ? "nonnull" : "_Nonnull";
case NullabilityKind::Nullable:
return isContextSensitive ? "nullable" : "_Nullable";
case NullabilityKind::Unspecified:
return isContextSensitive ? "null_unspecified" : "_Null_unspecified";
}
llvm_unreachable("Unknown nullability kind.");
}
| [
"[email protected]"
] | |
088e07cf5b8e57147205361a7bb8da08825fbeeb | 8dc84558f0058d90dfc4955e905dab1b22d12c08 | /third_party/blink/renderer/core/html/link_element_loading_test.cc | c82c7593f5fe8ef11d8e34e702f07dfa1a2f5fb7 | [
"LGPL-2.0-only",
"BSD-2-Clause",
"LGPL-2.1-only",
"LicenseRef-scancode-unknown-license-reference",
"BSD-3-Clause",
"LGPL-2.0-or-later",
"GPL-1.0-or-later",
"MIT",
"Apache-2.0"
] | permissive | meniossin/src | 42a95cc6c4a9c71d43d62bc4311224ca1fd61e03 | 44f73f7e76119e5ab415d4593ac66485e65d700a | refs/heads/master | 2022-12-16T20:17:03.747113 | 2020-09-03T10:43:12 | 2020-09-03T10:43:12 | 263,710,168 | 1 | 0 | BSD-3-Clause | 2020-05-13T18:20:09 | 2020-05-13T18:20:08 | null | UTF-8 | C++ | false | false | 1,395 | cc | // Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/blink/renderer/core/dom/document.h"
#include "third_party/blink/renderer/core/html/html_link_element.h"
#include "third_party/blink/renderer/core/testing/sim/sim_request.h"
#include "third_party/blink/renderer/core/testing/sim/sim_test.h"
namespace blink {
class LinkElementLoadingTest : public SimTest {};
TEST_F(LinkElementLoadingTest,
ShouldCancelLoadingStyleSheetIfLinkElementIsDisconnected) {
SimRequest main_resource("https://example.com/test.html", "text/html");
SimRequest css_resource("https://example.com/test.css", "text/css");
LoadURL("https://example.com/test.html");
main_resource.Start();
main_resource.Write(
"<!DOCTYPE html><link id=link rel=stylesheet href=test.css>");
// Sheet is streaming in, but not ready yet.
css_resource.Start();
// Remove a link element from a document
HTMLLinkElement* link =
ToHTMLLinkElement(GetDocument().getElementById("link"));
EXPECT_NE(nullptr, link);
link->remove();
// Finish the load.
css_resource.Complete();
main_resource.Finish();
// Link element's sheet loading should be canceled.
EXPECT_EQ(nullptr, link->sheet());
}
} // namespace blink
| [
"[email protected]"
] | |
181a9dfd827524c75789617744e569536f5485aa | 8c8ea797b0821400c3176add36dd59f866b8ac3d | /AOJ/aoj0025.cpp | c2403359a69322f0b035d629e82f658fe2bce624 | [] | no_license | fushime2/competitive | d3d6d8e095842a97d4cad9ca1246ee120d21789f | b2a0f5957d8ae758330f5450306b629006651ad5 | refs/heads/master | 2021-01-21T16:00:57.337828 | 2017-05-20T06:45:46 | 2017-05-20T06:45:46 | 78,257,409 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 594 | cpp | #include <iostream>
#include <map>
#include <vector>
using namespace std;
#define N 4
int main(void)
{
ios::sync_with_stdio(false);
int a[N], b[N];
int hit, blow;
while(cin >> a[0] >> a[1] >> a[2] >> a[3], !cin.eof()) {
for(int i=0; i<N; i++) cin >> b[i];
hit = blow = 0;
for(int i=0; i<N; i++) {
for(int j=0; j<N; j++) {
if(a[i] == b[j]) {
if(i == j) hit++;
else blow++;
}
}
}
cout << hit << " " << blow << endl;
}
return 0;
}
| [
"[email protected]"
] | |
29ada50980d562e467d8267b9d3af643f6559c76 | 3ff49c066ddaf7e97ed2631760d438c6a1a452c5 | /src/ast/ASTAbstractVisitor.h | 479f96b3bd7bc0b42631a05748bb30fce6d49deb | [] | no_license | rudo-rov/CppSOM | 26321838d058ec188ab72bfd70dca5c12184df1d | 0fff035f9a5989014fb6ed214b41e7bdf088b904 | refs/heads/main | 2023-05-05T14:15:42.562364 | 2021-05-24T12:24:19 | 2021-05-24T12:24:19 | 342,613,612 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,222 | h | #pragma once
#include <any>
namespace som {
// Forward declaration of AST nodes to resolve circular reference
struct Class;
struct Method;
struct Block;
struct NestedBlock;
struct UnaryPattern;
struct BinaryPattern;
struct KeywordPattern;
struct Keyword;
struct KeywordWithArgs;
struct UnarySelector;
struct BinarySelector;
struct BinaryOperand;
struct KeywordSelector;
struct UnaryMessage;
struct BinaryMessage;
struct KeywordMessage;
struct Formula;
struct LiteralInteger;
struct LiteralDouble;
struct LiteralArray;
struct LiteralString;
struct Assignation;
struct Evaluation;
struct Variable;
struct NestedTerm;
struct Result;
class CAstAbstractVisitor {
public:
virtual std::any visit(Method* method) = 0;
virtual std::any visit(Class* classNode) = 0;
virtual std::any visit(Block* block) = 0;
virtual std::any visit(NestedBlock* nestedBlock) = 0;
virtual std::any visit(UnaryPattern* unaryPattern) = 0;
virtual std::any visit(BinaryPattern* binaryPattern) = 0;
virtual std::any visit(KeywordPattern* keywordPattern) = 0;
virtual std::any visit(Keyword* keyword) = 0;
virtual std::any visit(KeywordWithArgs* keyword) = 0;
virtual std::any visit(UnarySelector* unarySelector) = 0;
virtual std::any visit(BinarySelector* binarySelector) = 0;
virtual std::any visit(KeywordSelector* keywordSelector) = 0;
virtual std::any visit(UnaryMessage* unaryMessage) = 0;
virtual std::any visit(BinaryMessage* binaryMessage) = 0;
virtual std::any visit(BinaryOperand* binaryOperand) = 0;
virtual std::any visit(KeywordMessage* keywordMessage) = 0;
virtual std::any visit(Formula* formula) = 0;
virtual std::any visit(LiteralInteger* litInteger) = 0;
virtual std::any visit(LiteralString* litString) = 0;
virtual std::any visit(LiteralArray* litArray) = 0;
virtual std::any visit(LiteralDouble* litDouble) = 0;
virtual std::any visit(Assignation* assignation) = 0;
virtual std::any visit(Evaluation* evaluation) = 0;
virtual std::any visit(Result* result) = 0;
virtual std::any visit(Variable* variable) = 0;
virtual std::any visit(NestedTerm* nestedTerm) = 0;
};
}
| [
"[email protected]"
] | |
76e76978aa547bdd62a466f226aa7723fe14facb | 9484781e2faf0889182bc9fc9071d2a81e15e341 | /Ground.cpp | 3eaa89f1d1492713517daa9c1a3a76cd8cc0b333 | [] | no_license | Tubbz-alt/trip-to-mars | 0e34a7a608d8868a16f1748e327ada85b6310300 | 2122bb58f63abad0a2e6d0e814f7d0f2c323c98f | refs/heads/master | 2021-05-28T23:14:41.708327 | 2015-03-27T19:11:12 | 2015-03-27T19:11:12 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,582 | cpp | #include "Ground.h"
/*---------------------------------------------------------------------------*/
Ground::Ground(int Xground, int Zground, float MaxHigh, float SoftCoef)
{
int i,j;
xground = Xground;
zground = Zground;
maxhigh = MaxHigh;
softcoef = SoftCoef;
map = new float* [xground];
for(i=0; i<xground; i++)
map[i] = new float [zground];
if( !USEFROMFILE )
{
for(i=0; i<xground; i++)
for(j=0; j<zground; j++)
map[i][j]=-1.0;
map[0][0]=xrand(0.0, maxhigh); // 1er rnd bug
map[0][0]=xrand(0.0, maxhigh);
map[xground-1][0]=xrand(0.0, maxhigh);
map[0][zground-1]=xrand(0.0, maxhigh);
map[xground-1][zground-1]=xrand(0.0, maxhigh);
map[0][0]=0.;
map[xground-1][0]=0.;
map[0][zground-1]=0.;
map[xground-1][zground-1]=0.;
buildground();
lissage(LISSAGEDEGRE);
HighCut(HIGHCUT);
}
else
{
loadheightmap();
lissage(LISSAGEDEGRE);
}
}
/*---------------------------------------------------------------------------*/
Ground::~Ground()
{
for(int i=0; i<xground; i++)
delete [] map[i];
delete [] map;
}
/*---------------------------------------------------------------------------*/
void Ground::loadheightmap()
{
int i, j;
set_color_depth(8);
//heightmap = load_bitmap("mountainheight513.bmp", NULL);
heightmap = load_bitmap("canyonheight2.bmp", NULL);
if ( !heightmap ) { allegro_message("No Highmap Found \n"); exit(1); }
for(j=0; j<zground; j++)
for(i=0; i<xground; i++)
map[i][j] = float( (unsigned char)getpixel(heightmap, i, j) );
destroy_bitmap(heightmap);
}
/*---------------------------------------------------------------------------*/
void Ground::buildground()
{
buildsubground(0, 0, xground-1, zground-1);
}
/*---------------------------------------------------------------------------*/
void Ground::buildsubground(int x1, int z1, int x2, int z2)
{
int xm = (x1+x2)/2;
int zm = (z1+z2)/2;
int dl = MIN(x2-x1,z2-z1);
int variance;
float scaledrnd;
variance = random(dl);
variance = 2*variance - dl;
scaledrnd = float(variance) * softcoef;
if((xm!=x1)||(zm!=z1))
{
// altitude new points
map[x1][zm] = (map[x1][zm]==-1.0) ? ((map[x1][z1]+map[x1][z2])/float(2))+scaledrnd : map[x1][zm];
map[xm][z1] = (map[xm][z1]==-1.0) ? ((map[x1][z1]+map[x2][z1])/float(2))+scaledrnd : map[xm][z1];
map[xm][z2] = (map[xm][z2]==-1.0) ? ((map[x1][z2]+map[x2][z2])/float(2))+scaledrnd : map[xm][z2];
map[x2][zm] = (map[x2][zm]==-1.0) ? ((map[x2][z1]+map[x2][z2])/float(2))+scaledrnd : map[x2][zm];
map[xm][zm] = (map[xm][zm]==-1.0) ?((map[x1][z1]+map[x2][z1]+map[x1][z2]+map[x2][z2])/float(4))+scaledrnd :
map[xm][zm];
// hauteur clipping
map[x1][zm] = (map[x1][zm]<0.0) ? 0.0 : map[x1][zm];
map[xm][z1] = (map[xm][z1]<0.0) ? 0.0 : map[xm][z1];
map[xm][z2] = (map[xm][z2]<0.0) ? 0.0 : map[xm][z2];
map[x2][zm] = (map[x2][zm]<0.0) ? 0.0 : map[x2][zm];
map[xm][zm] = (map[xm][zm]<0.0) ? 0.0 : map[xm][zm];
map[x1][zm] = (map[x1][zm]>maxhigh) ? maxhigh : map[x1][zm];
map[xm][z1] = (map[xm][z1]>maxhigh) ? maxhigh : map[xm][z1];
map[xm][z2] = (map[xm][z2]>maxhigh) ? maxhigh : map[xm][z2];
map[x2][zm] = (map[x2][zm]>maxhigh) ? maxhigh : map[x2][zm];
map[xm][zm] = (map[xm][zm]>maxhigh) ? maxhigh : map[xm][zm];
// rec (!ordre>)
buildsubground(x1,z1,xm,zm);
buildsubground(xm,z1,x2,zm);
buildsubground(x1,zm,xm,z2);
buildsubground(xm,zm,x2,z2);
}
}
/*---------------------------------------------------------------------------*/
void Ground::lissage(int degre)
{
int i, j, k;
for(k=0; k<degre; k++)
for(i=1; i<xground-1; i++)
for(j=1; j<zground-1; j++)
{
if(map[i][j]!=0)
{
map[i][j]=(map[i-1][j-1]+map[i-1][j]+map[i-1][j+1]+map[i][j-1]+
map[i][j+1]+map[i+1][j-1]+map[i+1][j]+map[i+1][j+1])/8.;
}
}
}
/*---------------------------------------------------------------------------*/
void Ground::HighCut(int highcut)
{
int i, j;
for(i=0; i<xground; i++)
for(j=0; j<zground; j++)
map[i][j] = (map[i][j]<(float)highcut) ? 0.0 : map[i][j];
}
/*---------------------------------------------------------------------------*/
float Ground::xrand(float xl, float xh)
{
#if defined(LINUX)
return (xl + (xh - xl) * drand48() );
#else
return (xl + (xh - xl) * rand() / 32767.0 );
#endif
}
int Ground::random(int rndmax)
{
return ( rand() % (rndmax+1) );
}
| [
"anthony.prieur@4cb61479-95d8-4551-e4b5-d013f55dcc39"
] | anthony.prieur@4cb61479-95d8-4551-e4b5-d013f55dcc39 |
d0037625ad2d3affbd5873f079c58a7a0a50304d | 2db92f5aed1f3a18de6bfad1818ae662137692b2 | /Default.h | c4b0f2e11e1a84c2feeb019b64a2b3af6fc57ca5 | [] | no_license | Gelya-Cyber/Restoraunt | ec0bea4e6cf43543f78e266df8dae2700da192b9 | 3d0fb719568f84467b0966cd24b3e1e6af08e085 | refs/heads/master | 2022-11-13T00:05:21.289599 | 2020-06-18T12:21:22 | 2020-06-18T12:21:22 | 273,228,806 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,936 | h | /*********************************************************************
Rhapsody : 9.0
Login : raxma
Component : DefaultComponent
Configuration : DefaultConfig
Model Element : Default
//! Generated Date : Thu, 18, Jun 2020
File Path : DefaultComponent\DefaultConfig\Default.h
*********************************************************************/
#ifndef Default_H
#define Default_H
//## auto_generated
#include <oxf\oxf.h>
//## auto_generated
#include <oxf\event.h>
//## auto_generated
class Authorization_Form;
//## auto_generated
class CancelReservation_Form;
//## auto_generated
class Database;
//## auto_generated
class Main_Form;
//## auto_generated
class MenuAdd_Form;
//## auto_generated
class MenuDelete_Form;
//## auto_generated
class MenuEdit_Form;
//## auto_generated
class Menu_Form;
//## auto_generated
class OrderAdd_Form;
//## auto_generated
class OrderDelete_Form;
//## auto_generated
class OrderEdit_Form;
//## auto_generated
class Order_Form;
//## auto_generated
class Reservation_Form;
//## auto_generated
class Table_Form;
//## auto_generated
class WaiterAdd_Form;
//## auto_generated
class WaiterDelete_Form;
//## auto_generated
class WaiterEdit_Form;
//## auto_generated
class Waiter_Form;
//#[ ignore
#define Enter_Password_Default_id 18601
//#]
//## package Default
//## event Enter_Password()
class Enter_Password : public OMEvent {
//// Constructors and destructors ////
public :
//## auto_generated
Enter_Password();
//// Framework operations ////
//## statechart_method
virtual bool isTypeOf(const short id) const;
};
#endif
/*********************************************************************
File Path : DefaultComponent\DefaultConfig\Default.h
*********************************************************************/
| [
"[email protected]"
] | |
a98e9f476dd86e348da9401f20f3a06c021ea80e | 8e4a2a7152e4b25641d72e930de8842732bcf53a | /OpenSeesCpp/eigen3/linearFunctionai.cpp | 48b55e4dcfecc4b8ffb1ebbb720b2ff0b2316df4 | [] | no_license | Mengsen-W/OpenSeesFiles | 9b9e8865a2b802047e419c5155aff5c20ac05937 | cda268d37cd17280dc18ada8c7f1b30af0b2bd6b | refs/heads/master | 2021-12-23T23:21:28.369076 | 2021-12-22T13:14:53 | 2021-12-22T13:14:53 | 239,237,550 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,450 | cpp | /*
* @Author: Mengsen.Wang
* @Date: 2020-07-17 09:49:15
* @Last Modified by: Mengsen.Wang
* @Last Modified time: 2020-07-17 10:47:16
*/
#include <ctime>
#include <eigen3/Eigen/Core>
#include <eigen3/Eigen/Dense>
#include <iostream>
#define MATRIX_SIZE 1000
int main() {
Eigen::MatrixXd A;
Eigen::MatrixXd B;
Eigen::MatrixXd X;
A = Eigen::MatrixXd::Random(MATRIX_SIZE, MATRIX_SIZE);
B = Eigen::MatrixXd::Random(MATRIX_SIZE, 1);
X = Eigen::MatrixXd::Random(MATRIX_SIZE, MATRIX_SIZE);
clock_t time_stt = clock();
std::cout << "----- QR decomposition colPivHouseholder -----" << std::endl;
X = A.colPivHouseholderQr().solve(B);
std::cout << "time use in QR colPivHouseholderQr decomposition is "
<< (1000) * (clock() - time_stt) /
static_cast<double>(CLOCKS_PER_SEC)
<< "ms" << std::endl;
time_stt = clock();
std::cout << "----- QR decomposition fullPivHouseholder -----" << std::endl;
X = A.fullPivHouseholderQr().solve(B);
std::cout << "time use in QR fullPivHouseholder decomposition is "
<< (1000) * (clock() - time_stt) /
static_cast<double>(CLOCKS_PER_SEC)
<< "ms" << std::endl;
time_stt = clock();
std::cout << "----- llt decomposition -----" << std::endl;
X = A.llt().solve(B);
std::cout << "time use in llt decomposition is "
<< (1000) * (clock() - time_stt) /
static_cast<double>(CLOCKS_PER_SEC)
<< "ms" << std::endl;
time_stt = clock();
std::cout << "----- ldlt decomposition -----" << std::endl;
X = A.ldlt().solve(B);
std::cout << "time use in ldlt decomposition is "
<< (1000) * (clock() - time_stt) /
static_cast<double>(CLOCKS_PER_SEC)
<< "ms" << std::endl;
time_stt = clock();
std::cout << "----- partialPivLu decomposition -----" << std::endl;
X = A.partialPivLu().solve(B);
std::cout << "time use in partialPivLu decomposition is "
<< (1000) * (clock() - time_stt) /
static_cast<double>(CLOCKS_PER_SEC)
<< "ms" << std::endl;
time_stt = clock();
std::cout << "----- fullPivLu decomposition -----" << std::endl;
X = A.fullPivLu().solve(B);
std::cout << "time use in fullPivLu decomposition is "
<< (1000) * (clock() - time_stt) /
static_cast<double>(CLOCKS_PER_SEC)
<< "ms" << std::endl;
return 0;
}
| [
"[email protected]"
] | |
df4686b64f23df1bd180ab71749f892557da3e90 | c50c4796cc416e78ef2c8883899d12f1d4e0a9e8 | /RPG/QuotesSettings.h | fcf5f16592a9e42f06884c6e6b893fd4d83f061d | [
"MIT"
] | permissive | kriskirov/RPG-Remote | 052b5c9eb24a1f61415def3cb3d72e0d30489a49 | f446f5461ad38267ed3a34dc80e8bd807ae29ef9 | refs/heads/master | 2021-01-20T01:19:10.416123 | 2017-05-09T11:37:42 | 2017-05-09T11:37:42 | 89,253,403 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 465 | h | #ifndef QUOTES_SETTINGS_H
#define QUOTES_SETTINGS_H
#include <string>
struct QuotesSettings{
QuotesSettings() = default;
QuotesSettings(
std::string attack,
std::string getAttacked,
std::string getAttackedWhileDead,
std::string dead
);
~QuotesSettings() = default;
QuotesSettings& operator=(const QuotesSettings& rhs) = default;
std::string mAttack;
std::string mGetAttacked;
std::string mGetAttackedWhileDead;
std::string mDead;
};
#endif | [
"[email protected]"
] | |
7ffec586c8dd2e09f767a0afadaac569716c3b06 | 8ac181aa59bbc34aa457ed90273b56763269859d | /Codeforces/668-DIV2/B.cpp | 9e90460de64ad73d97dd3b9bc8d34ae89d8b3dbc | [] | no_license | mohitmp9107/Competitive-Programming- | d8a85d37ad6eccb1c70e065f592f46961bdb21cf | d42ef49bfcd80ebfc87a75b544cf9d7d5afcc968 | refs/heads/master | 2021-07-11T11:09:14.808893 | 2020-10-03T08:15:36 | 2020-10-03T08:15:36 | 206,331,473 | 0 | 4 | null | 2020-10-03T08:15:38 | 2019-09-04T13:54:46 | C++ | UTF-8 | C++ | false | false | 1,304 | cpp | #include<bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace std;
using namespace __gnu_pbds;
template < typename T > using oset = tree < T, null_type, less < T >, rb_tree_tag, tree_order_statistics_node_update >;
// find_by_order(k) (k+1)th largest element
// order_of_key(k) no of elements <=k
typedef long long ll;
typedef long double ld;
#define endl '\n'
#define rep(i,n) for(ll i = 0; i < (n); ++i)
#define repA(i, a, n) for(ll i = a; i <= (n); ++i)
#define repD(i, a, n) for(ll i = a; i >= (n); --i)
#define trav(a, x) for(auto& a : x)
#define all(x) x.begin(), x.end()
#define sz(x) (ll)(x).size()
#define ff first
#define ss second
#define pb push_back
typedef vector<ll> vll;
typedef vector<pair<ll,ll>> vpl;
const ld PI = 4*atan((ld)1);
const ll INF = LLONG_MAX;
const ll mod = 1e9+7;
int main()
{
//freopen("input.txt","r",stdin);
//freopen("output.txt","w",stdout);
ios::sync_with_stdio(false); cin.tie(0); cout.tie(0);
ll tt=1;
cin >> tt;
repA(qq,1,tt){
ll n; cin >> n;
vll a(n);
ll ans = INF;
rep(i,n){
cin >> a[i];
if(i)a[i]+=a[i-1];
}
rep(i,n){
ans = min(ans,a[i]);
}
cout<< -ans << endl;
}
}
| [
"[email protected]"
] | |
e063d1a76d7610f8d626233ecb551423c89f987c | 3dbe2d0454979091d3f1f23c3bda6f8371efe8be | /arm_compute/runtime/CL/ICLGEMMKernelSelection.h | 69b941109d33bf329ad9fe1ab326458b98ddd52e | [
"MIT",
"LicenseRef-scancode-dco-1.1"
] | permissive | alexjung/ComputeLibrary | 399339e097a34cf28f64ac23b3ccb371e121a4c9 | a9d47c17791ebce45427ea6331bd6e35f7d721f4 | refs/heads/master | 2022-11-25T22:34:48.281986 | 2020-07-30T14:38:20 | 2020-07-30T14:38:20 | 283,794,492 | 0 | 0 | MIT | 2020-07-30T14:16:27 | 2020-07-30T14:16:26 | null | UTF-8 | C++ | false | false | 2,579 | h | /*
* Copyright (c) 2020 ARM Limited.
*
* SPDX-License-Identifier: MIT
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#ifndef ARM_COMPUTE_ICLGEMMKERNELSELECTION_H
#define ARM_COMPUTE_ICLGEMMKERNELSELECTION_H
#include "arm_compute/core/GPUTarget.h"
#include "arm_compute/core/Types.h"
#include "arm_compute/runtime/CL/CLTypes.h"
namespace arm_compute
{
namespace cl_gemm
{
/** Basic interface for the GEMM kernel selection */
class ICLGEMMKernelSelection
{
public:
/** Constructor
*
* @param[in] arch GPU target
*/
ICLGEMMKernelSelection(GPUTarget arch)
: _target(arch)
{
}
/** Default Move Constructor. */
ICLGEMMKernelSelection(ICLGEMMKernelSelection &&) = default;
/** Default move assignment operator */
ICLGEMMKernelSelection &operator=(ICLGEMMKernelSelection &&) = default;
/** Virtual destructor */
virtual ~ICLGEMMKernelSelection() = default;
/** Given the input parameters passed through @ref CLGEMMKernelSelectionParams, this method returns the @ref CLGEMMKernelType to use
*
* @param[in] params Input parameters used by the function to return the OpenCL GEMM's kernel
*
* @return @ref CLGEMMKernelType
*/
virtual CLGEMMKernelType select_kernel(const CLGEMMKernelSelectionParams ¶ms) = 0;
protected:
GPUTarget _target; /**< GPU target could be used to call a dedicated heuristic for each GPU IP for a given GPU architecture */
};
} // namespace cl_gemm
} // namespace arm_compute
#endif /*ARM_COMPUTE_ICLGEMMKERNELSELECTION_H */
| [
"[email protected]"
] | |
d5b10fd840e59b756c211cab4d2eb6bb258e3e76 | ef15a4a77b6e1fbb3220a5047885ba7568a80b74 | /src/core/Core/SignalToStop.hpp | b66f5a6ec1be9ca38fff701986ce19cd9dde6921 | [] | no_license | el-bart/ACARM-ng | 22ad5a40dc90a2239206f18dacbd4329ff8377de | de277af4b1c54e52ad96cbe4e1f574bae01b507d | refs/heads/master | 2020-12-27T09:24:14.591095 | 2014-01-28T19:24:34 | 2014-01-28T19:24:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 843 | hpp | /*
* SignalToStop.hpp
*
*/
#ifndef INCLUDE_CORE_SIGNALTOSTOP_HPP_FILE
#define INCLUDE_CORE_SIGNALTOSTOP_HPP_FILE
/* public header */
#include "System/SignalRegistrator.hpp"
#include "Logger/Node.hpp"
#include "Core/WorkThreads.hpp"
namespace Core
{
/** \brief handles given signal's registration and unregistration.
*
* when given signal is received system is triggered to stop.
*/
class SignalToStop: public System::SignalRegistrator
{
public:
/** \brief registers handle for signal.
* \param signum signal number to be handled.
* \param wt main system threads. if NULL, signal is ignored.
*/
SignalToStop(int signum, WorkThreads *wt);
/** \brief unregisters signal handle.
*/
~SignalToStop(void);
private:
int signum_;
Logger::Node log_;
}; // class SignalToStop
} // namespace Core
#endif
| [
"[email protected]"
] | |
60e5fb32350ab045ec71c799a0a5c28e815d2ca9 | 948f4e13af6b3014582909cc6d762606f2a43365 | /testcases/juliet_test_suite/testcases/CWE122_Heap_Based_Buffer_Overflow/s04/CWE122_Heap_Based_Buffer_Overflow__cpp_CWE806_wchar_t_loop_82_goodG2B.cpp | c33c8d71ef39b59ac89102c07f1b01680ea08a75 | [] | no_license | junxzm1990/ASAN-- | 0056a341b8537142e10373c8417f27d7825ad89b | ca96e46422407a55bed4aa551a6ad28ec1eeef4e | refs/heads/master | 2022-08-02T15:38:56.286555 | 2022-06-16T22:19:54 | 2022-06-16T22:19:54 | 408,238,453 | 74 | 13 | null | 2022-06-16T22:19:55 | 2021-09-19T21:14:59 | null | UTF-8 | C++ | false | false | 1,351 | cpp | /* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE122_Heap_Based_Buffer_Overflow__cpp_CWE806_wchar_t_loop_82_goodG2B.cpp
Label Definition File: CWE122_Heap_Based_Buffer_Overflow__cpp_CWE806.label.xml
Template File: sources-sink-82_goodG2B.tmpl.cpp
*/
/*
* @description
* CWE: 122 Heap Based Buffer Overflow
* BadSource: Initialize data as a large string
* GoodSource: Initialize data as a small string
* Sinks: loop
* BadSink : Copy data to string using a loop
* Flow Variant: 82 Data flow: data passed in a parameter to a virtual method called via a pointer
*
* */
#ifndef OMITGOOD
#include "std_testcase.h"
#include "CWE122_Heap_Based_Buffer_Overflow__cpp_CWE806_wchar_t_loop_82.h"
namespace CWE122_Heap_Based_Buffer_Overflow__cpp_CWE806_wchar_t_loop_82
{
void CWE122_Heap_Based_Buffer_Overflow__cpp_CWE806_wchar_t_loop_82_goodG2B::action(wchar_t * data)
{
{
wchar_t dest[50] = L"";
size_t i, dataLen;
dataLen = wcslen(data);
/* POTENTIAL FLAW: Possible buffer overflow if data is larger than dest */
for (i = 0; i < dataLen; i++)
{
dest[i] = data[i];
}
dest[50-1] = L'\0'; /* Ensure the destination buffer is null terminated */
printWLine(data);
delete [] data;
}
}
}
#endif /* OMITGOOD */
| [
"[email protected]"
] | |
7256649c1b45655ea0cc7a7affc81c5f3fe54265 | adbc979313cbc1f0d42c79ac4206d42a8adb3234 | /Source Code/李沿橙 2017-10-23/source/李沿橙/bus/bus.cpp | 0e0ba6ecc02f0bc9722cb827d7c4ccb465cb67b0 | [] | no_license | UnnamedOrange/Contests | a7982c21e575d1342d28c57681a3c98f8afda6c0 | d593d56921d2cde0c473b3abedb419bef4cf3ba4 | refs/heads/master | 2018-10-22T02:26:51.952067 | 2018-07-21T09:32:29 | 2018-07-21T09:32:29 | 112,301,400 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,218 | cpp | #pragma G++ optimize("O3")
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
#include <stack>
#include <queue>
#include <deque>
#include <map>
#include <set>
#include <bitset>
using std::cin;
using std::cout;
using std::endl;
typedef int INT;
inline INT readIn()
{
INT a = 0;
bool minus = false;
char ch = getchar();
while (!(ch == '-' || ch >= '0' && ch <= '9')) ch = getchar();
if (ch == '-')
{
minus = true;
ch = getchar();
}
while (ch >= '0' && ch <= '9')
{
a *= 10;
a += ch;
a -= '0';
ch = getchar();
}
if (minus) a = -a;
return a;
}
inline void printOut(INT x)
{
if (!x)
{
putchar('0');
}
else
{
char buffer[12];
INT length = 0;
bool minus = x < 0;
if (minus) x = -x;
while (x)
{
buffer[length++] = x % 10 + '0';
x /= 10;
}
if (minus) buffer[length++] = '-';
do
{
putchar(buffer[--length]);
} while (length);
}
putchar(' ');
}
const INT maxn = INT(1e6) + 5;
INT n, maxc;
INT c[maxn];
INT v[maxn];
struct stack : public std::vector<INT>
{
INT back2()
{
return std::vector<INT>::operator[](std::vector<INT>::size() - 2);
}
};
#define RunInstance(x) delete new x
struct cheat1
{
static const INT maxN = 5005;
INT f[maxN];
cheat1() : f()
{
f[0] = 0;
for (int i = 1; i <= n; i++)
{
f[i] = -1;
for (int j = 0; j < i; j++)
{
if ((i - j) % c[j] || f[j] == -1) continue;
INT t = f[j] + (i - j) / c[j] * v[j];
if (f[i] == -1 || f[i] > t) f[i] = t;
}
printOut(f[i]);
}
putchar('\n');
}
};
struct cheat2
{
cheat2()
{
INT cnt = v[0];
INT sum = 0;
for (int i = 1; i <= n; i++)
{
printOut(sum += cnt);
cnt = std::min(cnt, v[i]);
}
}
};
struct work
{
INT f[maxn];
stack q[11][10];
INT y(INT s)
{
return c[s] * f[s] - s * v[s];
}
INT x(INT s)
{
return v[s];
}
INT y(INT i, INT j)
{
return y(i) - y(j);
}
INT x(INT i, INT j)
{
return x(j) - x(i);
}
double slope(INT i, INT j)
{
INT x2 = x(i, j);
if (!x2) return 1e100;
return double(y(i, j)) / x2;
}
INT dp(INT i, INT j)
{
return f[j] + (i - j) / c[j] * v[j];
}
work() : f()
{
f[0] = 0;
q[c[0]][0].push_back(0);
for (int i = 1; i <= n; i++)
{
INT& ans = f[i];
ans = -1;
for (int j = 1; j <= maxc; j++)
{
stack& s = q[j][i % j];
if (s.empty()) continue;
while (s.size() > 1 &&
dp(i, s.back()) >= dp(i, s.back2()))
s.pop_back();
INT k = s.back();
INT t = dp(i, k);
if (ans == -1 || ans > t)
ans = t;
}
printOut(ans);
if (i != n && f[i] != -1)
{
stack& s = q[c[i]][i % c[i]];
while (s.size() && v[s.back()] >= v[i]) s.pop_back();
while (s.size() > 1 && slope(i, s.back()) >= slope(s.back(), s.back2()))
s.pop_back();
s.push_back(i);
}
}
}
};
void run()
{
n = readIn();
maxc = readIn();
for (int i = 0; i < n; i++)
{
c[i] = readIn();
v[i] = readIn();
}
//if (n <= 5000)
// RunInstance(cheat1);
//else if (maxc == 1)
// RunInstance(cheat2);
//else
RunInstance(work);
}
int main()
{
#ifndef JUDGE
freopen("bus.in", "r", stdin);
freopen("bus.out", "w", stdout);
#endif
run();
return 0;
}
| [
"[email protected]"
] | |
69721892a768fac6808ee60dfd9672acacbdc19b | b33a9177edaaf6bf185ef20bf87d36eada719d4f | /qtdeclarative/src/qml/jsruntime/qv4profiling_p.h | 6c54fc9bbdf19a1654d96b536ae8d0244adb9e27 | [
"Qt-LGPL-exception-1.1",
"LGPL-2.1-only",
"LGPL-2.0-or-later",
"LGPL-3.0-only",
"GPL-3.0-only",
"LGPL-2.1-or-later",
"GPL-1.0-or-later",
"LicenseRef-scancode-unknown-license-reference",
"GPL-2.0-only",
"GFDL-1.3-only",
"LicenseRef-scancode-digia-qt-preview",
"LicenseRef-scancode-warranty-disclaimer",
"LicenseRef-scancode-proprietary-license",
"LicenseRef-scancode-other-copyleft",
"LicenseRef-scancode-generic-exception"
] | permissive | wgnet/wds_qt | ab8c093b8c6eead9adf4057d843e00f04915d987 | 8db722fd367d2d0744decf99ac7bafaba8b8a3d3 | refs/heads/master | 2021-04-02T11:07:10.181067 | 2020-06-02T10:29:03 | 2020-06-02T10:34:19 | 248,267,925 | 1 | 0 | Apache-2.0 | 2020-04-30T12:16:53 | 2020-03-18T15:20:38 | null | UTF-8 | C++ | false | false | 6,825 | h | /****************************************************************************
**
** Copyright (C) 2015 The Qt Company Ltd.
** Contact: http://www.qt.io/licensing/
**
** This file is part of the QtQml module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL21$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see http://www.qt.io/terms-conditions. For further
** information use the contact form at http://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file. Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** As a special exception, The Qt Company gives you certain additional
** rights. These rights are described in The Qt Company LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** $QT_END_LICENSE$
**
****************************************************************************/
#ifndef QV4PROFILING_H
#define QV4PROFILING_H
//
// W A R N I N G
// -------------
//
// This file is not part of the Qt API. It exists purely as an
// implementation detail. This header file may change from version to
// version without notice, or even be removed.
//
// We mean it.
//
#include "qv4global_p.h"
#include "qv4engine_p.h"
#include "qv4function_p.h"
#include <QElapsedTimer>
QT_BEGIN_NAMESPACE
namespace QV4 {
namespace Profiling {
enum Features {
FeatureFunctionCall,
FeatureMemoryAllocation
};
enum MemoryType {
HeapPage,
LargeItem,
SmallItem
};
struct FunctionCallProperties {
qint64 start;
qint64 end;
QString name;
QString file;
int line;
int column;
};
struct MemoryAllocationProperties {
qint64 timestamp;
qint64 size;
MemoryType type;
};
class FunctionCall {
public:
FunctionCall() : m_function(0), m_start(0), m_end(0)
{ Q_ASSERT_X(false, Q_FUNC_INFO, "Cannot construct a function call without function"); }
FunctionCall(Function *function, qint64 start, qint64 end) :
m_function(function), m_start(start), m_end(end)
{ m_function->compilationUnit->addref(); }
FunctionCall(const FunctionCall &other) :
m_function(other.m_function), m_start(other.m_start), m_end(other.m_end)
{ m_function->compilationUnit->addref(); }
~FunctionCall()
{ m_function->compilationUnit->release(); }
FunctionCall &operator=(const FunctionCall &other) {
if (&other != this) {
if (m_function)
m_function->compilationUnit->release();
m_function = other.m_function;
m_start = other.m_start;
m_end = other.m_end;
m_function->compilationUnit->addref();
}
return *this;
}
FunctionCallProperties resolve() const;
private:
friend bool operator<(const FunctionCall &call1, const FunctionCall &call2);
Function *m_function;
qint64 m_start;
qint64 m_end;
};
#define Q_V4_PROFILE_ALLOC(engine, size, type)\
(engine->profiler &&\
(engine->profiler->featuresEnabled & (1 << Profiling::FeatureMemoryAllocation)) ?\
engine->profiler->trackAlloc(size, type) : size)
#define Q_V4_PROFILE_DEALLOC(engine, pointer, size, type) \
(engine->profiler &&\
(engine->profiler->featuresEnabled & (1 << Profiling::FeatureMemoryAllocation)) ?\
engine->profiler->trackDealloc(pointer, size, type) : pointer)
#define Q_V4_PROFILE(engine, function)\
(engine->profiler &&\
(engine->profiler->featuresEnabled & (1 << Profiling::FeatureFunctionCall)) ?\
Profiling::FunctionCallProfiler::profileCall(engine->profiler, engine, function) :\
function->code(engine, function->codeData))
class Q_QML_EXPORT Profiler : public QObject {
Q_OBJECT
Q_DISABLE_COPY(Profiler)
public:
Profiler(QV4::ExecutionEngine *engine);
size_t trackAlloc(size_t size, MemoryType type)
{
MemoryAllocationProperties allocation = {m_timer.nsecsElapsed(), (qint64)size, type};
m_memory_data.append(allocation);
return size;
}
void *trackDealloc(void *pointer, size_t size, MemoryType type)
{
MemoryAllocationProperties allocation = {m_timer.nsecsElapsed(), -(qint64)size, type};
m_memory_data.append(allocation);
return pointer;
}
quint64 featuresEnabled;
public slots:
void stopProfiling();
void startProfiling(quint64 features);
void reportData();
void setTimer(const QElapsedTimer &timer) { m_timer = timer; }
signals:
void dataReady(const QVector<QV4::Profiling::FunctionCallProperties> &,
const QVector<QV4::Profiling::MemoryAllocationProperties> &);
private:
QV4::ExecutionEngine *m_engine;
QElapsedTimer m_timer;
QVector<FunctionCall> m_data;
QVector<MemoryAllocationProperties> m_memory_data;
friend class FunctionCallProfiler;
};
class FunctionCallProfiler {
Q_DISABLE_COPY(FunctionCallProfiler)
public:
// It's enough to ref() the function in the destructor as it will probably not disappear while
// it's executing ...
FunctionCallProfiler(Profiler *profiler, Function *function) :
profiler(profiler), function(function), startTime(profiler->m_timer.nsecsElapsed())
{}
~FunctionCallProfiler()
{
profiler->m_data.append(FunctionCall(function, startTime, profiler->m_timer.nsecsElapsed()));
}
static ReturnedValue profileCall(Profiler *profiler, ExecutionEngine *engine, Function *function)
{
FunctionCallProfiler callProfiler(profiler, function);
return function->code(engine, function->codeData);
}
Profiler *profiler;
Function *function;
qint64 startTime;
};
} // namespace Profiling
} // namespace QV4
Q_DECLARE_TYPEINFO(QV4::Profiling::MemoryAllocationProperties, Q_MOVABLE_TYPE);
Q_DECLARE_TYPEINFO(QV4::Profiling::FunctionCallProperties, Q_MOVABLE_TYPE);
Q_DECLARE_TYPEINFO(QV4::Profiling::FunctionCall, Q_MOVABLE_TYPE);
QT_END_NAMESPACE
Q_DECLARE_METATYPE(QVector<QV4::Profiling::FunctionCallProperties>)
Q_DECLARE_METATYPE(QVector<QV4::Profiling::MemoryAllocationProperties>)
#endif // QV4PROFILING_H
| [
"[email protected]"
] | |
abb4494d31f83c59e62840a3cbee255fc3dd0ca4 | 3011f9e4204f2988c983b8815187f56a6bf58ebd | /src/ys_library/ysglcpp/src/nownd/ysglbuffermanager_nownd.h | af34a97c2e372bd4ad528a98ad9a18d6f039d852 | [] | no_license | hvantil/AR-BoardGames | 9e80a0f2bb24f8bc06902785d104178a214d0d63 | 71b9620df66d80c583191b8c8e8b925a6df5ddc3 | refs/heads/master | 2020-03-17T01:36:47.674272 | 2018-05-13T18:11:16 | 2018-05-13T18:11:16 | 133,160,216 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,763 | h | /* ////////////////////////////////////////////////////////////
File Name: ysglbuffermanager_nownd.h
Copyright (c) 2017 Soji Yamakawa. All rights reserved.
http://www.ysflight.com
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 COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//////////////////////////////////////////////////////////// */
#ifndef YSGLBUFFERMANAGER_GL2_IS_INCLUDED
#define YSGLBUFFERMANAGER_GL2_IS_INCLUDED
/* { */
#include <ysclass.h>
#include <ysglbuffermanager.h>
class YsGLBufferManager::ActualBuffer
{
public:
};
/* } */
#endif
| [
"[email protected]"
] | |
16797e4979a0f00c0f5408ba087dd3da9615e2ee | 446641d5115aaa8371a767e7e0e0597797568e33 | /Quarter 3/Week 5/closingthefarm.cpp | a811cf8531272c1710d89f581bee2d89071e997d | [
"MIT"
] | permissive | nwatx/CS3-Independent-Study | b4faa3442507121eef32e233bfacd8a549b85acc | 16b91d4e0503d10d825ae800c46ea9233cd5e066 | refs/heads/master | 2023-04-16T02:14:43.959564 | 2021-04-23T19:43:21 | 2021-04-23T19:43:21 | 290,934,485 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,207 | cpp | #include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp> // Common file
#include <ext/pb_ds/tree_policy.hpp> // Including tree_order_statistics_node_update
using namespace __gnu_pbds;
using namespace std;
#pragma GCC optimize("O3")
#pragma GCC optimization ("unroll-loops")
#pragma region
using ll = long long;
using db = long double; // or double, if TL is tight
using str = string; // yay python!
using pi = pair<int,int>;
using pl = pair<ll,ll>;
using pd = pair<db,db>;
using vi = vector<int>;
using vb = vector<bool>;
using vl = vector<ll>;
using vd = vector<db>;
using vs = vector<str>;
using vpi = vector<pi>;
using vpl = vector<pl>;
using vpd = vector<pd>;
#define tcT template<class T
#define tcTU tcT, class U
// ^ lol this makes everything look weird but I'll try it
tcT> using V = vector<T>;
tcT, size_t SZ> using AR = array<T,SZ>;
tcT> using PR = pair<T,T>;
// pairs
#define mp make_pair
#define f first
#define s second
// vectors
// oops size(x), rbegin(x), rend(x) need C++17
#define sz(x) (int)x.size()
#define bg(x) x.begin()
#define en(x) x.end()
#define all(x) bg(x), end(x)
#define rall(x) x.rbegin(), x.rend()
#define sor(x) sort(all(x))
#define rsz resize
#define ins insert
#define ft front()
#define bk back()
#define pb push_back
#define eb emplace_back
#define pf push_front
#define lb lower_bound
#define ub upper_bound
tcT> int lwb(V<T>& a, const T& b) { return int(lb(all(a),b)-bg(a)); }
// loops
#define FOR(i,a,b) for (int i = (a); i < (b); ++i)
#define F0R(i,a) FOR(i,0,a)
#define ROF(i,a,b) for (int i = (b)-1; i >= (a); --i)
#define R0F(i,a) ROF(i,0,a)
#define trav(a,x) for (auto& a: x)
const int MOD = 1e9+7; // 998244353;
const ll INF = 1e18; // not too close to LLONG_MAX
const char nl = '\n';
const db PI = acos((db)-1);
const int dx[4] = {1,0,-1,0}, dy[4] = {0,1,0,-1}; // for every grid problem!!
mt19937 rng((uint32_t)chrono::steady_clock::now().time_since_epoch().count());
template<class T> using pqg = priority_queue<T,vector<T>,greater<T>>;
template<class T> using ost = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>; //order statistic tree!
// bitwise ops
// also see https://gcc.gnu.org/onlinedocs/gcc/Other-Builtins.html
constexpr int pct(int x) { return __builtin_popcount(x); } // # of bits set
constexpr int bits(int x) { // assert(x >= 0); // make C++11 compatible until USACO updates ...
return x == 0 ? 0 : 31-__builtin_clz(x); } // floor(log2(x))
constexpr int p2(int x) { return 1<<x; }
constexpr int msk2(int x) { return p2(x)-1; }
ll cdiv(ll a, ll b) { return a/b+((a^b)>0&&a%b); } // divide a by b rounded up
ll fdiv(ll a, ll b) { return a/b-((a^b)<0&&a%b); } // divide a by b rounded down
tcT> bool ckmin(T& a, const T& b) {
return b < a ? a = b, 1 : 0; } // set a = min(a,b)
tcT> bool ckmax(T& a, const T& b) {
return a < b ? a = b, 1 : 0; }
tcTU> T fstTrue(T lo, T hi, U f) {
hi ++; assert(lo <= hi); // assuming f is increasing
while (lo < hi) { // find first index such that f is true
T mid = lo+(hi-lo)/2;
f(mid) ? hi = mid : lo = mid+1;
}
return lo;
}
tcTU> T lstTrue(T lo, T hi, U f) {
lo --; assert(lo <= hi); // assuming f is decreasing
while (lo < hi) { // find first index such that f is true
T mid = lo+(hi-lo+1)/2;
f(mid) ? lo = mid : hi = mid-1;
}
return lo;
}
tcT> void remDup(vector<T>& v) { // sort and remove duplicates
sort(all(v)); v.erase(unique(all(v)),end(v)); }
tcTU> void erase(T& t, const U& u) { // don't erase
auto it = t.find(u); assert(it != end(t));
t.erase(it); } // element that doesn't exist from (multi)set
// INPUT
#define tcTUU tcT, class ...U
tcT> void re(complex<T>& c);
tcTU> void re(pair<T,U>& p);
tcT> void re(V<T>& v);
tcT, size_t SZ> void re(AR<T,SZ>& a);
tcT> void re(T& x) { cin >> x; }
void re(double& d) { str t; re(t); d = stod(t); }
void re(long double& d) { str t; re(t); d = stold(t); }
tcTUU> void re(T& t, U&... u) { re(t); re(u...); }
tcT> void re(complex<T>& c) { T a,b; re(a,b); c = {a,b}; }
tcTU> void re(pair<T,U>& p) { re(p.f,p.s); }
tcT> void re(V<T>& x) { trav(a,x) re(a); }
tcT, size_t SZ> void re(AR<T,SZ>& x) { trav(a,x) re(a); }
tcT> void rv(int n, V<T>& x) { x.rsz(n); re(x); }
// TO_STRING
#define ts to_string
str ts(char c) { return str(1,c); }
str ts(const char* s) { return (str)s; }
str ts(str s) { return s; }
str ts(bool b) {
// #ifdef LOCAL
// return b ? "true" : "false";
// #else
return ts((int)b);
// #endif
}
tcT> str ts(complex<T> c) {
stringstream ss; ss << c; return ss.str(); }
str ts(V<bool> v) {
str res = "{"; F0R(i,sz(v)) res += char('0'+v[i]);
res += "}"; return res; }
template<size_t SZ> str ts(bitset<SZ> b) {
str res = ""; F0R(i,SZ) res += char('0'+b[i]);
return res; }
tcTU> str ts(pair<T,U> p);
tcT> str ts(T v) { // containers with begin(), end()
#ifdef LOCAL
bool fst = 1; str res = "{";
for (const auto& x: v) {
if (!fst) res += ", ";
fst = 0; res += ts(x);
}
res += "}"; return res;
#else
bool fst = 1; str res = "";
for (const auto& x: v) {
if (!fst) res += " ";
fst = 0; res += ts(x);
}
return res;
#endif
}
tcTU> str ts(pair<T,U> p) {
#ifdef LOCAL
return "("+ts(p.f)+", "+ts(p.s)+")";
#else
return ts(p.f)+" "+ts(p.s);
#endif
}
// OUTPUT
tcT> void pr(T x) { cout << ts(x); }
tcTUU> void pr(const T& t, const U&... u) {
pr(t); pr(u...); }
void ps() { pr("\n"); } // print w/ spaces
tcTUU> void ps(const T& t, const U&... u) {
pr(t); if (sizeof...(u)) pr(" "); ps(u...); }
// DEBUG
void DBG() { cerr << "]" << endl; }
tcTUU> void DBG(const T& t, const U&... u) {
cerr << ts(t); if (sizeof...(u)) cerr << ", ";
DBG(u...); }
#ifdef LOCAL // compile with -DLOCAL, chk -> fake assert
#define dbg(...) cerr << "Line(" << __LINE__ << ") -> [" << #__VA_ARGS__ << "]: [", DBG(__VA_ARGS__)
#define chk(...) if (!(__VA_ARGS__)) cerr << "Line(" << __LINE__ << ") -> function(" \
<< __FUNCTION__ << ") -> CHK FAILED: (" << #__VA_ARGS__ << ")" << "\n", exit(0);
#else
#define dbg(...) 0
#define chk(...) 0
#endif
void setPrec() { cout << fixed << setprecision(15); }
void unsyncIO() { cin.tie(0)->sync_with_stdio(0); }
// FILE I/O
void setIn(str s) { freopen(s.c_str(),"r",stdin); }
void setOut(str s) { freopen(s.c_str(),"w",stdout); }
void setIO(str s = "") {
unsyncIO(); setPrec();
// cin.exceptions(cin.failbit);
// throws exception when do smth illegal
// ex. try to read letter into int
if (sz(s)) setIn(s+".in"), setOut(s+".out"); // for USACO
}
#pragma endregion
const int MX = 2e5+1;
// make sure to intialize ALL GLOBAL VARS between tcs!
struct UF {
vi e;
UF(int n) : e(n, -1) {}
bool sameSet(int a, int b) { return find(a) == find(b); }
int size(int x) { return -e[find(x)]; }
int find(int x) { return e[x] < 0 ? x : e[x] = find(e[x]); }
bool join(int a, int b) {
a = find(a), b = find(b);
if (a == b) return false;
if (e[a] > e[b]) swap(a, b);
e[a] += e[b]; e[b] = a;
return true;
}
};
int N, M;
bool A[MX];
bool vis[MX];
vi adj[MX];
int main() {
// clock_t start = clock();
setIO("closing");
re(N, M);
UF uf(N);
F0R(i, M) {
int a, b;
re(a, b);
a--; b--;
adj[a].pb(b);
adj[b].pb(a);
}
vi order(N);
F0R(i, N) {
int a;
re(a);
a--;
order[i] = a;
}
R0F(i, N) {
vis[i] = true;
trav(e, adj[i]) {
if(vis[i] && vis[e]) uf.join(i, e);
}
uf.size(order[i]) == N-i ? pr("YES\n"): pr("NO\n");
}
// cerr << "Total Time: " << (double)(clock() - start)/ CLOCKS_PER_SEC;
}
/* stuff you should look for
* int overflow, array bounds
* special cases (n=1?)
* do smth instead of nothing and stay organized
* WRITE STUFF DOWN
* DON'T GET STUCK ON ONE APPROACH
*/ | [
"[email protected]"
] | |
4a76cac30b1bc4bf6696ab84973927450e320812 | 99ecca1944396fb67de3e64663d464d17c558e8f | /super_template.cpp | 2055f142955090c02af6cc83a611f4302d75b2ba | [] | no_license | fedepousa/codejam-practicas | c1cb88eb3d6c7ec39d33b92038f02616984c2f86 | dff985d02a83d2d196ec70453d0b57d4a2f68acc | refs/heads/master | 2020-12-25T19:03:56.651996 | 2011-05-10T13:38:48 | 2011-05-10T13:38:48 | 32,286,689 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,579 | cpp | #include <vector>
#include <list>
#include <map>
#include <set>
#include <deque>
#include <queue>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <cctype>
#include <string>
#include <cstring>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <string.h>
using namespace std;
#define forn(i, n) for(int i = 0; i < (int)(n); i++)
#define ford(i, n) for(int i = (int)(n) - 1; i >= 0; i--)
#define forab(i, a, b) for (int i = (int)(a); i <= (int)(b); i++)
#define forit(i, a) for (__typeof((a).begin()) i = (a).begin(); i != (a).end(); i++)
#define sz(a) (int)(a).size()
#define pb push_back
#define mp make_pair
#define fs first
#define sc second
#define last(a) int(a.size() - 1)
#define all(a) a.begin(), a.end()
#define zero(a) memset(a, 0, sizeof(a))
#define seta(a,x) memset (a, x, sizeof (a))
#define I (int)
typedef long long int64;//NOTES:int64
typedef unsigned long long uint64;//NOTES:uint64
const double pi=acos(-1.0);//NOTES:pi
const double eps=1e-11;//NOTES:eps
template<class T> inline T sqr(T x){return x*x;}//NOTES:sqr
//Numberic Functions
template<class T> inline T gcd(T a,T b)//NOTES:gcd(
{if(a<0)return gcd(-a,b);if(b<0)return gcd(a,-b);return (b==0)?a:gcd(b,a%b);}
template<class T> inline T lcm(T a,T b)//NOTES:lcm(
{if(a<0)return lcm(-a,b);if(b<0)return lcm(a,-b);return a*(b/gcd(a,b));}
template<class T> inline T euclide(T a,T b,T &x,T &y)//NOTES:euclide(
{if(a<0){T d=euclide(-a,b,x,y);x=-x;return d;}
if(b<0){T d=euclide(a,-b,x,y);y=-y;return d;}
if(b==0){x=1;y=0;return a;}else{T d=euclide(b,a%b,x,y);T t=x;x=y;y=t-(a/b)*y;return d;}}
template<class T> inline vector<pair<T,int> > factorize(T n)//NOTES:factorize(
{vector<pair<T,int> > R;for (T i=2;n>1;){if (n%i==0){int C=0;for (;n%i==0;C++,n/=i);R.push_back(make_pair(i,C));}
i++;if (i>n/i) i=n;}if (n>1) R.push_back(make_pair(n,1));return R;}
template<class T> inline bool isPrimeNumber(T n)//NOTES:isPrimeNumber(
{if(n<=1)return false;for (T i=2;i*i<=n;i++) if (n%i==0) return false;return true;}
template<class T> inline T eularFunction(T n)//NOTES:eularFunction(
{vector<pair<T,int> > R=factorize(n);T r=n;for (int i=0;i<R.size();i++)r=r/R[i].first*(R[i].first-1);return r;}
//Matrix Operations
const int MaxMatrixSize=40;//NOTES:MaxMatrixSize
template<class T> inline void showMatrix(int n,T A[MaxMatrixSize][MaxMatrixSize])//NOTES:showMatrix(
{for (int i=0;i<n;i++){for (int j=0;j<n;j++)cout<<A[i][j];cout<<endl;}}
template<class T> inline T checkMod(T n,T m) {return (n%m+m)%m;}//NOTES:checkMod(
template<class T> inline void identityMatrix(int n,T A[MaxMatrixSize][MaxMatrixSize])//NOTES:identityMatrix(
{for (int i=0;i<n;i++) for (int j=0;j<n;j++) A[i][j]=(i==j)?1:0;}
template<class T> inline void addMatrix(int n,T C[MaxMatrixSize][MaxMatrixSize],T A[MaxMatrixSize][MaxMatrixSize],T B[MaxMatrixSize][MaxMatrixSize])//NOTES:addMatrix(
{for (int i=0;i<n;i++) for (int j=0;j<n;j++) C[i][j]=A[i][j]+B[i][j];}
template<class T> inline void subMatrix(int n,T C[MaxMatrixSize][MaxMatrixSize],T A[MaxMatrixSize][MaxMatrixSize],T B[MaxMatrixSize][MaxMatrixSize])//NOTES:subMatrix(
{for (int i=0;i<n;i++) for (int j=0;j<n;j++) C[i][j]=A[i][j]-B[i][j];}
template<class T> inline void mulMatrix(int n,T C[MaxMatrixSize][MaxMatrixSize],T _A[MaxMatrixSize][MaxMatrixSize],T _B[MaxMatrixSize][MaxMatrixSize])//NOTES:mulMatrix(
{ T A[MaxMatrixSize][MaxMatrixSize],B[MaxMatrixSize][MaxMatrixSize];
for (int i=0;i<n;i++) for (int j=0;j<n;j++) A[i][j]=_A[i][j],B[i][j]=_B[i][j],C[i][j]=0;
for (int i=0;i<n;i++) for (int j=0;j<n;j++) for (int k=0;k<n;k++) C[i][j]+=A[i][k]*B[k][j];}
template<class T> inline void addModMatrix(int n,T m,T C[MaxMatrixSize][MaxMatrixSize],T A[MaxMatrixSize][MaxMatrixSize],T B[MaxMatrixSize][MaxMatrixSize])//NOTES:addModMatrix(
{for (int i=0;i<n;i++) for (int j=0;j<n;j++) C[i][j]=checkMod(A[i][j]+B[i][j],m);}
template<class T> inline void subModMatrix(int n,T m,T C[MaxMatrixSize][MaxMatrixSize],T A[MaxMatrixSize][MaxMatrixSize],T B[MaxMatrixSize][MaxMatrixSize])//NOTES:subModMatrix(
{for (int i=0;i<n;i++) for (int j=0;j<n;j++) C[i][j]=checkMod(A[i][j]-B[i][j],m);}
template<class T> inline T multiplyMod(T a,T b,T m) {return (T)((((int64)(a)*(int64)(b)%(int64)(m))+(int64)(m))%(int64)(m));}//NOTES:multiplyMod(
template<class T> inline void mulModMatrix(int n,T m,T C[MaxMatrixSize][MaxMatrixSize],T _A[MaxMatrixSize][MaxMatrixSize],T _B[MaxMatrixSize][MaxMatrixSize])//NOTES:mulModMatrix(
{ T A[MaxMatrixSize][MaxMatrixSize],B[MaxMatrixSize][MaxMatrixSize];
for (int i=0;i<n;i++) for (int j=0;j<n;j++) A[i][j]=_A[i][j],B[i][j]=_B[i][j],C[i][j]=0;
for (int i=0;i<n;i++) for (int j=0;j<n;j++) for (int k=0;k<n;k++) C[i][j]=(C[i][j]+multiplyMod(A[i][k],B[k][j],m))%m;}
template<class T> inline T powerMod(T p,int e,T m)//NOTES:powerMod(
{if(e==0)return 1%m;else if(e%2==0){T t=powerMod(p,e/2,m);return multiplyMod(t,t,m);}else return multiplyMod(powerMod(p,e-1,m),p,m);}
//Point&Line
double dist(double x1,double y1,double x2,double y2){return sqrt(sqr(x1-x2)+sqr(y1-y2));}//NOTES:dist(
double distR(double x1,double y1,double x2,double y2){return sqr(x1-x2)+sqr(y1-y2);}//NOTES:distR(
template<class T> T cross(T x0,T y0,T x1,T y1,T x2,T y2){return (x1-x0)*(y2-y0)-(x2-x0)*(y1-y0);}//NOTES:cross(
int crossOper(double x0,double y0,double x1,double y1,double x2,double y2)//NOTES:crossOper(
{double t=(x1-x0)*(y2-y0)-(x2-x0)*(y1-y0);if (fabs(t)<=eps) return 0;return (t<0)?-1:1;}
bool isIntersect(double x1,double y1,double x2,double y2,double x3,double y3,double x4,double y4)//NOTES:isIntersect(
{return crossOper(x1,y1,x2,y2,x3,y3)*crossOper(x1,y1,x2,y2,x4,y4)<0 && crossOper(x3,y3,x4,y4,x1,y1)*crossOper(x3,y3,x4,y4,x2,y2)<0;}
bool isMiddle(double s,double m,double t){return fabs(s-m)<=eps || fabs(t-m)<=eps || (s<m)!=(t<m);}//NOTES:isMiddle(
//Translator
bool isUpperCase(char c){return c>='A' && c<='Z';}//NOTES:isUpperCase(
bool isLowerCase(char c){return c>='a' && c<='z';}//NOTES:isLowerCase(
bool isLetter(char c){return c>='A' && c<='Z' || c>='a' && c<='z';}//NOTES:isLetter(
bool isDigit(char c){return c>='0' && c<='9';}//NOTES:isDigit(
char toLowerCase(char c){return (isUpperCase(c))?(c+32):c;}//NOTES:toLowerCase(
char toUpperCase(char c){return (isLowerCase(c))?(c-32):c;}//NOTES:toUpperCase(
template<class T> string toString(T n){ostringstream ost;ost<<n;ost.flush();return ost.str();}//NOTES:toString(
int toInt(string s){int r=0;istringstream sin(s);sin>>r;return r;}//NOTES:toInt(
int64 toInt64(string s){int64 r=0;istringstream sin(s);sin>>r;return r;}//NOTES:toInt64(
double toDouble(string s){double r=0;istringstream sin(s);sin>>r;return r;}//NOTES:toDouble(
template<class T> void stoa(string s,int &n,T A[]){n=0;istringstream sin(s);for(T v;sin>>v;A[n++]=v);}//NOTES:stoa(
template<class T> void atos(int n,T A[],string &s){ostringstream sout;for(int i=0;i<n;i++){if(i>0)sout<<' ';sout<<A[i];}s=sout.str();}//NOTES:atos(
template<class T> void atov(int n,T A[],vector<T> &vi){vi.clear();for (int i=0;i<n;i++) vi.push_back(A[i]);}//NOTES:atov(
template<class T> void vtoa(vector<T> vi,int &n,T A[]){n=vi.size();for (int i=0;i<n;i++)A[i]=vi[i];}//NOTES:vtoa(
template<class T> void stov(string s,vector<T> &vi){vi.clear();istringstream sin(s);for(T v;sin>>v;vi.push_bakc(v));}//NOTES:stov(
template<class T> void vtos(vector<T> vi,string &s){ostringstream sout;for (int i=0;i<vi.size();i++){if(i>0)sout<<' ';sout<<vi[i];}s=sout.str();}//NOTES:vtos(
//Fraction
template<class T> struct Fraction{T a,b;Fraction(T a=0,T b=1);string toString();};//NOTES:Fraction
template<class T> Fraction<T>::Fraction(T a,T b){T d=gcd(a,b);a/=d;b/=d;if (b<0) a=-a,b=-b;this->a=a;this->b=b;}
template<class T> string Fraction<T>::toString(){ostringstream sout;sout<<a<<"/"<<b;return sout.str();}
template<class T> Fraction<T> operator+(Fraction<T> p,Fraction<T> q){return Fraction<T>(p.a*q.b+q.a*p.b,p.b*q.b);}
template<class T> Fraction<T> operator-(Fraction<T> p,Fraction<T> q){return Fraction<T>(p.a*q.b-q.a*p.b,p.b*q.b);}
template<class T> Fraction<T> operator*(Fraction<T> p,Fraction<T> q){return Fraction<T>(p.a*q.a,p.b*q.b);}
template<class T> Fraction<T> operator/(Fraction<T> p,Fraction<T> q){return Fraction<T>(p.a*q.b,p.b*q.a);}
typedef vector<int> vint;
typedef struct _nodo{
vint adjs;
int color;
_nodo(){color=0;}
} nodo;
#define p(a) cout << a << endl
int main()
{
}
| [
"nicovaras22@132d8716-348d-89a7-68be-e1c8d3029e1a"
] | nicovaras22@132d8716-348d-89a7-68be-e1c8d3029e1a |
2816114820980efb09a736075066c1ae8208251b | 7052b9b0e0aea3524dd990bb97eacf3f492e1941 | /CC3000/examples/wlan_mag/wlan_mag.ino | 8e918bddd32ce336dcb8a9f51e0344cdf2d1d7e5 | [
"BSD-2-Clause"
] | permissive | pscholl/Adafruit_CC3000_Library | 64a1d03152ed465d61244286077686f8eed5693c | 1a571ff1a9ca7c482a497e6c94201c38ba09dc4d | refs/heads/master | 2021-01-24T20:02:10.598462 | 2015-06-23T11:35:58 | 2015-06-23T11:35:58 | 19,730,591 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,638 | ino |
/* ATTENTION: need to include Wire and I2CDev libs for
* jNode sensors (LSM9DS0, MPL115A2, VCNL4010, SHT21X)
*
* With this sample we've used 99% of available memory!
*/
#include <Wire.h>
#include <I2Cdev.h>
#include <LSM9DS0.h>
#include <Adafruit_CC3000.h>
#include <SPI.h>
#include "utility/debug.h"
#include "utility/socket.h"
unsigned long time=0;
// These are the interrupt and control pins
// DO NOT CHANGE!!!!
#define ADAFRUIT_CC3000_IRQ 11
#define ADAFRUIT_CC3000_VBAT 13
#define ADAFRUIT_CC3000_CS 10
Adafruit_CC3000 cc3000 = Adafruit_CC3000(ADAFRUIT_CC3000_CS,
ADAFRUIT_CC3000_IRQ,
ADAFRUIT_CC3000_VBAT,
SPI_CLOCK_DIVIDER);
#define WLAN_SSID "fsr_mobi" // cannot be longer than 32 characters!
#define WLAN_PASS "woh0Roo2The7chai"
#define WLAN_SECURITY WLAN_SEC_WPA2 // Security can be WLAN_SEC_UNSEC, WLAN_SEC_WEP, WLAN_SEC_WPA or WLAN_SEC_WPA2
#define LISTEN_PORT 7 // What TCP port to listen on for connections
Adafruit_CC3000_Server quatServer(LISTEN_PORT);
LSM9DS0 sen;
void setup(void)
{
Wire.begin();
Serial.begin(115200);
/* Initialise the module */
//Serial.println(F("\nInitializing..."));
if (!cc3000.begin() || (!cc3000.connectToAP(WLAN_SSID, WLAN_PASS, WLAN_SECURITY)) )
{
Serial.println(F("Failed!"));
while(1);
}
while (!cc3000.checkDHCP())
{
delay(100); // ToDo: Insert a DHCP timeout!
}
/*********************************************************/
/* You can safely remove this to save some flash memory! */
/*********************************************************/
// Serial.println(F("\r\nNOTE: This sketch may cause problems with other sketches"));
// Serial.println(F("since the .disconnect() function is never called, so the"));
// Serial.println(F("AP may refuse connection requests from the CC3000 until a"));
// Serial.println(F("timeout period passes. This is normal behaviour since"));
// Serial.println(F("there isn't an obvious moment to disconnect with a server.\r\n"));
// Start listening for connections
displayConnectionDetails();
quatServer.begin();
sen.initialize();
sen.setGyroFullScale(2000);
sen.setGyroOutputDataRate(LSM9DS0_RATE_95);
sen.setGyroBandwidthCutOffMode(LSM9DS0_BW_HIGH);
sen.setGyroDataFilter(LSM9DS0_LOW_PASS);
sen.setAccRate(LSM9DS0_ACC_RATE_100);
sen.setAccFullScale(LSM9DS0_ACC_8G);
sen.setAccAntiAliasFilterBandwidth(LSM9DS0_ACC_FILTER_BW_50);
sen.setMagFullScale(LSM9DS0_MAG_4_GAUSS);
sen.setMagOutputRate(LSM9DS0_M_ODR_100);
}
#define p(x) client.print(x)
void loop(void)
{
// Try to get a client which is connected.
Adafruit_CC3000_ClientRef client = quatServer.available();
if (client) {
measurement_t m = sen.getMeasurement();
p(m.ax); p("\t"); // acceleration
p(m.ay); p("\t");
p(m.az); p("\t");
p(m.gx); p("\t"); // gyroscope
p(m.gy); p("\t");
p(m.gz); p("\t");
p(m.mx); p("\t"); // magnetometer
p(m.my); p("\t");
p(m.mz); p("\n");
}
}
/**************************************************************************/
/*!
@brief Tries to read the IP address and other connection details
*/
/**************************************************************************/
bool displayConnectionDetails(void)
{
// There is not enough space to include code for printing the full IP
// address, so we just print the last byte of it.
tNetappIpconfigRetArgs ipconfig;
netapp_ipconfig(&ipconfig);
Serial.println(ipconfig.aucIP[0]);
}
| [
"[email protected]"
] | |
4c77e1da3e9e85add1f524b0e0252ea9224f9fd9 | d1e81fa4e8a54b5d5e0e4f85adb79971a8d3b4dd | /TFTTest/TftTest1/UTFT.cpp | 5854898716af44b286f7a598c26aa16e0cbbacfa | [] | no_license | SimonBlasen/Arduino | 8fd753d7c5075765a52b7d2b54e78a69c77886d9 | 623ecd8869231549871795730fa2c96452493d17 | refs/heads/master | 2023-07-06T23:21:55.518542 | 2023-07-02T13:08:47 | 2023-07-02T13:08:47 | 99,805,226 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 28,687 | cpp | /*
UTFT.cpp - Arduino/chipKit library support for Color TFT LCD Boards
Copyright (C)2010-2014 Henning Karlsen. All right reserved
This library is the continuation of my ITDB02_Graph, ITDB02_Graph16
and RGB_GLCD libraries for Arduino and chipKit. As the number of
supported display modules and controllers started to increase I felt
it was time to make a single, universal library as it will be much
easier to maintain in the future.
Basic functionality of this library was origianlly based on the
demo-code provided by ITead studio (for the ITDB02 modules) and
NKC Electronics (for the RGB GLCD module/shield).
This library supports a number of 8bit, 16bit and serial graphic
displays, and will work with both Arduino and chipKit boards. For a
full list of tested display modules and controllers, see the
document UTFT_Supported_display_modules_&_controllers.pdf.
When using 8bit and 16bit display modules there are some
requirements you must adhere to. These requirements can be found
in the document UTFT_Requirements.pdf.
There are no special requirements when using serdial displays.
You can always find the latest version of the library at
http://electronics.henningkarlsen.com/
http://www.buydisplay.com
If you make any modifications or improvements to the code, I would
appreciate that you share the code with me so that I might include
it in the next release. I can be contacted through
http://electronics.henningkarlsen.com/contact.php.
This library is free software; you can redistribute it and/or
modify it under the terms of the CC BY-NC-SA 3.0 license.
Please see the included documents for further information.
Commercial use of this library requires you to buy a license that
will allow commercial use. This includes using the library,
modified or not, as a tool to sell products.
The license applies to all part of the library including the
examples and tools supplied with the library.
*/
#include "UTFT.h"
#include <pins_arduino.h>
// Include hardware-specific functions for the correct MCU
#if defined(__AVR__)
#include <avr/pgmspace.h>
#include "hardware/avr/HW_AVR.h"
#if defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__)
#include "hardware/avr/HW_ATmega1280.h"
#elif defined(__AVR_ATmega328P__)
#include "hardware/avr/HW_ATmega328P.h"
#elif defined(__AVR_ATmega32U4__)
#include "hardware/avr/HW_ATmega32U4.h"
#elif defined(__AVR_ATmega168__)
#error "ATmega168 MCUs are not supported because they have too little flash memory!"
#elif defined(__AVR_ATmega1284P__)
#include "hardware/avr/HW_ATmega1284P.h"
#else
#error "Unsupported AVR MCU!"
#endif
#elif defined(__PIC32MX__)
#include "hardware/pic32/HW_PIC32.h"
#if defined(__32MX320F128H__)
#pragma message("Compiling for chipKIT UNO32 (PIC32MX320F128H)")
#include "hardware/pic32/HW_PIC32MX320F128H.h"
#elif defined(__32MX340F512H__)
#pragma message("Compiling for chipKIT uC32 (PIC32MX340F512H)")
#include "hardware/pic32/HW_PIC32MX340F512H.h"
#elif defined(__32MX795F512L__)
#pragma message("Compiling for chipKIT MAX32 (PIC32MX795F512L)")
#include "hardware/pic32/HW_PIC32MX795F512L.h"
#else
#error "Unsupported PIC32 MCU!"
#endif
#elif defined(__arm__)
#include "hardware/arm/HW_ARM.h"
#if defined(__SAM3X8E__)
#pragma message("Compiling for Arduino Due (AT91SAM3X8E)...")
#include "hardware/arm/HW_SAM3X8E.h"
#elif defined(__MK20DX128__) || defined(__MK20DX256__)
#pragma message("Compiling for Teensy 3.x (MK20DX128VLH7 / MK20DX256VLH7)...")
#include "hardware/arm/HW_MX20DX256.h"
#else
#error "Unsupported ARM MCU!"
#endif
#endif
#include "memorysaver.h"
UTFT::UTFT()
{
}
UTFT::UTFT(byte model, int RS, int WR, int CS, int RST, int SER)
{
word dsx[] = {239, 239, 239, 239, 239, 239, 175, 175, 239, 127, 127, 239, 271, 479, 239, 239, 239, 0, 0, 239, 479, 319, 239, 175, 127, 239, 239, 319, 319, 799, 127, 127, 239, 239, 319, 319, 319, 319, 127};
word dsy[] = {319, 399, 319, 319, 319, 319, 219, 219, 399, 159, 127, 319, 479, 799, 319, 319, 319, 0, 0, 319, 799, 479, 319, 219, 159, 319, 319, 479, 479, 479, 159, 159, 319, 319, 479, 239, 239, 239, 159};
byte dtm[] = {16, 16, 16, 8, 8, 16, 8, SERIAL_4PIN, 16, SERIAL_5PIN, SERIAL_5PIN, 16, 16, 16, 8, 16, LATCHED_16, 0, 0, 8, 16, 16, 16, 8, SERIAL_5PIN, SERIAL_5PIN, SERIAL_4PIN, 16, 16, 16, SERIAL_5PIN, SERIAL_5PIN, 8, 16, 16, 16, SERIAL_5PIN, SERIAL_4PIN, SERIAL_5PIN};
disp_x_size = dsx[model];
disp_y_size = dsy[model];
display_transfer_mode = dtm[model];
display_model = model;
__p1 = RS;
__p2 = WR;
__p3 = CS;
__p4 = RST;
__p5 = SER;
if (display_transfer_mode == SERIAL_4PIN)
{
display_transfer_mode=1;
display_serial_mode=SERIAL_4PIN;
}
if (display_transfer_mode == SERIAL_5PIN)
{
display_transfer_mode=1;
display_serial_mode=SERIAL_5PIN;
}
if (display_transfer_mode!=1)
{
_set_direction_registers(display_transfer_mode);
P_RS = portOutputRegister(digitalPinToPort(RS));
B_RS = digitalPinToBitMask(RS);
P_WR = portOutputRegister(digitalPinToPort(WR));
B_WR = digitalPinToBitMask(WR);
P_CS = portOutputRegister(digitalPinToPort(CS));
B_CS = digitalPinToBitMask(CS);
P_RST = portOutputRegister(digitalPinToPort(RST));
B_RST = digitalPinToBitMask(RST);
if (display_transfer_mode==LATCHED_16)
{
P_ALE = portOutputRegister(digitalPinToPort(SER));
B_ALE = digitalPinToBitMask(SER);
cbi(P_ALE, B_ALE);
pinMode(8,OUTPUT);
digitalWrite(8, LOW);
}
}
else
{
P_SDA = portOutputRegister(digitalPinToPort(RS));
B_SDA = digitalPinToBitMask(RS);
P_SCL = portOutputRegister(digitalPinToPort(WR));
B_SCL = digitalPinToBitMask(WR);
P_CS = portOutputRegister(digitalPinToPort(CS));
B_CS = digitalPinToBitMask(CS);
if (RST != NOTINUSE)
{
P_RST = portOutputRegister(digitalPinToPort(RST));
B_RST = digitalPinToBitMask(RST);
}
if (display_serial_mode!=SERIAL_4PIN)
{
P_RS = portOutputRegister(digitalPinToPort(SER));
B_RS = digitalPinToBitMask(SER);
}
}
}
void UTFT::LCD_Write_COM(char VL)
{
if (display_transfer_mode!=1)
{
cbi(P_RS, B_RS);
LCD_Writ_Bus(0x00,VL,display_transfer_mode);
}
else
LCD_Writ_Bus(0x00,VL,display_transfer_mode);
}
void UTFT::LCD_Write_DATA(char VH,char VL)
{
if (display_transfer_mode!=1)
{ if(display_transfer_mode==16)
{sbi(P_RS, B_RS);
LCD_Writ_Bus(VH,VL,display_transfer_mode);
}
else if(display_transfer_mode==8)
{sbi(P_RS, B_RS);
LCD_Writ_Bus(0x00,VH,display_transfer_mode);
LCD_Writ_Bus(0x00,VL,display_transfer_mode);
}
}
else
{
LCD_Writ_Bus(0x01,VH,display_transfer_mode);
LCD_Writ_Bus(0x01,VL,display_transfer_mode);
}
}
void UTFT::LCD_Write_DATA(char VL)
{
if (display_transfer_mode!=1)
{
sbi(P_RS, B_RS);
LCD_Writ_Bus(0x00,VL,display_transfer_mode);
}
else
LCD_Writ_Bus(0x01,VL,display_transfer_mode);
}
void UTFT::LCD_Write_COM_DATA(char com1,int dat1)
{
LCD_Write_COM(com1);
LCD_Write_DATA(dat1>>8,dat1);
}
void UTFT::InitLCD(byte orientation)
{
orient=orientation;
_hw_special_init();
pinMode(__p1,OUTPUT);
pinMode(__p2,OUTPUT);
pinMode(__p3,OUTPUT);
if (__p4 != NOTINUSE)
pinMode(__p4,OUTPUT);
if ((display_transfer_mode==LATCHED_16) or ((display_transfer_mode==1) and (display_serial_mode==SERIAL_5PIN)))
pinMode(__p5,OUTPUT);
if (display_transfer_mode!=1)
_set_direction_registers(display_transfer_mode);
sbi(P_RST, B_RST);
delay(5);
cbi(P_RST, B_RST);
delay(15);
sbi(P_RST, B_RST);
delay(15);
cbi(P_CS, B_CS);
switch(display_model)
{
/*#ifndef DISABLE_HX8347A
#include "tft_drivers/hx8347a/initlcd.h"
#endif
#ifndef DISABLE_ILI9327
#include "tft_drivers/ili9327/initlcd.h"
#endif
#ifndef DISABLE_SSD1289
#include "tft_drivers/ssd1289/initlcd.h"
#endif
#ifndef DISABLE_ILI9325C
#include "tft_drivers/ili9325c/initlcd.h"
#endif
#ifndef DISABLE_ILI9325D
#include "tft_drivers/ili9325d/default/initlcd.h"
#endif
#ifndef DISABLE_ILI9325D_ALT
#include "tft_drivers/ili9325d/alt/initlcd.h"
#endif
#ifndef DISABLE_HX8340B_8
#include "tft_drivers/hx8340b/8/initlcd.h"
#endif
#ifndef DISABLE_HX8340B_S
#include "tft_drivers/hx8340b/s/initlcd.h"
#endif
#ifndef DISABLE_ST7735
#include "tft_drivers/st7735/std/initlcd.h"
#endif
#ifndef DISABLE_ST7735_ALT
#include "tft_drivers/st7735/alt/initlcd.h"
#endif
#ifndef DISABLE_PCF8833
#include "tft_drivers/pcf8833/initlcd.h"
#endif
#ifndef DISABLE_S1D19122
#include "tft_drivers/s1d19122/initlcd.h"
#endif
#ifndef DISABLE_HX8352A
#include "tft_drivers/hx8352a/initlcd.h"
#endif*/
#ifndef DISABLE_SSD1963_480
#include "tft_drivers/ssd1963/480/initlcd.h"
#endif
#ifndef DISABLE_SSD1963_800
#include "tft_drivers/ssd1963/800/initlcd.h"
#endif
#ifndef DISABLE_SSD1963_800_ALT
#include "tft_drivers/ssd1963/800alt/initlcd.h"
#endif
/*#ifndef DISABLE_S6D1121
#include "tft_drivers/s6d1121/initlcd.h"
#endif
#ifndef DISABLE_ILI9481
#include "tft_drivers/ili9481/initlcd.h"
#endif
#ifndef DISABLE_S6D0164
#include "tft_drivers/s6d0164/initlcd.h"
#endif
#ifndef DISABLE_ST7735S
#include "tft_drivers/st7735s/initlcd.h"
#endif*/
#ifndef DISABLE_ILI9341_S4P
#include "tft_drivers/ili9341/s4p/initlcd.h"
#endif
#ifndef DISABLE_ILI9341_S5P
#include "tft_drivers/ili9341/s5p/initlcd.h"
#endif
/*#ifndef DISABLE_R61581
#include "tft_drivers/r61581/initlcd.h"
#endif
#ifndef DISABLE_ILI9486
#include "tft_drivers/ili9486/initlcd.h"
#endif
#ifndef DISABLE_CPLD
#include "tft_drivers/cpld/initlcd.h"
#endif
#ifndef DISABLE_HX8353C
#include "tft_drivers/hx8353c/initlcd.h"
#endif*/
#ifndef DISABLE_ILI9341_8
#include "tft_drivers/ili9341/8B/initlcd.h"
#endif
#ifndef DISABLE_ILI9341_16
#include "tft_drivers/ili9341/16B/initlcd.h"
#endif
#ifndef DISABLE_ILI9488_16
#include "tft_drivers/ili9488/16B/initlcd.h"
#endif
#ifndef DISABLE_ILI9342_16
#include "tft_drivers/ili9342/16B/initlcd.h"
#endif
#ifndef DISABLE_ILI9342_S4P
#include "tft_drivers/ili9342/s4p/initlcd.h"
#endif
#ifndef DISABLE_ILI9342_S5P
#include "tft_drivers/ili9342/s5p/initlcd.h"
#endif
#ifndef DISABLE_ILI9163_S5P
#include "tft_drivers/ili9163/s5p/initlcd.h"
#endif
}
sbi (P_CS, B_CS);
setColor(255, 255, 255);
setBackColor(0, 0, 0);
cfont.font=0;
_transparent = false;
}
void UTFT::setXY(word x1, word y1, word x2, word y2)
{
if (orient==LANDSCAPE)
{
swap(word, x1, y1);
swap(word, x2, y2)
y1=disp_y_size-y1;
y2=disp_y_size-y2;
swap(word, y1, y2)
}
switch(display_model)
{
/*#ifndef DISABLE_HX8347A
#include "tft_drivers/hx8347a/setxy.h"
#endif
#ifndef DISABLE_HX8352A
#include "tft_drivers/hx8352a/setxy.h"
#endif
#ifndef DISABLE_ILI9327
#include "tft_drivers/ili9327/setxy.h"
#endif
#ifndef DISABLE_SSD1289
#include "tft_drivers/ssd1289/setxy.h"
#endif
#ifndef DISABLE_ILI9325C
#include "tft_drivers/ili9325c/setxy.h"
#endif
#ifndef DISABLE_ILI9325D
#include "tft_drivers/ili9325d/default/setxy.h"
#endif
#ifndef DISABLE_ILI9325D_ALT
#include "tft_drivers/ili9325d/alt/setxy.h"
#endif
#ifndef DISABLE_HX8340B_8
#include "tft_drivers/hx8340b/8/setxy.h"
#endif
#ifndef DISABLE_HX8340B_S
#include "tft_drivers/hx8340b/s/setxy.h"
#endif
#ifndef DISABLE_ST7735
#include "tft_drivers/st7735/std/setxy.h"
#endif
#ifndef DISABLE_ST7735_ALT
#include "tft_drivers/st7735/alt/setxy.h"
#endif
#ifndef DISABLE_S1D19122
#include "tft_drivers/s1d19122/setxy.h"
#endif*/
#ifndef DISABLE_PCF8833
#include "tft_drivers/pcf8833/setxy.h"
#endif
#ifndef DISABLE_SSD1963_480
#include "tft_drivers/ssd1963/480/setxy.h"
#endif
#ifndef DISABLE_SSD1963_800
#include "tft_drivers/ssd1963/800/setxy.h"
#endif
#ifndef DISABLE_SSD1963_800_ALT
#include "tft_drivers/ssd1963/800alt/setxy.h"
#endif
#ifndef DISABLE_S6D1121
#include "tft_drivers/s6d1121/setxy.h"
#endif
#ifndef DISABLE_ILI9481
#include "tft_drivers/ili9481/setxy.h"
#endif
#ifndef DISABLE_S6D0164
#include "tft_drivers/s6d0164/setxy.h"
#endif
#ifndef DISABLE_ST7735S
#include "tft_drivers/st7735s/setxy.h"
#endif
#ifndef DISABLE_ILI9341_S4P
#include "tft_drivers/ili9341/s4p/setxy.h"
#endif
#ifndef DISABLE_ILI9341_S5P
#include "tft_drivers/ili9341/s5p/setxy.h"
#endif
#ifndef DISABLE_R61581
#include "tft_drivers/r61581/setxy.h"
#endif
#ifndef DISABLE_ILI9486
#include "tft_drivers/ili9486/setxy.h"
#endif
#ifndef DISABLE_CPLD
#include "tft_drivers/cpld/setxy.h"
#endif
#ifndef DISABLE_HX8353C
#include "tft_drivers/hx8353c/setxy.h"
#endif
#ifndef DISABLE_ILI9341_8
#include "tft_drivers/ili9341/8B/setxy.h"
#endif
#ifndef DISABLE_ILI9341_16
#include "tft_drivers/ili9341/16B/setxy.h"
#endif
#ifndef DISABLE_ILI9488_16
#include "tft_drivers/ili9488/16B/setxy.h"
#endif
#ifndef DISABLE_ILI9342_16
#include "tft_drivers/ili9342/16B/setxy.h"
#endif
#ifndef DISABLE_ILI9342_S4P
#include "tft_drivers/ili9342/s4p/setxy.h"
#endif
#ifndef DISABLE_ILI9342_S5P
#include "tft_drivers/ili9342/s5p/setxy.h"
#endif
#ifndef DISABLE_ILI9163_S5P
#include "tft_drivers/ili9163/s5p/setxy.h"
#endif
}
}
void UTFT::clrXY()
{
if (orient==PORTRAIT)
setXY(0,0,disp_x_size,disp_y_size);
else
setXY(0,0,disp_y_size,disp_x_size);
}
void UTFT::drawRect(int x1, int y1, int x2, int y2)
{
if (x1>x2)
{
swap(int, x1, x2);
}
if (y1>y2)
{
swap(int, y1, y2);
}
drawHLine(x1, y1, x2-x1);
drawHLine(x1, y2, x2-x1);
drawVLine(x1, y1, y2-y1);
drawVLine(x2, y1, y2-y1);
}
void UTFT::drawRoundRect(int x1, int y1, int x2, int y2)
{
if (x1>x2)
{
swap(int, x1, x2);
}
if (y1>y2)
{
swap(int, y1, y2);
}
if ((x2-x1)>4 && (y2-y1)>4)
{
drawPixel(x1+1,y1+1);
drawPixel(x2-1,y1+1);
drawPixel(x1+1,y2-1);
drawPixel(x2-1,y2-1);
drawHLine(x1+2, y1, x2-x1-4);
drawHLine(x1+2, y2, x2-x1-4);
drawVLine(x1, y1+2, y2-y1-4);
drawVLine(x2, y1+2, y2-y1-4);
}
}
void UTFT::fillRect(int x1, int y1, int x2, int y2)
{
if (x1>x2)
{
swap(int, x1, x2);
}
if (y1>y2)
{
swap(int, y1, y2);
}
if (display_transfer_mode==16)
{
cbi(P_CS, B_CS);
setXY(x1, y1, x2, y2);
sbi(P_RS, B_RS);
_fast_fill_16(fch,fcl,((long(x2-x1)+1)*(long(y2-y1)+1)));
sbi(P_CS, B_CS);
}
else if ((display_transfer_mode==8) and (fch==fcl))
{
cbi(P_CS, B_CS);
setXY(x1, y1, x2, y2);
sbi(P_RS, B_RS);
_fast_fill_8(fch,((long(x2-x1)+1)*(long(y2-y1)+1)));
sbi(P_CS, B_CS);
}
else
{
if (orient==PORTRAIT)
{
for (int i=0; i<((y2-y1)/2)+1; i++)
{
drawHLine(x1, y1+i, x2-x1);
drawHLine(x1, y2-i, x2-x1);
}
}
else
{
for (int i=0; i<((x2-x1)/2)+1; i++)
{
drawVLine(x1+i, y1, y2-y1);
drawVLine(x2-i, y1, y2-y1);
}
}
}
}
void UTFT::fillRoundRect(int x1, int y1, int x2, int y2)
{
if (x1>x2)
{
swap(int, x1, x2);
}
if (y1>y2)
{
swap(int, y1, y2);
}
if ((x2-x1)>4 && (y2-y1)>4)
{
for (int i=0; i<((y2-y1)/2)+1; i++)
{
switch(i)
{
case 0:
drawHLine(x1+2, y1+i, x2-x1-4);
drawHLine(x1+2, y2-i, x2-x1-4);
break;
case 1:
drawHLine(x1+1, y1+i, x2-x1-2);
drawHLine(x1+1, y2-i, x2-x1-2);
break;
default:
drawHLine(x1, y1+i, x2-x1);
drawHLine(x1, y2-i, x2-x1);
}
}
}
}
void UTFT::drawCircle(int x, int y, int radius)
{
int f = 1 - radius;
int ddF_x = 1;
int ddF_y = -2 * radius;
int x1 = 0;
int y1 = radius;
cbi(P_CS, B_CS);
setXY(x, y + radius, x, y + radius);
LCD_Write_DATA(fch,fcl);
setXY(x, y - radius, x, y - radius);
LCD_Write_DATA(fch,fcl);
setXY(x + radius, y, x + radius, y);
LCD_Write_DATA(fch,fcl);
setXY(x - radius, y, x - radius, y);
LCD_Write_DATA(fch,fcl);
while(x1 < y1)
{
if(f >= 0)
{
y1--;
ddF_y += 2;
f += ddF_y;
}
x1++;
ddF_x += 2;
f += ddF_x;
setXY(x + x1, y + y1, x + x1, y + y1);
LCD_Write_DATA(fch,fcl);
setXY(x - x1, y + y1, x - x1, y + y1);
LCD_Write_DATA(fch,fcl);
setXY(x + x1, y - y1, x + x1, y - y1);
LCD_Write_DATA(fch,fcl);
setXY(x - x1, y - y1, x - x1, y - y1);
LCD_Write_DATA(fch,fcl);
setXY(x + y1, y + x1, x + y1, y + x1);
LCD_Write_DATA(fch,fcl);
setXY(x - y1, y + x1, x - y1, y + x1);
LCD_Write_DATA(fch,fcl);
setXY(x + y1, y - x1, x + y1, y - x1);
LCD_Write_DATA(fch,fcl);
setXY(x - y1, y - x1, x - y1, y - x1);
LCD_Write_DATA(fch,fcl);
}
sbi(P_CS, B_CS);
clrXY();
}
void UTFT::fillCircle(int x, int y, int radius)
{
for(int y1=-radius; y1<=0; y1++)
for(int x1=-radius; x1<=0; x1++)
if(x1*x1+y1*y1 <= radius*radius)
{
drawHLine(x+x1, y+y1, 2*(-x1));
drawHLine(x+x1, y-y1, 2*(-x1));
break;
}
}
void UTFT::clrScr()
{
long i;
cbi(P_CS, B_CS);
clrXY();
if (display_transfer_mode!=1)
sbi(P_RS, B_RS);
if (display_transfer_mode==16)
_fast_fill_16(0,0,((disp_x_size+1)*(disp_y_size+1)));
else if (display_transfer_mode==8)
_fast_fill_8(0,((disp_x_size+1)*(disp_y_size+1)));
else
{
for (i=0; i<((disp_x_size+1)*(disp_y_size+1)); i++)
{
if (display_transfer_mode!=1)
LCD_Writ_Bus(0,0,display_transfer_mode);
else
{
LCD_Writ_Bus(1,0,display_transfer_mode);
LCD_Writ_Bus(1,0,display_transfer_mode);
}
}
}
sbi(P_CS, B_CS);
}
void UTFT::fillScr(byte r, byte g, byte b)
{
word color = ((r&248)<<8 | (g&252)<<3 | (b&248)>>3);
fillScr(color);
}
void UTFT::fillScr(word color)
{
long i;
char ch, cl;
ch=byte(color>>8);
cl=byte(color & 0xFF);
cbi(P_CS, B_CS);
clrXY();
if (display_transfer_mode!=1)
sbi(P_RS, B_RS);
if (display_transfer_mode==16)
_fast_fill_16(ch,cl,((disp_x_size+1)*(disp_y_size+1)));
else if ((display_transfer_mode==8) and (ch==cl))
_fast_fill_8(ch,((disp_x_size+1)*(disp_y_size+1)));
else
{
for (i=0; i<((disp_x_size+1)*(disp_y_size+1)); i++)
{
if (display_transfer_mode!=1)
{ if(display_transfer_mode==16)
{
LCD_Writ_Bus(ch,cl,display_transfer_mode);
}
else
{
LCD_Writ_Bus(0x00,ch,display_transfer_mode);
LCD_Writ_Bus(0x00,cl,display_transfer_mode);
}
}
else
{
LCD_Writ_Bus(1,ch,display_transfer_mode);
LCD_Writ_Bus(1,cl,display_transfer_mode);
}
}
}
sbi(P_CS, B_CS);
}
void UTFT::setColor(byte r, byte g, byte b)
{
fch=((r&248)|g>>5);
fcl=((g&28)<<3|b>>3);
// fch=((r&0x1f<<3)|(g&0x3f>>3));
// fcl=((g&0x3f)<<5|(b&0x1f));
}
void UTFT::setColor(word color)
{
fch=byte(color>>8);
fcl=byte(color & 0xFF);
}
word UTFT::getColor()
{
return (fch<<8) | fcl;
}
void UTFT::setBackColor(byte r, byte g, byte b)
{
bch=((r&248)|g>>5);
bcl=((g&28)<<3|b>>3);
_transparent=false;
}
void UTFT::setBackColor(uint32_t color)
{
if (color==VGA_TRANSPARENT)
_transparent=true;
else
{
bch=byte(color>>8);
bcl=byte(color & 0xFF);
_transparent=false;
}
}
word UTFT::getBackColor()
{
return (bch<<8) | bcl;
}
void UTFT::setPixel(word color)
{
LCD_Write_DATA((color>>8),(color&0xFF)); // rrrrrggggggbbbbb
}
void UTFT::drawPixel(int x, int y)
{
cbi(P_CS, B_CS);
setXY(x, y, x, y);
setPixel((fch<<8)|fcl);
sbi(P_CS, B_CS);
clrXY();
}
void UTFT::drawLine(int x1, int y1, int x2, int y2)
{
if (y1==y2)
drawHLine(x1, y1, x2-x1);
else if (x1==x2)
drawVLine(x1, y1, y2-y1);
else
{
unsigned int dx = (x2 > x1 ? x2 - x1 : x1 - x2);
short xstep = x2 > x1 ? 1 : -1;
unsigned int dy = (y2 > y1 ? y2 - y1 : y1 - y2);
short ystep = y2 > y1 ? 1 : -1;
int col = x1, row = y1;
cbi(P_CS, B_CS);
if (dx < dy)
{
int t = - (dy >> 1);
while (true)
{
setXY (col, row, col, row);
LCD_Write_DATA (fch, fcl);
if (row == y2)
return;
row += ystep;
t += dx;
if (t >= 0)
{
col += xstep;
t -= dy;
}
}
}
else
{
int t = - (dx >> 1);
while (true)
{
setXY (col, row, col, row);
LCD_Write_DATA (fch, fcl);
if (col == x2)
return;
col += xstep;
t += dy;
if (t >= 0)
{
row += ystep;
t -= dx;
}
}
}
sbi(P_CS, B_CS);
}
clrXY();
}
void UTFT::drawHLine(int x, int y, int l)
{
if (l<0)
{
l = -l;
x -= l;
}
cbi(P_CS, B_CS);
setXY(x, y, x+l, y);
if (display_transfer_mode == 16)
{
sbi(P_RS, B_RS);
_fast_fill_16(fch,fcl,l);
}
else if ((display_transfer_mode==8) and (fch==fcl))
{
sbi(P_RS, B_RS);
_fast_fill_8(fch,l);
}
else
{
for (int i=0; i<l+1; i++)
{
LCD_Write_DATA(fch, fcl);
}
}
sbi(P_CS, B_CS);
clrXY();
}
void UTFT::drawVLine(int x, int y, int l)
{
if (l<0)
{
l = -l;
y -= l;
}
cbi(P_CS, B_CS);
setXY(x, y, x, y+l);
if (display_transfer_mode == 16)
{
sbi(P_RS, B_RS);
_fast_fill_16(fch,fcl,l);
}
else if ((display_transfer_mode==8) and (fch==fcl))
{
sbi(P_RS, B_RS);
_fast_fill_8(fch,l);
}
else
{
for (int i=0; i<l+1; i++)
{
LCD_Write_DATA(fch, fcl);
}
}
sbi(P_CS, B_CS);
clrXY();
}
void UTFT::printChar(byte c, int x, int y)
{
byte i,ch;
word j;
word temp;
cbi(P_CS, B_CS);
if (!_transparent)
{
if (orient==PORTRAIT)
{
setXY(x,y,x+cfont.x_size-1,y+cfont.y_size-1);
temp=((c-cfont.offset)*((cfont.x_size/8)*cfont.y_size))+4;
for(j=0;j<((cfont.x_size/8)*cfont.y_size);j++)
{
ch=pgm_read_byte(&cfont.font[temp]);
for(i=0;i<8;i++)
{
if((ch&(1<<(7-i)))!=0)
{
setPixel((fch<<8)|fcl);
}
else
{
setPixel((bch<<8)|bcl);
}
}
temp++;
}
}
else
{
temp=((c-cfont.offset)*((cfont.x_size/8)*cfont.y_size))+4;
for(j=0;j<((cfont.x_size/8)*cfont.y_size);j+=(cfont.x_size/8))
{
setXY(x,y+(j/(cfont.x_size/8)),x+cfont.x_size-1,y+(j/(cfont.x_size/8)));
for (int zz=(cfont.x_size/8)-1; zz>=0; zz--)
{
ch=pgm_read_byte(&cfont.font[temp+zz]);
for(i=0;i<8;i++)
{
if((ch&(1<<i))!=0)
{
setPixel((fch<<8)|fcl);
}
else
{
setPixel((bch<<8)|bcl);
}
}
}
temp+=(cfont.x_size/8);
}
}
}
else
{
temp=((c-cfont.offset)*((cfont.x_size/8)*cfont.y_size))+4;
for(j=0;j<cfont.y_size;j++)
{
for (int zz=0; zz<(cfont.x_size/8); zz++)
{
ch=pgm_read_byte(&cfont.font[temp+zz]);
for(i=0;i<8;i++)
{
setXY(x+i+(zz*8),y+j,x+i+(zz*8)+1,y+j+1);
if((ch&(1<<(7-i)))!=0)
{
setPixel((fch<<8)|fcl);
}
}
}
temp+=(cfont.x_size/8);
}
}
sbi(P_CS, B_CS);
clrXY();
}
void UTFT::rotateChar(byte c, int x, int y, int pos, int deg)
{
byte i,j,ch;
word temp;
int newx,newy;
double radian;
radian=deg*0.0175;
cbi(P_CS, B_CS);
temp=((c-cfont.offset)*((cfont.x_size/8)*cfont.y_size))+4;
for(j=0;j<cfont.y_size;j++)
{
for (int zz=0; zz<(cfont.x_size/8); zz++)
{
ch=pgm_read_byte(&cfont.font[temp+zz]);
for(i=0;i<8;i++)
{
newx=x+(((i+(zz*8)+(pos*cfont.x_size))*cos(radian))-((j)*sin(radian)));
newy=y+(((j)*cos(radian))+((i+(zz*8)+(pos*cfont.x_size))*sin(radian)));
setXY(newx,newy,newx+1,newy+1);
if((ch&(1<<(7-i)))!=0)
{
setPixel((fch<<8)|fcl);
}
else
{
if (!_transparent)
setPixel((bch<<8)|bcl);
}
}
}
temp+=(cfont.x_size/8);
}
sbi(P_CS, B_CS);
clrXY();
}
void UTFT::print(char *st, int x, int y, int deg)
{
int stl, i;
stl = strlen(st);
if (orient==PORTRAIT)
{
if (x==RIGHT)
x=(disp_x_size+1)-(stl*cfont.x_size);
if (x==CENTER)
x=((disp_x_size+1)-(stl*cfont.x_size))/2;
}
else
{
if (x==RIGHT)
x=(disp_y_size+1)-(stl*cfont.x_size);
if (x==CENTER)
x=((disp_y_size+1)-(stl*cfont.x_size))/2;
}
for (i=0; i<stl; i++)
if (deg==0)
printChar(*st++, x + (i*(cfont.x_size)), y);
else
rotateChar(*st++, x, y, i, deg);
}
void UTFT::print(String st, int x, int y, int deg)
{
char buf[st.length()+1];
st.toCharArray(buf, st.length()+1);
print(buf, x, y, deg);
}
void UTFT::printNumI(long num, int x, int y, int length, char filler)
{
char buf[25];
char st[27];
boolean neg=false;
int c=0, f=0;
if (num==0)
{
if (length!=0)
{
for (c=0; c<(length-1); c++)
st[c]=filler;
st[c]=48;
st[c+1]=0;
}
else
{
st[0]=48;
st[1]=0;
}
}
else
{
if (num<0)
{
neg=true;
num=-num;
}
while (num>0)
{
buf[c]=48+(num % 10);
c++;
num=(num-(num % 10))/10;
}
buf[c]=0;
if (neg)
{
st[0]=45;
}
if (length>(c+neg))
{
for (int i=0; i<(length-c-neg); i++)
{
st[i+neg]=filler;
f++;
}
}
for (int i=0; i<c; i++)
{
st[i+neg+f]=buf[c-i-1];
}
st[c+neg+f]=0;
}
print(st,x,y);
}
void UTFT::printNumF(double num, byte dec, int x, int y, char divider, int length, char filler)
{
char st[27];
boolean neg=false;
if (dec<1)
dec=1;
else if (dec>5)
dec=5;
if (num<0)
neg = true;
_convert_float(st, num, length, dec);
if (divider != '.')
{
for (int i=0; i<sizeof(st); i++)
if (st[i]=='.')
st[i]=divider;
}
if (filler != ' ')
{
if (neg)
{
st[0]='-';
for (int i=1; i<sizeof(st); i++)
if ((st[i]==' ') || (st[i]=='-'))
st[i]=filler;
}
else
{
for (int i=0; i<sizeof(st); i++)
if (st[i]==' ')
st[i]=filler;
}
}
print(st,x,y);
}
void UTFT::setFont(uint8_t* font)
{
cfont.font=font;
cfont.x_size=font[0];//fontbyte(0);
cfont.y_size=font[1];//fontbyte(1);
cfont.offset=font[2];//fontbyte(2);
cfont.numchars=font[3];//fontbyte(3);
}
uint8_t* UTFT::getFont()
{
return cfont.font;
}
uint8_t UTFT::getFontXsize()
{
return cfont.x_size;
}
uint8_t UTFT::getFontYsize()
{
return cfont.y_size;
}
/*void UTFT::drawBitmap(int x, int y, int sx, int sy, bitmapdatatype data, int scale)
{
unsigned int col;
int tx, ty, tc, tsx, tsy;
if (scale==1)
{
if (orient==PORTRAIT)
{
cbi(P_CS, B_CS);
setXY(x, y, x+sx-1, y+sy-1);
for (tc=0; tc<(sx*sy); tc++)
{
col=pgm_read_word(&data[tc]);
LCD_Write_DATA(col>>8,col & 0xff);
}
sbi(P_CS, B_CS);
}
else
{
cbi(P_CS, B_CS);
for (ty=0; ty<sy; ty++)
{
setXY(x, y+ty, x+sx-1, y+ty);
for (tx=sx-1; tx>=0; tx--)
{
col=pgm_read_word(&data[(ty*sx)+tx]);
LCD_Write_DATA(col>>8,col & 0xff);
}
}
sbi(P_CS, B_CS);
}
}
else
{
if (orient==PORTRAIT)
{
cbi(P_CS, B_CS);
for (ty=0; ty<sy; ty++)
{
setXY(x, y+(ty*scale), x+((sx*scale)-1), y+(ty*scale)+scale);
for (tsy=0; tsy<scale; tsy++)
for (tx=0; tx<sx; tx++)
{
col=pgm_read_word(&data[(ty*sx)+tx]);
for (tsx=0; tsx<scale; tsx++)
LCD_Write_DATA(col>>8,col & 0xff);
}
}
sbi(P_CS, B_CS);
}
else
{
cbi(P_CS, B_CS);
for (ty=0; ty<sy; ty++)
{
for (tsy=0; tsy<scale; tsy++)
{
setXY(x, y+(ty*scale)+tsy, x+((sx*scale)-1), y+(ty*scale)+tsy);
for (tx=sx-1; tx>=0; tx--)
{
col=pgm_read_word(&data[(ty*sx)+tx]);
for (tsx=0; tsx<scale; tsx++)
LCD_Write_DATA(col>>8,col & 0xff);
}
}
}
sbi(P_CS, B_CS);
}
}
clrXY();
}
void UTFT::drawBitmap(int x, int y, int sx, int sy, bitmapdatatype data, int deg, int rox, int roy)
{
unsigned int col;
int tx, ty, newx, newy;
double radian;
radian=deg*0.0175;
if (deg==0)
drawBitmap(x, y, sx, sy, data);
else
{
cbi(P_CS, B_CS);
for (ty=0; ty<sy; ty++)
for (tx=0; tx<sx; tx++)
{
col=pgm_read_word(&data[(ty*sx)+tx]);
newx=x+rox+(((tx-rox)*cos(radian))-((ty-roy)*sin(radian)));
newy=y+roy+(((ty-roy)*cos(radian))+((tx-rox)*sin(radian)));
setXY(newx, newy, newx, newy);
LCD_Write_DATA(col>>8,col & 0xff);
}
sbi(P_CS, B_CS);
}
clrXY();
}*/
void UTFT::lcdOff()
{
cbi(P_CS, B_CS);
switch (display_model)
{
case PCF8833:
LCD_Write_COM(0x28);
break;
case CPLD:
LCD_Write_COM_DATA(0x01,0x0000);
LCD_Write_COM(0x0F);
break;
}
sbi(P_CS, B_CS);
}
void UTFT::lcdOn()
{
cbi(P_CS, B_CS);
switch (display_model)
{
case PCF8833:
LCD_Write_COM(0x29);
break;
case CPLD:
LCD_Write_COM_DATA(0x01,0x0010);
LCD_Write_COM(0x0F);
break;
}
sbi(P_CS, B_CS);
}
void UTFT::setContrast(char c)
{
cbi(P_CS, B_CS);
switch (display_model)
{
case PCF8833:
if (c>64) c=64;
LCD_Write_COM(0x25);
LCD_Write_DATA(c);
break;
}
sbi(P_CS, B_CS);
}
int UTFT::getDisplayXSize()
{
if (orient==PORTRAIT)
return disp_x_size+1;
else
return disp_y_size+1;
}
int UTFT::getDisplayYSize()
{
if (orient==PORTRAIT)
return disp_y_size+1;
else
return disp_x_size+1;
}
void UTFT::setBrightness(byte br)
{
cbi(P_CS, B_CS);
switch (display_model)
{
case CPLD:
if (br>16) br=16;
LCD_Write_COM_DATA(0x01,br);
LCD_Write_COM(0x0F);
break;
}
sbi(P_CS, B_CS);
}
void UTFT::setDisplayPage(byte page)
{
cbi(P_CS, B_CS);
switch (display_model)
{
case CPLD:
if (page>7) page=7;
LCD_Write_COM_DATA(0x04,page);
LCD_Write_COM(0x0F);
break;
}
sbi(P_CS, B_CS);
}
void UTFT::setWritePage(byte page)
{
cbi(P_CS, B_CS);
switch (display_model)
{
case CPLD:
if (page>7) page=7;
LCD_Write_COM_DATA(0x05,page);
LCD_Write_COM(0x0F);
break;
}
sbi(P_CS, B_CS);
}
| [
"[email protected]"
] | |
1b1db33275ca9020ab39e1df49702ad2e1dfa7d8 | e1c8e3767bac2d7d2bb83e56aa46bfad6286f734 | /games/anarchy/fireDepartment.h | 6856c29f0c39dee9a08ac9c174999225c4c62dfb | [
"MIT"
] | permissive | joeykuhn/Joueur.cpp | df2709357aae71be84100bf8c39f859ffe965a86 | 9b3f9d9a37f79aad958f179cb89c4f08706387b8 | refs/heads/master | 2021-01-24T09:19:20.206407 | 2016-09-27T23:04:41 | 2016-09-27T23:04:41 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,872 | h | // Generated by Creer at 01:31AM on December 23, 2015 UTC, git hash: '1b69e788060071d644dd7b8745dca107577844e1'
// Can put out fires completely.
#ifndef JOUEUR_ANARCHY_FIREDEPARTMENT_H
#define JOUEUR_ANARCHY_FIREDEPARTMENT_H
#include "anarchy.h"
#include "building.h"
// <<-- Creer-Merge: includes -->> - Code you add between this comment and the end comment will be preserved between Creer re-runs.
// you can add addtional #includes(s) here.
// <<-- /Creer-Merge: includes -->>
/// <summary>
/// Can put out fires completely.
/// </summary>
class Anarchy::FireDepartment : public Anarchy::Building
{
friend Anarchy::GameManager;
protected:
virtual void deltaUpdateField(const std::string& fieldName, boost::property_tree::ptree& delta);
FireDepartment() {};
~FireDepartment() {};
public:
/// <summary>
/// The amount of fire removed from a building when bribed to extinguish a building.
/// </summary>
int fireExtinguished;
// <<-- Creer-Merge: fields -->> - Code you add between this comment and the end comment will be preserved between Creer re-runs.
// you can add addtional fields(s) here. None of them will be tracked or updated by the server.
// <<-- /Creer-Merge: fields -->>
/// <summary>
/// Bribes this FireDepartment to extinguish the some of the fire in a building.
/// </summary>
/// <param name="building">The Building you want to extinguish.</param>
/// <returns>true if the bribe worked, false otherwise</returns>
bool extinguish(Anarchy::Building* building);
// <<-- Creer-Merge: methods -->> - Code you add between this comment and the end comment will be preserved between Creer re-runs.
// you can add addtional method(s) here.
// <<-- /Creer-Merge: methods -->>
};
#endif
| [
"[email protected]"
] | |
0811a45932f781306c79c102a317affdaf89c095 | fae45a23a885b72cd27c0ad1b918ad754b5de9fd | /benchmarks/shenango/parsec/pkgs/tools/cmake/src/Source/cmSeparateArgumentsCommand.cxx | ea6f065af9c9f954ceb35d70187934ff3500acf4 | [
"Apache-2.0",
"LicenseRef-scancode-free-unknown",
"LicenseRef-scancode-other-permissive",
"MIT"
] | permissive | bitslab/CompilerInterrupts | 6678700651c7c83fd06451c94188716e37e258f0 | 053a105eaf176b85b4c0d5e796ac1d6ee02ad41b | refs/heads/main | 2023-06-24T18:09:43.148845 | 2021-07-26T17:32:28 | 2021-07-26T17:32:28 | 342,868,949 | 3 | 3 | MIT | 2021-07-19T15:38:30 | 2021-02-27T13:57:16 | C | UTF-8 | C++ | false | false | 1,314 | cxx | /*=========================================================================
Program: CMake - Cross-Platform Makefile Generator
Module: $RCSfile: cmSeparateArgumentsCommand.cxx,v $
Language: C++
Date: $Date: 2012/03/29 17:21:08 $
Version: $Revision: 1.1.1.1 $
Copyright (c) 2002 Kitware, Inc., Insight Consortium. All rights reserved.
See Copyright.txt or http://www.cmake.org/HTML/Copyright.html 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 notices for more information.
=========================================================================*/
#include "cmSeparateArgumentsCommand.h"
// cmSeparateArgumentsCommand
bool cmSeparateArgumentsCommand
::InitialPass(std::vector<std::string> const& args, cmExecutionStatus &)
{
if(args.size() != 1 )
{
this->SetError("called with incorrect number of arguments");
return false;
}
const char* cacheValue = this->Makefile->GetDefinition(args[0].c_str());
if(!cacheValue)
{
return true;
}
std::string value = cacheValue;
cmSystemTools::ReplaceString(value," ", ";");
this->Makefile->AddDefinition(args[0].c_str(), value.c_str());
return true;
}
| [
"[email protected]"
] | |
0ebecc26962b4a030a103e91a8befd0cfbb7a7ea | 95273e09057dea3ee4d8b2c7405c62c511d76e6c | /src/ESPectroBase_GpioEx.cpp | cf2412036d67e8a1d928b4cc1a1afd5715308196 | [] | no_license | alwint3r/EspX | a3af26c86f7bdace1adfe8f3ab5b50a8344bcc05 | eed8cb93a18a11a6b72be85326e2fef900427dd7 | refs/heads/master | 2020-05-29T08:40:33.140368 | 2017-01-07T19:04:28 | 2017-01-07T19:04:28 | 69,655,952 | 0 | 0 | null | 2016-09-30T10:02:22 | 2016-09-30T10:02:22 | null | UTF-8 | C++ | false | false | 979 | cpp | //
// Created by Andri Yadi on 8/1/16.
//
#include "ESPectroBase_GpioEx.h"
ESPectroBase_GpioEx::ESPectroBase_GpioEx(uint8_t address):
SX1508(address), i2cDeviceAddress_(address)
{
}
ESPectroBase_GpioEx::~ESPectroBase_GpioEx() {
}
byte ESPectroBase_GpioEx::begin(byte address, byte resetPin) {
byte addr = (address != ESPECTRO_BASE_GPIOEX_ADDRESS)? address: i2cDeviceAddress_;
byte res = SX1508::begin(addr, resetPin);
if (res) {
SX1508::pinMode(ESPECTRO_BASE_GPIOEX_LED_PIN, OUTPUT);
clock(INTERNAL_CLOCK_2MHZ, 4);
}
return res;
}
void ESPectroBase_GpioEx::turnOnLED() {
SX1508::digitalWrite(ESPECTRO_BASE_GPIOEX_LED_PIN, LOW);
}
void ESPectroBase_GpioEx::turnOffLED() {
SX1508::digitalWrite(ESPECTRO_BASE_GPIOEX_LED_PIN, HIGH);
}
void ESPectroBase_GpioEx::blinkLED(unsigned long tOn, unsigned long tOff, byte onIntensity, byte offIntensity) {
blink(ESPECTRO_BASE_GPIOEX_LED_PIN, tOn, tOff, onIntensity, offIntensity);
}
| [
"[email protected]"
] | |
7a8ee6e89234f511f0c9621e346ef8e385c5868b | 9d4ad6d7f3122f8d32a4a713f06b81ecb7a47c6e | /headers/boost/1.31.0/boost/python/slice_nil.hpp | b77d06cb2248fb3ab7dd61b1ea1fd671d6904430 | [] | no_license | metashell/headers | 226d6d55eb659134a2ae2aa022b56b893bff1b30 | ceb6da74d7ca582791f33906992a5908fcaca617 | refs/heads/master | 2021-01-20T23:26:51.811362 | 2018-08-25T07:06:19 | 2018-08-25T07:06:19 | 13,360,747 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 913 | hpp | // Copyright David Abrahams 2002. Permission to copy, use,
// modify, sell and distribute this software is granted provided this
// copyright notice appears in all copies. This software is provided
// "as is" without express or implied warranty, and with no claim as
// to its suitability for any purpose.
#ifndef SLICE_NIL_DWA2002620_HPP
# define SLICE_NIL_DWA2002620_HPP
# include <boost/python/detail/prefix.hpp>
namespace boost { namespace python { namespace api {
class object;
enum slice_nil
{
# ifndef _ // Watch out for GNU gettext users, who #define _(x)
_
# endif
};
template <class T>
struct slice_bound
{
typedef object type;
};
template <>
struct slice_bound<slice_nil>
{
typedef slice_nil type;
};
}
using api::slice_nil;
# ifndef _ // Watch out for GNU gettext users, who #define _(x)
using api::_;
# endif
}} // namespace boost::python
#endif // SLICE_NIL_DWA2002620_HPP
| [
"[email protected]"
] | |
753d6db593d2dbb3cbc3552a2e76c038af4365c9 | f5f750efbde0ccd95856820c975ec88ee6ace0f8 | /aws-cpp-sdk-apigateway/include/aws/apigateway/model/PutMethodRequest.h | b09c86623a5a17eb3cc9a9ae9099ed949c7e68f2 | [
"JSON",
"MIT",
"Apache-2.0"
] | permissive | csimmons0/aws-sdk-cpp | 578a4ae6e7899944f8850dc37accba5568b919eb | 1d0e1ddb51022a02700a9d1d3658abf628bb41c8 | refs/heads/develop | 2020-06-17T14:58:41.406919 | 2017-04-12T03:45:33 | 2017-04-12T03:45:33 | 74,995,798 | 0 | 0 | null | 2017-03-02T05:35:49 | 2016-11-28T17:12:34 | C++ | UTF-8 | C++ | false | false | 25,054 | h | /*
* Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#pragma once
#include <aws/apigateway/APIGateway_EXPORTS.h>
#include <aws/apigateway/APIGatewayRequest.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/core/utils/memory/stl/AWSMap.h>
namespace Aws
{
namespace APIGateway
{
namespace Model
{
/**
* <p>Request to add a method to an existing <a>Resource</a>
* resource.</p><p><h3>See Also:</h3> <a
* href="http://docs.aws.amazon.com/goto/WebAPI/apigateway-2015-07-09/PutMethodRequest">AWS
* API Reference</a></p>
*/
class AWS_APIGATEWAY_API PutMethodRequest : public APIGatewayRequest
{
public:
PutMethodRequest();
Aws::String SerializePayload() const override;
/**
* <p>The <a>RestApi</a> identifier for the new <a>Method</a> resource.</p>
*/
inline const Aws::String& GetRestApiId() const{ return m_restApiId; }
/**
* <p>The <a>RestApi</a> identifier for the new <a>Method</a> resource.</p>
*/
inline void SetRestApiId(const Aws::String& value) { m_restApiIdHasBeenSet = true; m_restApiId = value; }
/**
* <p>The <a>RestApi</a> identifier for the new <a>Method</a> resource.</p>
*/
inline void SetRestApiId(Aws::String&& value) { m_restApiIdHasBeenSet = true; m_restApiId = value; }
/**
* <p>The <a>RestApi</a> identifier for the new <a>Method</a> resource.</p>
*/
inline void SetRestApiId(const char* value) { m_restApiIdHasBeenSet = true; m_restApiId.assign(value); }
/**
* <p>The <a>RestApi</a> identifier for the new <a>Method</a> resource.</p>
*/
inline PutMethodRequest& WithRestApiId(const Aws::String& value) { SetRestApiId(value); return *this;}
/**
* <p>The <a>RestApi</a> identifier for the new <a>Method</a> resource.</p>
*/
inline PutMethodRequest& WithRestApiId(Aws::String&& value) { SetRestApiId(value); return *this;}
/**
* <p>The <a>RestApi</a> identifier for the new <a>Method</a> resource.</p>
*/
inline PutMethodRequest& WithRestApiId(const char* value) { SetRestApiId(value); return *this;}
/**
* <p>The <a>Resource</a> identifier for the new <a>Method</a> resource.</p>
*/
inline const Aws::String& GetResourceId() const{ return m_resourceId; }
/**
* <p>The <a>Resource</a> identifier for the new <a>Method</a> resource.</p>
*/
inline void SetResourceId(const Aws::String& value) { m_resourceIdHasBeenSet = true; m_resourceId = value; }
/**
* <p>The <a>Resource</a> identifier for the new <a>Method</a> resource.</p>
*/
inline void SetResourceId(Aws::String&& value) { m_resourceIdHasBeenSet = true; m_resourceId = value; }
/**
* <p>The <a>Resource</a> identifier for the new <a>Method</a> resource.</p>
*/
inline void SetResourceId(const char* value) { m_resourceIdHasBeenSet = true; m_resourceId.assign(value); }
/**
* <p>The <a>Resource</a> identifier for the new <a>Method</a> resource.</p>
*/
inline PutMethodRequest& WithResourceId(const Aws::String& value) { SetResourceId(value); return *this;}
/**
* <p>The <a>Resource</a> identifier for the new <a>Method</a> resource.</p>
*/
inline PutMethodRequest& WithResourceId(Aws::String&& value) { SetResourceId(value); return *this;}
/**
* <p>The <a>Resource</a> identifier for the new <a>Method</a> resource.</p>
*/
inline PutMethodRequest& WithResourceId(const char* value) { SetResourceId(value); return *this;}
/**
* <p>Specifies the method request's HTTP method type.</p>
*/
inline const Aws::String& GetHttpMethod() const{ return m_httpMethod; }
/**
* <p>Specifies the method request's HTTP method type.</p>
*/
inline void SetHttpMethod(const Aws::String& value) { m_httpMethodHasBeenSet = true; m_httpMethod = value; }
/**
* <p>Specifies the method request's HTTP method type.</p>
*/
inline void SetHttpMethod(Aws::String&& value) { m_httpMethodHasBeenSet = true; m_httpMethod = value; }
/**
* <p>Specifies the method request's HTTP method type.</p>
*/
inline void SetHttpMethod(const char* value) { m_httpMethodHasBeenSet = true; m_httpMethod.assign(value); }
/**
* <p>Specifies the method request's HTTP method type.</p>
*/
inline PutMethodRequest& WithHttpMethod(const Aws::String& value) { SetHttpMethod(value); return *this;}
/**
* <p>Specifies the method request's HTTP method type.</p>
*/
inline PutMethodRequest& WithHttpMethod(Aws::String&& value) { SetHttpMethod(value); return *this;}
/**
* <p>Specifies the method request's HTTP method type.</p>
*/
inline PutMethodRequest& WithHttpMethod(const char* value) { SetHttpMethod(value); return *this;}
/**
* <p>Specifies the type of authorization used for the method.</p>
*/
inline const Aws::String& GetAuthorizationType() const{ return m_authorizationType; }
/**
* <p>Specifies the type of authorization used for the method.</p>
*/
inline void SetAuthorizationType(const Aws::String& value) { m_authorizationTypeHasBeenSet = true; m_authorizationType = value; }
/**
* <p>Specifies the type of authorization used for the method.</p>
*/
inline void SetAuthorizationType(Aws::String&& value) { m_authorizationTypeHasBeenSet = true; m_authorizationType = value; }
/**
* <p>Specifies the type of authorization used for the method.</p>
*/
inline void SetAuthorizationType(const char* value) { m_authorizationTypeHasBeenSet = true; m_authorizationType.assign(value); }
/**
* <p>Specifies the type of authorization used for the method.</p>
*/
inline PutMethodRequest& WithAuthorizationType(const Aws::String& value) { SetAuthorizationType(value); return *this;}
/**
* <p>Specifies the type of authorization used for the method.</p>
*/
inline PutMethodRequest& WithAuthorizationType(Aws::String&& value) { SetAuthorizationType(value); return *this;}
/**
* <p>Specifies the type of authorization used for the method.</p>
*/
inline PutMethodRequest& WithAuthorizationType(const char* value) { SetAuthorizationType(value); return *this;}
/**
* <p>Specifies the identifier of an <a>Authorizer</a> to use on this Method, if
* the type is CUSTOM.</p>
*/
inline const Aws::String& GetAuthorizerId() const{ return m_authorizerId; }
/**
* <p>Specifies the identifier of an <a>Authorizer</a> to use on this Method, if
* the type is CUSTOM.</p>
*/
inline void SetAuthorizerId(const Aws::String& value) { m_authorizerIdHasBeenSet = true; m_authorizerId = value; }
/**
* <p>Specifies the identifier of an <a>Authorizer</a> to use on this Method, if
* the type is CUSTOM.</p>
*/
inline void SetAuthorizerId(Aws::String&& value) { m_authorizerIdHasBeenSet = true; m_authorizerId = value; }
/**
* <p>Specifies the identifier of an <a>Authorizer</a> to use on this Method, if
* the type is CUSTOM.</p>
*/
inline void SetAuthorizerId(const char* value) { m_authorizerIdHasBeenSet = true; m_authorizerId.assign(value); }
/**
* <p>Specifies the identifier of an <a>Authorizer</a> to use on this Method, if
* the type is CUSTOM.</p>
*/
inline PutMethodRequest& WithAuthorizerId(const Aws::String& value) { SetAuthorizerId(value); return *this;}
/**
* <p>Specifies the identifier of an <a>Authorizer</a> to use on this Method, if
* the type is CUSTOM.</p>
*/
inline PutMethodRequest& WithAuthorizerId(Aws::String&& value) { SetAuthorizerId(value); return *this;}
/**
* <p>Specifies the identifier of an <a>Authorizer</a> to use on this Method, if
* the type is CUSTOM.</p>
*/
inline PutMethodRequest& WithAuthorizerId(const char* value) { SetAuthorizerId(value); return *this;}
/**
* <p>Specifies whether the method required a valid <a>ApiKey</a>.</p>
*/
inline bool GetApiKeyRequired() const{ return m_apiKeyRequired; }
/**
* <p>Specifies whether the method required a valid <a>ApiKey</a>.</p>
*/
inline void SetApiKeyRequired(bool value) { m_apiKeyRequiredHasBeenSet = true; m_apiKeyRequired = value; }
/**
* <p>Specifies whether the method required a valid <a>ApiKey</a>.</p>
*/
inline PutMethodRequest& WithApiKeyRequired(bool value) { SetApiKeyRequired(value); return *this;}
/**
* <p>A human-friendly operation identifier for the method. For example, you can
* assign the <code>operationName</code> of <code>ListPets</code> for the <code>GET
* /pets</code> method in <a
* href="http://petstore-demo-endpoint.execute-api.com/petstore/pets">PetStore</a>
* example.</p>
*/
inline const Aws::String& GetOperationName() const{ return m_operationName; }
/**
* <p>A human-friendly operation identifier for the method. For example, you can
* assign the <code>operationName</code> of <code>ListPets</code> for the <code>GET
* /pets</code> method in <a
* href="http://petstore-demo-endpoint.execute-api.com/petstore/pets">PetStore</a>
* example.</p>
*/
inline void SetOperationName(const Aws::String& value) { m_operationNameHasBeenSet = true; m_operationName = value; }
/**
* <p>A human-friendly operation identifier for the method. For example, you can
* assign the <code>operationName</code> of <code>ListPets</code> for the <code>GET
* /pets</code> method in <a
* href="http://petstore-demo-endpoint.execute-api.com/petstore/pets">PetStore</a>
* example.</p>
*/
inline void SetOperationName(Aws::String&& value) { m_operationNameHasBeenSet = true; m_operationName = value; }
/**
* <p>A human-friendly operation identifier for the method. For example, you can
* assign the <code>operationName</code> of <code>ListPets</code> for the <code>GET
* /pets</code> method in <a
* href="http://petstore-demo-endpoint.execute-api.com/petstore/pets">PetStore</a>
* example.</p>
*/
inline void SetOperationName(const char* value) { m_operationNameHasBeenSet = true; m_operationName.assign(value); }
/**
* <p>A human-friendly operation identifier for the method. For example, you can
* assign the <code>operationName</code> of <code>ListPets</code> for the <code>GET
* /pets</code> method in <a
* href="http://petstore-demo-endpoint.execute-api.com/petstore/pets">PetStore</a>
* example.</p>
*/
inline PutMethodRequest& WithOperationName(const Aws::String& value) { SetOperationName(value); return *this;}
/**
* <p>A human-friendly operation identifier for the method. For example, you can
* assign the <code>operationName</code> of <code>ListPets</code> for the <code>GET
* /pets</code> method in <a
* href="http://petstore-demo-endpoint.execute-api.com/petstore/pets">PetStore</a>
* example.</p>
*/
inline PutMethodRequest& WithOperationName(Aws::String&& value) { SetOperationName(value); return *this;}
/**
* <p>A human-friendly operation identifier for the method. For example, you can
* assign the <code>operationName</code> of <code>ListPets</code> for the <code>GET
* /pets</code> method in <a
* href="http://petstore-demo-endpoint.execute-api.com/petstore/pets">PetStore</a>
* example.</p>
*/
inline PutMethodRequest& WithOperationName(const char* value) { SetOperationName(value); return *this;}
/**
* <p>A key-value map defining required or optional method request parameters that
* can be accepted by Amazon API Gateway. A key defines a method request parameter
* name matching the pattern of <code>method.request.{location}.{name}</code>,
* where <code>location</code> is <code>querystring</code>, <code>path</code>, or
* <code>header</code> and <code>name</code> is a valid and unique parameter name.
* The value associated with the key is a Boolean flag indicating whether the
* parameter is required (<code>true</code>) or optional (<code>false</code>). The
* method request parameter names defined here are available in <a>Integration</a>
* to be mapped to integration request parameters or body-mapping templates.</p>
*/
inline const Aws::Map<Aws::String, bool>& GetRequestParameters() const{ return m_requestParameters; }
/**
* <p>A key-value map defining required or optional method request parameters that
* can be accepted by Amazon API Gateway. A key defines a method request parameter
* name matching the pattern of <code>method.request.{location}.{name}</code>,
* where <code>location</code> is <code>querystring</code>, <code>path</code>, or
* <code>header</code> and <code>name</code> is a valid and unique parameter name.
* The value associated with the key is a Boolean flag indicating whether the
* parameter is required (<code>true</code>) or optional (<code>false</code>). The
* method request parameter names defined here are available in <a>Integration</a>
* to be mapped to integration request parameters or body-mapping templates.</p>
*/
inline void SetRequestParameters(const Aws::Map<Aws::String, bool>& value) { m_requestParametersHasBeenSet = true; m_requestParameters = value; }
/**
* <p>A key-value map defining required or optional method request parameters that
* can be accepted by Amazon API Gateway. A key defines a method request parameter
* name matching the pattern of <code>method.request.{location}.{name}</code>,
* where <code>location</code> is <code>querystring</code>, <code>path</code>, or
* <code>header</code> and <code>name</code> is a valid and unique parameter name.
* The value associated with the key is a Boolean flag indicating whether the
* parameter is required (<code>true</code>) or optional (<code>false</code>). The
* method request parameter names defined here are available in <a>Integration</a>
* to be mapped to integration request parameters or body-mapping templates.</p>
*/
inline void SetRequestParameters(Aws::Map<Aws::String, bool>&& value) { m_requestParametersHasBeenSet = true; m_requestParameters = value; }
/**
* <p>A key-value map defining required or optional method request parameters that
* can be accepted by Amazon API Gateway. A key defines a method request parameter
* name matching the pattern of <code>method.request.{location}.{name}</code>,
* where <code>location</code> is <code>querystring</code>, <code>path</code>, or
* <code>header</code> and <code>name</code> is a valid and unique parameter name.
* The value associated with the key is a Boolean flag indicating whether the
* parameter is required (<code>true</code>) or optional (<code>false</code>). The
* method request parameter names defined here are available in <a>Integration</a>
* to be mapped to integration request parameters or body-mapping templates.</p>
*/
inline PutMethodRequest& WithRequestParameters(const Aws::Map<Aws::String, bool>& value) { SetRequestParameters(value); return *this;}
/**
* <p>A key-value map defining required or optional method request parameters that
* can be accepted by Amazon API Gateway. A key defines a method request parameter
* name matching the pattern of <code>method.request.{location}.{name}</code>,
* where <code>location</code> is <code>querystring</code>, <code>path</code>, or
* <code>header</code> and <code>name</code> is a valid and unique parameter name.
* The value associated with the key is a Boolean flag indicating whether the
* parameter is required (<code>true</code>) or optional (<code>false</code>). The
* method request parameter names defined here are available in <a>Integration</a>
* to be mapped to integration request parameters or body-mapping templates.</p>
*/
inline PutMethodRequest& WithRequestParameters(Aws::Map<Aws::String, bool>&& value) { SetRequestParameters(value); return *this;}
/**
* <p>A key-value map defining required or optional method request parameters that
* can be accepted by Amazon API Gateway. A key defines a method request parameter
* name matching the pattern of <code>method.request.{location}.{name}</code>,
* where <code>location</code> is <code>querystring</code>, <code>path</code>, or
* <code>header</code> and <code>name</code> is a valid and unique parameter name.
* The value associated with the key is a Boolean flag indicating whether the
* parameter is required (<code>true</code>) or optional (<code>false</code>). The
* method request parameter names defined here are available in <a>Integration</a>
* to be mapped to integration request parameters or body-mapping templates.</p>
*/
inline PutMethodRequest& AddRequestParameters(const Aws::String& key, bool value) { m_requestParametersHasBeenSet = true; m_requestParameters[key] = value; return *this; }
/**
* <p>A key-value map defining required or optional method request parameters that
* can be accepted by Amazon API Gateway. A key defines a method request parameter
* name matching the pattern of <code>method.request.{location}.{name}</code>,
* where <code>location</code> is <code>querystring</code>, <code>path</code>, or
* <code>header</code> and <code>name</code> is a valid and unique parameter name.
* The value associated with the key is a Boolean flag indicating whether the
* parameter is required (<code>true</code>) or optional (<code>false</code>). The
* method request parameter names defined here are available in <a>Integration</a>
* to be mapped to integration request parameters or body-mapping templates.</p>
*/
inline PutMethodRequest& AddRequestParameters(Aws::String&& key, bool value) { m_requestParametersHasBeenSet = true; m_requestParameters[key] = value; return *this; }
/**
* <p>A key-value map defining required or optional method request parameters that
* can be accepted by Amazon API Gateway. A key defines a method request parameter
* name matching the pattern of <code>method.request.{location}.{name}</code>,
* where <code>location</code> is <code>querystring</code>, <code>path</code>, or
* <code>header</code> and <code>name</code> is a valid and unique parameter name.
* The value associated with the key is a Boolean flag indicating whether the
* parameter is required (<code>true</code>) or optional (<code>false</code>). The
* method request parameter names defined here are available in <a>Integration</a>
* to be mapped to integration request parameters or body-mapping templates.</p>
*/
inline PutMethodRequest& AddRequestParameters(const char* key, bool value) { m_requestParametersHasBeenSet = true; m_requestParameters[key] = value; return *this; }
/**
* <p>Specifies the <a>Model</a> resources used for the request's content type.
* Request models are represented as a key/value map, with a content type as the
* key and a <a>Model</a> name as the value.</p>
*/
inline const Aws::Map<Aws::String, Aws::String>& GetRequestModels() const{ return m_requestModels; }
/**
* <p>Specifies the <a>Model</a> resources used for the request's content type.
* Request models are represented as a key/value map, with a content type as the
* key and a <a>Model</a> name as the value.</p>
*/
inline void SetRequestModels(const Aws::Map<Aws::String, Aws::String>& value) { m_requestModelsHasBeenSet = true; m_requestModels = value; }
/**
* <p>Specifies the <a>Model</a> resources used for the request's content type.
* Request models are represented as a key/value map, with a content type as the
* key and a <a>Model</a> name as the value.</p>
*/
inline void SetRequestModels(Aws::Map<Aws::String, Aws::String>&& value) { m_requestModelsHasBeenSet = true; m_requestModels = value; }
/**
* <p>Specifies the <a>Model</a> resources used for the request's content type.
* Request models are represented as a key/value map, with a content type as the
* key and a <a>Model</a> name as the value.</p>
*/
inline PutMethodRequest& WithRequestModels(const Aws::Map<Aws::String, Aws::String>& value) { SetRequestModels(value); return *this;}
/**
* <p>Specifies the <a>Model</a> resources used for the request's content type.
* Request models are represented as a key/value map, with a content type as the
* key and a <a>Model</a> name as the value.</p>
*/
inline PutMethodRequest& WithRequestModels(Aws::Map<Aws::String, Aws::String>&& value) { SetRequestModels(value); return *this;}
/**
* <p>Specifies the <a>Model</a> resources used for the request's content type.
* Request models are represented as a key/value map, with a content type as the
* key and a <a>Model</a> name as the value.</p>
*/
inline PutMethodRequest& AddRequestModels(const Aws::String& key, const Aws::String& value) { m_requestModelsHasBeenSet = true; m_requestModels[key] = value; return *this; }
/**
* <p>Specifies the <a>Model</a> resources used for the request's content type.
* Request models are represented as a key/value map, with a content type as the
* key and a <a>Model</a> name as the value.</p>
*/
inline PutMethodRequest& AddRequestModels(Aws::String&& key, const Aws::String& value) { m_requestModelsHasBeenSet = true; m_requestModels[key] = value; return *this; }
/**
* <p>Specifies the <a>Model</a> resources used for the request's content type.
* Request models are represented as a key/value map, with a content type as the
* key and a <a>Model</a> name as the value.</p>
*/
inline PutMethodRequest& AddRequestModels(const Aws::String& key, Aws::String&& value) { m_requestModelsHasBeenSet = true; m_requestModels[key] = value; return *this; }
/**
* <p>Specifies the <a>Model</a> resources used for the request's content type.
* Request models are represented as a key/value map, with a content type as the
* key and a <a>Model</a> name as the value.</p>
*/
inline PutMethodRequest& AddRequestModels(Aws::String&& key, Aws::String&& value) { m_requestModelsHasBeenSet = true; m_requestModels[key] = value; return *this; }
/**
* <p>Specifies the <a>Model</a> resources used for the request's content type.
* Request models are represented as a key/value map, with a content type as the
* key and a <a>Model</a> name as the value.</p>
*/
inline PutMethodRequest& AddRequestModels(const char* key, Aws::String&& value) { m_requestModelsHasBeenSet = true; m_requestModels[key] = value; return *this; }
/**
* <p>Specifies the <a>Model</a> resources used for the request's content type.
* Request models are represented as a key/value map, with a content type as the
* key and a <a>Model</a> name as the value.</p>
*/
inline PutMethodRequest& AddRequestModels(Aws::String&& key, const char* value) { m_requestModelsHasBeenSet = true; m_requestModels[key] = value; return *this; }
/**
* <p>Specifies the <a>Model</a> resources used for the request's content type.
* Request models are represented as a key/value map, with a content type as the
* key and a <a>Model</a> name as the value.</p>
*/
inline PutMethodRequest& AddRequestModels(const char* key, const char* value) { m_requestModelsHasBeenSet = true; m_requestModels[key] = value; return *this; }
private:
Aws::String m_restApiId;
bool m_restApiIdHasBeenSet;
Aws::String m_resourceId;
bool m_resourceIdHasBeenSet;
Aws::String m_httpMethod;
bool m_httpMethodHasBeenSet;
Aws::String m_authorizationType;
bool m_authorizationTypeHasBeenSet;
Aws::String m_authorizerId;
bool m_authorizerIdHasBeenSet;
bool m_apiKeyRequired;
bool m_apiKeyRequiredHasBeenSet;
Aws::String m_operationName;
bool m_operationNameHasBeenSet;
Aws::Map<Aws::String, bool> m_requestParameters;
bool m_requestParametersHasBeenSet;
Aws::Map<Aws::String, Aws::String> m_requestModels;
bool m_requestModelsHasBeenSet;
};
} // namespace Model
} // namespace APIGateway
} // namespace Aws
| [
"[email protected]"
] | |
822c0cbe1df8c14a644ce9901565c54c578f3ffc | 4a887b7390deb04cf908571876e33a3c6bc63826 | /3_2DEngineWithGUI/Base.h | ca97adadb48fe9a86cf60458c1e07489b0e947f7 | [
"MIT"
] | permissive | dnjfdkanwjr/2DEngine | 504d2a97638346fdf283c0889f40f16574d0ca4a | 8908073192b6a80a84d155f07061003800e8d0ce | refs/heads/master | 2021-02-09T19:34:56.041713 | 2020-03-19T05:41:25 | 2020-03-19T05:41:25 | 244,318,509 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 384 | h | #pragma once
#include <string>
namespace rp {
class Base
{
protected:
std::string name{};
bool state{};
public:
Base(std::string&& name);
virtual ~Base();
void SetName(std::string&& name)noexcept;
void SetName(std::string& name)noexcept;
void SetState(bool state)noexcept;
const std::string& GetName() const noexcept;
bool GetState() const noexcept;
};
}
| [
"[email protected]"
] | |
ec6638730f6368f85bfaef8cb895edcd78f1e02b | 9228d266b854a8767b2c3dd9f51a6cc07a9daf5e | /Source/Lutefisk3D/2D/Drawable2D.cpp | 9758ce2b0dd619b2bf62df7bcda9da0ff5f72761 | [
"Apache-2.0",
"BSD-2-Clause",
"Zlib",
"MIT",
"LicenseRef-scancode-khronos",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | Lutefisk3D/lutefisk3d | 9dfed84ab853134846ab9acf3c2fae419ec102f3 | d2132b82003427511df0167f613905191b006eb5 | refs/heads/master | 2021-10-19T03:58:00.025782 | 2019-02-17T18:14:49 | 2019-02-17T18:14:49 | 37,516,913 | 3 | 1 | NOASSERTION | 2018-10-20T12:51:56 | 2015-06-16T08:10:08 | C++ | UTF-8 | C++ | false | false | 3,563 | cpp | //
// Copyright (c) 2008-2016 the Urho3D project.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
#include "Drawable2D.h"
#include "Renderer2D.h"
#include "Lutefisk3D/Core/Context.h"
#include "Lutefisk3D/Graphics/Camera.h"
#include "Lutefisk3D/Graphics/Material.h"
#include "Lutefisk3D/Graphics/Texture2D.h"
#include "Lutefisk3D/Scene/Scene.h"
#include "Lutefisk3D/Container/HandleManager.h"
namespace Urho3D
{
const float PIXEL_SIZE = 0.01f;
Drawable2D::Drawable2D(Context* context) :
Drawable(context, DRAWABLE_GEOMETRY2D),
layer_(0),
orderInLayer_(0),
sourceBatchesDirty_(true)
{
}
Drawable2D::~Drawable2D()
{
if (renderer_)
renderer_->RemoveDrawable(this);
}
void Drawable2D::RegisterObject(Context* context)
{
URHO3D_ACCESSOR_ATTRIBUTE("Layer", GetLayer, SetLayer, int, 0, AM_DEFAULT);
URHO3D_ACCESSOR_ATTRIBUTE("Order in Layer", GetOrderInLayer, SetOrderInLayer, int, 0, AM_DEFAULT);
URHO3D_ATTRIBUTE("View Mask", int, viewMask_, DEFAULT_VIEWMASK, AM_DEFAULT);
}
/// Handle enabled/disabled state change.
void Drawable2D::OnSetEnabled()
{
bool enabled = IsEnabledEffective();
if (enabled && renderer_)
renderer_->AddDrawable(this);
else if (!enabled && renderer_)
renderer_->RemoveDrawable(this);
}
/// Set layer.
void Drawable2D::SetLayer(int layer)
{
if (layer == layer_)
return;
layer_ = layer;
OnDrawOrderChanged();
MarkNetworkUpdate();
}
/// Set order in layer.
void Drawable2D::SetOrderInLayer(int orderInLayer)
{
if (orderInLayer == orderInLayer_)
return;
orderInLayer_ = orderInLayer;
OnDrawOrderChanged();
MarkNetworkUpdate();
}
/// Return all source batches (called by Renderer2D).
const std::vector<SourceBatch2D>& Drawable2D::GetSourceBatches()
{
if (sourceBatchesDirty_)
UpdateSourceBatches();
return sourceBatch_;
}
/// Handle scene being assigned.
void Drawable2D::OnSceneSet(Scene* scene)
{
// Do not call Drawable::OnSceneSet(node), as 2D drawable components should not be added to the octree
// but are instead rendered through Renderer2D
if (scene)
{
renderer_ = scene->GetOrCreateComponent<Renderer2D>();
if (IsEnabledEffective())
renderer_->AddDrawable(this);
}
else
{
if (renderer_)
renderer_->RemoveDrawable(this);
}
}
/// Handle node transform being dirtied.
void Drawable2D::OnMarkedDirty(Node* node)
{
Drawable::OnMarkedDirty(node);
sourceBatchesDirty_ = true;
}
}
| [
"[email protected]"
] | |
2afdee78415e6b3b8019099f55955075a2ac3d2b | 9a3558d9cc1070d75b6972abaf12339f3c43b672 | /libraries/helper/helper.hpp | 8dfa3d61682d662d17355285d1b50d766492c757 | [] | no_license | kurokis/Ublox | 32888bb69d5eeebc8eab9d6e47997c5d825d1e35 | a434a513ba68d25e7badce022e73b77ca3e2f2a3 | refs/heads/master | 2021-01-21T12:30:40.132612 | 2017-09-03T11:23:12 | 2017-09-03T11:23:12 | 102,074,190 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 845 | hpp | //
// helper.hpp
// GPS_READER
//
// Created by blue-i on 01/09/2017.
// Copyright © 2017 blue-i. All rights reserved.
//
#ifndef helper_hpp
#define helper_hpp
#include <stdio.h>
#include "string.h"
#include <iostream>
#include <stdio.h>
#include <unistd.h> //Used for UART
#include <fcntl.h> //Used for UART
#include <termios.h> //Used for UART
#include <sys/ioctl.h> //Used for UART
#include <sys/stat.h> //Used for fifo
#include <poll.h> //Pollin()
#define UBLOX_INITIAL_BAUD B9600
#define UBLOX_OPERATING_BAUD B57600
#define GPS_PORT "/dev/ttyUSB_Ublox"
void UART_Init(int b);
void UBloxTxBuffer(const char b[], int t);
void UART_Close();
void GPS_Init(void);
bool file_exist(const std::string& name);
bool pollin(void);
void Reader_sender(void);
void run(void);
#endif /* helper_hpp */
| [
"[email protected]"
] | |
ffb32c7bfa66792ff42c6982c642d1dd258c2f1d | 4a4109182be077240476da145c1ea0366a190b7c | /Plugins/QFireBase/qfirebase.cpp | f49d959a1e797a0219f5ae4bff27ccb231e15e97 | [] | no_license | devkitcc/SDMedic | 5f7c0a59856108b4d55bc3f051eca3d241073e4b | 14509964f5730923268e138ccdb2e99bc944d7b2 | refs/heads/master | 2021-05-08T01:36:28.333248 | 2017-10-22T17:14:38 | 2017-10-22T17:14:38 | 107,885,884 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 58 | cpp | #include "qfirebase.h"
QFireBase::QFireBase()
{
}
| [
"[email protected]"
] | |
8a5aab971b95db02883d20232314fe4fad3c19c2 | f12e53b806ba418a58f814ebc87c4446a422b2f5 | /solutions/uri/1789/1789.cpp | c14cdae8df69b14fd26b05dda0d6eeafcb2cf0b5 | [
"MIT"
] | permissive | biadelmont/playground | f775cd86109e30ed464d4d6eff13f9ded40627cb | 93c6248ec6cd25d75f0efbda1d50e0705bbd1e5a | refs/heads/master | 2021-05-06T15:49:43.253788 | 2017-11-07T13:00:31 | 2017-11-07T13:00:31 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 402 | cpp | #include <cstdio>
int main() {
int l, v, fastest;
while (scanf("%d", &l) != EOF) {
fastest = 0;
while (l--) {
scanf("%d", &v);
if (v > fastest) fastest = v;
}
if (fastest < 10) {
puts("1");
} else if (fastest < 20) {
puts("2");
} else {
puts("3");
}
}
return 0;
}
| [
"[email protected]"
] | |
278610710edb06f4e8cfd21ed070aaad83328446 | 2eac4cb30dd9fbbf73e35c294f8549107dbeee0e | /src/Adjacency.h | 1f071998066f9571840d8a5dad9345aec43f4c24 | [] | no_license | patrickmacarthur/OurAdventure | 9f720f8523eea467f8d101e44613a4d0f5a92183 | 2db5450af6601f924f8de614fb3b83ed42e98b29 | refs/heads/master | 2021-01-23T07:08:54.335142 | 2014-10-28T18:03:36 | 2014-10-28T18:03:36 | 2,129,865 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,575 | h | #ifndef ADJACENCY_H
#define ADJACENCY_H
/* Adjacency.h
*
* Author: Patrick MacArthur
*
* This file is part of the CS 516 Final Project
*/
#include <istream>
#include <ostream>
#include <map>
#include "Direction.h"
#include "Item.h"
class Feature;
class Map;
/*
* This class represents an adjacency between rooms.
*/
class Adjacency : public Item
{
public:
Adjacency();
// constructor
virtual ~Adjacency();
// destructor
virtual void addToMap( Map * map );
// Adds this item to the map
virtual Item * clone() const;
// dynamic copy
virtual Feature * getExit( const Direction & );
// Gets the exit in the given direction. Returns 0 if
// there is no feature in that direction.
virtual int getExitCount() const;
// Returns the number of exits.
const ID & getFeatureID() const;
// Returns the ID of the "source" feature.
virtual void input( std::istream & s, Map * );
// Inputs the adjacency in the format:
// featureId directionCount directionName featureId ...
virtual void printDescription( std::ostream & s );
// Outputs the adjacency list in a human-readable
// format
virtual void save( std::ostream & s );
// Saves the adjacency list to disk in same format
// input, except adds type tag in front
private:
std::map<Direction, Feature *> m_table;
ID m_featureID;
};
/* vim: set et sw=4 tw=65: */
#endif
| [
"[email protected]"
] | |
bedd6b0597395d00f57558d719997af8cb55958f | 6c7cd2aecd2f055a34396cd555c3539d6bf521f1 | /sm_kinematics/src/Transformation.cpp | 1876fb255d4f7261f685e742d17a5c1e1a9e9a0b | [] | no_license | tsandy/Schweizer-Messer | 4dc3b100bd51eee78cdf9827db0143072dd7e5d3 | 77ba4c6c5668526f8dc8696375d44f5a85db0208 | refs/heads/master | 2021-01-21T00:01:20.531790 | 2013-03-22T10:35:17 | 2013-03-22T10:35:17 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,250 | cpp | #include <sm/kinematics/Transformation.hpp>
#include <sm/kinematics/quaternion_algebra.hpp>
#include <sm/kinematics/rotations.hpp>
#include <sm/random.hpp>
#include <sm/kinematics/UncertainHomogeneousPoint.hpp>
#include <sm/kinematics/UncertainTransformation.hpp>
#include <sm/kinematics/transformations.hpp>
namespace sm {
namespace kinematics {
Transformation::Transformation() :
_q_a_b(quatIdentity()), _t_a_b_a(0.0, 0.0, 0.0)
{
}
Transformation::Transformation(Eigen::Matrix4d const & T_a_b) :
_q_a_b( r2quat(T_a_b.topLeftCorner<3,3>()) ),
_t_a_b_a( T_a_b.topRightCorner<3,1>() )
{
}
Transformation::Transformation(const Eigen::Vector4d & q_a_b, const Eigen::Vector3d t_a_b_a) :
_q_a_b(q_a_b), _t_a_b_a(t_a_b_a)
{
_q_a_b.normalize();
}
Transformation::~Transformation(){}
/// @return the rotation matrix
Eigen::Matrix3d Transformation::C() const
{
return quat2r(_q_a_b);
}
/// @return the translation vector
const Eigen::Vector3d & Transformation::t() const
{
return _t_a_b_a;
}
const Eigen::Vector4d & Transformation::q() const
{
return _q_a_b;
}
Eigen::Matrix4d Transformation::T() const
{
Eigen::Matrix4d T_a_b;
// \todo...make this do less copying.
T_a_b.topLeftCorner<3,3>() = quat2r(_q_a_b);
T_a_b.topRightCorner<3,1>() = _t_a_b_a;
T_a_b.bottomLeftCorner<1,3>().setZero();
T_a_b(3,3) = 1.0;
return T_a_b;
}
Eigen::Matrix<double, 3,4> Transformation::T3x4() const
{
Eigen::Matrix<double, 3, 4> T3x4;
// \todo...make this do less copying.
T3x4.topLeftCorner<3,3>() = quat2r(_q_a_b);
T3x4.topRightCorner<3,1>() = _t_a_b_a;
return T3x4;
}
Transformation Transformation::inverse() const
{
// \todo Make this do less copying.
return Transformation(quatInv(_q_a_b), quatRotate(quatInv(_q_a_b),-_t_a_b_a));
}
void Transformation::checkTransformationIsValid( void ) const
{
// \todo.
}
Transformation Transformation::operator*(const Transformation & rhs) const
{
return Transformation(qplus(_q_a_b,rhs._q_a_b), quatRotate(_q_a_b,rhs._t_a_b_a) + _t_a_b_a);
}
Eigen::Vector3d Transformation::operator*(const Eigen::Vector3d & rhs) const
{
return quatRotate(_q_a_b, rhs) + _t_a_b_a;
}
Eigen::Vector4d Transformation::operator*(const Eigen::Vector4d & rhs) const
{
Eigen::Vector4d rval;
rval.head<3>() = quatRotate(_q_a_b, rhs.head<3>()) + rhs[3] * _t_a_b_a;
rval[3] = rhs[3];
return rval;
}
HomogeneousPoint Transformation::operator*(const HomogeneousPoint & rhs) const
{
Eigen::Vector4d rval = rhs.toHomogeneous();
rval.head<3>() = (quatRotate(_q_a_b, rhs.toHomogeneous().head<3>()) + rval[3] * _t_a_b_a).eval();
return HomogeneousPoint(rval);
}
void Transformation::setRandom()
{
_q_a_b = quatRandom();
_t_a_b_a = (Eigen::Vector3d::Random().array() - 0.5) * 100.0;
}
bool Transformation::isBinaryEqual(const Transformation & rhs) const
{
return _q_a_b == rhs._q_a_b && _t_a_b_a == rhs._t_a_b_a;
}
/// \brief The update step for this transformation from a minimal update.
void Transformation::oplus(const Eigen::Matrix<double,6,1> & dt)
{
_q_a_b = updateQuat( _q_a_b, dt.tail<3>() );
_t_a_b_a += dt.head<3>();
}
Eigen::Matrix<double,6,6> Transformation::S() const
{
Eigen::Matrix<double,6,6> S;
S.setIdentity();
S.topRightCorner<3,3>() = -crossMx(_t_a_b_a);
return S;
}
void Transformation::setIdentity()
{
_q_a_b = quatIdentity();
_t_a_b_a.setZero();
}
/// \brief Set this to a random transformation.
void Transformation::setRandom( double translationMaxMeters, double rotationMaxRadians)
{
// Create a random unit-length axis.
Eigen::Vector3d axis = Eigen::Vector3d::Random().array() - 0.5;
// Create a random rotation angle in radians.
double angle = sm::random::randLU(0.0, rotationMaxRadians);
// Now a random axis/angle.cp
axis.array() *= angle/axis.norm();
Eigen::Vector3d t;
t.setRandom();
t.array() -= 0.5;
t.array() *= sm::random::randLU(0.0, translationMaxMeters)/t.norm();
_q_a_b = axisAngle2quat(axis);
_t_a_b_a = t;
}
UncertainTransformation Transformation::operator*(const UncertainTransformation & UT_b_c) const
{
const Transformation & T_a_b = *this;
const Transformation & T_b_c = UT_b_c;
Transformation T_a_c = T_a_b * T_b_c;
UncertainTransformation::covariance_t T_a_b_boxtimes = boxTimes(T_a_b.T());
UncertainTransformation::covariance_t U_a_c = T_a_b_boxtimes * UT_b_c.U() * T_a_b_boxtimes.transpose();
return UncertainTransformation(T_a_c, U_a_c);
}
UncertainHomogeneousPoint Transformation::operator*(const UncertainHomogeneousPoint & p_1) const
{
const Transformation & T_0_1 = *this;
Eigen::Vector4d p_0 = T_0_1 * p_1.toHomogeneous();
Eigen::Matrix4d T01 = T_0_1.T();
UncertainHomogeneousPoint::covariance_t U = T01 * p_1.U4() * T01.transpose();
return UncertainHomogeneousPoint(p_0,U);
}
/// \brief rotate a point (do not translate)
Eigen::Vector3d Transformation::rotate(const Eigen::Vector3d & p) const
{
return quatRotate(_q_a_b, p);
}
/// \brief rotate a point (do not translate)
Eigen::Vector4d Transformation::rotate(const Eigen::Vector4d & p) const
{
Eigen::Vector4d rval = p;
rval.head<3>() = quatRotate(_q_a_b, rval.head<3>());
return rval;
}
UncertainVector3 Transformation::rotate(const UncertainVector3 & p) const
{
Eigen::Vector3d mean = rotate(p.mean());
Eigen::Matrix3d R = C();
Eigen::Matrix3d P = R * p.covariance() * R.transpose();
return UncertainVector3(mean, P);
}
} // namespace kinematics
} // namespace sm
| [
"[email protected]"
] | |
4954df9038975808ebc26d8174fd0b0356d08d0f | 1196266a7aa8230db1b86dcdd7efff85a43ff812 | /VST3_SDK/public.sdk/source/vst/vstcomponent.cpp | b69241908afb1eea9822d9ea88beec28081ef010 | [
"Unlicense"
] | permissive | fedden/RenderMan | c97547b9b5b3bddf1de6d9111e5eae6434e438ee | e81510d8b564a100899f4fed8c3049c8812cba8d | refs/heads/master | 2021-12-11T18:41:02.477036 | 2021-07-20T18:25:36 | 2021-07-20T18:25:36 | 82,790,125 | 344 | 45 | Unlicense | 2021-08-06T23:08:22 | 2017-02-22T10:09:32 | C++ | UTF-8 | C++ | false | false | 7,112 | cpp | //-----------------------------------------------------------------------------
// Project : VST SDK
//
// Category : Helpers
// Filename : public.sdk/source/vst/vstcomponent.cpp
// Created by : Steinberg, 04/2005
// Description : Basic VST Plug-in Implementation
//
//-----------------------------------------------------------------------------
// LICENSE
// (c) 2017, Steinberg Media Technologies GmbH, 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 the Steinberg Media Technologies nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
// IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
// INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
// OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
// OF THE POSSIBILITY OF SUCH DAMAGE.
//-----------------------------------------------------------------------------
#include "vstcomponent.h"
namespace Steinberg {
namespace Vst {
//------------------------------------------------------------------------
// Component Implementation
//------------------------------------------------------------------------
Component::Component ()
: audioInputs (kAudio, kInput)
, audioOutputs (kAudio, kOutput)
, eventInputs (kEvent, kInput)
, eventOutputs (kEvent, kOutput)
{}
//------------------------------------------------------------------------
tresult PLUGIN_API Component::initialize (FUnknown* context)
{
return ComponentBase::initialize (context);
}
//------------------------------------------------------------------------
tresult PLUGIN_API Component::terminate ()
{
// remove all buses
removeAllBusses ();
return ComponentBase::terminate ();
}
//------------------------------------------------------------------------
BusList* Component::getBusList (MediaType type, BusDirection dir)
{
if (type == kAudio)
return dir == kInput ? &audioInputs : &audioOutputs;
else if (type == kEvent)
return dir == kInput ? &eventInputs : &eventOutputs;
return 0;
}
//------------------------------------------------------------------------
tresult Component::removeAudioBusses ()
{
audioInputs.clear ();
audioOutputs.clear ();
return kResultOk;
}
//------------------------------------------------------------------------
tresult Component::removeEventBusses ()
{
eventInputs.clear ();
eventOutputs.clear ();
return kResultOk;
}
//------------------------------------------------------------------------
tresult Component::removeAllBusses ()
{
removeAudioBusses ();
removeEventBusses ();
return kResultOk;
}
//------------------------------------------------------------------------
tresult PLUGIN_API Component::getControllerClassId (TUID classID)
{
if (controllerClass.isValid ())
{
controllerClass.toTUID (classID);
return kResultTrue;
}
return kResultFalse;
}
//------------------------------------------------------------------------
tresult PLUGIN_API Component::setIoMode (IoMode /*mode*/)
{
return kNotImplemented;
}
//------------------------------------------------------------------------
int32 PLUGIN_API Component::getBusCount (MediaType type, BusDirection dir)
{
BusList* busList = getBusList (type, dir);
return busList ? static_cast<int32> (busList->size ()) : 0;
}
//------------------------------------------------------------------------
tresult PLUGIN_API Component::getBusInfo (MediaType type, BusDirection dir, int32 index, BusInfo& info)
{
if (index < 0)
return kInvalidArgument;
BusList* busList = getBusList (type, dir);
if (busList == 0)
return kInvalidArgument;
if (index >= static_cast<int32> (busList->size ()))
return kInvalidArgument;
Bus* bus = busList->at (index);
info.mediaType = type;
info.direction = dir;
if (bus->getInfo (info))
return kResultTrue;
return kResultFalse;
}
//------------------------------------------------------------------------
tresult PLUGIN_API Component::getRoutingInfo (RoutingInfo& /*inInfo*/, RoutingInfo& /*outInfo*/)
{
return kNotImplemented;
}
//------------------------------------------------------------------------
tresult PLUGIN_API Component::activateBus (MediaType type, BusDirection dir, int32 index, TBool state)
{
if (index < 0)
return kInvalidArgument;
BusList* busList = getBusList (type, dir);
if (busList == 0)
return kInvalidArgument;
if (index >= static_cast<int32> (busList->size ()))
return kInvalidArgument;
Bus* bus = busList->at (index);
bus->setActive (state);
return kResultTrue;
}
//------------------------------------------------------------------------
tresult PLUGIN_API Component::setActive (TBool /*state*/)
{
return kResultOk;
}
//------------------------------------------------------------------------
tresult PLUGIN_API Component::setState (IBStream* /*state*/)
{
return kNotImplemented;
}
//------------------------------------------------------------------------
tresult PLUGIN_API Component::getState (IBStream* /*state*/)
{
return kNotImplemented;
}
//------------------------------------------------------------------------
tresult Component::renameBus (MediaType type, BusDirection dir, int32 index, const String128 newName)
{
if (index < 0)
return kInvalidArgument;
BusList* busList = getBusList (type, dir);
if (busList == 0)
return kInvalidArgument;
if (index >= static_cast<int32> (busList->size ()))
return kInvalidArgument;
Bus* bus = busList->at (index);
bus->setName (newName);
return kResultTrue;
}
//------------------------------------------------------------------------
// Helpers Implementation
//------------------------------------------------------------------------
tresult getSpeakerChannelIndex (SpeakerArrangement arrangement, uint64 speaker, int32& channel)
{
channel = SpeakerArr::getSpeakerIndex (speaker, arrangement);
return channel < 0 ? kResultFalse : kResultTrue;
}
} // namespace Vst
} // namespace Steinberg
| [
"[email protected]"
] | |
b54eacb64f1d68645984c5b1e71e92db1c534771 | 332515cb827e57f3359cfe0562c5b91d711752df | /Application_UWP_WinRT/Generated Files/winrt/impl/Windows.UI.Xaml.Printing.2.h | 5e5ea5bc06e58dbf3fb9e73050c826b0a0063b8c | [
"MIT"
] | permissive | GCourtney27/DX12-Simple-Xbox-Win32-Application | 7c1f09abbfb768a1d5c2ab0d7ee9621f66ad85d5 | 4f0bc4a52aa67c90376f05146f2ebea92db1ec57 | refs/heads/master | 2023-02-19T06:54:18.923600 | 2021-01-24T08:18:19 | 2021-01-24T08:18:19 | 312,744,674 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,542 | h | // WARNING: Please don't edit this file. It was generated by C++/WinRT v2.0.201113.7
#ifndef WINRT_Windows_UI_Xaml_Printing_2_H
#define WINRT_Windows_UI_Xaml_Printing_2_H
#include "winrt/impl/Windows.UI.Xaml.1.h"
#include "winrt/impl/Windows.UI.Xaml.Printing.1.h"
WINRT_EXPORT namespace winrt::Windows::UI::Xaml::Printing
{
struct AddPagesEventHandler : Windows::Foundation::IUnknown
{
AddPagesEventHandler(std::nullptr_t = nullptr) noexcept {}
AddPagesEventHandler(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Foundation::IUnknown(ptr, take_ownership_from_abi) {}
template <typename L> AddPagesEventHandler(L lambda);
template <typename F> AddPagesEventHandler(F* function);
template <typename O, typename M> AddPagesEventHandler(O* object, M method);
template <typename O, typename M> AddPagesEventHandler(com_ptr<O>&& object, M method);
template <typename O, typename M> AddPagesEventHandler(weak_ref<O>&& object, M method);
auto operator()(Windows::Foundation::IInspectable const& sender, Windows::UI::Xaml::Printing::AddPagesEventArgs const& e) const;
};
struct GetPreviewPageEventHandler : Windows::Foundation::IUnknown
{
GetPreviewPageEventHandler(std::nullptr_t = nullptr) noexcept {}
GetPreviewPageEventHandler(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Foundation::IUnknown(ptr, take_ownership_from_abi) {}
template <typename L> GetPreviewPageEventHandler(L lambda);
template <typename F> GetPreviewPageEventHandler(F* function);
template <typename O, typename M> GetPreviewPageEventHandler(O* object, M method);
template <typename O, typename M> GetPreviewPageEventHandler(com_ptr<O>&& object, M method);
template <typename O, typename M> GetPreviewPageEventHandler(weak_ref<O>&& object, M method);
auto operator()(Windows::Foundation::IInspectable const& sender, Windows::UI::Xaml::Printing::GetPreviewPageEventArgs const& e) const;
};
struct PaginateEventHandler : Windows::Foundation::IUnknown
{
PaginateEventHandler(std::nullptr_t = nullptr) noexcept {}
PaginateEventHandler(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Foundation::IUnknown(ptr, take_ownership_from_abi) {}
template <typename L> PaginateEventHandler(L lambda);
template <typename F> PaginateEventHandler(F* function);
template <typename O, typename M> PaginateEventHandler(O* object, M method);
template <typename O, typename M> PaginateEventHandler(com_ptr<O>&& object, M method);
template <typename O, typename M> PaginateEventHandler(weak_ref<O>&& object, M method);
auto operator()(Windows::Foundation::IInspectable const& sender, Windows::UI::Xaml::Printing::PaginateEventArgs const& e) const;
};
struct __declspec(empty_bases) AddPagesEventArgs : Windows::UI::Xaml::Printing::IAddPagesEventArgs
{
AddPagesEventArgs(std::nullptr_t) noexcept {}
AddPagesEventArgs(void* ptr, take_ownership_from_abi_t) noexcept : Windows::UI::Xaml::Printing::IAddPagesEventArgs(ptr, take_ownership_from_abi) {}
AddPagesEventArgs();
};
struct __declspec(empty_bases) GetPreviewPageEventArgs : Windows::UI::Xaml::Printing::IGetPreviewPageEventArgs
{
GetPreviewPageEventArgs(std::nullptr_t) noexcept {}
GetPreviewPageEventArgs(void* ptr, take_ownership_from_abi_t) noexcept : Windows::UI::Xaml::Printing::IGetPreviewPageEventArgs(ptr, take_ownership_from_abi) {}
GetPreviewPageEventArgs();
};
struct __declspec(empty_bases) PaginateEventArgs : Windows::UI::Xaml::Printing::IPaginateEventArgs
{
PaginateEventArgs(std::nullptr_t) noexcept {}
PaginateEventArgs(void* ptr, take_ownership_from_abi_t) noexcept : Windows::UI::Xaml::Printing::IPaginateEventArgs(ptr, take_ownership_from_abi) {}
PaginateEventArgs();
};
struct __declspec(empty_bases) PrintDocument : Windows::UI::Xaml::Printing::IPrintDocument,
impl::base<PrintDocument, Windows::UI::Xaml::DependencyObject>,
impl::require<PrintDocument, Windows::UI::Xaml::IDependencyObject, Windows::UI::Xaml::IDependencyObject2>
{
PrintDocument(std::nullptr_t) noexcept {}
PrintDocument(void* ptr, take_ownership_from_abi_t) noexcept : Windows::UI::Xaml::Printing::IPrintDocument(ptr, take_ownership_from_abi) {}
PrintDocument();
[[nodiscard]] static auto DocumentSourceProperty();
};
}
#endif
| [
"[email protected]"
] | |
1a9621510a5890e6f3891087573b7d14d8e3f50b | 794decce384b8e0ba625e421cc35681b16eba577 | /tensorflow/core/data/service/snapshot/utils.h | 3ea632e5e304dbb17318c166b6eb6c58c530abb7 | [
"LicenseRef-scancode-generic-cla",
"Apache-2.0",
"BSD-2-Clause"
] | permissive | 911gt3/tensorflow | a6728e86100a2d5328280cfefcfa8e7c8de24c4c | 423ea74f41d5f605933a9d9834fe2420989fe406 | refs/heads/master | 2023-04-09T14:27:29.072195 | 2023-04-03T06:20:23 | 2023-04-03T06:22:54 | 258,948,634 | 0 | 0 | Apache-2.0 | 2020-04-26T05:36:59 | 2020-04-26T05:36:58 | null | UTF-8 | C++ | false | false | 1,592 | h | /* Copyright 2022 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#ifndef TENSORFLOW_CORE_DATA_SERVICE_SNAPSHOT_UTILS_H_
#define TENSORFLOW_CORE_DATA_SERVICE_SNAPSHOT_UTILS_H_
#include <cstdint>
#include <vector>
#include "absl/strings/string_view.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/tsl/platform/status.h"
namespace tensorflow {
namespace data {
int64_t EstimatedSizeBytes(const std::vector<Tensor>& tensors);
// Returns a `Status` that indicates the snapshot stream assignment has changed
// and the worker should retry unless it's cancelled.
Status StreamAssignmentChanged(absl::string_view worker_address,
int64_t stream_index);
// Returns true if `status` indicates the snapshot stream assignment has changed
// returned by `StreamAssignmentChanged`.
bool IsStreamAssignmentChanged(const Status& status);
} // namespace data
} // namespace tensorflow
#endif // TENSORFLOW_CORE_DATA_SERVICE_SNAPSHOT_UTILS_H_
| [
"[email protected]"
] | |
90e7de7b20078ef820c8452dca297570de5bbe97 | 959e014804f834564af221244cfb858a76f0907e | /src/NN/CellList/CellNNIteratorRuntime.hpp | b8c6d5c600658a200aad127391c7ee369464f09e | [] | no_license | rurban/openfpm_data_1.1.0 | 4626ab6fba2098c2d24f3634f3e2cf75c29eb18f | e8bb5c4ba150d13596b11daa40098612b7638c81 | refs/heads/master | 2023-06-24T16:29:45.223597 | 2019-06-05T15:23:18 | 2019-06-05T15:23:18 | 144,209,213 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,532 | hpp | /*
* CellNNIteratorRuntime.hpp
*
* Created on: Nov 18, 2016
* Author: i-bird
*/
#ifndef OPENFPM_DATA_SRC_NN_CELLLIST_CELLNNITERATORRUNTIME_HPP_
#define OPENFPM_DATA_SRC_NN_CELLLIST_CELLNNITERATORRUNTIME_HPP_
#include "util/mathutil.hpp"
#define FULL openfpm::math::pow(3,dim)
#define SYM openfpm::math::pow(3,dim)/2 + 1
#define CRS openfpm::math::pow(2,dim)
#define NO_CHECK 1
#define SAFE 2
#define RUNTIME -1
/*! \brief Iterator for the neighborhood of the cell structures
*
* In general you never create it directly but you get it from the CellList structures
*
* It iterate across all the element of the selected cell and the near cells
*
* \note to calculate quantities that involve a total reduction (like energies) use the CellIteratorSymRed
*
* \tparam dim dimensionality of the space where the cell live
* \tparam Cell cell type on which the iterator is working
* \tparam impl implementation specific options NO_CHECK do not do check on access, SAFE do check on access
*
*/
template<unsigned int dim, typename Cell,unsigned int impl>
class CellNNIterator<dim,Cell,RUNTIME,impl>
{
protected:
//! actual element id
const typename Cell::Mem_type_type::loc_index * start_id;
//! stop id to read the end of the cell
const typename Cell::Mem_type_type::loc_index * stop_id;
//! Actual NNc_id;
size_t NNc_id;
//! Size of the neighboring cells
size_t NNc_size;
//! Center cell, or cell for witch we are searching the NN-cell
const long int cell;
//! actual cell id = NNc[NNc_id]+cell stored for performance reason
size_t cell_id;
//! Cell list
Cell & cl;
//! NN cell id
const long int * NNc;
/*! \brief Select non-empty cell
*
*/
inline void selectValid()
{
while (start_id == stop_id)
{
NNc_id++;
// No more Cell
if (NNc_id >= NNc_size) return;
cell_id = NNc[NNc_id] + cell;
start_id = &cl.getStartId(cell_id);
stop_id = &cl.getStopId(cell_id);
}
}
private:
public:
/*! \brief
*
* Cell NN iterator
*
* \param cell Cell id
* \param NNc Cell neighborhood indexes (relative)
* \param NNc_size size of the neighborhood
* \param cl Cell structure
*
*/
inline CellNNIterator(size_t cell, const long int * NNc, size_t NNc_size, Cell & cl)
:NNc_id(0),NNc_size(NNc_size),cell(cell),cell_id(NNc[NNc_id] + cell),cl(cl),NNc(NNc)
{
start_id = &cl.getStartId(cell_id);
stop_id = &cl.getStopId(cell_id);
selectValid();
}
/*! \brief Check if there is the next element
*
* \return true if there is the next element
*
*/
inline bool isNext()
{
if (NNc_id >= NNc_size)
return false;
return true;
}
/*! \brief take the next element
*
* \return itself
*
*/
inline CellNNIterator & operator++()
{
start_id++;
selectValid();
return *this;
}
/*! \brief Get the value of the cell
*
* \return the next element object
*
*/
inline const typename Cell::Mem_type_type::loc_index & get()
{
return cl.get_lin(start_id);
}
};
/*! \brief Symmetric iterator for the neighborhood of the cell structures
*
* In general you never create it directly but you get it from the CellList structures
*
* It iterate across all the element of the selected cell and the near cells.
*
* \note if we query the neighborhood of p and q is the neighborhood of p
* when we will query the neighborhood of q p is not present. This is
* useful to implement formula like \f$ \sum_{q = neighborhood(p) and p <= q} \f$
*
* \tparam dim dimensionality of the space where the cell live
* \tparam Cell cell type on which the iterator is working
* \tparam NNc_size neighborhood size
* \tparam impl implementation specific options NO_CHECK do not do check on access, SAFE do check on access
*
*/
template<unsigned int dim, typename Cell,unsigned int impl>
class CellNNIteratorSym<dim,Cell,RUNTIME,impl> : public CellNNIterator<dim,Cell,RUNTIME,impl>
{
//! index of the particle p
size_t p;
//! Position of the particle p
const openfpm::vector<Point<dim,typename Cell::stype>> & v;
/*! Select the next valid element
*
*/
inline void selectValid()
{
if (this->NNc[this->NNc_id] == 0)
{
while (this->start_id < this->stop_id)
{
size_t q = this->cl.get_lin(this->start_id);
for (long int i = dim-1 ; i >= 0 ; i--)
{
if (v.template get<0>(p)[i] < v.template get<0>(q)[i])
return;
else if (v.template get<0>(p)[i] > v.template get<0>(q)[i])
goto next;
}
if (q >= p) return;
next:
this->start_id++;
}
CellNNIterator<dim,Cell,RUNTIME,impl>::selectValid();
}
else
{
CellNNIterator<dim,Cell,RUNTIME,impl>::selectValid();
}
}
public:
/*! \brief
*
* Cell NN iterator
*
* \param cell Cell id
* \param p index of the particle from which we are searching the neighborhood particles
* \param NNc Cell neighborhood indexes (relative)
* \param cl Cell structure
*
*/
inline CellNNIteratorSym(size_t cell,
size_t p,
const long int * NNc,
size_t NNc_size,
Cell & cl,
const openfpm::vector<Point<dim,typename Cell::stype>> & v)
:CellNNIterator<dim,Cell,RUNTIME,impl>(cell,NNc,NNc_size,cl),p(p),v(v)
{
if (this->NNc_id >= this->NNc_size)
return;
selectValid();
}
/*! \brief take the next element
*
* \return itself
*
*/
inline CellNNIteratorSym<dim,Cell,RUNTIME,impl> & operator++()
{
this->start_id++;
selectValid();
return *this;
}
};
#endif /* OPENFPM_DATA_SRC_NN_CELLLIST_CELLNNITERATORRUNTIME_HPP_ */
| [
"[email protected]"
] | |
ff2bc2760f6a38329c29c8103fd9ac79b6d2a8e9 | b13299265bb464aa42a73ba16ab02de672328337 | /include/lemviewer.h | 851e5b135bcf37936c872b4d93f4dc8cbc7234bd | [] | no_license | jamie124/DCPU-Developer | 65f98b33bb9420f1597bd0d2ff166924df9848db | 83e5e952872a054a44badc188d9a91390eaccc4c | refs/heads/master | 2021-01-01T15:36:11.234309 | 2013-01-19T11:40:45 | 2013-01-19T11:40:45 | 4,083,735 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,417 | h | #ifndef _LEMVIEWER_H
#define _LEMVIEWER_H
#include <QGLWidget>
#include "constants.h"
#include "emulator.h"
#include <QMutex>
const int CHAR_WIDTH = 4;
const int CHAR_HEIGHT = 8;
const int COLUMNS = 32;
const int ROWS = 12;
const int WIDTH = COLUMNS * CHAR_WIDTH;
const int HEIGHT = ROWS * CHAR_HEIGHT;
// Size of pixel, scaled up to create 0x10c look
const int PIXEL_WIDTH = 3;
const int PIXEL_HEIGHT = 3;
const int REAL_WIDTH = WIDTH * PIXEL_WIDTH;
const int REAL_HEIGHT = HEIGHT * PIXEL_HEIGHT;
const word_t defaultPalette[] = {
0x000, 0x00a, 0x0a0, 0x0aa,
0xa00, 0xa0a, 0xa50, 0xaaa,
0x555, 0x55f, 0x5f5, 0x5ff,
0xf55, 0xf5f, 0xff5, 0xfff
};
const word_t defaultFont[] = {
0xb79e, 0x388e, 0x722c, 0x75f4, 0x19bb, 0x7f8f, 0x85f9, 0xb158, 0x242e, 0x2400, 0x082a, 0x0800, 0x0008, 0x0000, 0x0808, 0x0808,
0x00ff, 0x0000, 0x00f8, 0x0808, 0x08f8, 0x0000, 0x080f, 0x0000, 0x000f, 0x0808, 0x00ff, 0x0808, 0x08f8, 0x0808, 0x08ff, 0x0000,
0x080f, 0x0808, 0x08ff, 0x0808, 0x6633, 0x99cc, 0x9933, 0x66cc, 0xfef8, 0xe080, 0x7f1f, 0x0701, 0x0107, 0x1f7f, 0x80e0, 0xf8fe,
0x5500, 0xaa00, 0x55aa, 0x55aa, 0xffaa, 0xff55, 0x0f0f, 0x0f0f, 0xf0f0, 0xf0f0, 0x0000, 0xffff, 0xffff, 0x0000, 0xffff, 0xffff,
0x0000, 0x0000, 0x005f, 0x0000, 0x0300, 0x0300, 0x3e14, 0x3e00, 0x266b, 0x3200, 0x611c, 0x4300, 0x3629, 0x7650, 0x0002, 0x0100,
0x1c22, 0x4100, 0x4122, 0x1c00, 0x1408, 0x1400, 0x081c, 0x0800, 0x4020, 0x0000, 0x0808, 0x0800, 0x0040, 0x0000, 0x601c, 0x0300,
0x3e49, 0x3e00, 0x427f, 0x4000, 0x6259, 0x4600, 0x2249, 0x3600, 0x0f08, 0x7f00, 0x2745, 0x3900, 0x3e49, 0x3200, 0x6119, 0x0700,
0x3649, 0x3600, 0x2649, 0x3e00, 0x0024, 0x0000, 0x4024, 0x0000, 0x0814, 0x2200, 0x1414, 0x1400, 0x2214, 0x0800, 0x0259, 0x0600,
0x3e59, 0x5e00, 0x7e09, 0x7e00, 0x7f49, 0x3600, 0x3e41, 0x2200, 0x7f41, 0x3e00, 0x7f49, 0x4100, 0x7f09, 0x0100, 0x3e41, 0x7a00,
0x7f08, 0x7f00, 0x417f, 0x4100, 0x2040, 0x3f00, 0x7f08, 0x7700, 0x7f40, 0x4000, 0x7f06, 0x7f00, 0x7f01, 0x7e00, 0x3e41, 0x3e00,
0x7f09, 0x0600, 0x3e61, 0x7e00, 0x7f09, 0x7600, 0x2649, 0x3200, 0x017f, 0x0100, 0x3f40, 0x7f00, 0x1f60, 0x1f00, 0x7f30, 0x7f00,
0x7708, 0x7700, 0x0778, 0x0700, 0x7149, 0x4700, 0x007f, 0x4100, 0x031c, 0x6000, 0x417f, 0x0000, 0x0201, 0x0200, 0x8080, 0x8000,
0x0001, 0x0200, 0x2454, 0x7800, 0x7f44, 0x3800, 0x3844, 0x2800, 0x3844, 0x7f00, 0x3854, 0x5800, 0x087e, 0x0900, 0x4854, 0x3c00,
0x7f04, 0x7800, 0x047d, 0x0000, 0x2040, 0x3d00, 0x7f10, 0x6c00, 0x017f, 0x0000, 0x7c18, 0x7c00, 0x7c04, 0x7800, 0x3844, 0x3800,
0x7c14, 0x0800, 0x0814, 0x7c00, 0x7c04, 0x0800, 0x4854, 0x2400, 0x043e, 0x4400, 0x3c40, 0x7c00, 0x1c60, 0x1c00, 0x7c30, 0x7c00,
0x6c10, 0x6c00, 0x4c50, 0x3c00, 0x6454, 0x4c00, 0x0836, 0x4100, 0x0077, 0x0000, 0x4136, 0x0800, 0x0201, 0x0201, 0x0205, 0x0200
};
class LemViewer :
public QGLWidget
{
Q_OBJECT
public:
LemViewer(Emulator *emu, QWidget *parent = 0);
~LemViewer();
void queueChar(int c, int r);
void drawScreen();
void drawChar(int c, int r);
void drawLoop();
void updateChar(word_t key);
word_t getColour(word_t value);
void setScreenAddress(long ramAddress);
public slots:
void animate();
protected:
void paintEvent(QPaintEvent *event);
private:
int elapsed;
Emulator *emulator;
long screenAddress;
word_map memory;
word_t videoBuffer[WIDTH][HEIGHT];
//QMap<int, QMap<int, int>> videoBuffer;
QMap<int, QMap<int, bool> > cellQueue;
bool initialised;
};
#endif
| [
"[email protected]"
] | |
9384681a8ebcae72126edc49a2f1a1bd6af8758e | e132d5b086464fe0651223df74f06ff16dfbdcff | /example/doc/http_examples.hpp | 4cd879ae33d50860d75cdddada4cbb427748f006 | [
"BSL-1.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | shibing/beast | fa1de3a19ecd1bf55120b92e4ebdf9cf99894f24 | c495f946c92c1175d30e1e8e60d412c3a30025b4 | refs/heads/develop | 2021-01-02T22:56:23.222703 | 2017-08-03T15:53:12 | 2017-08-03T15:53:12 | 99,427,713 | 1 | 0 | null | 2017-08-05T14:29:21 | 2017-08-05T14:29:21 | null | UTF-8 | C++ | false | false | 35,802 | hpp | //
// Copyright (c) 2016-2017 Vinnie Falco (vinnie dot falco at gmail dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
// Official repository: https://github.com/boostorg/beast
//
#include <boost/beast.hpp>
#include <iostream>
/* This file contains the functions and classes found in the documentation
They are compiled and run as part of the unit tests, so you can copy
the code and use it in your own projects as a starting point for
building a network application.
*/
// The documentation assumes the boost::beast::http namespace
namespace boost {
namespace beast {
namespace http {
//------------------------------------------------------------------------------
//
// Example: Expect 100-continue
//
//------------------------------------------------------------------------------
//[example_http_send_expect_100_continue
/** Send a request with Expect: 100-continue
This function will send a request with the Expect: 100-continue
field by first sending the header, then waiting for a successful
response from the server before continuing to send the body. If
a non-successful server response is received, the function
returns immediately.
@param stream The remote HTTP server stream.
@param buffer The buffer used for reading.
@param req The request to send. This function modifies the object:
the Expect header field is inserted into the message if it does
not already exist, and set to "100-continue".
@param ec Set to the error, if any occurred.
*/
template<
class SyncStream,
class DynamicBuffer,
class Body, class Allocator>
void
send_expect_100_continue(
SyncStream& stream,
DynamicBuffer& buffer,
request<Body, basic_fields<Allocator>>& req,
error_code& ec)
{
static_assert(is_sync_stream<SyncStream>::value,
"SyncStream requirements not met");
static_assert(is_dynamic_buffer<DynamicBuffer>::value,
"DynamicBuffer requirements not met");
// Insert or replace the Expect field
req.set(field::expect, "100-continue");
// Create the serializer
request_serializer<Body, basic_fields<Allocator>> sr{req};
// Send just the header
write_header(stream, sr, ec);
if(ec)
return;
// Read the response from the server.
// A robust client could set a timeout here.
{
response<string_body> res;
read(stream, buffer, res, ec);
if(ec)
return;
if(res.result() != status::continue_)
{
// The server indicated that it will not
// accept the request, so skip sending the body.
return;
}
}
// Server is OK with the request, send the body
write(stream, sr, ec);
}
//]
//[example_http_receive_expect_100_continue
/** Receive a request, handling Expect: 100-continue if present.
This function will read a request from the specified stream.
If the request contains the Expect: 100-continue field, a
status response will be delivered.
@param stream The remote HTTP client stream.
@param buffer The buffer used for reading.
@param ec Set to the error, if any occurred.
*/
template<
class SyncStream,
class DynamicBuffer>
void
receive_expect_100_continue(
SyncStream& stream,
DynamicBuffer& buffer,
error_code& ec)
{
static_assert(is_sync_stream<SyncStream>::value,
"SyncStream requirements not met");
static_assert(is_dynamic_buffer<DynamicBuffer>::value,
"DynamicBuffer requirements not met");
// Declare a parser for a request with a string body
request_parser<string_body> parser;
// Read the header
read_header(stream, buffer, parser, ec);
if(ec)
return;
// Check for the Expect field value
if(parser.get()[field::expect] == "100-continue")
{
// send 100 response
response<empty_body> res;
res.version = 11;
res.result(status::continue_);
res.set(field::server, "test");
write(stream, res, ec);
if(ec)
return;
}
// Read the rest of the message.
//
// We use parser.base() to return a basic_parser&, to avoid an
// ambiguous function error (from boost::asio::read). Another
// solution is to qualify the call, e.g. `beast::http::read`
//
read(stream, buffer, parser.base(), ec);
}
//]
//------------------------------------------------------------------------------
//
// Example: Send Child Process Output
//
//------------------------------------------------------------------------------
//[example_http_send_cgi_response
/** Send the output of a child process as an HTTP response.
The output of the child process comes from a @b SyncReadStream. Data
will be sent continuously as it is produced, without the requirement
that the entire process output is buffered before being sent. The
response will use the chunked transfer encoding.
@param input A stream to read the child process output from.
@param output A stream to write the HTTP response to.
@param ec Set to the error, if any occurred.
*/
template<
class SyncReadStream,
class SyncWriteStream>
void
send_cgi_response(
SyncReadStream& input,
SyncWriteStream& output,
error_code& ec)
{
static_assert(is_sync_read_stream<SyncReadStream>::value,
"SyncReadStream requirements not met");
static_assert(is_sync_write_stream<SyncWriteStream>::value,
"SyncWriteStream requirements not met");
using boost::asio::buffer_cast;
using boost::asio::buffer_size;
// Set up the response. We use the buffer_body type,
// allowing serialization to use manually provided buffers.
response<buffer_body> res;
res.result(status::ok);
res.version = 11;
res.set(field::server, "Beast");
res.set(field::transfer_encoding, "chunked");
// No data yet, but we set more = true to indicate
// that it might be coming later. Otherwise the
// serializer::is_done would return true right after
// sending the header.
res.body.data = nullptr;
res.body.more = true;
// Create the serializer.
response_serializer<buffer_body, fields> sr{res};
// Send the header immediately.
write_header(output, sr, ec);
if(ec)
return;
// Alternate between reading from the child process
// and sending all the process output until there
// is no more output.
do
{
// Read a buffer from the child process
char buffer[2048];
auto bytes_transferred = input.read_some(
boost::asio::buffer(buffer, sizeof(buffer)), ec);
if(ec == boost::asio::error::eof)
{
ec = {};
// `nullptr` indicates there is no buffer
res.body.data = nullptr;
// `false` means no more data is coming
res.body.more = false;
}
else
{
if(ec)
return;
// Point to our buffer with the bytes that
// we received, and indicate that there may
// be some more data coming
res.body.data = buffer;
res.body.size = bytes_transferred;
res.body.more = true;
}
// Write everything in the body buffer
write(output, sr, ec);
// This error is returned by body_buffer during
// serialization when it is done sending the data
// provided and needs another buffer.
if(ec == error::need_buffer)
{
ec = {};
continue;
}
if(ec)
return;
}
while(! sr.is_done());
}
//]
//--------------------------------------------------------------------------
//
// Example: HEAD Request
//
//--------------------------------------------------------------------------
//[example_http_do_head_response
/** Handle a HEAD request for a resource.
*/
template<
class SyncStream,
class DynamicBuffer
>
void do_server_head(
SyncStream& stream,
DynamicBuffer& buffer,
error_code& ec)
{
static_assert(is_sync_stream<SyncStream>::value,
"SyncStream requirements not met");
static_assert(is_dynamic_buffer<DynamicBuffer>::value,
"DynamicBuffer requirments not met");
// We deliver this payload for all GET requests
static std::string const payload = "Hello, world!";
// Read the request
request<string_body> req;
read(stream, buffer, req, ec);
if(ec)
return;
// Set up the response, starting with the common fields
response<string_body> res;
res.version = 11;
res.set(field::server, "test");
// Now handle request-specific fields
switch(req.method())
{
case verb::head:
case verb::get:
{
// A HEAD request is handled by delivering the same
// set of headers that would be sent for a GET request,
// including the Content-Length, except for the body.
res.result(status::ok);
res.set(field::content_length, payload.size());
// For GET requests, we include the body
if(req.method() == verb::get)
{
// We deliver the same payload for GET requests
// regardless of the target. A real server might
// deliver a file based on the target.
res.body = payload;
}
break;
}
default:
{
// We return responses indicating an error if
// we do not recognize the request method.
res.result(status::bad_request);
res.set(field::content_type, "text/plain");
res.body = "Invalid request-method '" + req.method_string().to_string() + "'";
res.prepare_payload();
break;
}
}
// Send the response
write(stream, res, ec);
if(ec)
return;
}
//]
//[example_http_do_head_request
/** Send a HEAD request for a resource.
This function submits a HEAD request for the specified resource
and returns the response.
@param res The response. This is an output parameter.
@param stream The synchronous stream to use.
@param buffer The buffer to use.
@param target The request target.
@param ec Set to the error, if any occurred.
@throws std::invalid_argument if target is empty.
*/
template<
class SyncStream,
class DynamicBuffer
>
response<empty_body>
do_head_request(
SyncStream& stream,
DynamicBuffer& buffer,
string_view target,
error_code& ec)
{
// Do some type checking to be a good citizen
static_assert(is_sync_stream<SyncStream>::value,
"SyncStream requirements not met");
static_assert(is_dynamic_buffer<DynamicBuffer>::value,
"DynamicBuffer requirments not met");
// The interfaces we are using are low level and do not
// perform any checking of arguments; so we do it here.
if(target.empty())
throw std::invalid_argument("target may not be empty");
// Build the HEAD request for the target
request<empty_body> req;
req.version = 11;
req.method(verb::head);
req.target(target);
req.set(field::user_agent, "test");
// A client MUST send a Host header field in all HTTP/1.1 request messages.
// https://tools.ietf.org/html/rfc7230#section-5.4
req.set(field::host, "localhost");
// Now send it
write(stream, req, ec);
if(ec)
return {};
// Create a parser to read the response.
// Responses to HEAD requests MUST NOT include
// a body, so we use the `empty_body` type and
// only attempt to read the header.
parser<false, empty_body> p;
read_header(stream, buffer, p, ec);
if(ec)
return {};
// Transfer ownership of the response to the caller.
return p.release();
}
//]
//------------------------------------------------------------------------------
//
// Example: HTTP Relay
//
//------------------------------------------------------------------------------
//[example_http_relay
/** Relay an HTTP message.
This function efficiently relays an HTTP message from a downstream
client to an upstream server, or from an upstream server to a
downstream client. After the message header is read from the input,
a user provided transformation function is invoked which may change
the contents of the header before forwarding to the output. This may
be used to adjust fields such as Server, or proxy fields.
@param output The stream to write to.
@param input The stream to read from.
@param buffer The buffer to use for the input.
@param transform The header transformation to apply. The function will
be called with this signature:
@code
template<class Body>
void transform(message<
isRequest, Body, Fields>&, // The message to transform
error_code&); // Set to the error, if any
@endcode
@param ec Set to the error if any occurred.
@tparam isRequest `true` to relay a request.
@tparam Fields The type of fields to use for the message.
*/
template<
bool isRequest,
class SyncWriteStream,
class SyncReadStream,
class DynamicBuffer,
class Transform>
void
relay(
SyncWriteStream& output,
SyncReadStream& input,
DynamicBuffer& buffer,
error_code& ec,
Transform&& transform)
{
static_assert(is_sync_write_stream<SyncWriteStream>::value,
"SyncWriteStream requirements not met");
static_assert(is_sync_read_stream<SyncReadStream>::value,
"SyncReadStream requirements not met");
// A small buffer for relaying the body piece by piece
char buf[2048];
// Create a parser with a buffer body to read from the input.
parser<isRequest, buffer_body> p;
// Create a serializer from the message contained in the parser.
serializer<isRequest, buffer_body, fields> sr{p.get()};
// Read just the header from the input
read_header(input, buffer, p, ec);
if(ec)
return;
// Apply the caller's header tranformation
transform(p.get(), ec);
if(ec)
return;
// Send the transformed message to the output
write_header(output, sr, ec);
if(ec)
return;
// Loop over the input and transfer it to the output
do
{
if(! p.is_done())
{
// Set up the body for writing into our small buffer
p.get().body.data = buf;
p.get().body.size = sizeof(buf);
// Read as much as we can
read(input, buffer, p, ec);
// This error is returned when buffer_body uses up the buffer
if(ec == error::need_buffer)
ec = {};
if(ec)
return;
// Set up the body for reading.
// This is how much was parsed:
p.get().body.size = sizeof(buf) - p.get().body.size;
p.get().body.data = buf;
p.get().body.more = ! p.is_done();
}
else
{
p.get().body.data = nullptr;
p.get().body.size = 0;
}
// Write everything in the buffer (which might be empty)
write(output, sr, ec);
// This error is returned when buffer_body uses up the buffer
if(ec == error::need_buffer)
ec = {};
if(ec)
return;
}
while(! p.is_done() && ! sr.is_done());
}
//]
//------------------------------------------------------------------------------
//
// Example: Serialize to std::ostream
//
//------------------------------------------------------------------------------
//[example_http_write_ostream
// The detail namespace means "not public"
namespace detail {
// This helper is needed for C++11.
// When invoked with a buffer sequence, writes the buffers `to the std::ostream`.
template<class Serializer>
class write_ostream_helper
{
Serializer& sr_;
std::ostream& os_;
public:
write_ostream_helper(Serializer& sr, std::ostream& os)
: sr_(sr)
, os_(os)
{
}
// This function is called by the serializer
template<class ConstBufferSequence>
void
operator()(error_code& ec, ConstBufferSequence const& buffers) const
{
// These asio functions are needed to access a buffer's contents
using boost::asio::buffer_cast;
using boost::asio::buffer_size;
// Error codes must be cleared on success
ec = {};
// Keep a running total of how much we wrote
std::size_t bytes_transferred = 0;
// Loop over the buffer sequence
for(auto it = buffers.begin(); it != buffers.end(); ++ it)
{
// This is the next buffer in the sequence
boost::asio::const_buffer const buffer = *it;
// Write it to the std::ostream
os_.write(
buffer_cast<char const*>(buffer),
buffer_size(buffer));
// If the std::ostream fails, convert it to an error code
if(os_.fail())
{
ec = make_error_code(errc::io_error);
return;
}
// Adjust our running total
bytes_transferred += buffer_size(buffer);
}
// Inform the serializer of the amount we consumed
sr_.consume(bytes_transferred);
}
};
} // detail
/** Write a message to a `std::ostream`.
This function writes the serialized representation of the
HTTP/1 message to the sream.
@param os The `std::ostream` to write to.
@param msg The message to serialize.
@param ec Set to the error, if any occurred.
*/
template<
bool isRequest,
class Body,
class Fields>
void
write_ostream(
std::ostream& os,
message<isRequest, Body, Fields>& msg,
error_code& ec)
{
// Create the serializer instance
serializer<isRequest, Body, Fields> sr{msg};
// This lambda is used as the "visit" function
detail::write_ostream_helper<decltype(sr)> lambda{sr, os};
do
{
// In C++14 we could use a generic lambda but since we want
// to require only C++11, the lambda is written out by hand.
// This function call retrieves the next serialized buffers.
sr.next(ec, lambda);
if(ec)
return;
}
while(! sr.is_done());
}
//]
//------------------------------------------------------------------------------
//
// Example: Parse from std::istream
//
//------------------------------------------------------------------------------
//[example_http_read_istream
/** Read a message from a `std::istream`.
This function attempts to parse a complete HTTP/1 message from the stream.
@param is The `std::istream` to read from.
@param buffer The buffer to use.
@param msg The message to store the result.
@param ec Set to the error, if any occurred.
*/
template<
class Allocator,
bool isRequest,
class Body>
void
read_istream(
std::istream& is,
basic_flat_buffer<Allocator>& buffer,
message<isRequest, Body, fields>& msg,
error_code& ec)
{
// Create the message parser
//
// Arguments passed to the parser's constructor are
// forwarded to the message constructor. Here, we use
// a move construction in case the caller has constructed
// their message in a non-default way.
//
parser<isRequest, Body> p{std::move(msg)};
do
{
// Extract whatever characters are presently available in the istream
if(is.rdbuf()->in_avail() > 0)
{
// Get a mutable buffer sequence for writing
auto const mb = buffer.prepare(
static_cast<std::size_t>(is.rdbuf()->in_avail()));
// Now get everything we can from the istream
buffer.commit(static_cast<std::size_t>(is.readsome(
boost::asio::buffer_cast<char*>(mb),
boost::asio::buffer_size(mb))));
}
else if(buffer.size() == 0)
{
// Our buffer is empty and we need more characters,
// see if we've reached the end of file on the istream
if(! is.eof())
{
// Get a mutable buffer sequence for writing
auto const mb = buffer.prepare(1024);
// Try to get more from the istream. This might block.
is.read(
boost::asio::buffer_cast<char*>(mb),
boost::asio::buffer_size(mb));
// If an error occurs on the istream then return it to the caller.
if(is.fail() && ! is.eof())
{
// We'll just re-use io_error since std::istream has no error_code interface.
ec = make_error_code(errc::io_error);
return;
}
// Commit the characters we got to the buffer.
buffer.commit(static_cast<std::size_t>(is.gcount()));
}
else
{
// Inform the parser that we've reached the end of the istream.
p.put_eof(ec);
if(ec)
return;
break;
}
}
// Write the data to the parser
auto const bytes_used = p.put(buffer.data(), ec);
// This error means that the parser needs additional octets.
if(ec == error::need_more)
ec = {};
if(ec)
return;
// Consume the buffer octets that were actually parsed.
buffer.consume(bytes_used);
}
while(! p.is_done());
// Transfer ownership of the message container in the parser to the caller.
msg = p.release();
}
//]
//------------------------------------------------------------------------------
//
// Example: Deferred Body Type
//
//------------------------------------------------------------------------------
//[example_http_defer_body
/** Handle a form POST request, choosing a body type depending on the Content-Type.
This reads a request from the input stream. If the method is POST, and
the Content-Type is "application/x-www-form-urlencoded " or
"multipart/form-data", a `string_body` is used to receive and store
the message body. Otherwise, a `dynamic_body` is used to store the message
body. After the request is received, the handler will be invoked with the
request.
@param stream The stream to read from.
@param buffer The buffer to use for reading.
@param handler The handler to invoke when the request is complete.
The handler must be invokable with this signature:
@code
template<class Body>
void handler(request<Body>&& req);
@endcode
@throws system_error Thrown on failure.
*/
template<
class SyncReadStream,
class DynamicBuffer,
class Handler>
void
do_form_request(
SyncReadStream& stream,
DynamicBuffer& buffer,
Handler&& handler)
{
// Start with an empty_body parser
request_parser<empty_body> req0;
// Read just the header. Otherwise, the empty_body
// would generate an error if body octets were received.
read_header(stream, buffer, req0);
// Choose a body depending on the method verb
switch(req0.get().method())
{
case verb::post:
{
// If this is not a form upload then use a string_body
if( req0.get()[field::content_type] != "application/x-www-form-urlencoded" &&
req0.get()[field::content_type] != "multipart/form-data")
goto do_dynamic_body;
// Commit to string_body as the body type.
// As long as there are no body octets in the parser
// we are constructing from, no exception is thrown.
request_parser<string_body> req{std::move(req0)};
// Finish reading the message
read(stream, buffer, req);
// Call the handler. It can take ownership
// if desired, since we are calling release()
handler(req.release());
break;
}
do_dynamic_body:
default:
{
// Commit to dynamic_body as the body type.
// As long as there are no body octets in the parser
// we are constructing from, no exception is thrown.
request_parser<dynamic_body> req{std::move(req0)};
// Finish reading the message
read(stream, buffer, req);
// Call the handler. It can take ownership
// if desired, since we are calling release()
handler(req.release());
break;
}
}
}
//]
//------------------------------------------------------------------------------
//
// Example: Custom Parser
//
//------------------------------------------------------------------------------
//[example_http_custom_parser
template<bool isRequest>
class custom_parser
: public basic_parser<isRequest, custom_parser<isRequest>>
{
private:
// The friend declaration is needed,
// otherwise the callbacks must be made public.
friend class basic_parser<isRequest, custom_parser>;
/// Called after receiving the request-line (isRequest == true).
void
on_request_impl(
verb method, // The method verb, verb::unknown if no match
string_view method_str, // The method as a string
string_view target, // The request-target
int version, // The HTTP-version
error_code& ec); // The error returned to the caller, if any
/// Called after receiving the start-line (isRequest == false).
void
on_response_impl(
int code, // The status-code
string_view reason, // The obsolete reason-phrase
int version, // The HTTP-version
error_code& ec); // The error returned to the caller, if any
/// Called after receiving a header field.
void
on_field_impl(
field f, // The known-field enumeration constant
string_view name, // The field name string.
string_view value, // The field value
error_code& ec); // The error returned to the caller, if any
/// Called after the complete header is received.
void
on_header_impl(
error_code& ec); // The error returned to the caller, if any
/// Called just before processing the body, if a body exists.
void
on_body_init_impl(
boost::optional<
std::uint64_t> const&
content_length, // Content length if known, else `boost::none`
error_code& ec); // The error returned to the caller, if any
/// Called for each piece of the body, if a body exists.
//!
//! This is used when there is no chunked transfer coding.
//!
//! The function returns the number of bytes consumed from the
//! input buffer. Any input octets not consumed will be will be
//! presented on subsequent calls.
//!
std::size_t
on_body_impl(
string_view s, // A portion of the body
error_code& ec); // The error returned to the caller, if any
/// Called for each chunk header.
void
on_chunk_header_impl(
std::uint64_t size, // The size of the upcoming chunk,
// or zero for the last chunk
string_view extension, // The chunk extensions (may be empty)
error_code& ec); // The error returned to the caller, if any
/// Called to deliver the chunk body.
//!
//! This is used when there is a chunked transfer coding. The
//! implementation will automatically remove the encoding before
//! calling this function.
//!
//! The function returns the number of bytes consumed from the
//! input buffer. Any input octets not consumed will be will be
//! presented on subsequent calls.
//!
std::size_t
on_chunk_body_impl(
std::uint64_t remain, // The number of bytes remaining in the chunk,
// including what is being passed here.
// or zero for the last chunk
string_view body, // The next piece of the chunk body
error_code& ec); // The error returned to the caller, if any
/// Called when the complete message is parsed.
void
on_finish_impl(error_code& ec);
public:
custom_parser() = default;
};
//]
// Definitions are not part of the docs but necessary to link
template<bool isRequest>
void custom_parser<isRequest>::
on_request_impl(verb method, string_view method_str,
string_view path, int version, error_code& ec)
{
boost::ignore_unused(method, method_str, path, version);
ec = {};
}
template<bool isRequest>
void custom_parser<isRequest>::
on_response_impl(
int status,
string_view reason,
int version,
error_code& ec)
{
boost::ignore_unused(status, reason, version);
ec = {};
}
template<bool isRequest>
void custom_parser<isRequest>::
on_field_impl(
field f,
string_view name,
string_view value,
error_code& ec)
{
boost::ignore_unused(f, name, value);
ec = {};
}
template<bool isRequest>
void custom_parser<isRequest>::
on_header_impl(error_code& ec)
{
ec = {};
}
template<bool isRequest>
void custom_parser<isRequest>::
on_body_init_impl(
boost::optional<std::uint64_t> const& content_length,
error_code& ec)
{
boost::ignore_unused(content_length);
ec = {};
}
template<bool isRequest>
std::size_t custom_parser<isRequest>::
on_body_impl(string_view body, error_code& ec)
{
boost::ignore_unused(body);
ec = {};
return body.size();
}
template<bool isRequest>
void custom_parser<isRequest>::
on_chunk_header_impl(
std::uint64_t size,
string_view extension,
error_code& ec)
{
boost::ignore_unused(size, extension);
ec = {};
}
template<bool isRequest>
std::size_t custom_parser<isRequest>::
on_chunk_body_impl(
std::uint64_t remain,
string_view body,
error_code& ec)
{
boost::ignore_unused(remain);
ec = {};
return body.size();
}
template<bool isRequest>
void custom_parser<isRequest>::
on_finish_impl(error_code& ec)
{
ec = {};
}
//------------------------------------------------------------------------------
//
// Example: Incremental Read
//
//------------------------------------------------------------------------------
//[example_incremental_read
/* This function reads a message using a fixed size buffer to hold
portions of the body, and prints the body contents to a `std::ostream`.
*/
template<
bool isRequest,
class SyncReadStream,
class DynamicBuffer>
void
read_and_print_body(
std::ostream& os,
SyncReadStream& stream,
DynamicBuffer& buffer,
error_code& ec)
{
parser<isRequest, buffer_body> p;
read_header(stream, buffer, p, ec);
if(ec)
return;
while(! p.is_done())
{
char buf[512];
p.get().body.data = buf;
p.get().body.size = sizeof(buf);
read(stream, buffer, p, ec);
if(ec == error::need_buffer)
ec.assign(0, ec.category());
if(ec)
return;
os.write(buf, sizeof(buf) - p.get().body.size);
}
}
//]
//------------------------------------------------------------------------------
//
// Example: Expect 100-continue
//
//------------------------------------------------------------------------------
//[example_chunk_parsing
/** Read a message with a chunked body and print the chunks and extensions
*/
template<
bool isRequest,
class SyncReadStream,
class DynamicBuffer>
void
print_chunked_body(
std::ostream& os,
SyncReadStream& stream,
DynamicBuffer& buffer,
error_code& ec)
{
// Declare the parser with an empty body since
// we plan on capturing the chunks ourselves.
parser<isRequest, empty_body> p;
// First read the complete header
read_header(stream, buffer, p, ec);
if(ec)
return;
// This container will hold the extensions for each chunk
chunk_extensions ce;
// This string will hold the body of each chunk
std::string chunk;
// Declare our chunk header callback This is invoked
// after each chunk header and also after the last chunk.
auto header_cb =
[&](std::uint64_t size, // Size of the chunk, or zero for the last chunk
string_view extensions, // The raw chunk-extensions string. Already validated.
error_code& ev) // We can set this to indicate an error
{
// Parse the chunk extensions so we can access them easily
ce.parse(extensions, ev);
if(ev)
return;
// See if the chunk is too big
if(size > (std::numeric_limits<std::size_t>::max)())
{
ev = error::body_limit;
return;
}
// Make sure we have enough storage, and
// reset the container for the upcoming chunk
chunk.reserve(static_cast<std::size_t>(size));
chunk.clear();
};
// Set the callback. The function requires a non-const reference so we
// use a local variable, since temporaries can only bind to const refs.
p.on_chunk_header(header_cb);
// Declare the chunk body callback. This is called one or
// more times for each piece of a chunk body.
auto body_cb =
[&](std::uint64_t remain, // The number of bytes left in this chunk
string_view body, // A buffer holding chunk body data
error_code& ec) // We can set this to indicate an error
{
// If this is the last piece of the chunk body,
// set the error so that the call to `read` returns
// and we can process the chunk.
if(remain == body.size())
ec = error::end_of_chunk;
// Append this piece to our container
chunk.append(body.data(), body.size());
// The return value informs the parser of how much of the body we
// consumed. We will indicate that we consumed everything passed in.
return body.size();
};
p.on_chunk_body(body_cb);
while(! p.is_done())
{
// Read as much as we can. When we reach the end of the chunk, the chunk
// body callback will make the read return with the end_of_chunk error.
read(stream, buffer, p, ec);
if(! ec)
continue;
else if(ec != error::end_of_chunk)
return;
else
ec.assign(0, ec.category());
// We got a whole chunk, print the extensions:
for(auto const& extension : ce)
{
os << "Extension: " << extension.first;
if(! extension.second.empty())
os << " = " << extension.second << std::endl;
else
os << std::endl;
}
// Now print the chunk body
os << "Chunk Body: " << chunk << std::endl;
}
// Get a reference to the parsed message, this is for convenience
auto const& msg = p.get();
// Check each field promised in the "Trailer" header and output it
for(auto const& name : token_list{msg[field::trailer]})
{
// Find the trailer field
auto it = msg.find(name);
if(it == msg.end())
{
// Oops! They promised the field but failed to deliver it
os << "Missing Trailer: " << name << std::endl;
continue;
}
os << it->name() << ": " << it->value() << std::endl;
}
}
//]
} // http
} // beast
} // boost
| [
"[email protected]"
] | |
b8858cf97fd7aab067a4c9453ac9560d552b4104 | a15ca13cce9b7abd1ae3ddaa255eb452b4b6f557 | /examples/compressor/ex_compressor.cpp | c96a6a88579c9ff4a38c4e661534993681117c1f | [
"MIT"
] | permissive | jrepp/DaisySP | 1b0dd4981ed02b5a04f560ff80635e62ea1c45ee | cc68b240424538c498b5c01b73ae44038458da2b | refs/heads/master | 2021-02-26T20:39:35.093106 | 2020-03-06T21:32:20 | 2020-03-06T21:32:20 | 245,552,003 | 1 | 0 | null | 2020-03-07T02:06:45 | 2020-03-07T02:06:44 | null | UTF-8 | C++ | false | false | 2,155 | cpp | #include "daisysp.h"
#include "daisy_seed.h"
// Shortening long macro for sample rate
#ifndef SAMPLE_RATE
#define SAMPLE_RATE DSY_AUDIO_SAMPLE_RATE
#endif
// Interleaved audio definitions
#define LEFT (i)
#define RIGHT (i+1)
using namespace daisysp;
static daisy_handle seed;
static Compressor comp;
// Helper Modules
static AdEnv env;
static Oscillator osc_a, osc_b;
static Metro tick;
static void AudioCallback(float *in, float *out, size_t size)
{
float osc_a_out, osc_b_out, env_out, sig_out;
for (size_t i = 0; i < size; i += 2)
{
// When the metro ticks:
// trigger the envelope to start
if (tick.Process())
{
env.Trigger();
}
// Use envelope to control the amplitude of the oscillator.
env_out = env.Process();
osc_a.SetAmp(env_out);
osc_a_out = osc_a.Process();
osc_b_out = osc_b.Process();
// Compress the steady tone with the enveloped tone.
sig_out = comp.Process(osc_b_out, osc_a_out);
// Output
out[LEFT] = sig_out; // compressed
out[RIGHT] = osc_a_out; // key signal
}
}
int main(void)
{
// initialize seed hardware and daisysp modules
daisy_seed_init(&seed);
comp.Init(SAMPLE_RATE);
env.Init(SAMPLE_RATE);
osc_a.Init(SAMPLE_RATE);
osc_b.Init(SAMPLE_RATE);
// Set up metro to pulse every second
tick.Init(1.0f, SAMPLE_RATE);
// set compressor parameters
comp.SetThreshold(-64.0f);
comp.SetRatio(2.0f);
comp.SetAttack(0.005f);
comp.SetRelease(0.1250);
// set adenv parameters
env.SetTime(ADENV_SEG_ATTACK, 0.001);
env.SetTime(ADENV_SEG_DECAY, 0.50);
env.SetMin(0.0);
env.SetMax(0.25);
env.SetCurve(0); // linear
// Set parameters for oscillator
osc_a.SetWaveform(Oscillator::WAVE_TRI);
osc_a.SetFreq(110);
osc_a.SetAmp(0.25);
osc_b.SetWaveform(Oscillator::WAVE_TRI);
osc_b.SetFreq(220);
osc_b.SetAmp(0.25);
// define callback
dsy_audio_set_callback(DSY_AUDIO_INTERNAL, AudioCallback);
// start callback
dsy_audio_start(DSY_AUDIO_INTERNAL);
while(1) {}
}
| [
"[email protected]"
] | |
04f3bf59a6968978a904c83f0712ca5e0ffa488f | be8718f6882f2b4b124b245d10d1d05c2e09a901 | /Engine/Source/Shared/Import/Mdl/MdlNode.cpp | 124f9d419de8f8cb5e8219e2d627270585d87776 | [] | no_license | kolhammer/Psybrus | fd907a8e25b488327846d46853ca219c55cca81b | 21c794568eed41aaacb633cd87dedd5ce2793115 | refs/heads/master | 2016-09-05T08:58:04.427316 | 2012-03-19T11:33:32 | 2012-03-19T11:33:32 | 3,031,999 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 6,811 | cpp | /**************************************************************************
*
* File: MdlNode.cpp
* Author: Neil Richardson
* Ver/Date:
* Description:
* Model node.
*
*
*
*
**************************************************************************/
#include "MdlNode.h"
#include "MdlMesh.h"
#include "MdlMorph.h"
#include "MdlEntity.h"
#include "Base/BcDebug.h"
#include "Base/BcString.h"
//////////////////////////////////////////////////////////////////////////
// Ctor
MdlNode::MdlNode():
NodeType_( eNT_EMPTY ),
pParent_( NULL ),
pChild_( NULL ),
pNext_( NULL )
{
RelativeTransform_.identity();
AbsoluteTransform_.identity();
pNodeMeshObject_ = NULL;
pNodeSkinObject_ = NULL;
pNodeColMeshObject_ = NULL;
pNodeMorphObject_ = NULL;
pNodeEntityObject_ = NULL;
pNodeLightObject_ = NULL;
pNodeProjectorObject_ = NULL;
}
//////////////////////////////////////////////////////////////////////////
// Dtor
MdlNode::~MdlNode()
{
delete pNodeMeshObject_;
delete pNodeSkinObject_;
delete pNodeColMeshObject_;
delete pNodeMorphObject_;
delete pNodeEntityObject_;
delete pNodeLightObject_;
delete pNodeProjectorObject_;
///* NOTE: Memory corruption somewhere.
MdlNode* pNext = pChild_;
while( pNext != NULL )
{
MdlNode* pTheNext = pNext->pNext_;
delete pNext;
pNext = pTheNext;
}
}
//////////////////////////////////////////////////////////////////////////
// name
void MdlNode::name( const BcChar* Name )
{
BcStrCopy( Name_, Name );
}
const BcChar* MdlNode::name()
{
return Name_;
}
//////////////////////////////////////////////////////////////////////////
// parentNode
BcBool MdlNode::parentNode( MdlNode* pNode, const BcChar* ParentName )
{
BcBool bParented = BcFalse;
// Parent another node to this tree.
if( ParentName == NULL || BcStrCompare( ParentName, Name_ ) )
{
// Tell the node who its parent is.
pNode->pParent_ = this;
// If we have a child already we need our next to match.
if( pChild_ != NULL )
{
MdlNode* pParentNode = pChild_;
// Find the last node
while( pParentNode->pNext_ != NULL )
{
BcAssert( pParentNode != pParentNode->pNext_ );
pParentNode = pParentNode->pNext_;
}
//
pParentNode->pNext_ = pNode;
bParented = BcTrue;
}
else
{
pChild_ = pNode;
bParented = BcTrue;
}
}
else
{
// If we are not the destined parent pass it to next and child.
// Find the last node
MdlNode* pNextNode = pChild_;
while( pNextNode != NULL )
{
bParented |= pNextNode->parentNode( pNode, ParentName );
pNextNode = pNextNode->pNext_;
}
}
return bParented;
}
//////////////////////////////////////////////////////////////////////////
// makeRelativeTransform
void MdlNode::makeRelativeTransform( const BcMat4d& ParentAbsolute )
{
// Parent another node to this tree.
MdlNode* pNextNode = pChild_;
//
BcMat4d InverseParent = ParentAbsolute;
InverseParent.inverse();
RelativeTransform_ = AbsoluteTransform_ * InverseParent;
// For all the nodes parented to the same as us.
while( pNextNode != NULL )
{
pNextNode->makeRelativeTransform( AbsoluteTransform_ );
pNextNode = pNextNode->pNext_;
}
}
//////////////////////////////////////////////////////////////////////////
// makeAbsoluteTransform
void MdlNode::makeAbsoluteTransform( const BcMat4d& ParentAbsolute )
{
// Parent another node to this tree.
MdlNode* pNextNode = pChild_;
//
BcMat4d InverseParent = ParentAbsolute;
InverseParent.inverse();
AbsoluteTransform_ = ParentAbsolute * RelativeTransform_;
// For all the nodes parented to the same as us.
while( pNextNode != NULL )
{
pNextNode->makeAbsoluteTransform( AbsoluteTransform_ );
pNextNode = pNextNode->pNext_;
}
}
//////////////////////////////////////////////////////////////////////////
// flipTransform
void MdlNode::flipTransform( BcMat4d& Transform )
{
Transform.transpose();
Transform[0][2] = -Transform[0][2];
Transform[1][2] = -Transform[1][2];
Transform[2][0] = -Transform[2][0];
Transform[2][1] = -Transform[2][1];
Transform[2][3] = -Transform[2][3];
Transform.transpose();
}
//////////////////////////////////////////////////////////////////////////
// flipTransforms
void MdlNode::flipCoordinateSpace()
{
// Parent another node to this tree.
MdlNode* pNextNode = pChild_;
// Flip absolute and inverse bind pose transforms.
flipTransform( AbsoluteTransform_ );
flipTransform( InverseBindpose_ );
// If we've got a mesh, flip it's coordinate space.
if( type() & eNT_MESH )
{
pNodeMeshObject_->flipCoordinateSpace();
}
if( type() & eNT_SKIN )
{
pNodeSkinObject_->flipCoordinateSpace();
}
if( type() & eNT_MORPH )
{
pNodeMorphObject_->flipCoordinateSpace();
}
// For all the nodes parented to the same as us.
while( pNextNode != NULL )
{
pNextNode->flipCoordinateSpace();
pNextNode = pNextNode->pNext_;
}
}
//////////////////////////////////////////////////////////////////////////
// type
void MdlNode::type( BcU32 NodeType )
{
if( NodeType != eNT_COLMESH && NodeType != eNT_ENTITY )
{
BcAssert( ( NodeType_ & ~NodeType ) == 0 );
}
if( ( NodeType_ & NodeType ) == 0 )
{
NodeType_ |= NodeType;
switch( NodeType )
{
case eNT_EMPTY:
break;
case eNT_MESH:
pNodeMeshObject_ = new MdlMesh();
break;
case eNT_SKIN:
pNodeSkinObject_ = new MdlMesh();
break;
case eNT_COLMESH:
// Naughty.
//pNodeColMeshObject_ = new MdlMesh();
BcAssert( pNodeMeshObject_ != NULL );
break;
case eNT_MORPH:
pNodeMorphObject_ = new MdlMesh();
break;
case eNT_ENTITY:
pNodeEntityObject_ = new MdlEntity();
break;
case eNT_LIGHT:
pNodeLightObject_ = new MdlLight();
break;
case eNT_PROJECTOR:
pNodeProjectorObject_ = new MdlProjector();
break;
}
}
}
//////////////////////////////////////////////////////////////////////////
// countJoints
void MdlNode::countJoints( BcU32& iCount )
{
if( type() & eNT_JOINT )
{
iCount++;
}
MdlNode* pNextNode = pChild_;
while( pNextNode != NULL )
{
if( pNextNode->type() & eNT_JOINT )
{
pNextNode->countJoints( iCount );
}
pNextNode = pNextNode->pNext_;
}
}
//////////////////////////////////////////////////////////////////////////
//
void MdlNode::findAllAABBs()
{
MdlNode* pNextNode = pChild_;
// If our AABB is empty, calculate our bounds based on child nodes.
if( AABB_.isEmpty() )
{
while( pNextNode != NULL )
{
// Find our childs..
pNextNode->findAllAABBs();
// Add its AABB to ours.
if( pNextNode->AABB_.isEmpty() == BcFalse )
{
AABB_.expandBy( pNextNode->AABB_ );
}
//
pNextNode = pNextNode->pNext_;
}
// Transform our AABB
if( AABB_.isEmpty() == BcFalse )
{
AABB_ = AABB_.transform( AbsoluteTransform_ );
}
}
else
{
// Transform ours.
AABB_ = AABB_.transform( AbsoluteTransform_ );
}
} | [
"[email protected]"
] | |
922f4765eedff3059156dd94eda2a1b6056103b8 | da33d7b0d05c8e3d3989dcbae0020594169350a8 | /public/klein/detail/inner_product.hpp | d80170c7fe73bb921b9656ebf6fd45513b92d49d | [
"MIT"
] | permissive | shrijitsingh99/klein | a2a03bffd07dda1ef53ba793ac4c5f69bc7096d7 | 9aa59b9e95e8ab607cdc415782cac6ae1b1a86fa | refs/heads/master | 2021-02-09T11:06:19.602097 | 2020-03-02T03:07:01 | 2020-03-02T03:07:01 | 244,275,143 | 2 | 0 | MIT | 2020-03-02T03:51:54 | 2020-03-02T03:51:53 | null | UTF-8 | C++ | false | false | 50 | hpp | #pragma once
#include "x86/x86_inner_product.hpp" | [
"[email protected]"
] | |
4c76f75b20942941b0554679ea78f9c18c709f74 | c27df8ce4903389256023f71fc8004c6caf41d21 | /examples/common/15_tim_usonic/main.cpp | 6de553fd9ed6fd2a348a75f8890e2366befaf687 | [] | no_license | atu-guda/stm32oxc | be8f584e6978fa40482bbd5df4a23bd6b41329eb | 591b43246b8928329642b06bad8b9de6802e62ed | refs/heads/master | 2023-09-03T08:42:36.058233 | 2023-09-02T19:15:15 | 2023-09-02T19:15:15 | 34,165,176 | 5 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,877 | cpp | #include <oxc_auto.h>
#include <oxc_tim.h>
using namespace std;
using namespace SMLRL;
USE_DIE4LED_ERROR_HANDLER;
BOARD_DEFINE_LEDS;
BOARD_CONSOLE_DEFINES;
const char* common_help_string = "App to test US-014 ultrasonic sensor with timer" NL;
TIM_HandleTypeDef tim_h;
void init_usonic();
// --- local commands;
int cmd_test0( int argc, const char * const * argv );
CmdInfo CMDINFO_TEST0 { "test0", 'T', cmd_test0, " [n] - test sensor" };
const CmdInfo* global_cmds[] = {
DEBUG_CMDS,
&CMDINFO_TEST0,
nullptr
};
int main(void)
{
BOARD_PROLOG;
UVAR('t') = 1000;
UVAR('n') = 20;
BOARD_POST_INIT_BLINK;
pr( NL "##################### " PROJ_NAME NL );
srl.re_ps();
oxc_add_aux_tick_fun( led_task_nortos );
init_usonic();
delay_ms( 50 );
std_main_loop_nortos( &srl, nullptr );
return 0;
}
// TEST0
int cmd_test0( int argc, const char * const * argv )
{
int n = arg2long_d( 1, argc, argv, UVAR('n'), 0 );
uint32_t t_step = UVAR('t');
std_out << NL "Test0: n= " << n << " t= " << t_step << NL;
tim_print_cfg( TIM_EXA );
delay_ms( 10 );
uint32_t tm0 = HAL_GetTick();
break_flag = 0;
for( int i=0; i<n && !break_flag; ++i ) {
std_out << "[" << i << "] l= " << UVAR('l') << NL;
std_out.flush();
delay_ms_until_brk( &tm0, t_step );
}
return 0;
}
// ----------------------------- configs ----------------
void init_usonic()
{
// 5.8 mks approx 1mm 170000 = v_c/2 in mm/s, 998 or 846
tim_h.Init.Prescaler = calc_TIM_psc_for_cnt_freq( TIM_EXA, 170000 );
tim_h.Instance = TIM_EXA;
tim_h.Init.Period = 8500; // F approx 20Hz: for future motor PWM
tim_h.Init.ClockDivision = 0;
tim_h.Init.CounterMode = TIM_COUNTERMODE_UP;
tim_h.Init.RepetitionCounter = 0;
if( HAL_TIM_PWM_Init( &tim_h ) != HAL_OK ) {
UVAR('e') = 1; // like error
return;
}
TIM_ClockConfigTypeDef sClockSourceConfig;
sClockSourceConfig.ClockSource = TIM_CLOCKSOURCE_INTERNAL;
HAL_TIM_ConfigClockSource( &tim_h, &sClockSourceConfig );
TIM_OC_InitTypeDef tim_oc_cfg;
tim_oc_cfg.OCMode = TIM_OCMODE_PWM1;
tim_oc_cfg.OCPolarity = TIM_OCPOLARITY_HIGH;
tim_oc_cfg.OCNPolarity = TIM_OCNPOLARITY_HIGH;
tim_oc_cfg.OCFastMode = TIM_OCFAST_DISABLE;
tim_oc_cfg.OCIdleState = TIM_OCIDLESTATE_RESET;
tim_oc_cfg.OCNIdleState = TIM_OCNIDLESTATE_RESET;
tim_oc_cfg.Pulse = 3; // 3 = approx 16 us
if( HAL_TIM_PWM_ConfigChannel( &tim_h, &tim_oc_cfg, TIM_CHANNEL_1 ) != HAL_OK ) {
UVAR('e') = 11;
return;
}
if( HAL_TIM_PWM_Start( &tim_h, TIM_CHANNEL_1 ) != HAL_OK ) {
UVAR('e') = 12;
return;
}
TIM_IC_InitTypeDef tim_ic_cfg;
// tim_ic_cfg.ICPolarity = TIM_ICPOLARITY_RISING;
tim_ic_cfg.ICPolarity = TIM_ICPOLARITY_BOTHEDGE; // rising - start, falling - stop
tim_ic_cfg.ICSelection = TIM_ICSELECTION_DIRECTTI;
tim_ic_cfg.ICPrescaler = TIM_ICPSC_DIV1;
tim_ic_cfg.ICFilter = 0; // 0 - 0x0F
if( HAL_TIM_IC_ConfigChannel( &tim_h, &tim_ic_cfg, TIM_CHANNEL_2 ) != HAL_OK ) {
UVAR('e') = 21;
return;
}
HAL_NVIC_SetPriority( TIM_EXA_IRQ, 7, 0 );
HAL_NVIC_EnableIRQ( TIM_EXA_IRQ );
if( HAL_TIM_IC_Start_IT( &tim_h, TIM_CHANNEL_2 ) != HAL_OK ) {
UVAR('e') = 23;
}
}
void TIM_EXA_IRQHANDLER(void)
{
HAL_TIM_IRQHandler( &tim_h );
}
void HAL_TIM_IC_CaptureCallback( TIM_HandleTypeDef *htim )
{
uint32_t cap2;
static uint32_t c_old = 0xFFFFFFFF;
if( htim->Channel == HAL_TIM_ACTIVE_CHANNEL_2 ) {
cap2 = HAL_TIM_ReadCapturedValue( htim, TIM_CHANNEL_2 );
if( cap2 > c_old ) {
UVAR('l') = cap2 - c_old ;
leds.reset( BIT2 );
} else {
leds.set( BIT2 );
}
c_old = cap2;
UVAR('m') = cap2;
UVAR('z') = htim->Instance->CNT;
}
}
// vim: path=.,/usr/share/stm32cube/inc/,/usr/arm-none-eabi/include,/usr/share/stm32oxc/inc
| [
"[email protected]"
] | |
fde7c6cfbc63c7a0c1dd0d967b977e264112cbc1 | 618729b2291385cd51e395db1dbca933439312b4 | /os.cpp | 45d040c176383938996e8c33040817a91f08459f | [] | no_license | grih9/fluffyOS | bfe2bfc7de37366c57d34fa50d1421c344b6a682 | f3ed3efd5863d857d76065b04216aa3298a09e0c | refs/heads/master | 2023-04-11T07:23:10.383620 | 2021-04-18T15:49:27 | 2021-04-18T15:49:27 | 359,168,571 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,815 | cpp | #include <stdio.h>
#include "sys.h"
#include "rtos_api.h"
// Инициализация стеков
void InitializeStacks(int numStack)
{
char cushionSpace[100000];
cushionSpace[99999] = 1; // отключаем оптимизацию массивов
for (int i = 0; i <= MAX_TASK; ++i) {
if (!setjmp(InitStacks[i])) {
continue;
} else {
TaskQueue[RunningTask].entry();
break;
}
}
}
int StartOS(TTaskCall entry, int priority, char *name)
{
RunningTask = TaskHead = -1;
TaskCount = 0; //подсчет задач
FreeTask = 0; //ожидающие задачи
printf("StartOS!\n");
InitializeStacks(0); //инициализация стека
for (int i = 0; i < MAX_TASK; i++)
{
TaskQueue[i].next = i + 1; // номер массива на след элемент
TaskQueue[i].prev = i - 1; // пред элемент
TaskQueue[i].task_state = TASK_SUSPENDED; // пометка ожидания (неактивная задача)
TaskQueue[i].switch_count = 0; // ключ
TaskQueue[i].waiting_events = 0; // ожидание задачи
TaskQueue[i].working_events = 0; // сработавшие задачи
} // создание массива задач
TaskQueue[MAX_TASK - 1].next = 0; // присваиваем последнему элементу 0
TaskQueue[0].prev = MAX_TASK - 1; // присваиваем предпоследний
if (!setjmp(MainContext)) {
ActivateTask(entry, priority, name); // запускаем функцию активации задачи
}
return 0;
}
// Завершает работу системы(задача завершена)
void ShutdownOS()
{
printf("ShutdownOS!\n");
} | [
"[email protected]"
] | |
8788db759d2467f2e5ce1f3747107a50c10284ea | c102d77e7e363d043e017360d329c93b9285a6be | /Sources/Samples/AI/UnitPathManager.h | 4c85b601bbdd834052649cd9ee5cd19276a8484b | [
"MIT"
] | permissive | jdelezenne/Sonata | b7b1faee54ea9dbd273eab53a7dedbf106373110 | fb1b1b64a78874a0ab2809995be4b6f14f9e4d56 | refs/heads/master | 2020-07-15T22:32:47.094973 | 2019-09-01T11:07:03 | 2019-09-01T11:07:03 | 205,662,360 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,466 | h | /*=============================================================================
UnitPathManager.h
Project: Sonata Engine
Copyright �by7
Julien Delezenne
=============================================================================*/
#ifndef _SE_UNITPATHMANAGER_H_
#define _SE_UNITPATHMANAGER_H_
#include "Common.h"
#include "World.h"
extern int8 TileUnitCosts[TileType_Count][UnitType_Count];
enum PathfinderType
{
PathfinderType_AStar
};
class UnitPathMap : public AI::AStarPathfinderMap
{
public:
UnitPathMap();
virtual int GetNeighbourCount(AI::PathfinderNode* node);
virtual AI::PathfinderNodeID GetNeighbour(AI::PathfinderNode* node, int neighbour);
virtual void SetAStarFlags(AI::PathfinderNodeID node, uint32 flags);
virtual uint32 GetAStarFlags(AI::PathfinderNodeID node);
virtual void InitializeNeighbour(AI::AStarPathfinderNode* parent, AI::AStarPathfinderNode* child);
AI::PathfinderNodeID CellToPathfinderNodeID(Cell* cell);
Cell* PathfinderNodeIDToCell(AI::PathfinderNodeID node);
void Initialize(Map* map);
Map* GetMap() const { return _Map; }
protected:
Map* _Map;
};
class UnitPathGoal : public AI::AStarPathfinderGoal
{
public:
UnitPathGoal();
virtual void SetDestinationNode(AI::PathfinderNodeID node);
virtual bool IsNodeValid(AI::PathfinderNodeID node);
virtual real32 GetHeuristic(AI::AStarPathfinderNode* node);
virtual real32 GetCost(AI::AStarPathfinderNode* nodeA, AI::AStarPathfinderNode* nodeB);
virtual bool IsSearchFinished(AI::AStarPathfinderNode* node);
void Initialize(UnitPathMap* map, Unit* unit);
protected:
AI::PathfinderNodeID _DestinationNode;
UnitPathMap* _Map;
Unit* _Unit;
};
template <class T>
class RefComparer : public IComparer<T>
{
public:
virtual int Compare(const T& x, const T& y) const
{
if (*x < *y)
return -1;
else if (*x > *y)
return 1;
else
return 0;
}
};
class PriorityQueueStorage : public AI::AStarPathfinderStorage
{
public:
PriorityQueueStorage();
virtual ~PriorityQueueStorage();
virtual void Reset();
virtual void AddToOpenList(AI::AStarPathfinderNode* node, AI::AStarPathfinderMap* map);
virtual void AddToClosedList(AI::AStarPathfinderNode* node, AI::AStarPathfinderMap* map);
virtual void RemoveFromOpenList(AI::AStarPathfinderNode* node);
virtual void RemoveFromClosedList(AI::AStarPathfinderNode* node);
virtual AI::AStarPathfinderNode* FindInOpenList(AI::PathfinderNodeID node);
virtual AI::AStarPathfinderNode* FindInClosedList(AI::PathfinderNodeID node);
virtual AI::AStarPathfinderNode* RemoveBestOpenNode();
protected:
typedef PriorityQueue< AI::AStarPathfinderNode*, RefComparer<AI::AStarPathfinderNode*> > OpenList;
OpenList _OpenList;
typedef Array<AI::AStarPathfinderNode*> ClosedList;
ClosedList _ClosedList;
};
class UnitPathStorage : public PriorityQueueStorage
{
public:
UnitPathStorage();
virtual AI::AStarPathfinderNode* CreateNode(AI::PathfinderNodeID node);
virtual void DestroyNode(AI::AStarPathfinderNode* node);
};
class UnitPathManager
{
public:
UnitPathManager();
virtual ~UnitPathManager();
void Initialize(PathfinderType type);
bool HasPath(Unit* unit, Cell* source, Cell* destination);
bool FindPath(Unit* unit, Cell* source, Cell* destination, UnitPath* path);
protected:
AI::PathfinderNode* FindPath(Unit* unit, Cell* source, Cell* destination);
protected:
AI::AStarPathfinder* _Pathfinder;
PriorityQueueStorage* _Storage;
UnitPathGoal* _Goal;
UnitPathMap* _Map;
};
#endif
| [
"[email protected]"
] | |
943e8c302a43a8030047d7f7c3e2006477bcda7a | f51b3b7f6a5110a704d5bd4e7920fc675a75f2bd | /src/lang/builtins/transforms/tile.cpp | e27d08d28f82a9ee5393867bf9f56f8e96f46bd0 | [
"MIT"
] | permissive | v-dobrev/occa | 6857905566e39334d47ff2efa6a8e5be9a085cde | 58e47f5ccf0d87f5b91e6851b2d74a9456c46b2c | refs/heads/master | 2020-03-26T07:50:51.784589 | 2018-08-26T19:10:56 | 2018-08-26T19:46:22 | 144,674,039 | 0 | 0 | MIT | 2018-08-14T05:45:39 | 2018-08-14T05:45:38 | null | UTF-8 | C++ | false | false | 12,149 | cpp | /* The MIT License (MIT)
*
* Copyright (c) 2014-2018 David Medina and Tim Warburton
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
*/
#include <occa/lang/exprNode.hpp>
#include <occa/lang/mode/oklForStatement.hpp>
#include <occa/lang/variable.hpp>
#include <occa/lang/builtins/types.hpp>
#include <occa/lang/builtins/transforms/tile.hpp>
#include <occa/lang/builtins/transforms/replacer.hpp>
namespace occa {
namespace lang {
namespace transforms {
tile::tile() {
validStatementTypes = statementType::for_;
}
statement_t* tile::transformStatement(statement_t &smnt) {
forStatement &forSmnt = (forStatement&) smnt;
attributeTokenMap::iterator it = forSmnt.attributes.find("tile");
if (it == forSmnt.attributes.end()) {
return &smnt;
}
attributeToken_t &attr = it->second;
exprNode &tileSize = *(attr.args[0].expr);
okl::oklForStatement oklForSmnt(forSmnt,
"@tile");
if (!oklForSmnt.isValid()) {
return NULL;
}
// Create the block and inner-block for-loops
forStatement &blockForSmnt = *(new forStatement(forSmnt.up,
forSmnt.source));
forStatement &innerForSmnt = *(new forStatement(&blockForSmnt,
forSmnt.source));
blockForSmnt.add(innerForSmnt);
// Rename the block interator
variable_t &iter = *(oklForSmnt.iterator);
variable_t &blockIter = iter.clone();
blockIter.name() = "_occa_tiled_" + iter.name();
blockForSmnt.scope.add(blockIter);
setupNewForStatements(attr,
oklForSmnt,
blockIter,
blockForSmnt, innerForSmnt);
setupBlockForStatement(oklForSmnt,
tileSize,
blockIter,
blockForSmnt, innerForSmnt);
setupInnerForStatement(oklForSmnt,
tileSize,
blockIter,
blockForSmnt, innerForSmnt);
setupCheckStatement(attr,
oklForSmnt,
blockIter,
blockForSmnt, innerForSmnt);
return &blockForSmnt;
}
void tile::setupNewForStatements(attributeToken_t &attr,
okl::oklForStatement &oklForSmnt,
variable_t &blockIter,
forStatement &blockForSmnt,
forStatement &innerForSmnt) {
// Add @tile attributes
const int attrArgCount = (int) attr.args.size();
if (attrArgCount > 1) {
attributeTokenMap &blockAttrs = attr.args[1].attributes;
blockForSmnt.attributes.insert(blockAttrs.begin(), blockAttrs.end());
if (attrArgCount > 2) {
attributeTokenMap &innerAttrs = attr.args[2].attributes;
innerForSmnt.attributes.insert(innerAttrs.begin(), innerAttrs.end());
}
}
// Remove @tile to prevent recursive updates
innerForSmnt.attributes.erase("tile");
forStatement &forSmnt = oklForSmnt.forSmnt;
innerForSmnt.swap(forSmnt);
// Setup initial statements
blockForSmnt.setLoopStatements(forSmnt.init, forSmnt.check, NULL);
innerForSmnt.setLoopStatements(NULL, NULL, forSmnt.update);
forSmnt.setLoopStatements(NULL, NULL, NULL);
// Replace instances of x with _occa_tiled_x
replaceVariables(*blockForSmnt.init,
*oklForSmnt.iterator,
blockIter);
replaceVariables(*blockForSmnt.check,
*oklForSmnt.iterator,
blockIter);
}
void tile::setupBlockForStatement(okl::oklForStatement &oklForSmnt,
exprNode &tileSize,
variable_t &blockIter,
forStatement &blockForSmnt,
forStatement &innerForSmnt) {
/*
for (x = START; x < END; x += INC)
->
for (xTile = START; xTile < END; NULL )
->
for (xTile = START; xTile < END; xTile += (TILE * (INC)))
*/
exprNode &updateExpr = *(((expressionStatement*) innerForSmnt.update)->expr);
opType_t opType = ((exprOpNode&) updateExpr).opType();
token_t *updateToken =updateExpr.startNode()->token;
exprNode *updateSizeExpr = &tileSize;
const binaryOperator_t *updateOp = &op::addEq;
if (opType & (operatorType::leftDecrement |
operatorType::rightDecrement)) {
updateOp = &op::subEq;
}
else if (opType & (operatorType::addEq |
operatorType::subEq)) {
// INC
exprNode *updateSize = ((binaryOpNode&) updateExpr).rightValue;
// (INC)
parenthesesNode updateInParen(updateToken,
*updateSize);
// TILE * (INC)
binaryOpNode mult(updateToken,
op::mult,
tileSize,
updateInParen);
// (TILE * (INC))
updateSizeExpr = new parenthesesNode(updateToken,
mult);
if (opType & operatorType::subEq) {
updateOp = &op::subEq;
}
}
// VAR += (TILE * (INC))
variableNode varNode(updateToken, blockIter);
exprNode *newUpdateExpr = new binaryOpNode(updateToken,
*updateOp,
varNode,
*updateSizeExpr);
if (updateSizeExpr != &tileSize) {
// Delete (TILE * (INC)) if it was created
delete updateSizeExpr;
}
blockForSmnt.update = new expressionStatement(&blockForSmnt,
*newUpdateExpr,
false);
}
void tile::setupInnerForStatement(okl::oklForStatement &oklForSmnt,
exprNode &tileSize,
variable_t &blockIter,
forStatement &blockForSmnt,
forStatement &innerForSmnt) {
/*
for (x = START; x < END; x += INC)
->
for (NULL; NULL; x += INC)
->
for (x = xTile; x < (xTile + TILE); x += INC)
*/
// Init variables
variableDeclaration &decl = (((declarationStatement*) blockForSmnt.init)
->declarations[0]);
token_t *initToken = decl.variable->source;
variableNode iterNode(initToken,
*oklForSmnt.iterator);
variableNode blockIterNode(initToken, blockIter);
// Check variables
binaryOpNode &checkExpr = ((binaryOpNode&)
*(((expressionStatement*) blockForSmnt.check)->expr));
token_t *checkToken = checkExpr.startNode()->token;
// Update variables
const operator_t &updateOp = (
((binaryOpNode&)
*(((expressionStatement*) blockForSmnt.update)->expr)
).op);
const bool addUpdate = (updateOp.opType & operatorType::addEq);
// Create init
innerForSmnt.init = new declarationStatement(&innerForSmnt, initToken);
variableDeclarationVector &decls = (
((declarationStatement*) innerForSmnt.init)
->declarations
);
decls.push_back(
variableDeclaration(*oklForSmnt.iterator,
*(blockIterNode.clone()))
);
// Create check
binaryOpNode checkValueNode(checkToken,
addUpdate ? op::add : op::sub,
blockIterNode,
tileSize);
parenthesesNode checkInParen(checkToken,
checkValueNode);
const bool varInLeft = oklForSmnt.checkValueOnRight;
binaryOpNode &newCheckNode = *(
new binaryOpNode(
checkToken,
(const binaryOperator_t&) checkExpr.op,
varInLeft ? (exprNode&) iterNode : (exprNode&) checkInParen,
varInLeft ? (exprNode&) checkInParen : (exprNode&) iterNode
));
innerForSmnt.check = new expressionStatement(&innerForSmnt,
newCheckNode);
}
void tile::setupCheckStatement(attributeToken_t &attr,
okl::oklForStatement &oklForSmnt,
variable_t &blockIter,
forStatement &blockForSmnt,
forStatement &innerForSmnt) {
attributeArgMap::iterator it = attr.kwargs.find("check");
bool check = true;
if (it != attr.kwargs.end()) {
check = (bool) it->second.expr->evaluate();
}
if (!check) {
return;
}
// Check variables
binaryOpNode &checkExpr = ((binaryOpNode&)
*(((expressionStatement*) blockForSmnt.check)->expr));
token_t *checkToken = checkExpr.startNode()->token;
const bool varInLeft = oklForSmnt.checkValueOnRight;
// Make ifStatement
ifStatement &ifSmnt = *(new ifStatement(&innerForSmnt,
checkToken));
innerForSmnt.swap(ifSmnt);
innerForSmnt.scope.swap(ifSmnt.scope);
innerForSmnt.add(ifSmnt);
// Get global check
token_t *iterToken = (varInLeft
? checkExpr.leftValue->token
: checkExpr.rightValue->token);
variableNode iterNode(iterToken,
*oklForSmnt.iterator);
binaryOpNode &newCheckNode = *(
new binaryOpNode(
checkExpr.token,
(const binaryOperator_t&) checkExpr.op,
varInLeft ? (exprNode&) iterNode : *(checkExpr.leftValue),
varInLeft ? (exprNode&) *(checkExpr.rightValue) : (exprNode&) iterNode
));
ifSmnt.setCondition(new expressionStatement(&ifSmnt,
newCheckNode,
false));
}
bool applyTileTransforms(statement_t &smnt) {
tile tileTransform;
return tileTransform.apply(smnt);
}
}
}
}
| [
"[email protected]"
] | |
a43f9f1dfb76961c6f5f3af11fd259bfd4d34983 | fc987ace8516d4d5dfcb5444ed7cb905008c6147 | /third_party/WebKit/Source/wtf/HashTraits.h | 68a18dd753fc4f94dcb94c71587b54a8c6724d89 | [
"LGPL-2.0-or-later",
"GPL-1.0-or-later",
"MIT",
"Apache-2.0",
"LicenseRef-scancode-warranty-disclaimer",
"LGPL-2.1-only",
"GPL-2.0-only",
"LGPL-2.0-only",
"BSD-2-Clause",
"LicenseRef-scancode-other-copyleft",
"BSD-3-Clause"
] | permissive | nfschina/nfs-browser | 3c366cedbdbe995739717d9f61e451bcf7b565ce | b6670ba13beb8ab57003f3ba2c755dc368de3967 | refs/heads/master | 2022-10-28T01:18:08.229807 | 2020-09-07T11:45:28 | 2020-09-07T11:45:28 | 145,939,440 | 2 | 4 | BSD-3-Clause | 2022-10-13T14:59:54 | 2018-08-24T03:47:46 | null | UTF-8 | C++ | false | false | 15,939 | h | /*
* Copyright (C) 2005, 2006, 2007, 2008, 2011, 2012 Apple Inc. All rights
* reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*
*/
#ifndef WTF_HashTraits_h
#define WTF_HashTraits_h
#include "wtf/Forward.h"
#include "wtf/HashFunctions.h"
#include "wtf/HashTableDeletedValueType.h"
#include "wtf/StdLibExtras.h"
#include "wtf/TypeTraits.h"
#include <limits>
#include <memory>
#include <string.h> // For memset.
#include <type_traits>
#include <utility>
namespace WTF {
template <bool isInteger, typename T>
struct GenericHashTraitsBase;
template <typename T>
struct HashTraits;
enum ShouldWeakPointersBeMarkedStrongly {
WeakPointersActStrong,
WeakPointersActWeak
};
template <typename T>
struct GenericHashTraitsBase<false, T> {
// The emptyValueIsZero flag is used to optimize allocation of empty hash
// tables with zeroed memory.
static const bool emptyValueIsZero = false;
// The hasIsEmptyValueFunction flag allows the hash table to automatically
// generate code to check for the empty value when it can be done with the
// equality operator, but allows custom functions for cases like String that
// need them.
static const bool hasIsEmptyValueFunction = false;
// The starting table size. Can be overridden when we know beforehand that a
// hash table will have at least N entries.
#if defined(MEMORY_SANITIZER_INITIAL_SIZE)
static const unsigned minimumTableSize = 1;
#else
static const unsigned minimumTableSize = 8;
#endif
// When a hash table backing store is traced, its elements will be
// traced if their class type has a trace method. However, weak-referenced
// elements should not be traced then, but handled by the weak processing
// phase that follows.
template <typename U = void>
struct IsTraceableInCollection {
static const bool value = IsTraceable<T>::value && !IsWeak<T>::value;
};
// The NeedsToForbidGCOnMove flag is used to make the hash table move
// operations safe when GC is enabled: if a move constructor invokes
// an allocation triggering the GC then it should be invoked within GC
// forbidden scope.
template <typename U = void>
struct NeedsToForbidGCOnMove {
// TODO(yutak): Consider using of std:::is_trivially_move_constructible
// when it is accessible.
static const bool value = !std::is_pod<T>::value;
};
static const WeakHandlingFlag weakHandlingFlag =
IsWeak<T>::value ? WeakHandlingInCollections
: NoWeakHandlingInCollections;
};
// Default integer traits disallow both 0 and -1 as keys (max value instead of
// -1 for unsigned).
template <typename T>
struct GenericHashTraitsBase<true, T> : GenericHashTraitsBase<false, T> {
static const bool emptyValueIsZero = true;
static void constructDeletedValue(T& slot, bool) {
slot = static_cast<T>(-1);
}
static bool isDeletedValue(T value) { return value == static_cast<T>(-1); }
};
template <typename T>
struct GenericHashTraits
: GenericHashTraitsBase<std::is_integral<T>::value, T> {
typedef T TraitType;
typedef T EmptyValueType;
static T emptyValue() { return T(); }
// Type for functions that do not take ownership, such as contains.
typedef const T& PeekInType;
typedef T* IteratorGetType;
typedef const T* IteratorConstGetType;
typedef T& IteratorReferenceType;
typedef const T& IteratorConstReferenceType;
static IteratorReferenceType getToReferenceConversion(IteratorGetType x) {
return *x;
}
static IteratorConstReferenceType getToReferenceConstConversion(
IteratorConstGetType x) {
return *x;
}
template <typename IncomingValueType>
static void store(IncomingValueType&& value, T& storage) {
storage = std::forward<IncomingValueType>(value);
}
// Type for return value of functions that do not transfer ownership, such
// as get.
// FIXME: We could change this type to const T& for better performance if we
// figured out a way to handle the return value from emptyValue, which is a
// temporary.
typedef T PeekOutType;
static const T& peek(const T& value) { return value; }
};
template <typename T>
struct HashTraits : GenericHashTraits<T> {};
template <typename T>
struct FloatHashTraits : GenericHashTraits<T> {
static T emptyValue() { return std::numeric_limits<T>::infinity(); }
static void constructDeletedValue(T& slot, bool) {
slot = -std::numeric_limits<T>::infinity();
}
static bool isDeletedValue(T value) {
return value == -std::numeric_limits<T>::infinity();
}
};
template <>
struct HashTraits<float> : FloatHashTraits<float> {};
template <>
struct HashTraits<double> : FloatHashTraits<double> {};
// Default unsigned traits disallow both 0 and max as keys -- use these traits
// to allow zero and disallow max - 1.
template <typename T>
struct UnsignedWithZeroKeyHashTraits : GenericHashTraits<T> {
static const bool emptyValueIsZero = false;
static T emptyValue() { return std::numeric_limits<T>::max(); }
static void constructDeletedValue(T& slot, bool) {
slot = std::numeric_limits<T>::max() - 1;
}
static bool isDeletedValue(T value) {
return value == std::numeric_limits<T>::max() - 1;
}
};
template <typename P>
struct HashTraits<P*> : GenericHashTraits<P*> {
static const bool emptyValueIsZero = true;
static void constructDeletedValue(P*& slot, bool) {
slot = reinterpret_cast<P*>(-1);
}
static bool isDeletedValue(P* value) {
return value == reinterpret_cast<P*>(-1);
}
};
template <typename T>
struct SimpleClassHashTraits : GenericHashTraits<T> {
static const bool emptyValueIsZero = true;
template <typename U = void>
struct NeedsToForbidGCOnMove {
static const bool value = false;
};
static void constructDeletedValue(T& slot, bool) {
new (NotNull, &slot) T(HashTableDeletedValue);
}
static bool isDeletedValue(const T& value) {
return value.isHashTableDeletedValue();
}
};
template <typename P>
struct HashTraits<RefPtr<P>> : SimpleClassHashTraits<RefPtr<P>> {
typedef std::nullptr_t EmptyValueType;
static EmptyValueType emptyValue() { return nullptr; }
static const bool hasIsEmptyValueFunction = true;
static bool isEmptyValue(const RefPtr<P>& value) { return !value; }
typedef RefPtrValuePeeker<P> PeekInType;
typedef RefPtr<P>* IteratorGetType;
typedef const RefPtr<P>* IteratorConstGetType;
typedef RefPtr<P>& IteratorReferenceType;
typedef const RefPtr<P>& IteratorConstReferenceType;
static IteratorReferenceType getToReferenceConversion(IteratorGetType x) {
return *x;
}
static IteratorConstReferenceType getToReferenceConstConversion(
IteratorConstGetType x) {
return *x;
}
static void store(PassRefPtr<P> value, RefPtr<P>& storage) {
storage = value;
}
typedef P* PeekOutType;
static PeekOutType peek(const RefPtr<P>& value) { return value.get(); }
static PeekOutType peek(std::nullptr_t) { return 0; }
};
template <typename T>
struct HashTraits<RawPtr<T>> : HashTraits<T*> {};
template <typename T>
struct HashTraits<std::unique_ptr<T>>
: SimpleClassHashTraits<std::unique_ptr<T>> {
using EmptyValueType = std::nullptr_t;
static EmptyValueType emptyValue() { return nullptr; }
static const bool hasIsEmptyValueFunction = true;
static bool isEmptyValue(const std::unique_ptr<T>& value) { return !value; }
using PeekInType = T*;
static void store(std::unique_ptr<T>&& value, std::unique_ptr<T>& storage) {
storage = std::move(value);
}
using PeekOutType = T*;
static PeekOutType peek(const std::unique_ptr<T>& value) {
return value.get();
}
static PeekOutType peek(std::nullptr_t) { return nullptr; }
static void constructDeletedValue(std::unique_ptr<T>& slot, bool) {
// Dirty trick: implant an invalid pointer to unique_ptr. Destructor isn't
// called for deleted buckets, so this is okay.
new (NotNull, &slot) std::unique_ptr<T>(reinterpret_cast<T*>(1u));
}
static bool isDeletedValue(const std::unique_ptr<T>& value) {
return value.get() == reinterpret_cast<T*>(1u);
}
};
template <>
struct HashTraits<String> : SimpleClassHashTraits<String> {
static const bool hasIsEmptyValueFunction = true;
static bool isEmptyValue(const String&);
};
// This struct template is an implementation detail of the
// isHashTraitsEmptyValue function, which selects either the emptyValue function
// or the isEmptyValue function to check for empty values.
template <typename Traits, bool hasEmptyValueFunction>
struct HashTraitsEmptyValueChecker;
template <typename Traits>
struct HashTraitsEmptyValueChecker<Traits, true> {
template <typename T>
static bool isEmptyValue(const T& value) {
return Traits::isEmptyValue(value);
}
};
template <typename Traits>
struct HashTraitsEmptyValueChecker<Traits, false> {
template <typename T>
static bool isEmptyValue(const T& value) {
return value == Traits::emptyValue();
}
};
template <typename Traits, typename T>
inline bool isHashTraitsEmptyValue(const T& value) {
return HashTraitsEmptyValueChecker<
Traits, Traits::hasIsEmptyValueFunction>::isEmptyValue(value);
}
template <typename FirstTraitsArg, typename SecondTraitsArg>
struct PairHashTraits
: GenericHashTraits<std::pair<typename FirstTraitsArg::TraitType,
typename SecondTraitsArg::TraitType>> {
typedef FirstTraitsArg FirstTraits;
typedef SecondTraitsArg SecondTraits;
typedef std::pair<typename FirstTraits::TraitType,
typename SecondTraits::TraitType>
TraitType;
typedef std::pair<typename FirstTraits::EmptyValueType,
typename SecondTraits::EmptyValueType>
EmptyValueType;
static const bool emptyValueIsZero =
FirstTraits::emptyValueIsZero && SecondTraits::emptyValueIsZero;
static EmptyValueType emptyValue() {
return std::make_pair(FirstTraits::emptyValue(),
SecondTraits::emptyValue());
}
static const bool hasIsEmptyValueFunction =
FirstTraits::hasIsEmptyValueFunction ||
SecondTraits::hasIsEmptyValueFunction;
static bool isEmptyValue(const TraitType& value) {
return isHashTraitsEmptyValue<FirstTraits>(value.first) &&
isHashTraitsEmptyValue<SecondTraits>(value.second);
}
static const unsigned minimumTableSize = FirstTraits::minimumTableSize;
static void constructDeletedValue(TraitType& slot, bool zeroValue) {
FirstTraits::constructDeletedValue(slot.first, zeroValue);
// For GC collections the memory for the backing is zeroed when it is
// allocated, and the constructors may take advantage of that,
// especially if a GC occurs during insertion of an entry into the
// table. This slot is being marked deleted, but If the slot is reused
// at a later point, the same assumptions around memory zeroing must
// hold as they did at the initial allocation. Therefore we zero the
// value part of the slot here for GC collections.
if (zeroValue)
memset(reinterpret_cast<void*>(&slot.second), 0, sizeof(slot.second));
}
static bool isDeletedValue(const TraitType& value) {
return FirstTraits::isDeletedValue(value.first);
}
};
template <typename First, typename Second>
struct HashTraits<std::pair<First, Second>>
: public PairHashTraits<HashTraits<First>, HashTraits<Second>> {};
template <typename KeyTypeArg, typename ValueTypeArg>
struct KeyValuePair {
typedef KeyTypeArg KeyType;
template <typename IncomingKeyType, typename IncomingValueType>
KeyValuePair(IncomingKeyType&& key, IncomingValueType&& value)
: key(std::forward<IncomingKeyType>(key)),
value(std::forward<IncomingValueType>(value)) {}
template <typename OtherKeyType, typename OtherValueType>
KeyValuePair(KeyValuePair<OtherKeyType, OtherValueType>&& other)
: key(std::move(other.key)), value(std::move(other.value)) {}
KeyTypeArg key;
ValueTypeArg value;
};
template <typename KeyTraitsArg, typename ValueTraitsArg>
struct KeyValuePairHashTraits
: GenericHashTraits<KeyValuePair<typename KeyTraitsArg::TraitType,
typename ValueTraitsArg::TraitType>> {
typedef KeyTraitsArg KeyTraits;
typedef ValueTraitsArg ValueTraits;
typedef KeyValuePair<typename KeyTraits::TraitType,
typename ValueTraits::TraitType>
TraitType;
typedef KeyValuePair<typename KeyTraits::EmptyValueType,
typename ValueTraits::EmptyValueType>
EmptyValueType;
static const bool emptyValueIsZero =
KeyTraits::emptyValueIsZero && ValueTraits::emptyValueIsZero;
static EmptyValueType emptyValue() {
return KeyValuePair<typename KeyTraits::EmptyValueType,
typename ValueTraits::EmptyValueType>(
KeyTraits::emptyValue(), ValueTraits::emptyValue());
}
template <typename U = void>
struct IsTraceableInCollection {
static const bool value = IsTraceableInCollectionTrait<KeyTraits>::value ||
IsTraceableInCollectionTrait<ValueTraits>::value;
};
template <typename U = void>
struct NeedsToForbidGCOnMove {
static const bool value =
KeyTraits::template NeedsToForbidGCOnMove<>::value ||
ValueTraits::template NeedsToForbidGCOnMove<>::value;
};
static const WeakHandlingFlag weakHandlingFlag =
(KeyTraits::weakHandlingFlag == WeakHandlingInCollections ||
ValueTraits::weakHandlingFlag == WeakHandlingInCollections)
? WeakHandlingInCollections
: NoWeakHandlingInCollections;
static const unsigned minimumTableSize = KeyTraits::minimumTableSize;
static void constructDeletedValue(TraitType& slot, bool zeroValue) {
KeyTraits::constructDeletedValue(slot.key, zeroValue);
// See similar code in this file for why we need to do this.
if (zeroValue)
memset(reinterpret_cast<void*>(&slot.value), 0, sizeof(slot.value));
}
static bool isDeletedValue(const TraitType& value) {
return KeyTraits::isDeletedValue(value.key);
}
};
template <typename Key, typename Value>
struct HashTraits<KeyValuePair<Key, Value>>
: public KeyValuePairHashTraits<HashTraits<Key>, HashTraits<Value>> {};
template <typename T>
struct NullableHashTraits : public HashTraits<T> {
static const bool emptyValueIsZero = false;
static T emptyValue() { return reinterpret_cast<T>(1); }
};
// This is for tracing inside collections that have special support for weak
// pointers. The trait has a trace method which returns true if there are weak
// pointers to things that have not (yet) been marked live. Returning true
// indicates that the entry in the collection may yet be removed by weak
// handling. Default implementation for non-weak types is to use the regular
// non-weak TraceTrait. Default implementation for types with weakness is to
// call traceInCollection on the type's trait.
template <WeakHandlingFlag weakHandlingFlag,
ShouldWeakPointersBeMarkedStrongly strongify,
typename T,
typename Traits>
struct TraceInCollectionTrait;
} // namespace WTF
using WTF::HashTraits;
using WTF::PairHashTraits;
using WTF::NullableHashTraits;
using WTF::SimpleClassHashTraits;
#endif // WTF_HashTraits_h
| [
"[email protected]"
] |
Subsets and Splits