blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 2 247 | content_id stringlengths 40 40 | detected_licenses listlengths 0 57 | license_type stringclasses 2 values | repo_name stringlengths 4 111 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringlengths 4 58 | visit_date timestamp[ns]date 2015-07-25 18:16:41 2023-09-06 10:45:08 | revision_date timestamp[ns]date 1970-01-14 14:03:36 2023-09-06 06:22:19 | committer_date timestamp[ns]date 1970-01-14 14:03:36 2023-09-06 06:22:19 | github_id int64 3.89k 689M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 25 values | gha_event_created_at timestamp[ns]date 2012-06-07 00:51:45 2023-09-14 21:58:52 ⌀ | gha_created_at timestamp[ns]date 2008-03-27 23:40:48 2023-08-24 19:49:39 ⌀ | gha_language stringclasses 159 values | src_encoding stringclasses 34 values | language stringclasses 1 value | is_vendor bool 1 class | is_generated bool 2 classes | length_bytes int64 7 10.5M | extension stringclasses 111 values | filename stringlengths 1 195 | text stringlengths 7 10.5M |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
5ec0b4c791141f4bf717fd2109484a0058ae29c8 | 1708ae0065594deb61ce54e74e08782caa1e5352 | /SnakeClient/network/jsnakesocket.h | 1d4f6e6b3b923e0061d3650c83e7c446ad259008 | [] | no_license | stareven/Dlut-Game-Platform | e9933214bb3984416414b19bf220390c7322182b | 0bbe52420ec337c1c77bda70d4d84cc865915cbb | refs/heads/master | 2021-01-18T04:53:10.054947 | 2011-08-28T23:23:28 | 2011-08-28T23:23:28 | 2,854,323 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,383 | h | jsnakesocket.h | #ifndef JSNAKESOCKET_H
#define JSNAKESOCKET_H
#include "network/jsocketbase.h"
namespace Snake
{
class JRoom;
}
class QPoint;
class JSnakeSocket : public JSocketBase
{
Q_OBJECT
explicit JSnakeSocket(QObject *parent = 0);
static JSnakeSocket s_socket;
public:
static JSnakeSocket& getInstance();
void sendHello(JID userId);
void sendRqsUserlist();
void sendAddRoom(const Snake::JRoom&);
void sendEnterRoom(JID roomId);
void sendEscapeRoom();
void sendRqsRoomlist();
void sendGA_Ready(bool ready);
void sendGA_Turn(qint16 dire);
signals:
void rcvHello(JCode code);
void rcvUserlist(JID roomId,const QList<JID>& userlist);
void rcvAddRoom(const Snake::JRoom&);
void rcvDeleteRoom(JID roomId);
void rcvEnterRoom(JID roomId,JID userId);
void rcvEscapeRoom(JID roomId,JID userId);
void rcvRoomlist(const QList<Snake::JRoom>& roomlist);
void rcvRoominfoUpdate(const Snake::JRoom& roominfo);
void rcvGA_Ready(bool ready,int num);
void rcvGA_CountDown(int sec);
void rcvGA_GetCommand();
void rcvGA_Turn(qint16 dire,int num);
void rcvGA_Collision(int num);
void rcvGA_CreateBean(const QPoint& pt);
void rcvGA_Increase(int num);
void rcvGA_MoveOn(int num);
void rcvGA_Stop();
protected:
void dataProcess(const QByteArray&);
private:
MagicNumber::JMagicNumber getMagicNumber()const
{
return MagicNumber::EMN_UserNumber+1;
}
};
#endif // JSNAKESOCKET_H
|
afe6ff5ab903b593c0ad7dc1f6a439ce1dad9da1 | a05e9799a7dbb11bf1ef93a7100a5bccdc2e0680 | /include/Algo.h | 97224c84648534412067e199b9b313bda28c3be9 | [] | no_license | Pudums/TTR | 67606429ad3c18d132df877c0132914e4e2fff36 | ac52a512f37cae96fc93edea1cf8690bb4e722c7 | refs/heads/main | 2023-05-04T11:00:30.779706 | 2021-05-28T17:36:49 | 2021-05-28T17:36:49 | 339,153,835 | 4 | 0 | null | 2021-02-25T15:14:52 | 2021-02-15T17:26:16 | C++ | UTF-8 | C++ | false | false | 771 | h | Algo.h | //
// Created by timofey on 24.02.2021.
//
#ifndef TTR_ALGO_H
#define TTR_ALGO_H
#include <iostream>
#include <map>
#include <set>
#include <string>
#include <vector>
#include "Path.h"
struct Algo {
std::map<std::string, std::vector<std::string>> g;
static int find_best_way(
const std::string &start,
const std::set<std::string> &visited_cities,
const std::vector<Path> &all_paths);
Algo() = default;
Algo(const std::vector<Path> &paths,
const int &player,
const std::set<int> &station_paths);
bool is_route_exists(const std::string &s, const std::string &t);
void dfs(const std::string ¤t,
const std::string &t,
std::set<std::string> &used);
};
#endif // TTR_ALGO_H
|
592948363f9d89c412300349147ce0351e230c2c | 510cfe880a475f0c572cc34c1b544e41911c3e6c | /nknumfre.cpp | 10e2157f6c914847ced05455a5a10f2c39047803 | [] | no_license | ptkhai1203/cf-problems | aa40a1233b490c0daa977f978bed5b517bc47190 | 421c8e43401aa409363d6653540d8d6238b0e1d3 | refs/heads/main | 2023-04-14T14:03:45.795965 | 2021-04-12T13:35:05 | 2021-04-12T13:35:05 | 340,100,309 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 553 | cpp | nknumfre.cpp | #include <bits/stdc++.h>
using namespace std;
#define send {ios_base::sync_with_stdio(0);}
#define help {cin.tie(0);};
int gcd(int a, int b){
if(a == 0)
return b;
return gcd(b % a, a);
}
int rev(int x){
int res = 0;
while(x != 0){
res = res * 10 + (x % 10);
x /= 10;
}
return res;
}
int main(){
int l, r;
while(cin >> l >> r){
int res = 0;
for(int i = l; i <= r; ++i)
if(gcd(i, rev(i)) == 1)
res++;
cout << res << '\n';
}
return 0;
} |
af1a2808cbf4ae339ce9574858657ef63a3df08b | 5db0a97a2419a5d5e77ed2aa9c940f41e95f71de | /HACKRNDM.cpp | e3e5544d3ee5997e989957be1e7cd20d13a756b2 | [] | no_license | dieuninh1997/spoj-2017 | 6599d839074389b07242c2884a51a123bdde45af | fba7af738f3050feb731acd96ffd5f5e5795ccdf | refs/heads/master | 2021-05-12T11:58:07.199952 | 2018-01-14T05:05:52 | 2018-01-14T05:05:52 | 117,400,402 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 460 | cpp | HACKRNDM.cpp | #include<bits/stdc++.h>
using namespace std;
typedef long long ll ;
#define FOR(i,a,b) for(int i=a;i<b;++i)
#define FORI(i,b,a) for(int i=b;i>=a;--i)
void solve()
{
int n,k;
cin>>n>>k;
map<int, int> m;
for(int i=0; i<n;i++)
{
int x;
cin>>x;
m[x]++;
}
int res=0;
map<int,int>::iterator it,a;
for(it=m.begin(); it!=m.end();it++)
{
a=m.find(it->first+k);
if(a!=m.end())
res+=a->second;
}
cout<<res;
}
int main()
{
solve();
return 0;
}
|
5f7152f305dadc6252013e6619f05331f1fdc15e | b9bdb782d585153a8cff6b17f7d3368d5c9a7081 | /linear_list/link_cycle_list.h | a253f6f3ab3c33946be80071dbcf3ffa576affe2 | [] | no_license | schwarzeni/kaoyan_data_structure | 904caa7c5a0c6d79e9173d39170a5b9c6a2a8e4c | a6c89ba148e2e1b326c13aac5a6bb3c23f4c2ff3 | refs/heads/master | 2020-03-25T06:30:28.937160 | 2018-08-27T08:00:15 | 2018-08-27T08:00:15 | 143,506,346 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,288 | h | link_cycle_list.h | //
// Created by schwarzeni on 2018/7/23.
//
#ifndef KAOYAN_DATA_STRUCTURE_LINK_CYCLE_LIST_H
#define KAOYAN_DATA_STRUCTURE_LINK_CYCLE_LIST_H
/**
* 2018/7/23
* 单向循环链表
*/
#include <iostream>
namespace linkCycleList {
int length = 5;
typedef int Elemtype;
Elemtype *data = new Elemtype[length]{1, 2, 3, 4, 5};
typedef struct LNode {
Elemtype data;
LNode *next;
} LNode, *LinkList;
/**
* 2018/7/23
* 初始化链表
* @param l
*/
void Init(LinkList &l) {
l = new LNode{};
l->next = nullptr;
bool isFirst = true;
LNode* tail = nullptr;
for (int i = length - 1; i >= 0; i--) {
auto node = new LNode{};
node->data = data[i];
node->next = l->next;
l->next = node;
if (isFirst) {
tail = node;
isFirst = false;
} else {
tail->next = node;
}
}
}
/**
* 2018/7/23
* 正向输出列表值
* @param l
* @param times
*/
void Display(LinkList &l, int times) {
if (l->next == nullptr) return;
auto tmp = l->next;
auto oneLineNum = 20;
for (int i = 1; i <= times; i++) {
std::cout << tmp->data << " " ;
if (tmp->next == l->next) {
std::cout << std::endl<< "=====" << std::endl;
}
tmp = tmp->next;
}
std::cout << std::endl;
}
}
#endif //KAOYAN_DATA_STRUCTURE_LINK_CYCLE_LIST_H
|
4cfabc9c33c6b9bb67322cd78e330bff280acab9 | cb9e1cbd351ebef1e5cffb386f9b0bb558273d80 | /listFuncs.h | 7c633421f0aceb55804be335a26e4cb67b3358d7 | [] | no_license | xzhang603/Hash-Table-with-LinkedList | 1626919f1483087207aff2f381294fc69715e19a | 9c0ec67cb7599604d34711911cbc103f3f6cb9de | refs/heads/main | 2023-04-17T08:44:54.890058 | 2021-05-11T18:10:35 | 2021-05-11T18:10:35 | 366,472,921 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,212 | h | listFuncs.h | // Name: Xin Zhang
// USC NetID: xzhang55 USCID:4998-6225-16
// CSCI 455 PA5
// Spring 2021
//*************************************************************************
// Node class definition
// and declarations for functions on ListType
// Note: we don't need Node in Table.h
// because it's used by the Table class; not by any Table client code.
// Note2: it's good practice to not put "using" statement in *header* files. Thus
// here, things from std libary appear as, for example, std::string
#ifndef LIST_FUNCS_H
#define LIST_FUNCS_H
#include <string>
struct Node {
std::string key;
int value;
Node *next;
Node(const std::string &theKey, int theValue);
Node(const std::string &theKey, int theValue, Node *n);
};
typedef Node * ListType;
//*************************************************************************
//add function headers (aka, function prototypes) for your functions
//that operate on a list here (i.e., each includes a parameter of type
//ListType or ListType&). No function definitions go in this file.
/*
Check Wether the key (word) in the entry. return False if not, return True if it is.
Input: Reference of List, the String we want to check
*/
bool containsKey(ListType & list, const std::string &this_key);
/*
Put the Key and its value into the linklist.
Input: Reference of List, the String and its corresponding value we want to put.
*/
void put(ListType & list, const std::string &key, int value);
/*
Remove the key in the linklist. Return False if the key not in the list. Return True if successfully remove
Input: Reference of List, the String we want to remove
*/
bool removeKey(ListType & list, const std::string &this_key);
/*
Get the a Address of the key, Return Address or NULL if not in the list.
Input: Reference of List, the String we want to get address
*/
ListType getAddress(ListType &list, const std::string &this_key);
/*
Print the entire list for debug and Table.
Input: Reference of list
*/
void printList(ListType & list);
/*
Return the length of the list.
Input: Reference of list
*/
int listLen(ListType & list);
// keep the following line at the end of the file
#endif
|
f3e81db787937e8f3857bea2c1126a7e0557743b | 2a573891e893ef0c985945dea8fd9e7ff5fea927 | /VoxFab/Dlg_FEAInfo.cpp | 1ba3ce289f931b6d6abcd2a09150a336a7ceb962 | [] | no_license | atsmsmr/VoxFab | e46fa18a11d85da9c408200484a9a1194c71e10f | 02f0b6384cf5961a692aa93cac4c5a693388dd01 | refs/heads/master | 2021-01-09T20:09:29.579248 | 2016-07-11T17:38:58 | 2016-07-11T17:38:58 | 63,086,828 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 5,833 | cpp | Dlg_FEAInfo.cpp | /*******************************************************************************
Copyright (c) 2016, Atsushi Masumori
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 <organization> 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 <COPYRIGHT HOLDER> 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.
*******************************************************************************/
// This software is developed based on VoxCad (https://svn.code.sf.net/p/voxcad/code/VoxCad/) developed by following author with following license.
/*******************************************************************************
Copyright (c) 2010, Jonathan Hiller
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.
* The name if its contributors may not be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*******************************************************************************/
#include "Dlg_FEAInfo.h"
Dlg_FEAInfo::Dlg_FEAInfo(QVX_FEA* pFEAIn, QWidget *parent)
: QWidget(parent)
{
pFEA = pFEAIn;
ui.setupUi(this);
ui.ViewTypeCombo->addItem("Displacement"); //Must be in same order as FeaViewMode enum
ui.ViewTypeCombo->addItem("Force");
ui.ViewTypeCombo->addItem("Strain");
ui.ViewTypeCombo->addItem("Reaction");
connect(ui.ViewTypeCombo, SIGNAL(currentIndexChanged(int)), this, SLOT(ApplyPreset(int)));
connect(ui.DefSlider, SIGNAL(valueChanged(int)), this, SLOT(ChangedDeflection(int)));
connect(ui.SectionSlider, SIGNAL(valueChanged(int)), this, SLOT(ChangedSection(int)));
connect(ui.IsoThreshSlider, SIGNAL(valueChanged(int)), this, SLOT(ChangedIso(int)));
connect(ui.DirXRadio, SIGNAL(clicked()), this, SLOT(SetDirToX()));
connect(ui.DirYRadio, SIGNAL(clicked()), this, SLOT(SetDirToY()));
connect(ui.DirZRadio, SIGNAL(clicked()), this, SLOT(SetDirToZ()));
connect(ui.DirMaxRadio, SIGNAL(clicked()), this, SLOT(SetDirToMax()));
connect(ui.DoneButton, SIGNAL(clicked()), this, SLOT(DoneButtonPressed()));
UpdateUI();
}
Dlg_FEAInfo::~Dlg_FEAInfo()
{
}
void Dlg_FEAInfo::ApplyPreset(int NewPreset)
{
switch (NewPreset){
case VIEW_DISP: pFEA->SetViewModeDisplacement(); break;
case VIEW_FORCE: pFEA->SetViewModeForce(); break;
case VIEW_STRAIN: pFEA->SetViewModeStrain(); break;
case VIEW_REACTION: pFEA->SetViewModeReaction(); break;
}
UpdateUI();
emit RequestUpdateGL();
}
void Dlg_FEAInfo::UpdateUI(void)
{
if (isVisible()){
ui.ViewTypeCombo->setCurrentIndex((int)pFEA->ViewMode);
ui.DefSlider->setValue(pFEA->ViewDefPerc*200.0); //set initial value of slider...
ui.SectionSlider->setValue(pFEA->ViewZChop*1000.0); //set initial value of slider...
ui.IsoThreshSlider->setValue(pFEA->ViewThresh*1000.0); //set initial value of slider...
switch(pFEA->ViewModeDir){
case XDIR: ui.DirXRadio->setChecked(true); break;
case YDIR: ui.DirYRadio->setChecked(true); break;
case ZDIR: ui.DirZRadio->setChecked(true); break;
case MAXDIR: ui.DirMaxRadio->setChecked(true); break;
}
UpdateText();
}
}
void Dlg_FEAInfo::UpdateText(void)
{
QString FullText;
int CurSel = -1;
emit GetCurIndex(&CurSel);
if (CurSel <0) emit GetFEAInfoString(&FullText);
else emit GetFEAInfoString(CurSel, &FullText);
ui.FEAInfoLabel->setText(FullText);
}
|
b4b816d311c469b38d225d520898c86cfb2f440f | 7926b330515aa573a810ed9cb298c3de93b007f9 | /陈磊贡献/强连通分量2.cpp | d51b24c1216df7ca48385b563488066db081076e | [] | no_license | laijirong/NOIP-C-files | 6f1dceae364e41625f3a4ef0e3897ef1c731d0fe | 951af9aa0b287a8c169b6ba03d618ba8ba2e0ae2 | refs/heads/master | 2020-04-20T11:38:00.485181 | 2019-06-16T03:00:55 | 2019-06-16T03:00:55 | 168,822,282 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,305 | cpp | 强连通分量2.cpp | #include<iostream>
#include<cstdio>
using namespace std;
int n,m,sum,p,q,red;
int head[10010],tail[10010],used[10010],d[10010],len[10010];
int seat[10010],l[10010];
struct ss
{
int last,val;
} mapz[500010];
struct sss
{
int last,start;
} mapf[500010];
void read1(int a,int b,int c)
{
mapz[c].last=head[a];
mapz[c].val=b;
head[a]=c;
}
void read2(int a,int b,int c)
{
mapf[c].last=tail[b];
mapf[c].start=a;
tail[b]=c;
}
void search2(int a)
{
used[a]=0;
seat[++red]=a;
for(int i=tail[a];i!=0;i=mapf[i].last)
if(used[mapf[i].start]!=0) search2(mapf[i].start);
}
void search1(int a)
{
used[a]=1;
for(int i=head[a];i!=0;i=mapz[i].last)
if(used[mapz[i].val]==0) search1(mapz[i].val);
d[++p]=a;
len[q]++;
}
int main()
{
int x,y;
scanf("%d%d",&n,&m);
for(int i=1;i<=m;i++)
{
scanf("%d%d",&x,&y);
read1(x,y,i);
read2(x,y,i);
}
for(int i=1;i<=n;i++)
if(used[i]==0)
{
q++;
search1(i);
}
for(int i=q;i>=1;i--)
{
for(int j=p;j>=p-len[i];j--)
if(used[d[j]]==1)
{
sum++;
search2(d[j]);
l[sum]=red;
}
p-=len[i];
}
printf("%d\n",sum);
for(int i=1;i<=sum;i++)
{
printf("%d ",l[i]-l[i-1]);
for(int j=l[i-1]+1;j<=l[i];j++)
printf("%d ",seat[j]);
printf("\n");
}
return 0;
}
|
606117b9a4b108f231b452ddfbfe2e05bbda07c6 | 604c3a16454625d5589fb768b0ea032ed234035c | /Aula07_13/Funcionario.h | bf48272ba85362084be0a8d18573149445e8afde | [] | no_license | marcosmn/LP1_2020.5 | 035ffa14c2d3f44735f1066d193289f1bf344af8 | 61b102495c0215161ddf63527e0e477b496c2fc9 | refs/heads/master | 2022-11-15T06:12:29.322254 | 2020-07-20T18:27:55 | 2020-07-20T18:27:55 | 274,411,676 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 568 | h | Funcionario.h | #include <string>
#include "Empresa.h"
using namespace std;
class Funcionario
{
public:
Funcionario();
~Funcionario();
void setEmpresa(Empresa novaEmpresa);
Empresa getEmpresa();
void setNome(string novoNome);
string getNome();
void setSalario(int novoSalario);
double getSalario();
void setDataAdmissao(int novaDataAdmissao);
int getDataAdmissao();
void setDepartamento(string novoDepartamento);
string getDepartamento();
private:
Empresa empresa;
string nome;
double salario;
int dataAdmissao;
string departamento;
}; |
05fa7c5bcd2d20e03b7a9929b8867fcf7f70d6dd | 4c642de2d9cf0f002a6c927e0c35e1ff8129378d | /examples/db_client/src/main.cpp | b0f8636c70a08b63163d96f1e5ca9b5720dd17eb | [
"MIT"
] | permissive | paceholder/mif | 93ca6818577d670e90829ad4e7a6fb87fe5ed84a | ff3c18f577048c94887220bb92477ce102f01599 | refs/heads/master | 2020-12-02T06:37:44.150255 | 2017-07-11T18:23:30 | 2017-07-11T18:23:30 | 96,864,887 | 4 | 1 | null | 2017-07-11T18:23:31 | 2017-07-11T07:37:15 | C++ | UTF-8 | C++ | false | false | 9,536 | cpp | main.cpp | //-------------------------------------------------------------------
// MetaInfo Framework (MIF)
// https://github.com/tdv/mif
// Created: 03.2017
// Copyright (C) 2016-2017 tdv
//-------------------------------------------------------------------
// STD
#include <cstdint>
#include <sstream>
#include <stdexcept>
#include <string>
// BOOST
#include <boost/algorithm/string.hpp>
#include <boost/filesystem.hpp>
#include <boost/scope_exit.hpp>
// MIF
#include <mif/application/application.h>
#include <mif/common/uuid_generator.h>
#include <mif/common/log.h>
#include <mif/db/transaction.h>
#include <mif/db/id/service.h>
#include <mif/service/create.h>
class Application
: public Mif::Application::Application
{
public:
Application(int argc, char const **argv)
: Mif::Application::Application{argc, argv}
{
boost::program_options::options_description commonOptions{"Common database options"};
commonOptions.add_options()
("type", boost::program_options::value<std::string>(&m_type)->default_value("sqlite"),
"Database type (postgres or sqlite)")
("db-prefix", boost::program_options::value<std::string>(&m_dbPrefix)->default_value("mif_db_test"),
"Database name prefix")
("clean", boost::program_options::value<bool>(&m_cleanResult)->default_value(true),
"Remove all generated data")
;
AddCustomOptions(commonOptions);
boost::program_options::options_description pgOptions{"PostgreSQL options"};
pgOptions.add_options()
("pg-host", boost::program_options::value<std::string>(&m_pgHost)->default_value("localhost"),
"PostgreSQL database host")
("pg-port", boost::program_options::value<std::uint16_t>(&m_pgPort)->default_value(5432),
"PostgreSQL database port")
("pg-user", boost::program_options::value<std::string>(&m_pgUser)->default_value("postgres"),
"PostgreSQL database user")
("pg-pwd", boost::program_options::value<std::string>(&m_pgPassword)->default_value(""),
"PostgreSQL database user password")
("pg-timeout", boost::program_options::value<std::uint32_t>(&m_pgConnectionTimeout)->default_value(10),
"PostgreSQL database connection timeout")
;
AddCustomOptions(pgOptions);
boost::program_options::options_description sqliteOptions{"SQLite options"};
sqliteOptions.add_options()
("sqlite-in-memory", boost::program_options::value<bool>(&m_sqliteInMemory)->default_value(true),
"SQLite in-memory database")
("sqlite-dir", boost::program_options::value<std::string>(&m_sqliteDir)->default_value("."),
"SQLite database dir")
;
AddCustomOptions(sqliteOptions);
}
private:
std::string m_type;
std::string m_dbPrefix;
bool m_cleanResult;
std::string m_pgHost;
std::uint16_t m_pgPort;
std::string m_pgUser;
std::string m_pgPassword;
std::uint32_t m_pgConnectionTimeout;
bool m_sqliteInMemory;
std::string m_sqliteDir;
std::string GenerateDbName() const
{
auto name = Mif::Common::UuidGenerator{}.Generate();
boost::algorithm::erase_all(name, "-");
if (!m_dbPrefix.empty())
name = m_dbPrefix + "_" + name;
return name;
}
// Mif.Application.Application
virtual void OnStart() override final
{
if (m_type == "postgres")
DemoPostgreSQL();
else if (m_type == "sqlite")
DemoSQLite();
else
throw std::invalid_argument{"Type \"" + m_type + "\" not supported."};
}
void ShowData(Mif::Db::IConnectionPtr connection)
{
// Run a parametrized query
auto statement = connection->CreateStatement(
"select * from test "
"where id >= $1 and id <= $2 "
"order by id;"
);
auto recordset = statement->Execute({"5", "7"});
auto const count = recordset->GetFieldsCount();
MIF_LOG(Info) << "Fields count: " << count;
for (std::size_t i = 0 ; i < count ; ++i)
MIF_LOG(Info) << "\"" << recordset->GetFieldName(i) << "\" is the name of the field " << i << ".";
while (recordset->Read())
{
for (std::size_t i = 0 ; i < count ; ++i)
{
MIF_LOG(Info) << recordset->GetFieldName(i) << ": "
<< (recordset->IsNull(i) ? std::string{"null"} : recordset->GetAsString(i));
}
}
}
void DemoPostgreSQL()
{
auto dbName = GenerateDbName();
// Create database
{
MIF_LOG(Info) << "Create database \"" << dbName << "\"";
auto connection = Mif::Service::Create<Mif::Db::Id::Service::PostgreSQL, Mif::Db::IConnection>(
m_pgHost, m_pgPort, m_pgUser, m_pgPassword, std::string{}, m_pgConnectionTimeout);
connection->ExecuteDirect(
"CREATE DATABASE " + dbName + " WITH OWNER " + m_pgUser + ";"
);
}
// Drop database on exit from method
BOOST_SCOPE_EXIT(&m_pgHost, &m_pgPort, &m_pgUser, &m_pgPassword, &m_pgConnectionTimeout,
&m_cleanResult, &dbName)
{
if (m_cleanResult)
{
try
{
MIF_LOG(Info) << "Drop database \"" << dbName << "\"";
auto connection = Mif::Service::Create<Mif::Db::Id::Service::PostgreSQL, Mif::Db::IConnection>(
m_pgHost, m_pgPort, m_pgUser, m_pgPassword, std::string{}, m_pgConnectionTimeout);
connection->ExecuteDirect("DROP DATABASE " + dbName + ";");
}
catch (std::exception const &e)
{
MIF_LOG(Warning) << "Failed to drop database \"" << dbName << "\" Error: " << e.what();
}
}
}
BOOST_SCOPE_EXIT_END
// Connect to database
MIF_LOG(Info) << "Connect ot database \"" << dbName << "\"";
auto connection = Mif::Service::Create<Mif::Db::Id::Service::PostgreSQL, Mif::Db::IConnection>(
m_pgHost, m_pgPort, m_pgUser, m_pgPassword, dbName, m_pgConnectionTimeout);
Mif::Db::Transaction transaction{connection};
// Create table 'test'
MIF_LOG(Info) << "Create table 'test'";
connection->ExecuteDirect(
"create table test"
"("
" id serial not null primary key,"
" key varchar not null,"
" value varchar"
");"
);
// Create index
MIF_LOG(Info) << "Create index";
connection->ExecuteDirect(
"create unique index test_unique_key_index on test (key);"
);
// Fill table
MIF_LOG(Info) << "Fill table";
connection->ExecuteDirect(
"insert into test (key, value) "
"select 'key_' || t.i::text, 'value_' || t.i::text "
"from generate_series(1, 10) as t(i);"
);
transaction.Commit();
// Show data
ShowData(connection);
}
void DemoSQLite()
{
std::string fileName;
BOOST_SCOPE_EXIT(&m_cleanResult, &fileName)
{
if (m_cleanResult && !fileName.empty())
{
// Remove database file
MIF_LOG(Info) << "Remove database file \"" << fileName << "\"";
boost::filesystem::remove(fileName);
}
}
BOOST_SCOPE_EXIT_END
// Connect to database
Mif::Db::IConnectionPtr connection;
if (m_sqliteInMemory)
{
MIF_LOG(Info) << "Create in-memory database";
connection = Mif::Service::Create<Mif::Db::Id::Service::SQLite, Mif::Db::IConnection>();
}
else
{
auto const path = boost::filesystem::absolute(m_sqliteDir).parent_path() / GenerateDbName();
fileName = path.c_str();
MIF_LOG(Info) << "Create or connect database from file \"" << fileName << "\"";
connection = Mif::Service::Create<Mif::Db::Id::Service::SQLite, Mif::Db::IConnection>(fileName);
}
Mif::Db::Transaction transaction{connection};
// Create table 'test'
MIF_LOG(Info) << "Create table 'test'";
connection->ExecuteDirect(
"create table test"
"("
" id integer primary key autoincrement,"
" key varchar not null,"
" value varchar"
");"
);
// Fill table
MIF_LOG(Info) << "Fill table";
for (int i = 1 ; i <= 10 ; ++i)
{
auto const index = std::to_string(i);
connection->ExecuteDirect(
"insert into test (key, value) values ('key_" + index + "', 'value_" + index + "')"
);
}
transaction.Commit();
// Show data
ShowData(connection);
}
};
int main(int argc, char const **argv)
{
return Mif::Application::Run<Application>(argc, argv);
}
|
cff0ec2d82bc2ca0f4c4f0949525df2580febb19 | 5a7c2a825728acdc41ba1c883e64def2aa0d8970 | /tfs2/src/master/ChunkHelper.hpp | 8858109bba201ac851f038eec5714cf5cd202107 | [] | no_license | kyhhdm/TPlatform | 6f4df42b3e628f116ae4f8efb91a5a363e2e82ed | 77020007648d609e074959b7cb29ee246e0cd400 | refs/heads/master | 2021-01-22T23:16:35.491597 | 2012-08-30T04:07:30 | 2012-08-30T04:07:30 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,455 | hpp | ChunkHelper.hpp | /**
* @file ChunkHelper.hpp
* Helper functions of Chunk related class.
*
* @author Zhifeng YANG
* @date 2007-07-11
*/
#ifndef _CHUNKHELPER_HPP
#define _CHUNKHELPER_HPP 1
#include <iostream>
#include <ext/hash_set>
#include <ext/hash_map>
#include "common/IceGenerated.hpp"
#include "master/AddressHelper.hpp"
namespace tfs
{
/// global operators
// inline bool operator == (const Chunk& chk1, const Chunk& chk2)
// {
// return chk1.id == chk2.id;
// }
inline std::ostream& operator << (std::ostream &os, const Chunk& chk)
{
os << "chunk(id:" << chk.id << " size:" << chk.size << " version: " << chk.version << ")";
return os;
}
inline std::ostream& operator << (std::ostream &os, const Chunks& chks)
{
os << "chunks(";
for (int i = 0; i < chks.size(); i++){
os << "[" << i << "]" << chks[i];
}
os << ")";
return os;
}
/// functors
struct ChunkEqual
{
bool operator()(const Chunk& chk1, const Chunk& chk2) const {
return chk1.id == chk2.id;
}
};
struct ChunkHash
{
size_t operator()(const Chunk& chk) const{
return chk.id;
}
};
// types
typedef __gnu_cxx::hash_set<Chunk, ChunkHash, ChunkEqual> ChunkSet;
typedef __gnu_cxx::hash_map<Chunk, AddressSet, ChunkHash, ChunkEqual> ChunkAddressMap;
}
#endif /* _CHUNKHELPER_HPP */
|
6f4bac4ac4e6e5f68d428d95f93eb3b0470c6768 | c102d77e7e363d043e017360d329c93b9285a6be | /Sources/Engine/Core/ValueType.inl | cc3a11692f9545c7da64b0d1d439165a0d66c8a9 | [
"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 | 821 | inl | ValueType.inl | /*=============================================================================
ValueType.inl
Project: Sonata Engine
Author: Julien Delezenne
=============================================================================*/
/*
SE_INLINE int32 ValueType::GetHashCode(int8 value)
{
return ((int32)(value));
}
SE_INLINE int32 ValueType::GetHashCode(int16 value)
{
return ((int32)(value | (value << 16)));
}
SE_INLINE int32 ValueType::GetHashCode(int32 value)
{
return (value);
}
SE_INLINE int32 ValueType::GetHashCode(int64 value)
{
return (((int32)value) ^ ((int32)(value >> 32)));
}
SE_INLINE int32 ValueType::GetHashCode(real32 value)
{
int32 i = (int32)(*(&value));
return i;
}
SE_INLINE int32 ValueType::GetHashCode(real64 value)
{
int64 l = (int64)(*(&value));
return (((int32)l) ^ ((int32)(l >> 32)));
}
*/ |
d312caa97f1a62adc3146afd2a1629dcc44e25e0 | a3d6556180e74af7b555f8d47d3fea55b94bcbda | /components/filename_generation/filename_generation.cc | 5c304ea53b5a2acd0de571e54f122f303ec72233 | [
"BSD-3-Clause"
] | permissive | chromium/chromium | aaa9eda10115b50b0616d2f1aed5ef35d1d779d6 | a401d6cf4f7bf0e2d2e964c512ebb923c3d8832c | refs/heads/main | 2023-08-24T00:35:12.585945 | 2023-08-23T22:01:11 | 2023-08-23T22:01:11 | 120,360,765 | 17,408 | 7,102 | BSD-3-Clause | 2023-09-10T23:44:27 | 2018-02-05T20:55:32 | null | UTF-8 | C++ | false | false | 7,252 | cc | filename_generation.cc | // Copyright 2018 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "components/filename_generation/filename_generation.h"
#include "base/check.h"
#include "base/files/file_path.h"
#include "base/files/file_util.h"
#include "base/i18n/file_util_icu.h"
#include "base/strings/string_util.h"
#include "base/strings/sys_string_conversions.h"
#include "base/strings/utf_string_conversions.h"
#include "base/third_party/icu/icu_utf.h"
#include "build/build_config.h"
#include "build/chromeos_buildflags.h"
#include "components/url_formatter/url_formatter.h"
#include "net/base/filename_util.h"
#include "net/base/mime_util.h"
#include "url/gurl.h"
namespace filename_generation {
namespace {
// The lower bound for file name truncation. If the truncation results in a name
// shorter than this limit, we give up automatic truncation and prompt the user.
const size_t kTruncatedNameLengthLowerbound = 5;
const base::FilePath::CharType kDefaultHtmlExtension[] =
FILE_PATH_LITERAL("html");
// Check whether we can save page as complete-HTML for the contents which
// have specified a MIME type. Now only contents which have the MIME type
// "text/html" can be saved as complete-HTML.
bool CanSaveAsComplete(const std::string& contents_mime_type) {
return contents_mime_type == "text/html" ||
contents_mime_type == "application/xhtml+xml";
}
} // namespace
const base::FilePath::CharType* ExtensionForMimeType(
const std::string& contents_mime_type) {
static const struct {
const char* mime_type;
const base::FilePath::CharType* suggested_extension;
} kExtensions[] = {
{"text/html", kDefaultHtmlExtension},
{"text/xml", FILE_PATH_LITERAL("xml")},
{"application/xhtml+xml", FILE_PATH_LITERAL("xhtml")},
{"text/plain", FILE_PATH_LITERAL("txt")},
{"text/css", FILE_PATH_LITERAL("css")},
{"multipart/related", FILE_PATH_LITERAL("mhtml")},
};
for (const auto& extension : kExtensions) {
if (contents_mime_type == extension.mime_type)
return extension.suggested_extension;
}
return FILE_PATH_LITERAL("");
}
base::FilePath EnsureHtmlExtension(const base::FilePath& name) {
base::FilePath::StringType ext = name.Extension();
if (!ext.empty())
ext.erase(ext.begin()); // Erase preceding '.'.
std::string mime_type;
if (!net::GetMimeTypeFromExtension(ext, &mime_type) ||
!CanSaveAsComplete(mime_type)) {
return base::FilePath(name.value() + FILE_PATH_LITERAL(".") +
kDefaultHtmlExtension);
}
return name;
}
base::FilePath EnsureMimeExtension(const base::FilePath& name,
const std::string& contents_mime_type) {
// Start extension at 1 to skip over period if non-empty.
base::FilePath::StringType ext = name.Extension();
if (!ext.empty())
ext = ext.substr(1);
base::FilePath::StringType suggested_extension =
ExtensionForMimeType(contents_mime_type);
std::string mime_type;
if (!suggested_extension.empty() &&
!net::GetMimeTypeFromExtension(ext, &mime_type)) {
// Extension is absent or needs to be updated.
return base::FilePath(name.value() + FILE_PATH_LITERAL(".") +
suggested_extension);
}
// Special treatment for MHTML: we would always want to add ".mhtml" as the
// extension even if there's another recognized mime_type based on |ext|.
// For example: the name is "page.html", we would like to have
// "page.html.mhtml" instead of "page.html".
if (contents_mime_type == "multipart/related" &&
mime_type != "multipart/related") {
return base::FilePath(name.value() + FILE_PATH_LITERAL(".mhtml"));
}
return name;
}
base::FilePath GenerateFilename(const std::u16string& title,
const GURL& url,
bool can_save_as_complete,
std::string contents_mime_type) {
base::FilePath name_with_proper_ext = base::FilePath::FromUTF16Unsafe(title);
// If the page's title matches its URL, use the URL. Try to use the last path
// component or if there is none, the domain as the file name.
// Normally we want to base the filename on the page title, or if it doesn't
// exist, on the URL. It's not easy to tell if the page has no title, because
// if the page has no title, WebContents::GetTitle() will return the page's
// URL (adjusted for display purposes). Therefore, we convert the "title"
// back to a URL, and if it matches the original page URL, we know the page
// had no title (or had a title equal to its URL, which is fine to treat
// similarly).
if (title == url_formatter::FormatUrl(
url,
url_formatter::kFormatUrlOmitDefaults |
url_formatter::kFormatUrlOmitTrivialSubdomains |
url_formatter::kFormatUrlOmitHTTPS,
base::UnescapeRule::SPACES, nullptr, nullptr, nullptr)) {
std::string url_path;
if (!url.SchemeIs(url::kDataScheme)) {
name_with_proper_ext = net::GenerateFileName(
url, std::string(), std::string(), std::string(), contents_mime_type,
std::string());
// If host is used as file name, try to decode punycode.
if (name_with_proper_ext.AsUTF8Unsafe() == url.host()) {
name_with_proper_ext = base::FilePath::FromUTF16Unsafe(
url_formatter::IDNToUnicode(url.host()));
}
} else {
name_with_proper_ext = base::FilePath::FromUTF8Unsafe("dataurl");
}
}
// Ask user for getting final saving name.
name_with_proper_ext =
EnsureMimeExtension(name_with_proper_ext, contents_mime_type);
// Adjust extension for complete types.
if (can_save_as_complete)
name_with_proper_ext = EnsureHtmlExtension(name_with_proper_ext);
base::FilePath::StringType file_name = name_with_proper_ext.value();
base::i18n::ReplaceIllegalCharactersInPath(&file_name, '_');
return base::FilePath(file_name);
}
bool TruncateFilename(base::FilePath* path, size_t limit) {
base::FilePath basename(path->BaseName());
// It is already short enough.
if (basename.value().size() <= limit)
return true;
base::FilePath dir(path->DirName());
base::FilePath::StringType ext(basename.Extension());
base::FilePath::StringType name(basename.RemoveExtension().value());
// Impossible to satisfy the limit.
if (limit < kTruncatedNameLengthLowerbound + ext.size())
return false;
limit -= ext.size();
// Encoding specific truncation logic.
base::FilePath::StringType truncated;
#if BUILDFLAG(IS_CHROMEOS_ASH) || BUILDFLAG(IS_APPLE)
// UTF-8.
base::TruncateUTF8ToByteSize(name, limit, &truncated);
#elif BUILDFLAG(IS_WIN)
// UTF-16.
DCHECK(name.size() > limit);
truncated = name.substr(0, CBU16_IS_TRAIL(name[limit]) ? limit - 1 : limit);
#else
// We cannot generally assume that the file name encoding is in UTF-8 (see
// the comment for FilePath::AsUTF8Unsafe), hence no safe way to truncate.
#endif
if (truncated.size() < kTruncatedNameLengthLowerbound)
return false;
*path = dir.Append(truncated + ext);
return true;
}
} // namespace filename_generation
|
854e8ae837bc64141802d6bc8ddf3aa80ea621c3 | 2eb6a1f3af503535e21d4ad03e42636b92d54466 | /Programas de Comp 2/Rectangle/Project2/Rectangle.cpp | 9e89b6cd55f46a590a59e7dac6c5d0743e8ed77d | [] | no_license | JMAvillan/Cpp-Projects | 1f62c742710dfb3de835ec33c7e79ce82392a60b | 512cbb1005dffb4320dd6a67b4d78210c8a4f79d | refs/heads/main | 2023-06-20T12:20:12.005058 | 2021-07-07T23:38:06 | 2021-07-07T23:38:06 | 383,950,049 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,888 | cpp | Rectangle.cpp | #include "Rectangle.h"
#include <iostream>
Rectangle::Rectangle() {
width = 1.0;
length = 1.0;
}
Rectangle::Rectangle(double aWidth, double aLenght) {
setWidth(aWidth);
setLength(aLenght);
}
Rectangle::Rectangle(const Rectangle&anRectangle)
{
setWidth(anRectangle.getWidth());
setLength(anRectangle.getLength());
}
void Rectangle::setWidth(double w) throw (NegativeWidth)
{
if (w >= 0)
width = w;
else
NegativeWidth(w);
}
//***************************************************
// setLength assigns a value to the length member. *
//***************************************************
void Rectangle::setLength(double len) throw (NegativeLength)
{
if (len >= 0)
length = len;
else {
NegativeLength(len);
}
}
//***************************************************
// getWidth returns the value in the width member. *
//***************************************************
double Rectangle::getWidth() const
{
return width;
}
//****************************************************
// getLength returns the value in the length member. *
//****************************************************
double Rectangle::getLength() const
{
return length;
}
//******************************************************
// getArea returns the product of width times length. *
//******************************************************
double Rectangle::getArea() const
{
return getWidth() * getLength();
}
//*****************************************************
// Function main *
//*****************************************************
double Rectangle::getPerimeter() const {
return 2 * getWidth() + 2 * getLength();
}
void Rectangle::display() const
{
cout << "Here is the rectangle's data:\n";
cout << "Width: " << getWidth() << endl;
cout << "Length: " << getLength() << endl;
cout << "Area: " << getArea() << endl;
cout << "Perimeter:" << getPerimeter() << endl;
} |
b6addbfb4c655c43d48025f29fbd7a060c6b6b99 | 08ed38b70ccde334ddf6abbf6d740df559731e2b | /TRC2PMBUSTool/BaseWritePage.cpp | 1c7bd72125a59714f8f8ad51805190dd36822fa4 | [] | no_license | bingshiue/wxPSU | 32ac806cdbada9c934b18ddd00c152d0eb433c3b | 33d0bf9e3c324b69e2c9f22db8c5c9d9fb6ebd13 | refs/heads/master | 2021-01-23T21:37:41.981082 | 2018-02-05T03:42:46 | 2018-02-05T03:42:46 | 57,594,833 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,087 | cpp | BaseWritePage.cpp | /**
* @file BaseWritePage.cpp
*/
#include "BaseWritePage.h"
BaseWritePage::BaseWritePage(wxWindow* parent, wxString& label) : wxPanel(parent) {
// Set Parent
this->m_parent = parent;
// Set Label
this->m_Label = label;
// Data Format
this->m_dataFormat = cmd_data_format_LinearData_Format;
// Base LayOut
this->BaseLayOut();
// Setup Validator
this->SetupValidator();
// Set Background Color
this->SetBackgroundColour(wxColour(248, 168, 133));//255, 94, 25
// Set Coifficients Static Text
this->m_coefficientsST = NULL;
}
BaseWritePage::~BaseWritePage(){
}
void BaseWritePage::BaseLayOut(void){
// Initial Static Box
m_staticBox = new wxStaticBox(this, wxID_ANY, this->m_Label);
// Initial Sizer
m_staticBoxlSizer = new wxStaticBoxSizer(this->m_staticBox, wxVERTICAL);
m_horizonSizer1 = new wxBoxSizer(wxHORIZONTAL);
// Initialize Radio Button
this->m_cookRadioButton = new wxRadioButton(this, CID_RADIO_BOX_COOK, L"decimal", wxDefaultPosition, wxSize(75, -1));
this->m_rawRadioButton = new wxRadioButton(this, CID_RADIO_BOX_RAW, L"hex", wxDefaultPosition, wxSize(75, -1));
// Initial Button
this->m_writeButton = new wxButton(this, CID_BUTTON_WRITE, L"Write");
// Initial Padding Static Text
m_stPadding_WriteButton = new wxStaticText(this, wxID_ANY, wxString(" "), wxDefaultPosition, wxSize(30, PADDING_DEFAULT_HEIGHT));
m_stPadding_1 = new wxStaticText(this, wxID_ANY, wxString(" "), wxDefaultPosition, wxSize(PADDING_DEFAULT_WIDTH, PADDING_DEFAULT_HEIGHT));
m_stPadding_2 = new wxStaticText(this, wxID_ANY, wxString(" "), wxDefaultPosition, wxSize(PADDING_DEFAULT_WIDTH, PADDING_DEFAULT_HEIGHT));
// Initail Static Line
m_staticLine_1 = new wxStaticLine(this, wxID_ANY, wxDefaultPosition, wxSize(280, -1));
// Add Component To Sizer
m_horizonSizer1->Add(this->m_cookRadioButton, wxSizerFlags(0).Border());//0, wxALIGN_CENTER_VERTICAL);
m_horizonSizer1->Add(this->m_rawRadioButton, wxSizerFlags(0).Border());//0, wxALIGN_CENTER_VERTICAL);
m_horizonSizer1->Add(this->m_stPadding_WriteButton, wxSizerFlags(0).Expand().Border());
m_horizonSizer1->Add(this->m_writeButton, wxSizerFlags(1).Align(wxALIGN_CENTER_VERTICAL));
m_staticBoxlSizer->Add(m_horizonSizer1, wxSizerFlags(0).Expand());
m_staticBoxlSizer->Add(m_stPadding_1);
m_staticBoxlSizer->Add(m_staticLine_1, wxSizerFlags(0).Expand());
m_staticBoxlSizer->Add(m_stPadding_2);
SetSizer(m_staticBoxlSizer);
}
void BaseWritePage::changeLayOutByDataFormat(unsigned int dataFormat, PMBUSCOMMAND_t *pmbuscmd) {
PSU_DEBUG_PRINT(MSG_DEBUG, "Base Class")
}
void BaseWritePage::SetupValidator(void){
DecimalCharIncludes = wxT("0123456789.");
m_numberValidator.SetStyle(wxFILTER_INCLUDE_CHAR_LIST);
m_numberValidator.SetCharIncludes(DecimalCharIncludes);
HexCharIncludes = wxT("0123456789abcdefABCDEF");
m_hexValidator.SetStyle(wxFILTER_INCLUDE_CHAR_LIST);
m_hexValidator.SetCharIncludes(HexCharIncludes);
}
wxStaticBox* BaseWritePage::getStaticBox(void){
return this->m_staticBox;
}
wxBEGIN_EVENT_TABLE(BaseWritePage, wxPanel)
// Empty
wxEND_EVENT_TABLE() |
168f52acac90d74b0aeb6e583699e2ead9570d2d | 0eff74b05b60098333ad66cf801bdd93becc9ea4 | /second/download/CMake/CMake-gumtree/Kitware_CMake_repos_basic_block_block_15852.cpp | 281866b3a161d00e426e4e401790737762cb71be | [] | no_license | niuxu18/logTracker-old | 97543445ea7e414ed40bdc681239365d33418975 | f2b060f13a0295387fe02187543db124916eb446 | refs/heads/master | 2021-09-13T21:39:37.686481 | 2017-12-11T03:36:34 | 2017-12-11T03:36:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 128 | cpp | Kitware_CMake_repos_basic_block_block_15852.cpp | {
if (wb_write_to_temp(a, buff, ws) != ARCHIVE_OK)
return (ARCHIVE_FATAL);
iso9660->cur_file->cur_content->size += ws;
} |
f28d031e69751e8f735c6868d87c6d9b004f015d | f95341dd85222aa39eaa225262234353f38f6f97 | /DesktopX/Plugins/DXSysStats/SysStatsODCOM/Dummy.cpp | f0fa6ab72deec27450cba866ea9090c8f6725cae | [] | no_license | Templier/threeoaks | 367b1a0a45596b8fe3607be747b0d0e475fa1df2 | 5091c0f54bd0a1b160ddca65a5e88286981c8794 | refs/heads/master | 2020-06-03T11:08:23.458450 | 2011-10-31T04:33:20 | 2011-10-31T04:33:20 | 32,111,618 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 196 | cpp | Dummy.cpp | // Dummy.cpp : Implementation of CDummy
#include "stdafx.h"
#include "SysStatsODCOM.h"
#include "Dummy.h"
/////////////////////////////////////////////////////////////////////////////
// CDummy
|
d15a5720778cc6006896b5aef140ed314165fef9 | 0f8a33cd80c1c619eca85b256c184a155308e99d | /src/point_cloud_cleaner.cpp | 49b168bef573715b4afdf9d487a37c080d5faca1 | [] | no_license | Moult/stone-drone-robots | ad7da7de21a99e8232b10c26e557b0cbf0c3a532 | 83735e29343971a329f709f467efb95354deb034 | refs/heads/master | 2021-01-10T16:24:35.860115 | 2015-12-14T00:02:56 | 2015-12-14T00:02:56 | 47,295,074 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 34,504 | cpp | point_cloud_cleaner.cpp | #include <cstdlib>
#include <cstring>
#include <fstream>
#include <iostream>
#include <MathGeoLib.h>
#include <tr1/functional>
#include <ply.hpp>
#ifdef HAVE_CONFIG_H
# include <config.h>
#endif
// Disclaimer: I don't know C++
using namespace std::tr1::placeholders;
class Repository
{
public:
static bool is_loading_boundary;
static int current_face_index;
static ply::float32 current_vertex[3];
static int current_face[3];
};
bool Repository::is_loading_boundary = true;
int Repository::current_face_index = 0;
float Repository::current_vertex[3] = {0, 0, 0};
int Repository::current_face[3] = {0, 0, 0};
class BoundaryChecker
{
public:
static Polyhedron polyhedron;
static void add_vertex_from_repository();
static void add_face_from_repository();
};
Polyhedron BoundaryChecker::polyhedron;
void BoundaryChecker::add_vertex_from_repository()
{
BoundaryChecker::polyhedron.v.push_back(
POINT_VEC(
Repository::current_vertex[0],
Repository::current_vertex[1],
Repository::current_vertex[2]
)
);
}
void BoundaryChecker::add_face_from_repository()
{
Polyhedron::Face face;
face.v.insert(face.v.end(), Repository::current_face, Repository::current_face+3);
BoundaryChecker::polyhedron.f.push_back(face);
}
class ply_to_ply_converter
{
public:
typedef int format_type;
enum format {
same_format,
ascii_format,
binary_format,
binary_big_endian_format,
binary_little_endian_format
};
ply_to_ply_converter(format_type format) : format_(format) {}
bool load_boundary(std::istream& bstream, std::ostream& ostream);
bool convert(std::istream& istream, std::ostream& ostream);
private:
void info_callback(const std::string& filename, std::size_t line_number, const std::string& message);
void warning_callback(const std::string& filename, std::size_t line_number, const std::string& message);
void error_callback(const std::string& filename, std::size_t line_number, const std::string& message);
void magic_callback();
void format_callback(ply::format_type format, const std::string& version);
void element_begin_callback();
void element_end_callback();
std::tr1::tuple<std::tr1::function<void()>, std::tr1::function<void()> > element_definition_callback(const std::string& element_name, std::size_t count);
template <typename ScalarType> void x_property_callback(ScalarType scalar);
template <typename ScalarType> void y_property_callback(ScalarType scalar);
template <typename ScalarType> void z_property_callback(ScalarType scalar);
template <typename ScalarType> void scalar_property_callback(ScalarType scalar);
template <typename ScalarType> std::tr1::function<void (ScalarType)> scalar_property_definition_callback(const std::string& element_name, const std::string& property_name);
template <typename SizeType, typename ScalarType> void list_property_begin_callback(SizeType size);
template <typename SizeType, typename ScalarType> void list_property_face_callback(ScalarType scalar);
template <typename SizeType, typename ScalarType> void list_property_element_callback(ScalarType scalar);
template <typename SizeType, typename ScalarType> void list_property_end_callback();
template <typename SizeType, typename ScalarType> std::tr1::tuple<std::tr1::function<void (SizeType)>, std::tr1::function<void (ScalarType)>, std::tr1::function<void ()> > list_property_definition_callback(const std::string& element_name, const std::string& property_name);
void comment_callback(const std::string& comment);
void obj_info_callback(const std::string& obj_info);
bool end_header_callback();
format_type format_;
ply::format_type input_format_, output_format_;
bool bol_;
std::ostream* ostream_;
};
void ply_to_ply_converter::info_callback(const std::string& filename, std::size_t line_number, const std::string& message)
{
std::cerr << filename << ":" << line_number << ": " << "info: " << message << std::endl;
}
void ply_to_ply_converter::warning_callback(const std::string& filename, std::size_t line_number, const std::string& message)
{
std::cerr << filename << ":" << line_number << ": " << "warning: " << message << std::endl;
}
void ply_to_ply_converter::error_callback(const std::string& filename, std::size_t line_number, const std::string& message)
{
std::cerr << filename << ":" << line_number << ": " << "error: " << message << std::endl;
}
void ply_to_ply_converter::magic_callback()
{
(*ostream_) << "ply" << "\n";
}
void ply_to_ply_converter::format_callback(ply::format_type format, const std::string& version)
{
input_format_ = format;
switch (format_) {
case same_format:
output_format_ = input_format_;
break;
case ascii_format:
output_format_ = ply::ascii_format;
break;
case binary_format:
output_format_ = ply::host_byte_order == ply::little_endian_byte_order ? ply::binary_little_endian_format : ply::binary_big_endian_format;
break;
case binary_big_endian_format:
output_format_ = ply::binary_big_endian_format;
break;
case binary_little_endian_format:
output_format_ = ply::binary_little_endian_format;
break;
};
(*ostream_) << "format ";
switch (output_format_) {
case ply::ascii_format:
(*ostream_) << "ascii";
break;
case ply::binary_little_endian_format:
(*ostream_) << "binary_little_endian";
break;
case ply::binary_big_endian_format:
(*ostream_) << "binary_big_endian";
break;
}
(*ostream_) << " " << version << "\n";
}
void ply_to_ply_converter::element_begin_callback()
{
if (output_format_ == ply::ascii_format) {
bol_ = true;
}
}
void ply_to_ply_converter::element_end_callback()
{
if (output_format_ == ply::ascii_format) {
(*ostream_) << "\n";
}
}
std::tr1::tuple<std::tr1::function<void()>, std::tr1::function<void()> > ply_to_ply_converter::element_definition_callback(const std::string& element_name, std::size_t count)
{
(*ostream_) << "element " << element_name << " " << count << "\n";
return std::tr1::tuple<std::tr1::function<void()>, std::tr1::function<void()> >(
std::tr1::bind(&ply_to_ply_converter::element_begin_callback, this),
std::tr1::bind(&ply_to_ply_converter::element_end_callback, this)
);
}
template <typename ScalarType>
void ply_to_ply_converter::x_property_callback(ScalarType scalar)
{
Repository::current_vertex[0] = scalar;
ply_to_ply_converter::scalar_property_callback(scalar);
}
template <typename ScalarType>
void ply_to_ply_converter::y_property_callback(ScalarType scalar)
{
Repository::current_vertex[1] = scalar;
ply_to_ply_converter::scalar_property_callback(scalar);
}
template <typename ScalarType>
void ply_to_ply_converter::z_property_callback(ScalarType scalar)
{
Repository::current_vertex[2] = scalar;
if (Repository::is_loading_boundary) {
BoundaryChecker::add_vertex_from_repository();
} else {
float3 point;
point.Set(Repository::current_vertex[0], Repository::current_vertex[1], Repository::current_vertex[2]);
if (BoundaryChecker::polyhedron.Contains(point)) {
ply_to_ply_converter::scalar_property_callback(scalar);
} else {
(*ostream_) << "DEL";
}
}
}
template <typename ScalarType>
void ply_to_ply_converter::scalar_property_callback(ScalarType scalar)
{
if (Repository::is_loading_boundary) {
return;
}
if (output_format_ == ply::ascii_format) {
using namespace ply::io_operators;
if (bol_) {
bol_ = false;
(*ostream_) << scalar;
}
else {
(*ostream_) << " " << scalar;
}
}
else {
if (((ply::host_byte_order == ply::little_endian_byte_order) && (output_format_ == ply::binary_big_endian_format))
|| ((ply::host_byte_order == ply::big_endian_byte_order) && (output_format_ == ply::binary_little_endian_format))) {
ply::swap_byte_order(scalar);
}
ostream_->write(reinterpret_cast<char*>(&scalar), sizeof(scalar));
}
}
template <typename ScalarType>
std::tr1::function<void (ScalarType)> ply_to_ply_converter::scalar_property_definition_callback(const std::string& element_name, const std::string& property_name)
{
(*ostream_) << "property " << ply::type_traits<ScalarType>::old_name() << " " << property_name << "\n";
if (element_name == "vertex") {
if (property_name == "x") {
return std::tr1::bind(&ply_to_ply_converter::x_property_callback<ScalarType>, this, _1);
} else if (property_name == "y") {
return std::tr1::bind(&ply_to_ply_converter::y_property_callback<ScalarType>, this, _1);
} else if (property_name == "z") {
return std::tr1::bind(&ply_to_ply_converter::z_property_callback<ScalarType>, this, _1);
} else {
return std::tr1::bind(&ply_to_ply_converter::scalar_property_callback<ScalarType>, this, _1);
}
}
}
template <typename SizeType, typename ScalarType>
void ply_to_ply_converter::list_property_begin_callback(SizeType size)
{
if (output_format_ == ply::ascii_format) {
using namespace ply::io_operators;
if (bol_) {
bol_ = false;
(*ostream_) << size;
}
else {
(*ostream_) << " " << size;
}
}
else {
if (((ply::host_byte_order == ply::little_endian_byte_order) && (output_format_ == ply::binary_big_endian_format))
|| ((ply::host_byte_order == ply::big_endian_byte_order) && (output_format_ == ply::binary_little_endian_format))) {
ply::swap_byte_order(size);
}
ostream_->write(reinterpret_cast<char*>(&size), sizeof(size));
}
}
template <typename SizeType, typename ScalarType>
void ply_to_ply_converter::list_property_face_callback(ScalarType scalar)
{
Repository::current_face[Repository::current_face_index] = scalar;
Repository::current_face_index++;
if (Repository::current_face_index > 2) {
BoundaryChecker::add_face_from_repository();
Repository::current_face_index = 0;
}
// This is copy-pasted from ply_to_ply_converter::list_property_element_callback(ScalarType scalar), because I don't know C++.
if (output_format_ == ply::ascii_format) {
using namespace ply::io_operators;
(*ostream_) << " " << scalar;
}
else {
if (((ply::host_byte_order == ply::little_endian_byte_order) && (output_format_ == ply::binary_big_endian_format))
|| ((ply::host_byte_order == ply::big_endian_byte_order) && (output_format_ == ply::binary_little_endian_format))) {
ply::swap_byte_order(scalar);
}
ostream_->write(reinterpret_cast<char*>(&scalar), sizeof(scalar));
}
}
template <typename SizeType, typename ScalarType>
void ply_to_ply_converter::list_property_element_callback(ScalarType scalar)
{
if (output_format_ == ply::ascii_format) {
using namespace ply::io_operators;
(*ostream_) << " " << scalar;
}
else {
if (((ply::host_byte_order == ply::little_endian_byte_order) && (output_format_ == ply::binary_big_endian_format))
|| ((ply::host_byte_order == ply::big_endian_byte_order) && (output_format_ == ply::binary_little_endian_format))) {
ply::swap_byte_order(scalar);
}
ostream_->write(reinterpret_cast<char*>(&scalar), sizeof(scalar));
}
}
template <typename SizeType, typename ScalarType>
void ply_to_ply_converter::list_property_end_callback()
{
}
template <typename SizeType, typename ScalarType>
std::tr1::tuple<std::tr1::function<void (SizeType)>, std::tr1::function<void (ScalarType)>, std::tr1::function<void ()> > ply_to_ply_converter::list_property_definition_callback(const std::string& element_name, const std::string& property_name)
{
// XXX
(*ostream_) << "property list " << ply::type_traits<SizeType>::old_name() << " " << ply::type_traits<ScalarType>::old_name() << " " << property_name << "\n";
if (element_name == "face") {
return std::tr1::tuple<std::tr1::function<void (SizeType)>, std::tr1::function<void (ScalarType)>, std::tr1::function<void ()> >(
std::tr1::bind(&ply_to_ply_converter::list_property_begin_callback<SizeType, ScalarType>, this, _1),
std::tr1::bind(&ply_to_ply_converter::list_property_face_callback<SizeType, ScalarType>, this, _1),
std::tr1::bind(&ply_to_ply_converter::list_property_end_callback<SizeType, ScalarType>, this)
);
} else {
return std::tr1::tuple<std::tr1::function<void (SizeType)>, std::tr1::function<void (ScalarType)>, std::tr1::function<void ()> >(
std::tr1::bind(&ply_to_ply_converter::list_property_begin_callback<SizeType, ScalarType>, this, _1),
std::tr1::bind(&ply_to_ply_converter::list_property_element_callback<SizeType, ScalarType>, this, _1),
std::tr1::bind(&ply_to_ply_converter::list_property_end_callback<SizeType, ScalarType>, this)
);
}
}
void ply_to_ply_converter::comment_callback(const std::string& comment)
{
(*ostream_) << comment << "\n";
}
void ply_to_ply_converter::obj_info_callback(const std::string& obj_info)
{
(*ostream_) << obj_info << "\n";
}
bool ply_to_ply_converter::end_header_callback()
{
(*ostream_) << "end_header" << "\n";
return true;
}
bool ply_to_ply_converter::load_boundary(std::istream& istream, std::ostream& ostream)
{
ply::ply_parser::flags_type ply_parser_flags = 0;
ply::ply_parser ply_parser(ply_parser_flags);
std::string ifilename;
ply_parser.info_callback(std::tr1::bind(&ply_to_ply_converter::info_callback, this, std::tr1::ref(ifilename), _1, _2));
ply_parser.warning_callback(std::tr1::bind(&ply_to_ply_converter::warning_callback, this, std::tr1::ref(ifilename), _1, _2));
ply_parser.error_callback(std::tr1::bind(&ply_to_ply_converter::error_callback, this, std::tr1::ref(ifilename), _1, _2));
ply_parser.magic_callback(std::tr1::bind(&ply_to_ply_converter::magic_callback, this));
ply_parser.format_callback(std::tr1::bind(&ply_to_ply_converter::format_callback, this, _1, _2));
ply_parser.element_definition_callback(std::tr1::bind(&ply_to_ply_converter::element_definition_callback, this, _1, _2));
ply::ply_parser::scalar_property_definition_callbacks_type scalar_property_definition_callbacks;
ply::at<ply::int8>(scalar_property_definition_callbacks) = std::tr1::bind(&ply_to_ply_converter::scalar_property_definition_callback<ply::int8>, this, _1, _2);
ply::at<ply::int16>(scalar_property_definition_callbacks) = std::tr1::bind(&ply_to_ply_converter::scalar_property_definition_callback<ply::int16>, this, _1, _2);
ply::at<ply::int32>(scalar_property_definition_callbacks) = std::tr1::bind(&ply_to_ply_converter::scalar_property_definition_callback<ply::int32>, this, _1, _2);
ply::at<ply::uint8>(scalar_property_definition_callbacks) = std::tr1::bind(&ply_to_ply_converter::scalar_property_definition_callback<ply::uint8>, this, _1, _2);
ply::at<ply::uint16>(scalar_property_definition_callbacks) = std::tr1::bind(&ply_to_ply_converter::scalar_property_definition_callback<ply::uint16>, this, _1, _2);
ply::at<ply::uint32>(scalar_property_definition_callbacks) = std::tr1::bind(&ply_to_ply_converter::scalar_property_definition_callback<ply::uint32>, this, _1, _2);
ply::at<ply::float32>(scalar_property_definition_callbacks) = std::tr1::bind(&ply_to_ply_converter::scalar_property_definition_callback<ply::float32>, this, _1, _2);
ply::at<ply::float64>(scalar_property_definition_callbacks) = std::tr1::bind(&ply_to_ply_converter::scalar_property_definition_callback<ply::float64>, this, _1, _2);
ply_parser.scalar_property_definition_callbacks(scalar_property_definition_callbacks);
ply::ply_parser::list_property_definition_callbacks_type list_property_definition_callbacks;
ply::at<ply::uint8, ply::int8>(list_property_definition_callbacks) = std::tr1::bind(&ply_to_ply_converter::list_property_definition_callback<ply::uint8, ply::int8>, this, _1, _2);
ply::at<ply::uint8, ply::int16>(list_property_definition_callbacks) = std::tr1::bind(&ply_to_ply_converter::list_property_definition_callback<ply::uint8, ply::int16>, this, _1, _2);
ply::at<ply::uint8, ply::int32>(list_property_definition_callbacks) = std::tr1::bind(&ply_to_ply_converter::list_property_definition_callback<ply::uint8, ply::int32>, this, _1, _2);
ply::at<ply::uint8, ply::uint8>(list_property_definition_callbacks) = std::tr1::bind(&ply_to_ply_converter::list_property_definition_callback<ply::uint8, ply::uint8>, this, _1, _2);
ply::at<ply::uint8, ply::uint16>(list_property_definition_callbacks) = std::tr1::bind(&ply_to_ply_converter::list_property_definition_callback<ply::uint8, ply::uint16>, this, _1, _2);
ply::at<ply::uint8, ply::uint32>(list_property_definition_callbacks) = std::tr1::bind(&ply_to_ply_converter::list_property_definition_callback<ply::uint8, ply::uint32>, this, _1, _2);
ply::at<ply::uint8, ply::float32>(list_property_definition_callbacks) = std::tr1::bind(&ply_to_ply_converter::list_property_definition_callback<ply::uint8, ply::float32>, this, _1, _2);
ply::at<ply::uint8, ply::float64>(list_property_definition_callbacks) = std::tr1::bind(&ply_to_ply_converter::list_property_definition_callback<ply::uint8, ply::float64>, this, _1, _2);
ply::at<ply::uint16, ply::int8>(list_property_definition_callbacks) = std::tr1::bind(&ply_to_ply_converter::list_property_definition_callback<ply::uint16, ply::int8>, this, _1, _2);
ply::at<ply::uint16, ply::int16>(list_property_definition_callbacks) = std::tr1::bind(&ply_to_ply_converter::list_property_definition_callback<ply::uint16, ply::int16>, this, _1, _2);
ply::at<ply::uint16, ply::int32>(list_property_definition_callbacks) = std::tr1::bind(&ply_to_ply_converter::list_property_definition_callback<ply::uint16, ply::int32>, this, _1, _2);
ply::at<ply::uint16, ply::uint8>(list_property_definition_callbacks) = std::tr1::bind(&ply_to_ply_converter::list_property_definition_callback<ply::uint16, ply::uint8>, this, _1, _2);
ply::at<ply::uint16, ply::uint16>(list_property_definition_callbacks) = std::tr1::bind(&ply_to_ply_converter::list_property_definition_callback<ply::uint16, ply::uint16>, this, _1, _2);
ply::at<ply::uint16, ply::uint32>(list_property_definition_callbacks) = std::tr1::bind(&ply_to_ply_converter::list_property_definition_callback<ply::uint16, ply::uint32>, this, _1, _2);
ply::at<ply::uint16, ply::float32>(list_property_definition_callbacks) = std::tr1::bind(&ply_to_ply_converter::list_property_definition_callback<ply::uint16, ply::float32>, this, _1, _2);
ply::at<ply::uint16, ply::float64>(list_property_definition_callbacks) = std::tr1::bind(&ply_to_ply_converter::list_property_definition_callback<ply::uint16, ply::float64>, this, _1, _2);
ply::at<ply::uint32, ply::int8>(list_property_definition_callbacks) = std::tr1::bind(&ply_to_ply_converter::list_property_definition_callback<ply::uint32, ply::int8>, this, _1, _2);
ply::at<ply::uint32, ply::int16>(list_property_definition_callbacks) = std::tr1::bind(&ply_to_ply_converter::list_property_definition_callback<ply::uint32, ply::int16>, this, _1, _2);
ply::at<ply::uint32, ply::int32>(list_property_definition_callbacks) = std::tr1::bind(&ply_to_ply_converter::list_property_definition_callback<ply::uint32, ply::int32>, this, _1, _2);
ply::at<ply::uint32, ply::uint8>(list_property_definition_callbacks) = std::tr1::bind(&ply_to_ply_converter::list_property_definition_callback<ply::uint32, ply::uint8>, this, _1, _2);
ply::at<ply::uint32, ply::uint16>(list_property_definition_callbacks) = std::tr1::bind(&ply_to_ply_converter::list_property_definition_callback<ply::uint32, ply::uint16>, this, _1, _2);
ply::at<ply::uint32, ply::uint32>(list_property_definition_callbacks) = std::tr1::bind(&ply_to_ply_converter::list_property_definition_callback<ply::uint32, ply::uint32>, this, _1, _2);
ply::at<ply::uint32, ply::float32>(list_property_definition_callbacks) = std::tr1::bind(&ply_to_ply_converter::list_property_definition_callback<ply::uint32, ply::float32>, this, _1, _2);
ply::at<ply::uint32, ply::float64>(list_property_definition_callbacks) = std::tr1::bind(&ply_to_ply_converter::list_property_definition_callback<ply::uint32, ply::float64>, this, _1, _2);
ply_parser.list_property_definition_callbacks(list_property_definition_callbacks);
ply_parser.comment_callback(std::tr1::bind(&ply_to_ply_converter::comment_callback, this, _1));
ply_parser.obj_info_callback(std::tr1::bind(&ply_to_ply_converter::obj_info_callback, this, _1));
ply_parser.end_header_callback(std::tr1::bind(&ply_to_ply_converter::end_header_callback, this));
ostream_ = &ostream;
return ply_parser.parse(istream);
}
bool ply_to_ply_converter::convert(std::istream& istream, std::ostream& ostream)
{
ply::ply_parser::flags_type ply_parser_flags = 0;
ply::ply_parser ply_parser(ply_parser_flags);
std::string ifilename;
ply_parser.info_callback(std::tr1::bind(&ply_to_ply_converter::info_callback, this, std::tr1::ref(ifilename), _1, _2));
ply_parser.warning_callback(std::tr1::bind(&ply_to_ply_converter::warning_callback, this, std::tr1::ref(ifilename), _1, _2));
ply_parser.error_callback(std::tr1::bind(&ply_to_ply_converter::error_callback, this, std::tr1::ref(ifilename), _1, _2));
ply_parser.magic_callback(std::tr1::bind(&ply_to_ply_converter::magic_callback, this));
ply_parser.format_callback(std::tr1::bind(&ply_to_ply_converter::format_callback, this, _1, _2));
ply_parser.element_definition_callback(std::tr1::bind(&ply_to_ply_converter::element_definition_callback, this, _1, _2));
ply::ply_parser::scalar_property_definition_callbacks_type scalar_property_definition_callbacks;
ply::at<ply::int8>(scalar_property_definition_callbacks) = std::tr1::bind(&ply_to_ply_converter::scalar_property_definition_callback<ply::int8>, this, _1, _2);
ply::at<ply::int16>(scalar_property_definition_callbacks) = std::tr1::bind(&ply_to_ply_converter::scalar_property_definition_callback<ply::int16>, this, _1, _2);
ply::at<ply::int32>(scalar_property_definition_callbacks) = std::tr1::bind(&ply_to_ply_converter::scalar_property_definition_callback<ply::int32>, this, _1, _2);
ply::at<ply::uint8>(scalar_property_definition_callbacks) = std::tr1::bind(&ply_to_ply_converter::scalar_property_definition_callback<ply::uint8>, this, _1, _2);
ply::at<ply::uint16>(scalar_property_definition_callbacks) = std::tr1::bind(&ply_to_ply_converter::scalar_property_definition_callback<ply::uint16>, this, _1, _2);
ply::at<ply::uint32>(scalar_property_definition_callbacks) = std::tr1::bind(&ply_to_ply_converter::scalar_property_definition_callback<ply::uint32>, this, _1, _2);
ply::at<ply::float32>(scalar_property_definition_callbacks) = std::tr1::bind(&ply_to_ply_converter::scalar_property_definition_callback<ply::float32>, this, _1, _2);
ply::at<ply::float64>(scalar_property_definition_callbacks) = std::tr1::bind(&ply_to_ply_converter::scalar_property_definition_callback<ply::float64>, this, _1, _2);
ply_parser.scalar_property_definition_callbacks(scalar_property_definition_callbacks);
ply::ply_parser::list_property_definition_callbacks_type list_property_definition_callbacks;
ply::at<ply::uint8, ply::int8>(list_property_definition_callbacks) = std::tr1::bind(&ply_to_ply_converter::list_property_definition_callback<ply::uint8, ply::int8>, this, _1, _2);
ply::at<ply::uint8, ply::int16>(list_property_definition_callbacks) = std::tr1::bind(&ply_to_ply_converter::list_property_definition_callback<ply::uint8, ply::int16>, this, _1, _2);
ply::at<ply::uint8, ply::int32>(list_property_definition_callbacks) = std::tr1::bind(&ply_to_ply_converter::list_property_definition_callback<ply::uint8, ply::int32>, this, _1, _2);
ply::at<ply::uint8, ply::uint8>(list_property_definition_callbacks) = std::tr1::bind(&ply_to_ply_converter::list_property_definition_callback<ply::uint8, ply::uint8>, this, _1, _2);
ply::at<ply::uint8, ply::uint16>(list_property_definition_callbacks) = std::tr1::bind(&ply_to_ply_converter::list_property_definition_callback<ply::uint8, ply::uint16>, this, _1, _2);
ply::at<ply::uint8, ply::uint32>(list_property_definition_callbacks) = std::tr1::bind(&ply_to_ply_converter::list_property_definition_callback<ply::uint8, ply::uint32>, this, _1, _2);
ply::at<ply::uint8, ply::float32>(list_property_definition_callbacks) = std::tr1::bind(&ply_to_ply_converter::list_property_definition_callback<ply::uint8, ply::float32>, this, _1, _2);
ply::at<ply::uint8, ply::float64>(list_property_definition_callbacks) = std::tr1::bind(&ply_to_ply_converter::list_property_definition_callback<ply::uint8, ply::float64>, this, _1, _2);
ply::at<ply::uint16, ply::int8>(list_property_definition_callbacks) = std::tr1::bind(&ply_to_ply_converter::list_property_definition_callback<ply::uint16, ply::int8>, this, _1, _2);
ply::at<ply::uint16, ply::int16>(list_property_definition_callbacks) = std::tr1::bind(&ply_to_ply_converter::list_property_definition_callback<ply::uint16, ply::int16>, this, _1, _2);
ply::at<ply::uint16, ply::int32>(list_property_definition_callbacks) = std::tr1::bind(&ply_to_ply_converter::list_property_definition_callback<ply::uint16, ply::int32>, this, _1, _2);
ply::at<ply::uint16, ply::uint8>(list_property_definition_callbacks) = std::tr1::bind(&ply_to_ply_converter::list_property_definition_callback<ply::uint16, ply::uint8>, this, _1, _2);
ply::at<ply::uint16, ply::uint16>(list_property_definition_callbacks) = std::tr1::bind(&ply_to_ply_converter::list_property_definition_callback<ply::uint16, ply::uint16>, this, _1, _2);
ply::at<ply::uint16, ply::uint32>(list_property_definition_callbacks) = std::tr1::bind(&ply_to_ply_converter::list_property_definition_callback<ply::uint16, ply::uint32>, this, _1, _2);
ply::at<ply::uint16, ply::float32>(list_property_definition_callbacks) = std::tr1::bind(&ply_to_ply_converter::list_property_definition_callback<ply::uint16, ply::float32>, this, _1, _2);
ply::at<ply::uint16, ply::float64>(list_property_definition_callbacks) = std::tr1::bind(&ply_to_ply_converter::list_property_definition_callback<ply::uint16, ply::float64>, this, _1, _2);
ply::at<ply::uint32, ply::int8>(list_property_definition_callbacks) = std::tr1::bind(&ply_to_ply_converter::list_property_definition_callback<ply::uint32, ply::int8>, this, _1, _2);
ply::at<ply::uint32, ply::int16>(list_property_definition_callbacks) = std::tr1::bind(&ply_to_ply_converter::list_property_definition_callback<ply::uint32, ply::int16>, this, _1, _2);
ply::at<ply::uint32, ply::int32>(list_property_definition_callbacks) = std::tr1::bind(&ply_to_ply_converter::list_property_definition_callback<ply::uint32, ply::int32>, this, _1, _2);
ply::at<ply::uint32, ply::uint8>(list_property_definition_callbacks) = std::tr1::bind(&ply_to_ply_converter::list_property_definition_callback<ply::uint32, ply::uint8>, this, _1, _2);
ply::at<ply::uint32, ply::uint16>(list_property_definition_callbacks) = std::tr1::bind(&ply_to_ply_converter::list_property_definition_callback<ply::uint32, ply::uint16>, this, _1, _2);
ply::at<ply::uint32, ply::uint32>(list_property_definition_callbacks) = std::tr1::bind(&ply_to_ply_converter::list_property_definition_callback<ply::uint32, ply::uint32>, this, _1, _2);
ply::at<ply::uint32, ply::float32>(list_property_definition_callbacks) = std::tr1::bind(&ply_to_ply_converter::list_property_definition_callback<ply::uint32, ply::float32>, this, _1, _2);
ply::at<ply::uint32, ply::float64>(list_property_definition_callbacks) = std::tr1::bind(&ply_to_ply_converter::list_property_definition_callback<ply::uint32, ply::float64>, this, _1, _2);
ply_parser.list_property_definition_callbacks(list_property_definition_callbacks);
ply_parser.comment_callback(std::tr1::bind(&ply_to_ply_converter::comment_callback, this, _1));
ply_parser.obj_info_callback(std::tr1::bind(&ply_to_ply_converter::obj_info_callback, this, _1));
ply_parser.end_header_callback(std::tr1::bind(&ply_to_ply_converter::end_header_callback, this));
ostream_ = &ostream;
return ply_parser.parse(istream);
}
int main(int argc, char* argv[])
{
ply_to_ply_converter::format_type ply_to_ply_converter_format = ply_to_ply_converter::same_format;
int argi;
for (argi = 1; argi < argc; ++argi) {
if (argv[argi][0] != '-') {
break;
}
if (argv[argi][1] == 0) {
++argi;
break;
}
char short_opt, *long_opt, *opt_arg;
if (argv[argi][1] != '-') {
short_opt = argv[argi][1];
opt_arg = &argv[argi][2];
long_opt = &argv[argi][2];
while (*long_opt != '\0') {
++long_opt;
}
}
else {
short_opt = 0;
long_opt = &argv[argi][2];
opt_arg = long_opt;
while ((*opt_arg != '=') && (*opt_arg != '\0')) {
++opt_arg;
}
if (*opt_arg == '=') {
*opt_arg++ = '\0';
}
}
if ((short_opt == 'h') || (std::strcmp(long_opt, "help") == 0)) {
std::cout << "Usage: point_cloud_cleaner [OPTION] <BOUNDARYFILE> [[INFILE] OUTFILE]\n";
std::cout << "Parse a triangulated PLY file, and remove all vertices outside a bounding polyhedron.\n";
std::cout << "\n";
std::cout << " -h, --help display this help and exit\n";
std::cout << " -v, --version output version information and exit\n";
std::cout << " -f, --format=FORMAT set format\n";
std::cout << "\n";
std::cout << "FORMAT may be one of the following: ascii, binary, binary_big_endian,\n";
std::cout << "binary_little_endian.\n";
std::cout << "If no format is given, the format of INFILE is kept.\n";
std::cout << "\n";
std::cout << "With no INFILE/OUTFILE, or when INFILE/OUTFILE is -, read standard input/output.\n";
return EXIT_SUCCESS;
}
else if ((short_opt == 'v') || (std::strcmp(long_opt, "version") == 0)) {
std::cout << "point_cloud_cleaner v0.1\n";
std::cout << "Copyright (C) 2015 Dion Moult <dion@thinkmoult.com>\n";
std::cout << "\n";
std::cout << "This program is free software; you can redistribute it and/or modify\n";
std::cout << "it under the terms of the GNU General Public License as published by\n";
std::cout << "the Free Software Foundation; either version 2 of the License, or\n";
std::cout << "(at your option) any later version.\n";
std::cout << "\n";
std::cout << "This program is distributed in the hope that it will be useful,\n";
std::cout << "but WITHOUT ANY WARRANTY; without even the implied warranty of\n";
std::cout << "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n";
std::cout << "GNU General Public License for more details.\n";
std::cout << "\n";
std::cout << "You should have received a copy of the GNU General Public License\n";
std::cout << "along with this program; if not, write to the Free Software\n";
std::cout << "Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n";
return EXIT_SUCCESS;
}
else if ((short_opt == 'f') || (std::strcmp(long_opt, "format") == 0)) {
if (strcmp(opt_arg, "ascii") == 0) {
ply_to_ply_converter_format = ply_to_ply_converter::ascii_format;
}
else if (strcmp(opt_arg, "binary") == 0) {
ply_to_ply_converter_format = ply_to_ply_converter::binary_format;
}
else if (strcmp(opt_arg, "binary_little_endian") == 0) {
ply_to_ply_converter_format = ply_to_ply_converter::binary_little_endian_format;
}
else if (strcmp(opt_arg, "binary_big_endian") == 0) {
ply_to_ply_converter_format = ply_to_ply_converter::binary_big_endian_format;
}
else {
std::cerr << "point_cloud_cleaner: " << "invalid option `" << argv[argi] << "'" << "\n";
std::cerr << "Try `" << argv[0] << " --help' for more information.\n";
return EXIT_FAILURE;
}
}
else {
std::cerr << "point_cloud_cleaner: " << "invalid option `" << argv[argi] << "'" << "\n";
std::cerr << "Try `" << argv[0] << " --help' for more information.\n";
return EXIT_FAILURE;
}
}
int parc = argc - argi;
char** parv = argv + argi;
if (parc > 3) {
std::cerr << "point_cloud_cleaner: " << "too many parameters" << "\n";
std::cerr << "Try `" << argv[0] << " --help' for more information.\n";
return EXIT_FAILURE;
}
std::ifstream bfstream;
const char* bfilename = "";
if (parc > 0) {
bfilename = parv[0];
if (std::strcmp(bfilename, "-") != 0) {
bfstream.open(bfilename);
if (!bfstream.is_open()) {
std::cerr << "point_cloud_cleaner: " << bfilename << ": " << "no such file or directory" << "\n";
return EXIT_FAILURE;
}
}
}
std::ifstream ifstream;
const char* ifilename = "";
if (parc > 1) {
ifilename = parv[1];
if (std::strcmp(ifilename, "-") != 0) {
ifstream.open(ifilename);
if (!ifstream.is_open()) {
std::cerr << "point_cloud_cleaner: " << ifilename << ": " << "no such file or directory" << "\n";
return EXIT_FAILURE;
}
}
}
std::ofstream ofstream;
const char* ofilename = "";
if (parc > 2) {
ofilename = parv[2];
if (std::strcmp(ofilename, "-") != 0) {
ofstream.open(ofilename);
if (!ofstream.is_open()) {
std::cerr << "point_cloud_cleaner: " << ofilename << ": " << "could not open file" << "\n";
return EXIT_FAILURE;
}
}
}
std::istream& bstream = bfstream;
std::istream& istream = ifstream.is_open() ? ifstream : std::cin;
std::ostream& ostream = ofstream.is_open() ? ofstream : std::cout;
class ply_to_ply_converter ply_to_ply_converter(ply_to_ply_converter_format);
ply_to_ply_converter.load_boundary(bstream, ostream);
Repository::is_loading_boundary = false;
int result = ply_to_ply_converter.convert(istream, ostream);
std::cout << "Loaded boundary polygon ...\n";
std::cout << "Boundary vertices loaded: ";
std::cout << BoundaryChecker::polyhedron.NumVertices();
std::cout << "\n";
std::cout << "Boundary faces loaded: ";
std::cout << BoundaryChecker::polyhedron.NumFaces();
std::cout << "\n";
std::cout << "All done, please run the following commands to clean up:\n";
std::cout << "sed -i '1,/ply/d' " << parv[2] << "\n";
std::cout << "sed -i '1s/^/ply\\n/' " << parv[2] << "\n";
std::cout << "sed -i '/DEL/d' " << parv[2] << "\n";
std::cout << "VERTNUM=$(expr $(wc -l < " << parv[2] << ") - 13)\n";
std::cout << "sed -i \"s/element vertex .*/element vertex $VERTNUM/\" " << parv[2] << "\n";
return result;
}
|
80836c80b7c6c2905c2eb7537921bbba1577fa4c | f4cf5d8fcc7b59f32e2e92dd445ee0894b19743a | /Code/header/lightsensor.h | 8ac52cfcdd16df07b14bf57b4999e6bef56a1b43 | [] | no_license | laodengtou6/SpaceMaster-FloatSat-2017 | 37f0f0a6241f728a4ff8c09b4066011d351612bf | b4e5ea6d8e0bbf73c4c098a4fce4f96188c66bd3 | refs/heads/master | 2023-04-28T13:52:19.951321 | 2017-12-07T00:46:24 | 2017-12-07T00:46:24 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 430 | h | lightsensor.h | /*
* lightsensor.h
*
* Created on: 13.12.2016
* Author: Oliver Struckmeier
*
* Old lightsensor h-file for the non thread lightsensor class
*/
#ifndef HEADER_LIGHTSENSOR_H_
#define HEADER_LIGHTSENSOR_H_
#include <rodos.h>
#include "stdint.h"
#include <string>
class LIGHT {
public:
LIGHT();
void init();
void readLight(uint32_t* data);
};
#endif /* HEADER_LIGHTSENSOR_H_ */
|
525434fc23fb5e581da7fae303d99ad8361be226 | aaca8264af3d742a2e2a88042c51cb38ccc1db0c | /chrono_example.cpp | 830d13cc2474530c14eb5c701c1e89aa60336670 | [] | no_license | sid1980/otus-cpp-basics-hw05 | c40679b84d209b519e3e8cd067fde3ace31bd6da | 69b3909d632e80c6d3eb20956265e962e25b18fa | refs/heads/main | 2023-07-09T15:58:39.350514 | 2021-08-22T00:10:32 | 2021-08-22T00:10:32 | 398,673,882 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,871 | cpp | chrono_example.cpp | #include <chrono>
#include <iostream>
#include <vector>
#include <algorithm> // std::shuffle
#include <random> // std::default_random_engine
void fill_vector(std::vector<int> &values, size_t count) {
values.resize(count);
for (size_t i = 0; i < count; ++i) {
values[i] = static_cast<int>(i);
}
}
template <typename T>
void make_random_shuffle(std::vector<T> &values) {
// 1. Take current time (count of seconds since `epoch begining`) as a seed
auto seconds_count = std::chrono::system_clock::now().time_since_epoch().count();
unsigned int seed = static_cast<unsigned int>(seconds_count);
// 2. Initialize random engine
std::default_random_engine engine{seed};
// 3. Shuffle values
std::shuffle(values.begin(), values.end(), engine);
}
void run_test_suite(size_t iteration_count) {
const size_t elements_count = 100000;
std::vector<int> values;
// fill values with elements_count elements
fill_vector(values, elements_count);
// random shuffle values
make_random_shuffle(values);
std::cout << "iteration_count = " << iteration_count << std::endl;
// std::sort algorithm measuring
{
// Take a start time
auto start_time = std::chrono::system_clock::now();
// Make a several iterations
for (size_t i = 0; i < iteration_count; ++i) {
std::vector<int> test_data = values;
std::sort(test_data.begin(), test_data.end());
}
// Take an end time
auto end_time = std::chrono::system_clock::now();
// Calculate a duration
auto milliseconds = std::chrono::duration_cast<std::chrono::milliseconds>(
end_time - start_time);
std::cout << "std::sort duration = " << milliseconds.count() << "ms" << std::endl;
std::cout << "std::sort avg = " << milliseconds.count() / iteration_count << "ms" << std::endl;
}
// C-style quick-sort algorithm measuring
{
// Take a start time
auto start_time = std::chrono::system_clock::now();
// Make a several iterations
for (size_t i = 0; i < iteration_count; ++i) {
std::vector<int> test_data = values;
std::qsort(
test_data.data(),
test_data.size(),
sizeof(int),
[](const void *x, const void *y) {
const int arg1 = *static_cast<const int *>(x);
const int arg2 = *static_cast<const int *>(y);
if (arg1 < arg2)
return -1;
if (arg1 > arg2)
return 1;
return 0;
});
}
// Take an end time
auto end_time = std::chrono::system_clock::now();
// Calculate a duration
auto milliseconds = std::chrono::duration_cast<std::chrono::milliseconds>(
end_time - start_time);
std::cout << "qsort duration = " << milliseconds.count() << "ms" << std::endl;
std::cout << "qsort avg = " << milliseconds.count() / iteration_count << "ms" << std::endl;
}
}
int main() {
run_test_suite(1);
std::cout << std::endl;
run_test_suite(10);
std::cout << std::endl;
run_test_suite(100);
std::cout << std::endl;
return 0;
}
|
1b459364d88b5959c63e1de9dab2115fb285dcdf | 11e9fdc832e174c35ee9f678890b319526e506c6 | /PowerPaint/tlswin.cpp | 4d32cda89bbc0ea4b4522451cbed55d98763c052 | [] | no_license | wangdi190/ChengGong | 96a5c9073f8b269cebbdf02e09df2687a40d5cce | ae03dc97c98f5dc7fbdd75a8ba5869f423b83a48 | refs/heads/master | 2020-05-29T09:16:20.922613 | 2016-09-28T08:13:13 | 2016-09-28T08:13:13 | 69,441,767 | 4 | 2 | null | null | null | null | GB18030 | C++ | false | false | 5,597 | cpp | tlswin.cpp | // tlswin.cpp : implementation file
//
#include "stdafx.h"
#include "PowerPaint.h"
#include "tlswin.h"
#include "gdata.h"
#include "comobj.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
extern gdata dbm;
extern comobj cobj;
extern char *tlstr[];
int hg[]={120,120,120,120,120,120};
/////////////////////////////////////////////////////////////////////////////
// tlswin
tlswin::tlswin()
{
int i;
tw[0].wnd=&egpw;
tw[1].wnd=&spiw;
tw[2].wnd=&layw;
tw[3].wnd=&objw;
for(i=0;i<4;i++){
tw[i].active=0;
strcpy(tw[i].str,tlstr[i]);
tw[i].height=hg[i];
tw[i].sel=0;
tw[i].menu=1;
}
tw[0].active=1;
tw[3].menu=0;
tw[0].cmenu.LoadMenu(IDR_ELEMENU);
tw[1].cmenu.LoadMenu(IDR_SPICMG);
tw[2].cmenu.LoadMenu(IDR_LMENU);
mdc.Create(1,1);
img.Create(IDR_TLIMG,16,0,RGB(255,0,255));
oldsel=-1;
olds=-1;
cobj.nwin=&navw;
cobj.egpw=&egpw;
cobj.spiw=&spiw;
cobj.layw=&layw;
cobj.objw=&objw;
}
tlswin::~tlswin()
{
tw[0].cmenu.DestroyMenu();
tw[1].cmenu.DestroyMenu();
tw[2].cmenu.DestroyMenu();
}
BEGIN_MESSAGE_MAP(tlswin, CWnd)
//{{AFX_MSG_MAP(tlswin)
ON_WM_CREATE()
ON_WM_SIZE()
ON_WM_PAINT()
ON_WM_MOUSEMOVE()
ON_WM_LBUTTONUP()
ON_COMMAND(DataChanged, OnEditchange)
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// tlswin message handlers
BOOL tlswin::PreCreateWindow(CREATESTRUCT& cs)
{
if (!CWnd::PreCreateWindow(cs))
return FALSE;
//cs.dwExStyle |= WS_EX_CLIENTEDGE;
cs.style &= ~WS_BORDER;
cs.lpszClass = AfxRegisterWndClass(CS_HREDRAW|CS_VREDRAW|CS_DBLCLKS,
::LoadCursor(NULL, IDC_ARROW), NULL, NULL);
return TRUE;
}
int tlswin::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
if (CWnd::OnCreate(lpCreateStruct) == -1)
return -1;
navw.Create("","",WS_CHILD|WS_VISIBLE,CRect(0,0,1,1),this,100);
egpw.Create("","",WS_CHILD|WS_VISIBLE,CRect(0,0,1,1),this,101);
spiw.Create("","",WS_CHILD|WS_VISIBLE,CRect(0,0,1,1),this,102);
layw.Create("","",WS_CHILD|WS_VISIBLE|WS_VSCROLL,CRect(0,0,1,1),this,103);
objw.Create("","",WS_CHILD|WS_VISIBLE,CRect(0,0,1,1),this,104);
return 0;
}
void tlswin::OnSize(UINT nType, int cx, int cy)
{
CWnd::OnSize(nType, cx, cy);
wx=cx;
wy=cy;
mdc.SizeChange(wx,30);
ComputSelWin();
navw.MoveWindow(CRect(0,0,wx,175));
}
void tlswin::OnPaint()
{
CPaintDC dc(this);
ShowTitle(dc);
dc.FillSolidRect(CRect(0,wy-25,wx,wy),GetSysColor(COLOR_3DFACE));
}
//计算选择窗口
void tlswin::ComputSelWin()
{
int i,h,y;
h=wy-100-175;
if(h<0) return;
y=175;
for(i=0;i<4;i++){
tw[i].sel=0;
if(tw[i].active==1){ //只能保证有一个活动窗口
tw[i].selrt=CRect(0,y,wx,y+25);
y+=25;
tw[i].rtw=CRect(0,y,wx,y+h);
y+=h;
tw[i].wnd->MoveWindow(tw[i].rtw);
}else{
tw[i].selrt=CRect(0,y,wx,y+25);
y+=25;
tw[i].rtw=CRect(0,0,1,1);
tw[i].wnd->MoveWindow(tw[i].rtw);
};
}
}
void tlswin::ShowTitle(CDC&dc)
{
int i;
for(i=0;i<5;i++){
DrawATitle(dc, i);
}
}
void tlswin::OnMouseMove(UINT nFlags, CPoint point)
{
int i,sel;
CClientDC dc(this);
i=GetSel(point,sel);
if(i!=oldsel){
DrawATitle(dc,oldsel);
if(i>=0) DrawATitle(dc,i);
}
if(i==oldsel&&sel!=olds) DrawATitle(dc,i);
oldsel=i;
olds=sel;
CWnd::OnMouseMove(nFlags, point);
}
void tlswin::OnLButtonUp(UINT nFlags, CPoint point)
{
CMenu *mm;
int i,j,sel;
CPoint pt;
j=GetSel(point,sel);
if(j>=0){
switch(sel){
case 1: //切换显示
for(i=0;i<4;i++) tw[i].active=0;
tw[j].active=1;
ComputSelWin();
DrawShow();
break;
case 2: //打开菜单
pt=point;
ClientToScreen(&pt);
mm=tw[j].cmenu.GetSubMenu(0);
mm->TrackPopupMenu(TPM_LEFTALIGN,pt.x,pt.y,tw[j].wnd);
break;
}
}
CWnd::OnLButtonUp(nFlags, point);
}
void tlswin::DrawATitle(CDC &dc, int index)
{
LOGFONT lf;
CRect rt,rt1;
CDC dc1;
DWORD c1,c2;
if(index>3||index<0) return;
c1=0x7f7f7f;
c2=0xffffff;
rt=CRect(0,0,wx,25);
rt1=CRect(40,5,wx-25,wy);
dc1.Attach(mdc.m_hDC);
lf=cobj.sysfont;
lf.lfHeight=14;
lf.lfWidth=7;
mdc.CRectc(rt,c1,c2,1);
mdc.CDraw3DRect(CRect(-1,0,wx+1,2),0x7f7f7f,0xffffff);
if(tw[index].active==1) img.Draw(&dc1,1,CPoint(20,5),ILD_NORMAL);
else img.Draw(&dc1,0,CPoint(20,5),ILD_NORMAL);
if(tw[index].menu==1) img.Draw(&dc1,2,CPoint(wx-20,5),ILD_NORMAL);
mdc.CTextOut(tw[index].str,rt1,&lf,0,0,0);
mdc.CDraw3DRect(CRect(2,4,4,18),0xffffff,0);
mdc.CDraw3DRect(CRect(5,4,7,18),0xffffff,0);
if(tw[index].sel==1) mdc.CDraw3DRect(CRect(20,5,wx-25,22),0xffffff,0);
if(tw[index].sel==2) mdc.CDraw3DRect(CRect(wx-20,5,wx-2,22),0xffffff,0);
mdc.BitBltRect(dc.m_hDC,rt,tw[index].selrt);
dc1.Detach();
}
int tlswin::GetSel(CPoint point,int &sel)
{
int i,rtn;
CRect rt,rt1,rt2;
rtn=-1;
sel=0;
for(i=0;i<4;i++){
tw[i].sel=0;
rt=tw[i].selrt;
rt1=CRect(rt.left+20,rt.top+5,rt.right-25,rt.top+22);
rt2=CRect(rt.right-20,rt.top+5,rt.right-2,rt.top+22);
if(rt1.PtInRect(point)&&tw[i].active==0){
tw[i].sel=1;
sel=1;
rtn=i;
}else if(rt2.PtInRect(point)&&tw[i].menu==1&&tw[i].active==1)
{
tw[i].sel=2;
sel=2;
rtn=i;
};
}
return rtn;
}
void tlswin::DrawShow()
{
CClientDC dc(this);
ShowTitle(dc);
}
void tlswin::ReFreshWin()
{
layw.AddLayer();
cobj.pgcw->AddPage();
layw.DrawCurLayerPic();
layw.Invalidate();
}
//让编辑框有效
void tlswin::EnableEditTool()
{
int i;
for(i=0;i<4;i++) tw[i].active=0;
tw[3].active=1;
ComputSelWin();
DrawShow();
}
bool tlswin::IsEditActive()
{
return tw[3].active==0 ? false:true;
}
//编辑发生变化
void tlswin::OnEditchange()
{
cobj.cvs->DrawShow();
} |
48cd966e140e9ed8a754591a3f17bc5d9b791376 | 0eff74b05b60098333ad66cf801bdd93becc9ea4 | /second/download/rsync/gumtree/rsync_old_log_499.cpp | 0ed3793a9f3918f6c5ce5fa25f5fa73d04f42c47 | [] | no_license | niuxu18/logTracker-old | 97543445ea7e414ed40bdc681239365d33418975 | f2b060f13a0295387fe02187543db124916eb446 | refs/heads/master | 2021-09-13T21:39:37.686481 | 2017-12-11T03:36:34 | 2017-12-11T03:36:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 80 | cpp | rsync_old_log_499.cpp | fprintf(f,"-T --temp-dir DIR create temporary files in directory DIR\n"); |
306a0172a71da0967a1976db4e1dbee9c86d1cd0 | a4b9122cc3151a73a46d243a3e69af7834309ad9 | /src/Cpp/RessourceManager.cpp | 17214d6cdb43d67403a75d164853916327b8705a | [] | no_license | OdenOfTheNorth/AsteroidsGameFiles | 6e3b1dee32387cfe247914c7ef8ff64dc394d078 | 8399bbb8cc66f9f5a0e34d5a9fd91dbf3c9f1711 | refs/heads/main | 2023-03-18T06:12:48.621632 | 2021-03-14T12:43:25 | 2021-03-14T12:43:25 | 347,617,082 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 848 | cpp | RessourceManager.cpp | #include "RessourceManager.h"
void RessourceManager::RessourceInit(SDL_Renderer* renderer)
{
PlayerTexture = RenderingUtilities::LoadTexture(playerTexturePath, renderer);
AsteroidTexture = RenderingUtilities::LoadTexture(asteroidTexturePath, renderer);
RocketTexture = RenderingUtilities::LoadTexture(rocketTexturePath, renderer);
RollingStoneTexture = RenderingUtilities::LoadTexture(rollingStoneTexturePath, renderer);
SkyStoneTexture = RenderingUtilities::LoadTexture(skyTexturePath, renderer);
}
SDL_Texture * RessourceManager::GetText(std::string text, int fontSize, SDL_Color color, SDL_Renderer* renderer)
{
font = TTF_OpenFont(fontAPath.c_str(), fontSize);
SDL_Surface* surface = TTF_RenderText_Solid(font, text.c_str(), color);
SDL_Texture* fontTexture = SDL_CreateTextureFromSurface(renderer, surface);
return fontTexture;
}
|
0face75a519b2dbe6bcbac65468a3eebd114ade8 | f87d9f0d61a21e5207a2b842f01b0e26098b4bda | /Gadgets/Socket_Replay/Socket_Replay/SocketParser.h | 2999a49784a5823890b98ffbcb7014433e81cc35 | [] | no_license | githu86/MTConnectToolbox | 8c982dc477feeb1847531ef59a9638d1d7b6fa7e | 2b5b55d1776dc84f2f4bb103a1875da0ca6bbcec | refs/heads/master | 2023-04-01T18:49:08.072328 | 2020-04-03T16:16:16 | 2020-04-03T16:16:16 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,596 | h | SocketParser.h | //
// SocketParser.h
//
/*
* DISCLAIMER:
* This software was produced by the National Institute of Standards
* and Technology (NIST), an agency of the U.S. government, and by statute is
* not subject to copyright in the United States. Recipients of this software
* assume all responsibility associated with its operation, modification,
* maintenance, and subsequent redistribution.
*
* See NIST Administration Manual 4.09.07 b and Appendix I.
*/
#pragma once
#include <vector>
#include <map>
#include <string>
#include <iostream>
#include <fstream>
#include "SocketBackEnd.h"
#include "StdStringFcn.h"
#include "Timing.h"
using namespace Timing;
typedef std::vector<uint8_t> raw_message_t;
/**
* \brief Class provides a simple file shdr parser.
*/
class SocketParser
{
public:
/**
* \brief Constructor that turn repeat of file off, set first time and captures current time.
* Todo: the clock resolution is only second level, and MTConnect easily has millisecond Socket updates.
*/
SocketParser(SocketBackEnd & backEnd) : _backEnd(backEnd)
{
_bRepeat=false;
_bFirstTime=true;
_realtimetime = Timing::Now(); // COleDateTime::GetCurrentTime();
_linenum=0;
}
/**
* \brief Reset is done before the beginning of a file. Either first or each repeated time.
*/
void Reset(void)
{
_bFirstTime=true;
_realtimetime = Timing::Now(); // COleDateTime::GetCurrentTime();
_linenum=0;
_backEnd.Reset();
}
void split(std::string str, raw_message_t& msg)
{
const std::string::size_type size(str.size());
size_t start=0;
size_t range=0;
msg.clear();
/* Explanation:
* Range - Length of the word to be extracted without spaces.
* start - Start of next word. During initialization, starts at space 0.
*
* Runs until it encounters a ' ', then splits the string with a substr() function,
* as well as making sure that all characters are lower-case (without wasting time
* to check if they already are, as I feel a char-by-char check for upper-case takes
* just as much time as lowering them all anyway.
*/
size_t i;
for(i=0; i < str.size(); i++ )
{
if(i==443)
i=i;
if( str[i] == ',' )
{
std::string buf = str.substr(start, range);
int uc;
OutputDebugString(StrFormat("Start=%d Range=%d i=%d Size=%d\n", start,range,i, size).c_str());
sscanf(buf.c_str(), "%2X", &uc);
msg.push_back((uint8_t) uc );
start = i + 1;
range = 0;
} else
++range;
}
//msg.push_back( toLower(str.substr(start, range)) );
// skip trailing \n
}
/**
* \brief Processes a line from the given Socket file.
* Extracts timestamp (first field until | delimiter) and computes how long from last timestamp.
* If the repeat flag is set, will repeat Socket file from start, resetting all timestamp value to new current time.
* \return amount of time to delay in seconds given shdr.
*/
double ProcessStream()
{
//Get line from "in" stream into string _buffer until line feed found.
// If the line feed delimiter is found, it is extracted and discarded
getline(in,_buffer);
//_buffer.clear();
//char ch;
//do{
// ch = in.get();
// _buffer+=ch;
//}
//while(ch!='\n');
//
//_buffer=Trim(_buffer); // this will remove trailing \n
if(in.eof( ))
{
if(!Repeat())
return -1;
Reset();
in.clear(); // forget we hit the end of file
in.seekg(0, std::ios::beg); // move to the start of the file
getline(in, _buffer);
}
_linenum++;
// Check for empty buffer - return 0 wait
if(_buffer.empty())
return 0;
// Now get timestamp - in field 1
size_t delim = _buffer.find( "|");
if( delim == std::string::npos)
return 0;
std::string timestamp = _buffer.substr(0,delim);
if(!timestamp.empty())
{
_lasttime=_currenttime;
_currenttime=Timing::GetDateTime(timestamp);
if(_bFirstTime)
{
_duration = boost::posix_time::seconds(0) ;
_bFirstTime=false;
}
else
{
_duration = _currenttime-_lasttime;
_realtimetime+=_duration;
}
// in shdr this returns a shdr string with new timestamp.
_timestamp=Timing::GetDateTimeString(_realtimetime);
_buffer=_buffer.substr(delim+1); // after the |
split(_buffer, _msg);
// For binary hex dump need to translate ascii hex into raw binary.
// also need to add timestamp for timing and remove trailing \n
}
else
{
_duration = boost::posix_time::seconds(0);
}
//http://www.boost.org/doc/libs/1_31_0/libs/date_time/doc/class_time_duration.html
return _duration.total_milliseconds();
}
/**
* \brief Attempts to open Socket file for echoing, throw execption if unable to open file.
* \param filename is the Socket filename including path
*/
void Init(std::string filename)
{
// FIXME: blank lines and other stuff not handled well.
_binaryfilename=filename;
#ifdef WIN32
if(GetFileAttributesA(_binaryfilename.c_str())== INVALID_FILE_ATTRIBUTES)
{
throw std::runtime_error(StrFormat("Bad Socket file",_binaryfilename.c_str()));
}
#endif
in.open(_binaryfilename.c_str());
}
/**
* \brief Flag to determine replaying of file. True replay. False one-time play.
* \return reference to replay flag.
*/
bool & Repeat() { return _bRepeat; }
/**
* \brief Get latest buffer from shdr file, with updated timestamp.
*/
std::string & GetLatestBuffer() { return _buffer; }
raw_message_t & GetLatestMsg() { return _msg; }
std::string & GetLatestTimestamp() { return _timestamp; }
/**
* \brief Get latest buffer from shdr file, with updated timestamp.
*/
size_t & LineNumber() { return _linenum; }
//////////////////////////////////////////////////////////////////////
protected:
boost::posix_time::ptime _realtimetime; /**< now + elapsed Socket time */
boost::posix_time::ptime _currenttime; /**< shdr current timestamps */
boost::posix_time::ptime _lasttime; /**< last shdr current timestamps */
boost::posix_time::time_duration _duration; /**< duration between last and current shdr timestamps */
std::string _timestamp; /**< string with updated timestamp Socket */
std::string _buffer; /**< string with raw data as hex ascii */
raw_message_t _msg; /**< buffer with raw binary data */
std::string _binaryfilename; /**< string with Socket filename incl path*/
bool _bRepeat; /**< repeat Socket flag*/
bool _bFirstTime; /**< first time flag for deciphering timestamps*/
std::ifstream in; /**< input filestream*/
size_t _linenum; /**< current line number in file useful for exceptions*/
SocketBackEnd & _backEnd;
};
inline void test_socket_parser()
{
SocketBackEnd be;
SocketParser test(be);
raw_message_t msg;
std::string str = "2017-11-03 09:00:09.0471 |00,00,00,90,00,00,00,0F,00,00,00,01,00,00,00,00,00,00,00,00,00,00,00,02,00,00,00,00,3F,4B,11,AF,3E,C1,FE,4D,00,00,00,00,BF,F7,DA,1F,BA,56,FF,35,BF,52,0B,20,BF,65,F7,BA,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,\n";
size_t delim = str.find( "|");
str=str.substr(delim+1);
str=Trim(str);
test.split(str, msg);
} |
ac71f8915b414a55fd760b789b27fbbd90d71b8e | 9540d166e89b3b8319e913d362de261079f420f5 | /EXERCICIO 1/exercicio 10.cpp | 859f659385db5413549cab1de0e6af94cb3f8d12 | [] | no_license | patrickallan5/Estrutura_De_Dados | 4ffb907372e9cb53e3a2ddb2faf44803ba8660c3 | 8cc5176a2bb6ba1b26ef71d43d7f539c755d41ae | refs/heads/master | 2022-12-31T11:05:53.290584 | 2020-10-21T23:17:09 | 2020-10-21T23:17:09 | 288,864,249 | 0 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 2,235 | cpp | exercicio 10.cpp | /*Em um cinema, certo dia, cada espectador respondeu a um questionário,
que perguntava a sua idade (ID) e a opinião em relação ao filme (OP),
seguindo os seguintes critérios:
OP : 1 otimo, 2 bom, 3 regular, 4ruim
Ao final da pesquisa será indicado quando a idade do usuário for informada
como negativa (idade inexistente). Construa um programa em C++ que, lendo
esses dados, calcule e apresente:
A. Quantidade de pessoas que respondeu a pesquisa
B. Média de idade das pessoas que responderam a pesquisa
C. Porcentagem de cada uma das respostas*/
#include <iostream>
using namespace std;
int cont1 , cont2, cont3, cont4;
float p1, p2, p3, p4;
int OP;
int ID;
int fim;
int contador = 0;
float mediaID;
int somador =0;
int main(int argc, char** argv)
{
fim = 1;
while(fim != 0)
{
int a = 1;
while( a != 0 )
{
cout << " QUAL SUA IDADE " << endl;
cin >> ID;
if (ID < 0 ){
cout << "idade inexistente" << endl;
}else
break;
}
cout << "" << endl;
cout << "QUAL SUA OPINIAL SOBRE O FILME " << endl;
cout << "" << endl;
cout << " OPCOES " <<endl;
cout << " _______________" << endl;
cout << " 1 OTIMO" <<endl;
cout << " 2 BOM" <<endl;
cout << " 3 REGULAR" <<endl;
cout << " 4 RUIM " <<endl;
cout << "" << endl;
cin >> OP;
switch(OP)
{
case 1 :
contador++;
cont1++;
break;
case 2 :
contador++;
cont2++;
break;
case 3 :
contador++;
cont3++;
break;
case 4 :
contador++;
cont4++;
break;
default:
cout << "opcao invalida" << endl;
cout << "reiniciando questionario" << endl;
cout << " " << endl;
continue;
}
somador = somador +ID ;
cout << "finalizar pesquisa, digite 0 ?" << endl;
cin >> fim ;
cout << " " << endl;
}
mediaID = somador/contador;
p1 = (cont1 * 100/contador);
p2 = (cont2 * 100/contador);
p3 = (cont3 * 100/contador);
p4 = (cont4 * 100/contador);
cout << contador << " PESSOAS RESPONDERA A PESQUISA" << endl;
cout << mediaID << " FOI A MEDIA DE IDADES DOS PARTICIPANTES" << endl;
cout << p1 << "% responderam otimo" << endl;
cout << p2 << "% responderam bom" << endl;
cout << p3 << "% responderam regular" << endl;
cout << p4 << "% responderam ruim" << endl;
return 0;
} |
e93aa8b3443e78bf13b81ca18e5a049eefc41aa4 | 8b4532590d2b643296f0b05c81fcbb3bf8271117 | /1-Coding_Interviews/07-QueueWithTwoStacks/cpp/cqueue.h | a371a8f83f68492fbd97a63f06b0b5902953dcc8 | [] | no_license | Alexkun/to-programming | e0617776e52cff1a004303dae45fb247469800b4 | b4ab572940d6544740cfe7ba26dcd66044d8686e | refs/heads/master | 2020-06-20T00:22:41.893371 | 2017-09-27T03:03:43 | 2017-09-27T03:03:43 | 94,189,152 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 849 | h | cqueue.h | #include <iostream>
#include <stack>
#include <exception>
using namespace std;
template <typename T>
class CQueue
{
public:
void appendTail(const T & element)
{
while(!stack2.empty())
{
T& data = stack2.top();
stack2.pop();
stack1.push(data);
}
stack1.push(element);
}
T deleteHead() throw(std::logic_error)
{
int num = stack1.size() - 1;
for(int i = 0; i < num; i++)
{
T & data = stack1.top();
stack1.pop();
stack2.push(data);
}
if(stack1.size() == 1)
{
T & data = stack1.top();
stack1.pop();
return data;
}
else if(stack2.size() > 0)
{
T & data = stack2.top();
stack2.pop();
return data;
}
else
{
throw new logic_error("Queue is empty.");
}
}
bool empty()
{
return stack1.empty() && stack2.empty();
}
private:
stack<T> stack1;
stack<T> stack2;
};
|
087269598f959276171df387b331ba43cc4e48d1 | 2b7c153b602325204c4906ad1b974091522760a3 | /BankingSystem/SavingsAccount.cpp | a1142c70cc4107ae204a5f5922a5186d89f1378f | [] | no_license | bradbow/inb305 | 947482e7170a6a34023f9c7372de1b1d7344e835 | 242ff38973df11128fe403a6b9bb46430ee85186 | refs/heads/master | 2021-01-20T12:04:58.218179 | 2011-10-15T23:46:22 | 2011-10-15T23:46:22 | 2,553,600 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,457 | cpp | SavingsAccount.cpp | // SavingsAccount.cpp
// Models a customer credit account and contains
// accessors and mutators for credit account
// information. These include the ability to increment
// and decrement the account balance which may never fall
// below zero
#include "SavingsAccount.h"
#include <boost/lexical_cast.hpp>
// constructor
// precondition: valid account details passed in
// postcondition: savings account created
SavingsAccount::SavingsAccount( int accountID,
string accountName,
double interestRate,
double balance) :
Account(accountID,
accountName,
interestRate,
balance)
{
}
// destructor
// precondition: none
// postcondition: memory deallocted
SavingsAccount::~SavingsAccount(void)
{
}
// precondition: valid amount passed in
// postcondition: balance incremented by amount
void SavingsAccount::incrementBalance(double amount){
_balance += amount;
}
// precondition: valid amount passed in; amount
// is less than balance
// postcondition: balance decremented by amount
void SavingsAccount::decrementBalance(double amount){
_balance -=amount;
}
string SavingsAccount::operator<< (const SavingsAccount &rhs){
SavingsAccount temp = rhs;
string delimited =
temp.getAccountId() + "," +
temp._accountName + "," +
boost::lexical_cast<std::string>(temp._interestRate)
+ "," +
boost::lexical_cast<std::string>(temp._balance);
return delimited += "," + NUM_FIELDS;
}
|
285fbdc156685981492be98b44f2f250e2db75e3 | 9594f8af13c7fcacfb2dad07ead7add41a0ba59d | /binary-tree/Leetcode_109.cpp | 89ddd798b54fdb417d6c5a9a4622d7acb91a2382 | [] | no_license | BossChengZhe/Practice-Leetcode | 7a4f11ce78081a088748144145bfdf3636f7cd28 | 22c1cec34d4b706222a2bf0446fba57bedc1f698 | refs/heads/master | 2023-07-25T11:15:13.232001 | 2021-09-05T10:17:41 | 2021-09-05T10:17:41 | 267,491,589 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,799 | cpp | Leetcode_109.cpp | #include "iostream"
#include "vector"
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode() : val(0), next(nullptr) {}
ListNode(int x) : val(x), next(nullptr) {}
ListNode(int x, ListNode *next) : val(x), next(next) {}
};
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode() : val(0), left(nullptr), right(nullptr) {}
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};
void curr(TreeNode* &root, vector<int> &temp, int start, int end)
{
if (start>end)
return;
else if (start==end)
{
root = new TreeNode(temp[start]);
return;
}
int mid = start + (end-start)/2;
root = new TreeNode(temp[mid]);
curr(root->left, temp, start, mid - 1);
curr(root->right, temp, mid + 1, end);
}
TreeNode* sortedListToBST1(ListNode* head) {
vector<int> temp;
while(head)
{
temp.push_back(head->val);
head = head->next;
}
TreeNode * root = nullptr;
curr(root, temp, 0, temp.size()-1);
return root;
}
// 方法二
int get_length(ListNode *head)
{
int res=0;
while(head)
{
res ++;
head = head->next;
}
return res;
}
TreeNode* build(ListNode* &head, int left, int right)
{
if(left > right)
return nullptr;
int mid = left + (right-left) / 2;
TreeNode* root = new TreeNode(head->val);
root->left = build(head, left, mid-1);
head = head->next;
root->right = build(head, mid + 1, right);
return root;
}
TreeNode* sortedListToBST(ListNode* head) {
return build(head, 0, get_length(head)-1);
} |
f88f913e15375868e150595acb4f67a69bb97af6 | 61834cd79b8b314a9d6de3a0425f8dea7ee021b7 | /TestCodes/AtomicSpeedMeasurement.cpp | 5edc300876f1e791c984b72c3731f1b8c76de584 | [] | no_license | brandnewdata/PerformanceNCodeTest | 10be8c4c56ac414b565db82af5cec40d4901c12d | b3773b5a4a8a7dd66982db1945ca989a22b682ec | refs/heads/main | 2023-08-31T12:15:22.119820 | 2021-10-08T09:38:43 | 2021-10-08T09:38:43 | 414,719,845 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 837 | cpp | AtomicSpeedMeasurement.cpp | #include <atomic>
#include <Windows.h>
#include <iostream>
// 테스트 내용 : atomic과 non atomic의 성능차이 측정
// 테스트 결과 : atomic이 약 50배정도 느리다.
using namespace std;
#define BENCHMARK( name, func, its ) {\
int st = GetTickCount(); \
func( its ); \
printf(" [%s] - %dms\n", name, GetTickCount() - st ); \
}
void testbed_non_atomic(int n) {
int value = 1234;
int* ptr = &value;
for (int i = 0; i < n; i++) {
if (ptr != nullptr)
{
}
}
}
void testbed_atomic(int n) {
int value = 1234;
atomic<int*> atomic_ptr(&value);
for (int i = 0; i < n; i++) {
int* ptr = atomic_ptr.load();
if (ptr != nullptr)
{
}
}
}
int main()
{
const int its = 100000000;
BENCHMARK("non-atomic", testbed_non_atomic, its);
BENCHMARK("atomic", testbed_atomic, its);
return 0;
}
|
a1c3fd11ec84253ac050593414fbd1bdb5b450f1 | f1bd4d38d8a279163f472784c1ead12920b70be2 | /xr_3da/xrGame/ActorInput.cpp | 71f38cce4e250cb542fd3030cc1ec3055e0ca4f7 | [] | no_license | YURSHAT/stk_2005 | 49613f4e4a9488ae5e3fd99d2b60fd9c6aca2c83 | b68bbf136688d57740fd9779423459ef5cbfbdbb | refs/heads/master | 2023-04-05T16:08:44.658227 | 2021-04-18T09:08:18 | 2021-04-18T18:35:59 | 361,129,668 | 1 | 0 | null | null | null | null | WINDOWS-1251 | C++ | false | false | 12,645 | cpp | ActorInput.cpp | #include "stdafx.h"
#include <dinput.h>
#include "Actor.h"
#include "Torch.h"
#include "trade.h"
#include "../CameraBase.h"
#ifdef DEBUG
#include "PHDebug.h"
#endif
#include "hit.h"
#include "PHDestroyable.h"
#include "Car.h"
#include "HudManager.h"
#include "UIGameSP.h"
#include "inventory.h"
#include "level.h"
#include "game_cl_base.h"
#include "xr_level_controller.h"
#include "UsableScriptObject.h"
#include "clsid_game.h"
#include "actorcondition.h"
#include "actor_input_handler.h"
float gCheckHitK = 1.0f;
void CActor::IR_OnKeyboardPress(int cmd)
{
if (Remote()) return;
if(GameID()!=GAME_DEATHMATCH){
if(cmd == kEXT_14)
gCheckHitK = 2.0f;
if(cmd == kEXT_13)
gCheckHitK = 4.0f;
}
if (conditions().IsSleeping()) return;
if (IsTalking()) return;
if (m_input_external_handler && !m_input_external_handler->authorized(cmd)) return;
switch (cmd)
{
case kWPN_FIRE:
{
mstate_wishful &=~mcSprint;
//-----------------------------
if (OnServer())
{
NET_Packet P;
P.w_begin(M_PLAYER_FIRE);
P.w_u16(ID());
u_EventSend(P);
}
}break;
default:
{
}break;
}
if (!g_Alive()) return;
/*
switch(cmd){
case kFOLLOWER1:
case kFOLLOWER2:
case kFOLLOWER3:
case kFOLLOWER4:
case kFOLLOWER5:
SendCmdToFollowers(cmd); break;
};
*/
if(m_holder && kUSE != cmd)
{
m_holder->OnKeyboardPress (cmd);
if(m_holder->allowWeapon() && inventory().Action(cmd, CMD_START)) return;
return;
}else
if(inventory().Action(cmd, CMD_START)) return;
switch(cmd){
case kACCEL: mstate_wishful |= mcAccel; break;
case kL_STRAFE: mstate_wishful |= mcLStrafe; break;
case kR_STRAFE: mstate_wishful |= mcRStrafe; break;
case kL_LOOKOUT:
mstate_wishful |= mcLLookout;
// mstate_wishful &= ~mcAnyMove;
break;
case kR_LOOKOUT:
mstate_wishful |= mcRLookout;
// mstate_wishful &= ~mcAnyMove;
break;
case kFWD: mstate_wishful |= mcFwd; break;
case kBACK: mstate_wishful |= mcBack; break;
case kJUMP: mstate_wishful |= mcJump; break;
case kCROUCH: mstate_wishful |= mcCrouch; break;
case kCROUCH_TOGGLE:
{
if (mstate_wishful & mcCrouch)
mstate_wishful &=~mcCrouch;
else
mstate_wishful |= mcCrouch;
}break;
case kSPRINT_TOGGLE:
{
if (mstate_wishful & mcSprint)
mstate_wishful &=~mcSprint;
else
mstate_wishful |= mcSprint;
}break;
case kCAM_1: cam_Set (eacFirstEye); break;
case kCAM_2: cam_Set (eacLookAt); break;
case kCAM_3: cam_Set (eacFreeLook); break;
case kNIGHT_VISION: {
PIItem I = CAttachmentOwner::attachedItem(CLSID_DEVICE_TORCH);
if (I){
CTorch* torch = smart_cast<CTorch*>(I);
if (torch) torch->SwitchNightVision();
}
}break;
case kTORCH:{
PIItem I = CAttachmentOwner::attachedItem(CLSID_DEVICE_TORCH);
if (I){
CTorch* torch = smart_cast<CTorch*>(I);
if (torch) torch->Switch();
}
}break;
case kWPN_1:
case kWPN_2:
case kWPN_3:
case kWPN_4:
case kWPN_5:
case kWPN_6:
case kWPN_7:
case kWPN_8:
case kWPN_9:
//Weapons->ActivateWeaponID (cmd-kWPN_1);
break;
case kBINOCULARS:
//Weapons->ActivateWeaponID (Weapons->WeaponCount()-1);
break;
case kWPN_RELOAD:
//Weapons->Reload ();
break;
case kUSE:
ActorUse();
break;
case kDROP:
b_DropActivated = TRUE;
f_DropPower = 0;
break;
//-----------------------------------------------------
/*
case kHyperJump:
{
Fvector pos = Device.vCameraPosition;
Fvector dir = Device.vCameraDirection;
collide::rq_result result;
BOOL reach_wall = Level().ObjectSpace.RayPick(pos, dir, 100.0f,
collide::rqtBoth, result,Level().CurrentControlEntity()) && !result.O;
////////////////////////////////////
if (!reach_wall || result.range < 1) break;
dir.mul(result.range-0.5f);
Fmatrix M = Level().CurrentControlEntity()->XFORM();
M.translate_add(dir);
Level().CurrentControlEntity()->ForceTransform(M);
}break;
*/
case kHyperKick:
{
m_dwStartKickTime = Level().timeServer();
}break;
//-----------------------------------------------------
case kNEXT_SLOT:
{
OnNextWeaponSlot();
}break;
case kPREV_SLOT:
{
OnPrevWeaponSlot();
}break;
}
}
void CActor::IR_OnMouseWheel(int direction)
{
if(inventory().Action( (direction>0)? kWPN_ZOOM_DEC:kWPN_ZOOM_INC , CMD_START)) return;
if (direction>0)
OnNextWeaponSlot ();
else
OnPrevWeaponSlot ();
}
void CActor::IR_OnKeyboardRelease(int cmd)
{
if (Remote()) return;
if(GameID()!=GAME_DEATHMATCH){
if(cmd == kEXT_14)
gCheckHitK = 1.0f;
if(cmd == kEXT_13)
gCheckHitK = 1.0f;
}
if (conditions().IsSleeping()) return;
if (m_input_external_handler && !m_input_external_handler->authorized(cmd)) return;
if (g_Alive())
{
if (cmd == kUSE)
PickupModeOff();
if(m_holder)
{
m_holder->OnKeyboardRelease(cmd);
if(m_holder->allowWeapon() && inventory().Action(cmd, CMD_STOP)) return;
return;
}else
if(inventory().Action(cmd, CMD_STOP)) return;
switch(cmd)
{
case kACCEL: mstate_wishful &=~mcAccel; break;
case kL_STRAFE: mstate_wishful &=~mcLStrafe; break;
case kR_STRAFE: mstate_wishful &=~mcRStrafe; break;
case kL_LOOKOUT:mstate_wishful &=~mcLLookout; break;
case kR_LOOKOUT:mstate_wishful &=~mcRLookout; break;
case kFWD: mstate_wishful &=~mcFwd; break;
case kBACK: mstate_wishful &=~mcBack; break;
case kJUMP: mstate_wishful &=~mcJump; break;
case kCROUCH: mstate_wishful &=~mcCrouch; break;
case kHyperKick:
{
u32 FullKickTime = Level().timeServer() - m_dwStartKickTime;
collide::rq_result& RQ = HUD().GetCurrentRayQuery();
CActor* pActor = smart_cast<CActor*>(RQ.O);
if (!pActor || pActor->g_Alive()) break;
Fvector original_dir, position_in_bone_space;
original_dir.set(0, 1, 0);
position_in_bone_space.set(0, 1, 0);
NET_Packet P;
CGameObject::u_EventGen (P,GE_HIT,RQ.O->ID());
P.w_u16 (ID());
P.w_u16 (ID());
P.w_dir (original_dir);
P.w_float (0);
P.w_s16 ((s16)RQ.element);
P.w_vec3 (position_in_bone_space);
P.w_float (float(FullKickTime)*10);
P.w_u16 (2);
Level().Send(P);
}break;
case kDROP: if(GAME_PHASE_INPROGRESS == Game().Phase()) g_PerformDrop(); break;
}
}
}
void CActor::IR_OnKeyboardHold(int cmd)
{
if (Remote() || !g_Alive()) return;
if (conditions().IsSleeping()) return;
if (m_input_external_handler && !m_input_external_handler->authorized(cmd)) return;
if (IsTalking()) return;
if(m_holder)
{
m_holder->OnKeyboardHold(cmd);
return;
}
float LookFactor = GetLookFactor();
switch(cmd)
{
case kUP:
case kDOWN:
cam_Active()->Move(cmd, 0, LookFactor); break;
case kCAM_ZOOM_IN:
case kCAM_ZOOM_OUT:
cam_Active()->Move(cmd); break;
case kLEFT:
case kRIGHT:
if (eacFreeLook!=cam_active) cam_Active()->Move(cmd, 0, LookFactor); break;
}
}
void CActor::IR_OnMouseMove(int dx, int dy)
{
if (Remote()) return;
if (conditions().IsSleeping()) return;
if(m_holder)
{
m_holder->OnMouseMove(dx,dy);
return;
}
float LookFactor = GetLookFactor();
CCameraBase* C = cameras [cam_active];
float scale = (C->f_fov/DEFAULT_FOV)*psMouseSens * psMouseSensScale/50.f / LookFactor;
if (dx){
float d = float(dx)*scale;
cam_Active()->Move((d<0)?kLEFT:kRIGHT, _abs(d));
}
if (dy){
float d = ((psMouseInvert.test(1))?-1:1)*float(dy)*scale*3.f/4.f;
cam_Active()->Move((d>0)?kUP:kDOWN, _abs(d));
}
}
bool CActor::use_Holder (CHolderCustom* holder)
{
if(m_holder){
CGameObject* holderGO = smart_cast<CGameObject*>(m_holder);
if(smart_cast<CCar*>(holderGO))
return use_Vehicle(0);
if (holderGO->CLS_ID==CLSID_OBJECT_W_MOUNTED ||
holderGO->CLS_ID==CLSID_OBJECT_W_STATMGUN)
return use_MountedWeapon(0);
}else{
bool b = false;
CGameObject* holderGO = smart_cast<CGameObject*>(holder);
if(smart_cast<CCar*>(holder))
b = use_Vehicle(holder);
if (holderGO->CLS_ID==CLSID_OBJECT_W_MOUNTED ||
holderGO->CLS_ID==CLSID_OBJECT_W_STATMGUN)
b = use_MountedWeapon(holder);
if(b){//used succesfully
// switch off torch...
PIItem I = CAttachmentOwner::attachedItem(CLSID_DEVICE_TORCH);
if (I){
CTorch* torch = smart_cast<CTorch*>(I);
if (torch) torch->Switch(false);
}
}
return b;
}
return false;
}
void CActor::ActorUse()
{
mstate_real = 0;
PickupModeOn();
if (m_holder)
{
CGameObject* GO = smart_cast<CGameObject*>(m_holder);
NET_Packet P;
CGameObject::u_EventGen (P, GEG_PLAYER_DETACH_HOLDER, ID());
P.w_u32 (GO->ID());
CGameObject::u_EventSend (P);
return;
}
if(m_PhysicMovementControl->PHCapture())
m_PhysicMovementControl->PHReleaseObject();
if(m_pUsableObject)m_pUsableObject->use(this);
if(!m_pUsableObject||m_pUsableObject->nonscript_usable())
{
if(m_pPersonWeLookingAt)
{
CEntityAlive* pEntityAliveWeLookingAt =
smart_cast<CEntityAlive*>(m_pPersonWeLookingAt);
VERIFY(pEntityAliveWeLookingAt);
if(pEntityAliveWeLookingAt->g_Alive())
{
TryToTalk();
}
//обыск трупа
else if(!Level().IR_GetKeyState(DIK_LSHIFT))
{
//только если находимся в режиме single
CUIGameSP* pGameSP = smart_cast<CUIGameSP*>(HUD().GetUI()->UIGame());
if(pGameSP)pGameSP->StartCarBody(&inventory(), this,
&m_pPersonWeLookingAt->inventory(),
smart_cast<CGameObject*>(m_pPersonWeLookingAt));
}
}
else if(m_pVehicleWeLookingAt && smart_cast<CCar*>(m_pVehicleWeLookingAt) && Level().IR_GetKeyState(DIK_LSHIFT))
{
//только если находимся в режиме single
CUIGameSP* pGameSP = smart_cast<CUIGameSP*>(HUD().GetUI()->UIGame());
if(pGameSP)pGameSP->StartCarBody(&inventory(), this,
m_pVehicleWeLookingAt->GetInventory(),
smart_cast<CGameObject*>(m_pVehicleWeLookingAt));
}
collide::rq_result& RQ = HUD().GetCurrentRayQuery();
CPhysicsShellHolder* object = smart_cast<CPhysicsShellHolder*>(RQ.O);
u16 element = BI_NONE;
if(object)
element = (u16)RQ.element;
if(Level().IR_GetKeyState(DIK_LSHIFT))
{
if(!m_PhysicMovementControl->PHCapture())
{
m_PhysicMovementControl->PHCaptureObject(object,element);
}
}
else
{
if (object && smart_cast<CHolderCustom*>(object))
{
NET_Packet P;
CGameObject::u_EventGen (P, GEG_PLAYER_ATTACH_HOLDER, ID());
P.w_u32 (object->ID());
CGameObject::u_EventSend (P);
return;
}
}
}
}
BOOL CActor::HUDview ( )const
{
return IsFocused()&&(cam_active==eacFirstEye)&&
((!m_holder) || (m_holder && m_holder->allowWeapon() && m_holder->HUDView() ) );
}
//void CActor::IR_OnMousePress(int btn)
static u32 SlotsToCheck [] = {
KNIFE_SLOT , // 0
PISTOL_SLOT , // 1
RIFLE_SLOT , // 2
GRENADE_SLOT , // 3
APPARATUS_SLOT , // 4
};
void CActor::OnNextWeaponSlot()
{
u32 ActiveSlot = inventory().GetActiveSlot();
if (ActiveSlot == NO_ACTIVE_SLOT) ActiveSlot = inventory().GetPrevActiveSlot();
if (ActiveSlot == NO_ACTIVE_SLOT) return;
u32 NumSlotsToCheck = sizeof(SlotsToCheck)/sizeof(u32);
for (u32 CurSlot=0; CurSlot<NumSlotsToCheck; CurSlot++)
{
if (SlotsToCheck[CurSlot] == ActiveSlot) break;
};
if (CurSlot >= NumSlotsToCheck) return;
for (u32 i=CurSlot+1; i<NumSlotsToCheck; i++)
{
if (inventory().ItemFromSlot(SlotsToCheck[i]))
{
IR_OnKeyboardPress(kWPN_1+(i-KNIFE_SLOT));
return;
}
}
};
void CActor::OnPrevWeaponSlot()
{
u32 ActiveSlot = inventory().GetActiveSlot();
if (ActiveSlot == NO_ACTIVE_SLOT) ActiveSlot = inventory().GetPrevActiveSlot();
if (ActiveSlot == NO_ACTIVE_SLOT) return;
u32 NumSlotsToCheck = sizeof(SlotsToCheck)/sizeof(u32);
for (u32 CurSlot=0; CurSlot<NumSlotsToCheck; CurSlot++)
{
if (SlotsToCheck[CurSlot] == ActiveSlot) break;
};
if (CurSlot >= NumSlotsToCheck) return;
for (s32 i=s32(CurSlot-1); i>=0; i--)
{
if (inventory().ItemFromSlot(SlotsToCheck[i]))
{
IR_OnKeyboardPress(kWPN_1+(i-KNIFE_SLOT));
return;
}
}
};
float CActor::GetLookFactor()
{
if (m_input_external_handler)
return m_input_external_handler->mouse_scale_factor();
float factor = 1.f;
// [7/19/2005]
PIItem pItem = (inventory().GetActiveSlot() != NO_ACTIVE_SLOT ?
inventory().ItemFromSlot(inventory().GetActiveSlot()) : NULL);
if (pItem)
{
factor *= pItem->GetControlInertionFactor();
}
// [7/19/2005]
VERIFY(!fis_zero(factor));
return factor;
}
void CActor::set_input_external_handler(CActorInputHandler *handler)
{
m_input_external_handler = handler;
if (handler)
mstate_wishful = 0;
}
|
56439ecb56c179e1137d2a72f666da8ffe8f5796 | a5e05718b6f8b402141e6cfd963b340c613200bc | /Submodules/mxml/src/mxml/EventSequence.cpp | 4565737b6dbc5ecda798ec102aaf14fb62a62d5a | [
"MIT"
] | permissive | yk81708090/musitkit | 8617699d49da9ddea0dc28897c0f6a0895fac9de | 7d57e4dd3a21df2dc82f6725accdd89a8560d7d2 | refs/heads/master | 2022-04-07T08:23:46.894850 | 2019-12-20T19:25:29 | 2019-12-20T19:25:29 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,149 | cpp | EventSequence.cpp | // Copyright © 2016 Venture Media Labs.
//
// This file is part of mxml. The full mxml copyright notice, including
// terms governing use, modification, and redistribution, is contained in the
// file LICENSE at the root of the source code distribution tree.
#include "EventSequence.h"
#include <algorithm>
namespace mxml {
EventSequence::EventSequence(const ScoreProperties& scoreProperties) : _scoreProperties(scoreProperties) {
}
Event& EventSequence::addEvent(const Event& event) {
auto it = std::lower_bound(_events.begin(), _events.end(), event);
if (it != _events.end() && it->absoluteTime() == event.absoluteTime()) {
auto& oldEvent = *it;
// Event already exists, merge
oldEvent.setMeasureIndex(event.measureIndex());
oldEvent.setMeasureTime(event.measureTime());
oldEvent.setBeatMark(oldEvent.isBeatMark() || event.isBeatMark());
oldEvent.onNotes().insert(oldEvent.onNotes().end(), event.onNotes().begin(), event.onNotes().end());
oldEvent.offNotes().insert(oldEvent.offNotes().end(), event.offNotes().begin(), event.offNotes().end());
return oldEvent;
} else {
return *_events.insert(it, event);
}
}
void EventSequence::clear() {
_events.clear();
}
dom::time_t EventSequence::startTime() const {
if (_events.empty())
return 0;
auto& firstEvent = _events.front();
return firstEvent.absoluteTime();
}
dom::time_t EventSequence::endTime() const {
if (_events.empty())
return 0;
auto& lastEvent = _events.back();
return lastEvent.absoluteTime() + lastEvent.maxDuration();
}
EventSequence::ConstIterator EventSequence::find(dom::time_t time) const {
auto it = std::lower_bound(_events.begin(), _events.end(), time, [](const Event& event, dom::time_t time) {
return event.absoluteTime() < time;
});
if (it == _events.end() || it->absoluteTime() != time)
return _events.end();
return it;
}
EventSequence::Iterator EventSequence::find(dom::time_t time) {
auto it = std::lower_bound(_events.begin(), _events.end(), time, [](const Event& event, dom::time_t time) {
return event.absoluteTime() < time;
});
if (it == _events.end() || it->absoluteTime() != time)
return _events.end();
return it;
}
EventSequence::ConstIterator EventSequence::findClosest(MeasureLocation measureLocation) const {
auto it2 = std::lower_bound(_events.begin(), _events.end(), measureLocation, [](const Event& event, MeasureLocation measureLocation) {
return event.measureLocation() < measureLocation;
});
if (it2->measureLocation() == measureLocation || it2 == _events.begin())
return it2;
auto it1 = std::prev(it2);
if (it1 == _events.end())
return it2;
return it1;
}
EventSequence::ConstIterator EventSequence::findClosest(dom::time_t time) const {
auto it2 = std::lower_bound(_events.begin(), _events.end(), time, [](const Event& event, dom::time_t time) {
return event.absoluteTime() < time;
});
auto it1 = std::prev(it2);
if (it2 == _events.begin())
return it2;
if (it1 == _events.end())
return it2;
auto d1 = std::abs(time - it1->absoluteTime());
auto d2 = std::abs(time - it2->absoluteTime());
if (d1 < d2)
return it1;
return it2;
}
EventSequence::Iterator EventSequence::findClosest(dom::time_t time) {
auto it2 = std::lower_bound(_events.begin(), _events.end(), time, [](const Event& event, dom::time_t time) {
return event.absoluteTime() < time;
});
auto it1 = std::prev(it2);
if (it2 == _events.begin())
return it2;
if (it1 == _events.end())
return it2;
auto d1 = std::abs(time - it1->absoluteTime());
auto d2 = std::abs(time - it2->absoluteTime());
if (d1 < d2)
return it1;
return it2;
}
EventSequence::ConstIterator EventSequence::firstInMeasure(std::size_t measureIndex) const {
return std::find_if(_events.begin(), _events.end(), [=](const Event& event) {
return event.measureIndex() == measureIndex;
});
}
} // namespace mxml
|
bbf9e44c818a54864c4466fa48ebb472be6d3ebb | f7e6e53476341f82c5c01c71bba0fcd0e5a1decd | /server.cpp | 5a5ff4126e9e107ea8154d0d5c16d6e73a20ca6d | [] | no_license | pegnovi/COMP3203 | d05396a44b3b602cd6f9004e3968cd922d2ace5d | e279140135cf1cf9e85c4b6f9c3706492d18b317 | refs/heads/master | 2021-01-10T19:05:34.145874 | 2015-08-17T04:04:57 | 2015-08-17T04:04:57 | 24,702,624 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,411 | cpp | server.cpp | #include <iostream>
#include <fstream>
#include <vector>
#include <string.h>
#include <cstdlib>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <sys/types.h>
#include <unistd.h>
using namespace std;
#define SERVER_PORT 5432
#define MAX_PENDING 5
#define MAX_LINE 1000
void clearBuffer(char* buf);
//Puts the contents of the ls command into buf and calls fillBuffersWithStream
void lsCommand(vector<char>& buf);
//Opens the file specified in buf
//If the file exists, fillBufferWithStream is called
void getFileCommand(char* command, vector<char>& buf, int commandLength);
//Fills buf with the contents of fp
//appends -1 to the end of the buffer
void fillBufferWithStream(vector<char>& buf, FILE* fp);
//like the above except it takes in a filename and reads from a file in binary
void fillBufferWithStreamBinary(vector<char>& buf, string filename);
//Fills buf with the contents of message
//appends -1 to the end of the buffer
void fillBufferWithMessage(vector<char>& buf, string message);
//Creates a server socket with the specified port number and gives a handle to the socket through socketHandle
void createServerSocket(int& socketHandle, struct sockaddr_in& sin, socklen_t& len, int port);
int main(int argc, char* argv[]) {
cout << "I am Server" << endl;
int socketHandle;
struct sockaddr_in sin;
socklen_t len;
char buf[MAX_LINE]; //only used for recieving requests
vector<char> buffer;
buffer.reserve(MAX_LINE);
int clientSocketHandle;
createServerSocket(socketHandle, sin, len, SERVER_PORT);
cout << "Accepting..." << endl;
if((clientSocketHandle = accept(socketHandle, (struct sockaddr*)&sin, &len)) < 0) {
perror("simplex-talk: accept");
exit(1);
}
cout << "=== Accepted!!! ===" << endl;
//receive and do processes
while(1) {
while(len = recv(clientSocketHandle, buf, sizeof(buf), 0)) {
//If client has sent the quit command or has disconnected
if(strcmp(buf, "q\n") == 0 || len == 0) {
cout << "Server exiting" << endl;
close(clientSocketHandle);
close(socketHandle);
exit(0);
}
//1. ls: print on the client window a listing of the contents of the current directory on the server machine.
if(strcmp(buf, "ls\n") == 0) { //ls command
lsCommand(buffer);
send(clientSocketHandle, buffer.data(), buffer.size(), 0);
buffer.clear();
}
//2. Another file transfer command of your choice.
//cd command
else if(buf[0] == 'c' && buf[1] == 'd' && buf[2] == ' ' && len > 3) {
//trim "cd " from the command to get the path
string command(buf);
command = command.substr(3, len);
//take out any newlines
string path;
for(int i=0; i<command.length(); i++) {
if(command.at(i) != '\n') {
path += command.at(i);
}
}
cout << "path = " << path << endl;
int result = chdir(path.c_str());
if(result == 0) {
fillBufferWithMessage(buffer, "Changed directory");
}
else {
fillBufferWithMessage(buffer, "Unable to change directory");
}
send(clientSocketHandle, buffer.data(), buffer.size(), 0);
buffer.clear();
}
//2. get remote-file: retrieve the remote-‐file on the server and store it on the client machine.
//It is given the same name it has on the server machine.
else if(buf[0] == 'g' && buf[1] == 'e' && buf[2] == 't' && buf[3] == ' ' && len > 4) { //get remote-file
//create new connection with client just for this file transfer
int tempSocketHandle;
int tempClientSocketHandle;
struct sockaddr_in tempSin;
socklen_t tempLen;
createServerSocket(tempSocketHandle, tempSin, tempLen, 5431);
while((tempClientSocketHandle = accept(socketHandle, (struct sockaddr*)&sin, &len)) < 0) {}
getFileCommand(buf, buffer, len);
send(tempClientSocketHandle, buffer.data(), buffer.size(), 0);
buffer.clear();
close(tempClientSocketHandle);
close(tempSocketHandle);
}
else {
fillBufferWithMessage(buffer, "Invalid Command");
send(clientSocketHandle, buffer.data(), buffer.size(), 0);
buffer.clear();
}
clearBuffer(buf);
}
}
return 0;
}
void lsCommand(vector<char>& buf) {
FILE *fp = popen("ls", "r");
fillBufferWithStream(buf, fp);
pclose(fp);
}
void getFileCommand(char* command, vector<char>& buf, int commandLength) {
string theCommand(command);
//take out the "get " from the command char array
theCommand = theCommand.substr(4, commandLength);
string filename;
//take out the newline at the end
for(int i=0; i<theCommand.length(); i++) {
if(theCommand[i] != '\n') {
filename += theCommand[i];
}
}
fillBufferWithStreamBinary(buf, filename);
}
void fillBufferWithStreamBinary(vector<char>& buf, string filename) {
ifstream file(filename.c_str(), ios::in|ios::binary|ios::ate); //ios::ate sets the initial position at the end of the file
streampos size;
char* memblock;
if(file.is_open()) {
size = file.tellg();
memblock = new char[size];
file.seekg(0, ios::beg);
file.read(memblock, size);
file.close();
buf.assign(memblock, memblock+size-1);
delete[] memblock;
}
else {
cout << "Unable to open the file" << endl;
}
}
void fillBufferWithStream(vector<char>& buffer, FILE* fp) {
buffer.clear();
char c;
while((c = fgetc(fp)) != EOF) {
buffer.push_back(c);
}
buffer.push_back(-1);
}
void fillBufferWithMessage(vector<char>& buffer, string message) {
buffer.assign(message.c_str(), message.c_str()+message.length());
buffer.push_back(-1);
}
void clearBuffer(char* buf) {
memset(buf, 0, sizeof(char)*MAX_LINE);
}
void createServerSocket(int& socketHandle, struct sockaddr_in& sin, socklen_t& len, int port) {
//Build address data structure
memset((char*)&sin, 0, sizeof(sin));
sin.sin_family = AF_INET;
//By not specifying an IP address,
// the application program is willing to accept connections on any of the local host’s IP addresses
sin.sin_addr.s_addr = INADDR_ANY;
sin.sin_port = htons(port);
len = sizeof(sin);
//setup passive open
if((socketHandle = socket(PF_INET, SOCK_STREAM, 0)) < 0) {
perror("simplex-talk: socket");
exit(1);
}
if((bind(socketHandle, (struct sockaddr*)&sin, sizeof(sin))) < 0) {
perror("simplex-talk: bind");
exit(1);
}
if(listen(socketHandle, MAX_PENDING) < 0) {
perror("simplex-talk: listen");
exit(1);
}
}
|
a5c3cd90b0deb6900ec340cfc5a22a963400dc50 | 5e19823e200be4e23acca3e4b63c2a9ea52fa4cb | /Firmware/aire_apollo/src/ApolloEncoder.h | 02fd59a2a4807419d12a418480341ff95eb154ba | [] | no_license | balrog-kun/ApolloVentilator | 96e235e044fe9f3414c5b82f3285fbaec74fc97e | 7eecf6ccd98fcf35a0bba1635121ccae2c483a29 | refs/heads/master | 2021-05-19T11:16:33.881912 | 2020-03-31T12:06:31 | 2020-03-31T16:52:08 | 251,669,288 | 0 | 0 | null | 2020-03-31T16:49:04 | 2020-03-31T16:49:04 | null | UTF-8 | C++ | false | false | 635 | h | ApolloEncoder.h | #ifndef ENCODER_H
#define ENCODER_H
#define LATCHSTATE 3
#include "../lib/Encoder-1.4.1/Encoder.h"
class ApolloEncoder : public Encoder
{
public:
ApolloEncoder(uint8_t pinDT, uint8_t pinCLK, uint8_t pinSW) : Encoder(pinDT, pinCLK)
{
_pulsador = pinSW;
};
bool readButton();
bool swapValue(int *valor);
bool swapValue(bool *valor);
bool updateValue(int *valor, int delta = 1);
bool updateValue(float *valor, float delta = 1.0);
protected:
//Encoder encoder;
private:
int _pulsador;
int _oldState;
bool _flag;
unsigned long _tiempo;
int move();
};
#endif // ENCODER_H
|
2a6b38654a07c68b5d2c0c54acd597e7c0b49260 | 38bf4953d979b301efa8dbad62feac9d4768e543 | /primes/sieve.cpp | 19a19a80fd504b284ef9ca140e90c7285a6665f4 | [] | no_license | Jaxan/parallel-algorithms | 69855fb5ac3f0807334718080e417b5beb10076e | 3bda4e13640649c3d3a0ff33f16b94e94dc4456e | refs/heads/master | 2020-12-30T10:12:35.386245 | 2014-01-20T19:36:48 | 2014-01-20T19:36:48 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,263 | cpp | sieve.cpp | #include <cstdlib>
#include <cstdio>
#include <iostream>
#include <vector>
#include <cassert>
#include <cmath>
#include <time.h>
struct options_t {
int n;
bool use_twins;
bool output_list;
bool test_goldbach;
} options;
int main(int argc, char **argv){
options.n = (argc > 1) ? std::atoi(argv[1]) : 1000;
options.use_twins = false;
options.output_list = false;
options.test_goldbach = false;
int n = options.n;
assert(n > 0);
// sets all to false
std::vector<bool> not_prime(n+1);
// sieve
int sn = std::sqrt(n);
double time0 = clock() / (CLOCKS_PER_SEC / 1000);
for(int i = 2; i <= sn; i++){
// goto first prime (i = sn+1 does not matter, as we start at a multiple)
while(i <= sn && not_prime[i]) i++;
// cross out multiples
for(int j = i*i; j <= n; j += i) not_prime[j] = true;
}
double time1 = clock() / (CLOCKS_PER_SEC / 1000);
// gather primes
std::vector<int> primes;
if(options.use_twins){
for(int i = 2; i <= n-2; i++)
if(!not_prime[i] && !not_prime[i+2]) primes.push_back(i);
} else {
for(int i = 2; i <= n; i++)
if(!not_prime[i]) primes.push_back(i);
}
double time2 = clock() / (CLOCKS_PER_SEC / 1000);
not_prime.clear();
// output
if(options.output_list)
for(int i = 0; i < primes.size(); ++i)
printf("%d\n", primes[i]);
// do the goldbach thing
if(options.test_goldbach){
// For goldbach we can check up to n, we only have to check evens
// So we will check n/2-1 (excluding 0 and 2) integers
int counterexample = 0;
for(int i = 4; i <= n; i += 2){
counterexample = i;
std::vector<int>::const_iterator small_prime = primes.begin();
std::vector<int>::const_iterator big_prime = primes.end()-1;
while(small_prime <= big_prime){
if(*small_prime + *big_prime > counterexample) big_prime--;
if(*small_prime + *big_prime < counterexample) small_prime++;
if(*small_prime + *big_prime == counterexample) {
// Oh, it was no counterexample!
counterexample = 0;
break;
}
}
if(counterexample) break;
}
if(counterexample) printf("found the following counterexample: %d\n", counterexample);
else printf("no counterexample found\n");
}
printf("sieving %f\n", (time1 - time0)/1000.0);
printf("gathering %f\n", (time2 - time0)/1000.0);
}
|
4acc15ead960c7034bf6bdfc825c0fd67b187c32 | b750a42b4085bff7ab66322cd7f50750a98a2cd7 | /trajectory.h | 4dfecb48f0a2a9da6604dbda7a4ac860db76dc54 | [] | no_license | agungmini/swarmGUI | d542e2e12e22aeb448f9540035b227cc3e39fee3 | 2e8ba06c7bd9a21ef5fa8df53f1c2a1e58c9841f | refs/heads/master | 2022-07-05T22:45:46.642670 | 2020-05-14T13:54:23 | 2020-05-14T13:54:23 | 260,999,227 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 894 | h | trajectory.h | #ifndef TRAJECTORY_H
#define TRAJECTORY_H
#include <QWidget>
#include <qcustomplot.h>
#include <QFile>
#include <QTextStream>
#include <QDir>
#include <iostream>
namespace Ui {
class trajectory;
}
class trajectory : public QWidget
{
Q_OBJECT
public:
explicit trajectory(QWidget *parent = nullptr);
~trajectory();
public slots:
void draw_trajectory(float *val);
void openFile(char *dir);
void get_LiDAR(QVector<double> Ax,QVector<double> Ay,QVector<double> Bx,QVector<double> By,QVector<double> Cx,QVector<double> Cy);
void plot_graph(QCustomPlot* plot,QVector<double> val,QVector<double> val1,QVector<double> val2,QVector<double> val3,QVector<double> val4,QVector<double> val5);
private:
Ui::trajectory *ui;
QVector<double> pathAx,pathAy,pathBx,pathBy,pathCx,pathCy;
private slots:
//fungsi fungsi
void chart_cfg();
};
#endif // TRAJECTORY_H
|
3cd49b77e12e1a95aa5ebb14f0c60f1aa64670e2 | 6bc82e4e6433ffad07e2f70e6c4c0c94c673e48a | /src/CameraSample/rc_genicam_api/imagelist.cc | 3f517dd3c4cbbec576ac71cc2054b8f4ef279d27 | [
"BSD-2-Clause"
] | permissive | fastvideo/gpu-camera-sample | 643673c221c70767a4628e4c458c005317531924 | e0f6fd1f1c9d281be8bae78391bbde631294b6d4 | refs/heads/master | 2023-08-14T06:42:00.663407 | 2023-07-25T10:11:39 | 2023-07-25T10:11:39 | 224,174,376 | 285 | 55 | NOASSERTION | 2021-05-23T19:57:54 | 2019-11-26T11:20:18 | C++ | UTF-8 | C++ | false | false | 3,256 | cc | imagelist.cc | /*
* This file is part of the rc_genicam_api package.
*
* Copyright (c) 2017 Roboception GmbH
* All rights reserved
*
* Author: Heiko Hirschmueller
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its contributors
* may be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "imagelist.h"
#include <algorithm>
namespace rcg
{
ImageList::ImageList(size_t _maxsize)
{
maxsize=std::max(static_cast<size_t>(1), _maxsize);
}
void ImageList::add(const std::shared_ptr<const Image> &image)
{
list.push_back(image);
while (list.size() > maxsize)
{
list.erase(list.begin());
}
}
void ImageList::add(const Buffer *buffer, uint32_t part)
{
list.push_back(std::shared_ptr<const Image>(new Image(buffer, part)));
while (list.size() > maxsize)
{
list.erase(list.begin());
}
}
void ImageList::removeOld(uint64_t timestamp)
{
size_t i=0;
while (i < list.size())
{
if (list[i]->getTimestampNS() <= timestamp)
{
list.erase(list.begin()+static_cast<int>(i));
}
else
{
i++;
}
}
}
uint64_t ImageList::getOldestTime() const
{
uint64_t ret=0;
if (list.size() > 0)
{
ret=list[0]->getTimestampNS();
}
return ret;
}
std::shared_ptr<const Image> ImageList::find(uint64_t timestamp) const
{
for (size_t i=0; i<list.size(); i++)
{
if (list[i]->getTimestampNS() == timestamp)
{
return list[i];
}
}
return std::shared_ptr<const Image>();
}
std::shared_ptr<const Image> ImageList::find(uint64_t timestamp, uint64_t tolerance) const
{
if (tolerance > 0)
{
for (size_t i=0; i<list.size(); i++)
{
if (list[i]->getTimestampNS() >= timestamp-tolerance &&
list[i]->getTimestampNS() <= timestamp+tolerance)
{
return list[i];
}
}
}
else
{
return find(timestamp);
}
return std::shared_ptr<const Image>();
}
}
|
769f3013958e3e82425a350f5b458dd544c4024a | f6ef1f50a476c3ed58b4f268feb6fb438996f06a | /有OJ/刷题指南(包含leetcode, POJ, PAT等)/POJ-2/problems/1130AlienSecurity.cpp | be33f09be1559479f66ff9602039f2de4a7bb0d9 | [] | no_license | February13/OJ_Guide | f9d6c72fc2863f5b6f3ad80b0d6c68b51f9a07db | a190942fae29a0dbee306adc81ee245be7fda44a | refs/heads/master | 2020-04-25T09:01:48.458939 | 2018-01-18T08:31:30 | 2018-01-18T08:31:30 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,138 | cpp | 1130AlienSecurity.cpp | #include<queue>
#include<iostream>
#include<vector>
#include<string.h>
using namespace std;
int n,e;
vector<vector<int> > g;
vector<vector<int> > rg;
vector<int> dist;
vector<int> vis;
void dfs(int u){
if(vis[u]) return;
vis[u] = 1;
for(int i=0;i<g[u].size();i++)
dfs(g[u][i]);
}
bool check(int i){
//put gurad in room i
vis = vector<int>(n,0);
vis[i] = 1;
dfs(0);
return !vis[e];
}
int bfs(){
dist = vector<int>(n,-1);
dist[e] = 0;
queue<int> q;
q.push(e);
while(!q.empty()){
int h = q.front();
q.pop();
int d = dist[h];
if(d && check(h)) return h;
for(int i=0;i<rg[h].size();i++){
int b = rg[h][i];
if(dist[b]!=-1) continue;
dist[b] = d+1;
q.push(b);
}
}
return -1;
}
int main()
{
cin>>n>>e;
g = vector<vector<int> >(n,vector<int>());
rg = vector<vector<int> >(n,vector<int>());
vis = vector<int>(n,0);
int a,b;
while(cin>>a>>b)
g[a].push_back(b), rg[b].push_back(a);
cout<<"Put guards in room "<<bfs()<<"."<<endl;
return 0;
}
|
46534220eb1ca8ba3406dcba71eebf4909871da6 | 5d31e16d91827369634ee2478d06e514a2c15f1c | /scratchpad/CopernicusTSIP/CopernicusTSIP.ino | 8ae14933421c916a147d53efec06e6d1acae2b8b | [
"MIT"
] | permissive | AdlerFarHorizons/GpsDevices | 07f4981b2213e575e03e0bcf9735cec62c1c6760 | 7eadcc9ebd4bfab87d9d40db4a821cf40f55a1b9 | refs/heads/master | 2021-01-18T14:02:43.333384 | 2018-04-08T17:42:49 | 2018-04-08T17:42:49 | 20,674,623 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,396 | ino | CopernicusTSIP.ino | /*
TTY TSIP I/O for Trimble's Copernicus II GPS module.
Connected to Arduino per the schematic
"CopernicusBasicTestCircuit".
Far Horizons Lab
June 2014
*/
/*
NOTES:
Serial baud rate change is limited to 38400 for sake of AltSoftwareSerial on Arduino UNO.
It can't handle anything faster. Not tested on 8MHz 3V Arduino Mini, may be worse.
GGA is 78 chars, GSV is 52. Serial B delivers this in (130*10 bits)/baudRate sec, or
271ms at 4800 baud with default configuration. This would be the minimum latency for
the fix.
NMEA sentences are 82 chars maximum including CR and LF, so maximum time per sentence
is 171ms at 4800 baud.
*/
#include <AltSoftSerial.h>
AltSoftSerial altSerial; // TX Pin 9, RX Pin 8
const long rateLimit = 38400; //Set for Arduino UNO AltSoftSerial limitations.
char modeChange = ':';
boolean sentencePending, sentenceRdy;
byte cmdBuf[82];
byte sentenceBuf[100];
int sentenceBufIndex = 0;
int cmdBufIndex = 0;
boolean cmdMode, cmdRdy, rateChangeFlag, rateChangePending;
long rate;
byte dle = 0x10;
byte etx = 0x03;
char* baudRates[] = { "004800", "009600", "019200", "038400", "057600", "115200" };
int baudRatesLen = 6;
void setup() {
Serial.begin( 115200 );
while( !Serial );
findBaudRate();
// clear input buffer
while ( Serial.available() > 0 ) Serial.read();
while ( altSerial.available() > 0 ) altSerial.read();
cmdMode = false;
cmdRdy = false;
sentencePending = false;
sentenceRdy = false;
rateChangeFlag = false;
rateChangePending = false;
sentenceBuf[0] = 0;
sentenceBufIndex = 0;
cmdBuf[0] = 0;
cmdBufIndex = 0;
}
void loop() {
getCharGPS();
getCharTerm();
if ( cmdMode ) {
if ( cmdRdy ) {
sendCmd();
if ( cmdBuf[0] != 0 ) {
getCmdResponse();
if ( rateChangeFlag ) {
rateChangeFlag = false;
}
Serial.print( "cmd:" );
}
cmdRdy = false;
for ( int i = 0 ; i < cmdBufIndex ; i++ ) cmdBuf[i] = '\0';
cmdBufIndex = 0;
}
} else {
if (sentenceRdy) {
for ( int i = 0 ; i < sentenceBufIndex ; i++ ) {
Serial.print( hexFill( sentenceBuf[sentenceBufIndex] ) );
}
//Serial.print( sentenceBuf );//Serial.print(freeRam());
sentenceRdy = false;
sentenceBuf[0] = 0;
sentenceBufIndex = 0;
}
}
}
void getCmdResponse() {
sentenceRdy = false;
sentencePending = false;
long timer = millis() + 2000;
sentence = String();
while ( !sentenceRdy && millis() < timer ) {
getCharGPS();
}
if ( sentenceRdy ) {
if ( sentence.charAt(5) == 'R' ) {
if ( sentence.charAt(9) == 'V' ) {
Serial.print( "err:" );
} else {
Serial.print( " ok:" );
}
Serial.println( sentence);
} else {
Serial.println( "err:No Reply" );
Serial.println( "" );
}
sentenceRdy = false;
sentence = String();
}
}
void sendCmd() {
int i = 0;
// Strip CR + LF
while ( cmdBuf[i] |= 0 ) {
if ( cmdBuf[i] == 13 ) cmdBuf[i] = 0;
if ( cmdBuf[i] == 10 ) cmdBuf[i] = 0;
i++;
}
// Check for null command when switch into cmd mode.
String tmpStr = cmdPrefix + (String)cmdBuf;
tmpStr.toUpperCase();
if ( cmdBuf[0] != 0 ) {
Serial.print( "$" + tmpStr + "*" + checkStr( tmpStr ) );
ss.print( "$" + tmpStr + "*" + checkStr( tmpStr ) +"\r\n");
}
Serial.println( "" );
}
String checkStr( String str ) {
char buf[80]; // Max length of NMEA excl. '$',CR,LF = 79, + null
str.toCharArray(buf, 80);
byte check = 0x00;
for ( int i = 0 ; i < str.length() ; i++ ) {
check ^= (byte)buf[i];
}
String chkStr = String( check, HEX );
if ( check < 0x10 ) {
chkStr = '0' + chkStr;
}
chkStr.toUpperCase();
return chkStr;
}
void findBaudRate() {
cmdMode = true;
Serial.println( "Finding baud rate..." );
boolean baudFound = false;
int baudIndex = 0;
char temp[7];
rate = 0;
while ( !baudFound && rate < rateLimit ) {
rate = atol( baudRates[baudIndex] );
Serial.print( "Trying " );Serial.print( rate );Serial.println( "..." );
altSerial.begin( rate );
delay(2000);
while ( altSerial.available() > 0 ) altSerial.read();
//String tmpStr = "PTNLQPT";
cmdBuf[0] = dle;
cmdBuf[1] = 0xFF;
cmdBuf[2] = dle;
cmdBuf[3] = dle;
cmdBuf[4] = etx;
//altSerial.print( "$" + tmpStr + "*" + checkStr( tmpStr ) +"\r\n" );
altSerial.write( cmdBuf, 5 );
delay(1000);
if ( getCmdResponse() == 0 ) {
baudFound = true;
} else {
Serial.println( " no joy." );
}
baudIndex++;
}
if ( !baudFound ) Serial.println( "couldn't find baud rate" );
cmdMode = false;
}
void getCharTerm() {
char c;
if (Serial.available() ) {
c = Serial.read();
if ( c == ':' ) {
cmdMode = !cmdMode;
while ( Serial.read() >= 0 );
while ( ss.read() >= 0 );
sentenceRdy = false;
sentencePending = false;
sentence = String();
if ( !cmdMode ) {
Serial.println("\n");
} else {
Serial.print( "\ncmd:" );
}
} else if ( cmdMode && !cmdRdy) {
if ( c == 8 ) { // Backspace
cmdBuf[cmdBufIndex] = 0;
if ( cmdBufIndex != 0 ) cmdBufIndex -= 1;
} else {
if ( c == 10 ) {
cmdRdy = true;
}
cmdBuf[cmdBufIndex] = c;
cmdBufIndex +=1;
}
}
}
}
void getCharGPS() {
byte c;
if ( ss.available() ) {
c = ss.read();
if ( !sentenceRdy ) {
if ( c == dle ) {
if ( dleLast ) {
dleOdd = !dleOdd;
else {
dleOdd = true;
}
sentencePending = true;
}
if ( c == etx && sentencePending && dleLast && dleOdd ) {
sentenceRdy = true;
sentencePending = false;
dleOdd = false;
}
// Write only if it's not the second of a pair of dle's
if ( !( c == dle && !dleOdd ) ) {
sentenceBufIndex++;
sentenceBuf[sentencBufIndex] = c;
}
dleLast = ( c == dle );
}
}
}
int freeRam()
{
extern int __heap_start, *__brkval;
int v;
return (int) &v - (__brkval == 0 ? (int) &__heap_start : (int) __brkval);
}
String hexFill( byte inbyte ) {
String chkStr = String( inbyte, HEX );
if ( inbyte < 0x10 ) {
chkStr = '0' + chkStr;
}
chkStr.toUpperCase();
return chkStr;
}
|
2c56c577421ad0009a910a6062dd7a1730e25d6c | 109f316138b6e359fcb9c60bd376fb0f3f42bd5d | /aaaa.cpp | e3cca3e99677937b0668632b38361356b5cc1492 | [] | no_license | DominikZawadzkii/da | 3fb945fc99bb182f53d46c06c32f4c2989f7d4a9 | be44b5eacc5fcbded8c574651e39462373efeca2 | refs/heads/master | 2022-08-02T19:58:45.979170 | 2020-05-20T08:56:15 | 2020-05-20T08:56:15 | 265,506,069 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 624 | cpp | aaaa.cpp | #include <iostream>
#include <fstream>
using namespace std;
int t[1000] ;
for ( int i = 0; i <1000 i++) {
if (zmienna == t[i] )
return false;
else return true;
}
int main ()
{
ifstream wej;
ofstream wyj;
wej.open("wej.txt");
wyj.open("wyj.txt");
int licznik = 0;
if (wejscie.good()){
while(!wej.eof())
{
for (int: i = 0; i < 1000; i++)
wej >> t [i] ;
}
for(int i = 0; i>= licznik; i++) {
if(i == licznik){
if(a_liczba(licznik) == true)
t[licznik] = i;
wyjscie << " [ \n { \n "liczba" :" " << i;
}
licznik++;
}
wej.close();
wyj.close();
return 0;
}
|
3652531d9b0725f1953daca11ec878692191a0fa | 9af742eed28e85cf25affae8c0de5a58bf681df8 | /Client/Client/PlaySound1.h | 709ef60f3586c65a44c04d1d2e5c6c4fe23cbb2b | [] | no_license | Erls-Corporation/VoiceChatWindows | 8d9e77cdfb0741c14ba34c27c8666253b7202c39 | 818d5f7a5fe24e029797c7cc0e85c0024af4f7ff | refs/heads/master | 2016-09-10T17:26:28.942282 | 2014-03-04T11:24:34 | 2014-03-04T11:24:34 | 17,399,722 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,570 | h | PlaySound1.h | /// PlaySound1.h: interface for the PlaySound1 class.
//
//////////////////////////////////////////////////////////////////////
#if !defined(AFX_PlaySound1_H__EA26EF42_4169_11D6_8886_F00753C10001__INCLUDED_)
#define AFX_PlaySound1_H__EA26EF42_4169_11D6_8886_F00753C10001__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#define WM_PLAYSOUND_STARTPLAYING WM_USER+600
#define WM_PLAYSOUND_STOPPLAYING WM_USER+601
#define WM_PLAYSOUND_PLAYBLOCK WM_USER+602
#define WM_PLAYSOUND_ENDTHREAD WM_USER+603
#define SOUNDSAMPLES 1000
#define PLAYBUFFER 2000
#define SAMPLEPSEC 8000
#include<afxmt.h>
#include<mmsystem.h>
class PlaySound1 : public CWinThread
{
DECLARE_DYNCREATE(PlaySound1)
public:
WAVEFORMATEX m_WaveFormatEx;
BOOL Playing;
HWAVEOUT m_hPlay;
CStdioFile log;
CDialog *dlg;
PlaySound1();
PlaySound1(CDialog *dlg);
virtual ~PlaySound1();
BOOL InitInstance();
int ExitInstance();
void displayError(int code,char []);
void displayHeader(LPWAVEHDR lphdr);
LPWAVEHDR CreateWaveHeader(CString mesg);
void ProcessSoundData(short int *sound, DWORD dwSamples);
void GetDevProperty();
afx_msg LRESULT OnStartPlaying(WPARAM wParam, LPARAM lParam);
afx_msg LRESULT OnStopPlaying(WPARAM wParam, LPARAM lParam);
afx_msg LRESULT OnEndPlaySound1Data(WPARAM wParam, LPARAM lParam);
afx_msg LRESULT OnWriteSoundData(WPARAM wParam, LPARAM lParam);
afx_msg LRESULT OnEndThread(WPARAM wParam, LPARAM lParam);
DECLARE_MESSAGE_MAP()
};
#endif // !defined(AFX_PlaySound1_H__EA26EF42_4169_11D6_8886_F00753C10001__INCLUDED_)
|
fe86ea52060a4c420da249247c0f084b2e97021f | 7bce8fa45a4ff17ef1f7a5b5bda9fd54e4c0d2f2 | /PhysicsEngine/source/Physics/Object.cpp | 98a138160c101fd8a0193494fd1036158107151e | [
"MIT"
] | permissive | Kaizen5000/PhysicsEngine | ecc19a51002d80aa9a9cf700c6706c2d72a3fa1e | 11125ffbee7c497a00727b068be7ecaff67ba031 | refs/heads/master | 2020-03-16T13:06:11.003645 | 2018-05-24T13:11:47 | 2018-05-24T13:11:47 | 132,681,402 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,919 | cpp | Object.cpp | #include "Physics/Object.h"
#include "Physics/Sphere.h"
#include "Physics/Plane.h"
#include "Physics/AABB.h"
#include "Gizmos.h"
#include <glm/geometric.hpp>
using namespace Physics;
using glm::vec3;
// Constructor
Physics::Object::Object(ShapeType shape, vec3 pos, float mass, vec4 color, bool isStatic) :
m_shape (shape), m_position(pos), m_mass(mass), m_color(color), m_isStatic(isStatic)
{
// Sets the velocity and acceleration to 0 on initialisation
m_velocity = vec3();
m_acceleration = vec3();
}
// Destructor
Object::~Object()
{
}
// This uses case statements to identify this object and the other object
bool Physics::Object::isColliding(Object * other, vec3 & collisionNormal)
{
// Case statement to identify this shape
switch (m_shape)
{
case ShapeType::SPHERE:
{
// After identifying this shape is a sphere, another case statement is used to identify the other shape
switch (other->getShapeType())
{
case ShapeType::SPHERE:
{
return isCollidingSphereSphere((Sphere*)this, (Sphere*)other, collisionNormal);
}
case ShapeType::PLANE:
{
return isCollidingPlaneSphere((Plane*)other, (Sphere*)this, collisionNormal);
}
case ShapeType::AABB:
{
return isCollidingSphereAABB((Sphere*)this, (AABB*)other, collisionNormal);
}
}
}
case ShapeType::AABB:
{
switch (other->getShapeType())
{
case ShapeType::PLANE:
{
return isCollidingPlaneAABB((Plane*)other, (AABB*)this, collisionNormal);
}
case ShapeType::SPHERE:
{
return isCollidingSphereAABB((Sphere*)other, (AABB*)this, collisionNormal);
}
case ShapeType::AABB:
{
return isCollidingAABBAABB((AABB*)this, (AABB*)other, collisionNormal);
}
}
}
case ShapeType::PLANE:
{
// After identifying this shape is a plane, another case statement is used to identify the other shape
switch (other->getShapeType())
{
case ShapeType::SPHERE:
{
return isCollidingPlaneSphere((Plane*)this, (Sphere*)other, collisionNormal);
}
case ShapeType::AABB:
{
return isCollidingPlaneAABB((Plane*)this, (AABB*)other, collisionNormal);
}
}
}
}
return false;
}
bool Physics::Object::isCollidingSphereSphere(Sphere * objA, Sphere * objB, vec3 &collisionNormal)
{
// Checks that both object pointers are not null
assert(objA != nullptr);
assert(objB != nullptr);
// Find distance between centers
float distance = glm::distance(objB->getPosition(), objA->getPosition());
// Add up the two radii
float radii = objA->getRadius() + objB->getRadius();
// Checks if the distance is less than the radii
if (distance < radii)
{
// Set collision normal
collisionNormal = glm::normalize(objB->getPosition() - objA->getPosition());
// Return true as there is a collision
return true;
}
// If the distance is not less than the radii, there is no collision
return false;
}
bool Physics::Object::isCollidingPlaneSphere(Plane * objA, Sphere * objB, vec3 &collisionNormal)
{
// The distance is the dot product of the spherePosition and plane normal, minus the plane distance
// This projects the sphere distance onto the closest point on the plane
float distance = glm::dot(objB->getPosition(), objA->getDirection()) - objA->getDistance();
// If the distance is less than the radius of the sphere, there is a collision
if (distance < objB->getRadius())
{
// Assigns the collision normal, which for plane - sphere collison is always the plane normal
collisionNormal = objA->getDirection();
// Seperate the sphere from the plane if they are overlapping
objB->setPosition(objB->getPosition() + collisionNormal * (objB->getRadius() - distance));
return true;
}
return false;
}
bool Physics::Object::isCollidingPlaneAABB(Plane * objA, AABB * objB, vec3 & collisionNormal)
{
// Get the distance of the AABB from the plane
float distance = glm::dot(objB->getPosition(), objA->getDirection()) - objA->getDistance();
// Calculate the "radius" of the AABB but projecting each axis along the plane normal
float radius = glm::dot(objB->getExtents().x, objA->getDirection().x) +
glm::dot(objB->getExtents().y, objA->getDirection().y) +
glm::dot(objB->getExtents().z, objA->getDirection().z);
// If it is not touching on every axis, there is no collision
if (distance > objB->getExtents().x || distance > objB->getExtents().y || distance > objB->getExtents().z)
{
return false;
}
else
{
// The collision normal is the plane normal
collisionNormal = objA->getDirection();
// Separation
objB->setPosition(objB->getPosition() + collisionNormal * (radius - distance));
return true;
}
return false;
}
bool Physics::Object::isCollidingAABBAABB(AABB * objA, AABB * objB, vec3 & collisionNormal)
{
// Displacement
vec3 distance = objB->getPosition() - objA->getPosition();
// Get the absolute value of the distance to account for objB being behind objA
vec3 absDistance = glm::abs(distance);
// The sum of the extents of both AABBs,
vec3 totalExtents = objA->getExtents() + objB->getExtents();
// If the distance is larger than the total extent on any axis, there is no collision
if (absDistance.x > totalExtents.x || absDistance.y > totalExtents.y || absDistance.z > totalExtents.z)
{
// No collision
return false;
}
// Get the overlap
glm::vec3 overlap = totalExtents - absDistance;
// The axis with the smallest overlap is the axis the collision is happening on, thereby determining the collision normal
float smallestOverlap = glm::min(glm::min(overlap.x, overlap.y), overlap.z);
if (smallestOverlap == overlap.x)
{
// Multiply the collision normal but the sign of the distance, if the distance is negative, the collision normal will be negated
collisionNormal = glm::vec3(1, 0, 0) * glm::sign(distance.x);
}
else if (smallestOverlap == overlap.y)
{
collisionNormal = glm::vec3(0, 1, 0) * glm::sign(distance.y);
}
else // z
{
collisionNormal = glm::vec3(0, 0, 1) * glm::sign(distance.z);
}
return true;
}
bool Physics::Object::isCollidingSphereAABB(Sphere * objA, AABB * objB, vec3 & collisionNormal)
{
// Displacement
vec3 distance = objB->getPosition() - objA->getPosition();
// Get the absolute value of the distance to account for objB being behind objA
vec3 absDistance = glm::abs(distance);
// The sum of the extents of both AABBs,
vec3 totalExtents = objA->getRadius() + objB->getExtents();
// If the distance is larger than the total extent on any axis, there is no collision
if (absDistance.x > totalExtents.x || absDistance.y > totalExtents.y || absDistance.z > totalExtents.z)
{
// No collision
return false;
}
// Get the overlap
glm::vec3 overlap = totalExtents - absDistance;
// The axis with the smallest overlap is the axis the collision is happening on, thereby determining the collision normal
float smallestOverlap = glm::min(glm::min(overlap.x, overlap.y), overlap.z);
if (smallestOverlap == overlap.x)
{
collisionNormal = glm::vec3(1, 0, 0) * glm::sign(distance.x);
}
else if (smallestOverlap == overlap.y)
{
collisionNormal = glm::vec3(0, 1, 0) * glm::sign(distance.y);
}
else // z
{
collisionNormal = glm::vec3(0, 0, 1) * glm::sign(distance.z);
}
return true;
}
void Object::update(float deltaTime)
{
// If the object is not static, update
if (!m_isStatic)
{
// Apply friction (dampening)
applyForce(-m_velocity * m_friction);
// Increase velocity by acceleration times delta time
m_velocity += m_acceleration * deltaTime;
// Moves the object's position by velocity times delta time
m_position += m_velocity * deltaTime;
// Reset acceleration to zero
m_acceleration = vec3();
}
}
void Object::applyForce(const vec3 & force)
{
// Increases acceleration by force divided my mass
// Force = Mass * Acceleration
m_acceleration += force / m_mass;
}
void Physics::Object::applyImpulse(const vec3 & impulse)
{
// Adds impulse to velocity, not altered by delta time
m_velocity += impulse;
}
|
36e52486d8750c254be50ba4dcdb5d2afc0c59de | 04b886bcb4eae8b4cd656b2917a82a13067ca2b7 | /src/cpp/oclint/oclint-rules/rules/custom2/FunctionReceivesAnOddArgumentRule.cpp | 6e106a47c4a361cf37c6295cd89c299e5f547b6b | [
"BSD-3-Clause"
] | permissive | terryhu08/MachingLearning | 4d01ba9c72e931a82db0992ea58ad1bd425f1544 | 45ccc79ee906e072bb40552c211579e2c677f459 | refs/heads/master | 2021-09-16T01:38:10.364942 | 2018-06-14T13:45:39 | 2018-06-14T13:45:39 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,732 | cpp | FunctionReceivesAnOddArgumentRule.cpp | #include "oclint/AbstractASTVisitorRule.h"
#include "oclint/RuleSet.h"
using namespace std;
using namespace clang;
using namespace oclint;
class FunctionReceivesAnOddArgumentRule : public AbstractASTVisitorRule<FunctionReceivesAnOddArgumentRule>
{
public:
virtual const string name() const override
{
return "function receives an odd argument";
}
virtual int priority() const override
{
return 3;
}
virtual const string category() const override
{
return "custom2";
}
#ifdef DOCGEN
virtual const std::string since() const override
{
return "0.12";
}
virtual const std::string description() const override
{
return ""; // TODO: fill in the description of the rule.
}
virtual const std::string example() const override
{
return R"rst(
.. code-block:: cpp
void example()
{
// TODO: modify the example for this rule.
}
)rst";
}
/* fill in the file name only when it does not match the rule identifier
virtual const std::string fileName() const override
{
return "";
}
*/
/* add each threshold's key, description, and its default value to the map.
virtual const std::map<std::string, std::string> thresholds() const override
{
std::map<std::string, std::string> thresholdMapping;
return thresholdMapping;
}
*/
/* add additional document for the rule, like references, notes, etc.
virtual const std::string additionalDocument() const override
{
return "";
}
*/
/* uncomment this method when the rule is enabled to be suppressed.
virtual bool enableSuppress() const override
{
return true;
}
*/
#endif
virtual void setUp() override {}
virtual void tearDown() override {}
/* Visit CallExpr */
bool VisitCallExpr(CallExpr *callExpr)
{
string funName = callExpr->getDirectCallee()->getNameInfo().getAsString();
if(funName=="memset" && callExpr->getNumArgs()==3){//memset函数,第三个参数表示设置内存大小,如果是0存在问题
Expr* arg3 = callExpr->getArg(2); //获取第3个参数
if(isa<IntegerLiteral>(arg3)){
IntegerLiteral* integerLiteral = dyn_cast_or_null<IntegerLiteral>(arg3);
if(integerLiteral->getValue().getSExtValue()==0){
string message = "The 'memset' function processes '0' elements. Inspect the third argument.";
addViolation(callExpr, this, message);
}
}
}
return true;
}
};
static RuleSet rules(new FunctionReceivesAnOddArgumentRule());
|
8c4ca5507e1d9dbc76e04e26e1b73fa2cffa05e6 | 49ba7d71174e9a3843c63f2d8cddb5288afa73d1 | /libraries/Hellschreiber/Hellschreiber.h | e98f5bfdab6d3cfc79617635cc74ddb316ded2c5 | [] | no_license | martinw89/SSDC-HAB | 630352e6b96cf33f7116e7bfeb7b9275bb609fc5 | ab944b27a4766898dc954e68f7a6a1fc62add886 | refs/heads/master | 2020-05-19T11:56:56.050581 | 2013-03-19T22:14:23 | 2013-03-19T22:14:23 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,831 | h | Hellschreiber.h | #ifndef Hellschreiber_h
#define Hellschreiber_h
#include "Arduino.h"
#define A 0b0111111010011111
#define B 0b0010101010111111
#define C 0b0100011000101110
#define D 0b0011101000111111
#define E 0b0100011010111111
#define FF 0b0100001010011111
#define G 0b0100111000101110
#define H 0b0111110010011111
#define I 0b0100011111110001
#define J 0b0111110000100011
#define K 0b0110110010011111
#define L 0b0000010000111111
#define M 0b0111110110011111
#define N 0b0011111000001111
#define O 0b0011101000101110
#define P 0b0010001010011111
#define Q 0b0111011001011110
#define R 0b0010111010011111
#define S 0b0100101010101001
#define T 0b0100001111110000
#define U 0b0111110000111111
#define V 0b0111100000111110
#define W 0b0111110001111111
#define X 0b0110110010011011
#define Y 0b0110000011111000
#define Z 0b0110011010110011
#define n0 0b0111111000111111
#define n1 0b0000011111101001
#define n2 0b0111011010110111
#define n3 0b0111111010110001
#define n4 0b0111110010011100
#define n5 0b0101111010111101
#define n6 0b0101111010111111
#define n7 0b0110001011110000
#define n8 0b0111111010111111
#define n9 0b0111111010111101
#define SP 0b0000000000000000
#define BK 0b0111111111111111
#define SQ 0b0001000111000100
#define PR 0b0000110001100011
#define AR 0b0001000111011111
class Hellschreiber
{
public:
Hellschreiber(int pin, int speed);
void sendMessage(char message[], int length);
void setWidth(char _width);
void setSPD(int _spd);
private:
void sendChar(int toSend);
void rest(char times);
void on(char restfor);
void off(char restfor);
int _pin;
};
#endif |
598a141da112ae5763767201bb4c01bdcad528bd | 8e31b21b19f39613751d27598be31a1cde318777 | /TexasHoldem/Administrador.h | d872c55fc94963cbddf039c25135f4221ac0ce00 | [] | no_license | julianx2rl/Poker | 90247b6a31dfd1204bb7ee7a4b752e6f6492838e | b85c6c95fe0c7a2dea40a22092811e9bb046a986 | refs/heads/master | 2021-01-21T13:53:17.842356 | 2016-05-26T00:34:39 | 2016-05-26T00:34:39 | 55,553,652 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,938 | h | Administrador.h |
/**
* @file Administrador.h
* @version 1.0
* @date 07/05/2016
* @author GrupoProgra: Julian Arguedas Torres B50587 - Milton Delgado Fernandez B12188 - Kenneth Walker Fernandez B37663
* @title Clase Administrador
* @brief Controla la simulacion del poker
*/
#pragma once
#include "Jugador.h"
#include "Carta.h"
#include "Baraja.h"
#include "stdafx.h"
class Administrador
{
public:
int lote;
int apuestaMinima;
list<Jugador*> juego;
list<Carta*> mesa;
Baraja* mano;
/**
* @brief Constructor por defecto del Administrador
*/
Administrador();
/**
* @brief Inicia la simulacion del poker
* @param jugadores Numero de jugadores
*/
void iniciarJuego();
/**
* @brief Da dos cartas a cada uno de los jugadores.
*/
void reparto();
/**
* @brief Inicia el juego.
*/
void jugar();
/**
* @brief Coloca una carta en la mesa.
*/
void poner();
/**
* @brief Le presenta las opciones disponibles al jugador.
*/
void preguntar();
/**
* @brief La primera opcion del jugador.
* @param it El jugador activo
*/
void apostar(Jugador* it);
/**
* @brief Imprime las cartas que han sido colocadas en la mesa.
*/
void imprimir();
/**
* @brief Calcula cual jugador tiene la mejor jugada.
* @return Retorna al ganador de la partida
*/
Jugador* calcular();
/**
* @brief Calcula el valor de la jugada del conjunto de cartas, los que le siguen son fragmentos de este.
* @param listaCartas.
* @return Valor de la jugada en las cartas del maso obtenido.
*/
// TODO Separar esto de la clase Administrador!!!!
int valorJugada(list<Carta*> listaCartas);
int straight(list<Carta*> listaCartas);
int four(list<Carta*> listaCartas);
int big(list<Carta*> listaCartas, int numero);
int three(list<Carta*> listaCartas);
int full(list<Carta*> listaCartas);
int flush(list<Carta*> listaCartas);
int pair(list<Carta*> listaCartas);
/**
* @brief Destructor de Administrador
*/
~Administrador();
};
|
f864a6555bdadcf430a472d34675fffbfab57767 | 8e59ba2835b0a81c20541643e82b3fc77998ac6e | /PointGroupOld/GroupPointsEM.cpp | 9330946395d1ef266b92e9458d5e4c72acbf7bb2 | [] | no_license | toshirokubota/straight_polygon_grouping_V2 | aa33a52a528ca73d04b99c7273ea0bec1fd4b2e4 | 948065188aa3ef12940bb5539f9498ef85f98f05 | refs/heads/master | 2021-01-10T01:57:13.976860 | 2016-03-10T12:21:39 | 2016-03-10T12:21:39 | 36,931,779 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 15,093 | cpp | GroupPointsEM.cpp | /*
This routine implements grouping of moving points.
*/
#include <iostream>
#include <fstream>
using namespace std;
#include <mytype.h>
#include <ImageProc.h>
#include <Feature.h>
#include <Convolve.h>
#include <Gradient.h>
#include <Misc.h>
#include <Draw.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
#include "MCpoint.h"
int Factor=4;
int Width=256;
int Height=256;
real FrameRate=1.0;
real Rate=0.25;
int NumIter=20;
real NoiseVar=1.0;
int NumGroup=3;
int PointsPerGroup=6;
int NoisePoints=20;
int NumPoints=NumGroup*PointsPerGroup+NoisePoints;
real Epsilon=0.00001;
real Threshold1=.01;
real Threshold2=.01;
int Seed=54;
real Sigma1=sqrt(2.0)*NoiseVar;
real Sigma2=1.0;
real Sigma3=1.0;
const int MaxNumGroups=10;
//const int MaxCandidates=10;
real MaxRange=25.0;
real VelocityY[]={20.0, 20.0, -20.0};
real VelocityX[]={-20.0, 20.0, 20.0};
char infile[256];
char outfile[256];
//
// Usage - argument parsing routines
//
void
Usage(char* program) {
cerr << program << ": usage" << endl;
cerr << "Required arguments:" << endl;
//cerr << "\t -i <input file name>" << endl;
cerr << "\t -o <output file name>" << endl;
cerr << "Optional arguments:" << endl;
cerr << "\t -m (int) set the # of iterations" << endl;
cerr << "\t \t default value is " << NumIter << endl;
cerr << "\t -rt (int) set the update rate (>0)" << endl;
cerr << "\t \t default value is " << Rate << endl;
cerr << "\t -nv (int) set the noise variance" << endl;
cerr << "\t \t default value is " << NoiseVar << endl;
cerr << "\t -np (int) set the # of sample points" << endl;
cerr << "\t \t default value is " << NumPoints << endl;
cerr << "\t -seed (int) set the seed value for random number generator" << endl;
cerr << "\t \t default value is " << Seed << endl;
}
void
PrintParameters() {
cout << "input file: " << infile << endl;
cout << "output file: " << outfile << endl;
cout << "# of iterations: " << NumIter << endl;
cout << "the update rate: " << Rate << endl;
cout << "the noise variance: " << NoiseVar << endl;
cout << "# of sample points: " << NumPoints << endl;
cout << "Seed number: " << Seed << endl;
}
int
ReadArguments(int argc, char* argv[]) {
int in_found=0;
int out_found=0;
real tempval;
for(int i=1; i<argc; ++i) {
if(strcmp(argv[i],"-i")==0) {
if(argc>i+1) {
in_found=1;
strcpy(infile,argv[++i]);
}
else
return 1; // no file specified
}
else if(strcmp(argv[i],"-o")==0) {
if(argc>i+1) {
out_found=1;
strcpy(outfile,argv[++i]);
}
else
return 2; // no file specified
}
else if(strcmp(argv[i],"-m")==0) {
if(argc>i+1) {
NumIter=atoi(argv[++i]);
}
else
return 6; // no value specified
}
else if(strcmp(argv[i],"-seed")==0) {
if(argc>i+1) {
Seed=atoi(argv[++i]);
}
else
return 6; // no value specified
}
else if(strcmp(argv[i],"-np")==0) {
if(argc>i+1) {
NumPoints=atoi(argv[++i]);
}
else
return 6; // no value specified
}
else if(strcmp(argv[i],"-rt")==0) {
if(argc>i+1) {
tempval=strtod(argv[++i],NULL);
if(tempval<0)
return 8;
else
Rate=tempval;
}
else
return 6; // no value specified
}
else if(strcmp(argv[i],"-nv")==0) {
if(argc>i+1) {
NoiseVar=strtod(argv[++i],NULL);
//MaxRange=NoiseVar*NoiseVar;
Sigma1=sqrt(2.)*NoiseVar;
}
else
return 6; // no value specified
}
}
//if(!in_found)
// return 11;
rndm(Seed);
if(!out_found)
return 12;
else
return 0;
}
RealImage
ShowPoints(const vMCpoint& points, int h, int w, int nump) {
RealImage im(1,h,w,0);
int i;
int length=5;
for(i=0; i<nump; ++i) {
real x=points[i].GetX();
real y=points[i].GetY();
int ix=Round(x);
int iy=Round(y);
if(iy>=0 && iy<h && ix>=0 && ix<w)
im.SetPixel(0,iy,ix,1.0);
//DrawCross(im,0,iy,ix,0);
}
return im;
}
void
TraceLink(const vMCpoint& points, ByteImage& flag, RealImage& im,
int i, real color) {
int nump=points.size();
for(int j=0; j<nump; ++j) {
if(flag.GetPixel(0,i,j))
continue;
for(int m=0; m<points[i].GetNumCandidates(); ++m) {
for(int n=0; n<points[j].GetNumCandidates(); ++n) {
if(points[i].GetLink(j,m,n)>=.5) {
flag.SetPixel(0,i,j,1);
flag.SetPixel(0,j,i,1);
int y1=Round(points[i].GetY());
int x1=Round(points[i].GetX());
int y2=Round(points[j].GetY());
int x2=Round(points[j].GetX());
DrawLine(im,0,y1,x1,y2,x2,color);
TraceLink(points,flag,im,j,color);
}
}
}
flag.SetPixel(0,i,j,1);
flag.SetPixel(0,j,i,1);
}
}
RealImage
ShowLinks(const vMCpoint points, int h, int w) {
int nump=points.size();
RealImage im(1,h,w,0);
ByteImage flag(1,nump,nump,0);
int i;
for(i=0; i<nump; ++i)
flag.SetPixel(0,i,i,1);
real color=1.0;
for(i=0; i<nump; ++i) {
TraceLink(points,flag,im,i,color);
color+=1.0;
}
return im;
}
RealImage
ShowOnlyPoints(const vMCpoint& points, int h, int w) {
int nump=points.size();
RealImage im(1,h,w,0);
int i;
real color=1.0;
for(i=0; i<nump; ++i) {
int y1=Round(points[i].GetY());
int x1=Round(points[i].GetX());
if(y1>=0 && y1<h && x1>=0 && x1<w)
DrawCross(im,0,y1,x1,5);
}
return im;
}
RealImage
ShowGroundTruthLinks(const vMCpoint& points, int h, int w) {
int nump=points.size();
RealImage im(NumGroup,h,w,0);
int i,j,j2;
for(i=0; i<NumGroup; ++i) {
for(j=0; j<PointsPerGroup; ++j) {
real y1=points[i*PointsPerGroup+j].GetY();
real x1=points[i*PointsPerGroup+j].GetX();
for(j2=0; j2<PointsPerGroup; ++j2) {
if(j!=j2) {
real y2=points[i*PointsPerGroup+j2].GetY();
real x2=points[i*PointsPerGroup+j2].GetX();
DrawLine(im,i,Round(y1),Round(x1),Round(y2),Round(x2),1);
}
}
}
}
for(i=NumGroup*PointsPerGroup; i<NumPoints; ++i) {
real y1=points[i].GetY();
real x1=points[i].GetX();
DrawCross(im,0,Round(y1),Round(x1),5);
DrawCross(im,1,Round(y1),Round(x1),5);
DrawCross(im,2,Round(y1),Round(x1),5);
}
return im;
}
vMCpoint
MovePoints(const vMCpoint& points, real rate, real var) {
int nump=points.size();
vMCpoint res=points;
int i;
for(i=0; i<nump; ++i) {
res[i].Move(rate,var);
}
return res;
}
vMCpoint
ShufflePoints(const vMCpoint& points) {
int nump=points.size();
vMCpoint res(nump);
int i;
for(i=0; i<nump; ++i) {
res[nump-i-1]=points[i];
}
return res;
}
real
Dist(real y1, real x1, real y2, real x2) {
return (y1-y2)*(y1-y2)+(x1-x2)*(x1-x2);
}
void
PlacePoints(vMCpoint& points, int height, int width) {
int nump=points.size();
int i,j,k,m;
int offy=30;
int offx=30;
for(i=0,m=0; i<NumGroup; ++i) {
for(j=0; j<PointsPerGroup; ++j,m++) {
real y;
real x;
points[m].SetNumPoints(nump);
y=(height-2*offy)*rndm(0)+offy;
x=(width-2*offx)*rndm(0)+offx;
points[m].SetY(y);
points[m].SetX(x);
points[m].SetVelocityY(VelocityY[i]);
points[m].SetVelocityX(VelocityX[i]);
}
}
for(i=NumGroup*PointsPerGroup; i<NumPoints; ++i){
points[i].SetNumPoints(nump);
points[i].SetY(rndm(0)*height);
points[i].SetX(rndm(0)*width);
points[i].SetVelocityY(rndm(0)*50);
points[i].SetVelocityX(rndm(0)*50);
}
}
/*
Sort y, x and index according to the dist using bubble sort.
*/
void
SortCandidates(real* dist, real* y, real* x, int* index, int count) {
for(int i=0; i<count; ++i) {
real max=dist[i];
int maxi=i;
for(int j=i; j<count; ++j) {
if(max<dist[j]) {
maxi=j;
max=dist[i];
}
}
if(maxi!=i) {
real temp=dist[i];
dist[i]=dist[maxi];
dist[maxi]=temp;
temp=y[i];
y[i]=y[maxi];
y[maxi]=temp;
temp=x[i];
x[i]=x[maxi];
x[maxi]=temp;
int tempi=index[i];
index[i]=index[maxi];
index[maxi]=tempi;
}
}
}
const int MaxNumPoints=256;
void
EstimateTransform(vMCpoint& p1, const vMCpoint& p2) {
int nump=p1.size();
real dist[MaxNumPoints];
real est_vy[MaxNumPoints];
real est_vx[MaxNumPoints];
int index[MaxNumPoints];
int i,j,k;
for(i=0; i<nump; ++i) {
real x0=p1[i].GetX();
real y0=p1[i].GetY();
int count=0;
for(j=0; j<nump; ++j) {
real x1=p2[j].GetX();
real y1=p2[j].GetY();
real dd=(x0-x1)*(x0-x1)+(y0-y1)*(y0-y1);
if(dd<2.*MaxRange*MaxRange) {
est_vy[count]=y1-y0;
est_vx[count]=x1-x0;
index[count]=j;
count++;
}
}
if(count==0)
cout << "Count=0 @ " << i << endl;
cout << i << ":" << count << endl;
assert(count>0);
SortCandidates(dist,est_vy,est_vx,index,count);
count=Min(count,MCpointMaxCandidates);
p1[i].SetNumCandidates(count);
for(k=0; k<count; ++k) {
p1[i].SetEstimateVelocityY(k,est_vy[k]);
p1[i].SetEstimateVelocityX(k,est_vx[k]);
p1[i].SetIndex(k,index[k]);
p1[i].SetProb(k,1.0/(count+1));
}
p1[i].SetProb(count,1.0/(count+1));
}
cout << "Done estimate transform.\n";
}
real
CompatibilityTransform(const MCpoint& p1, const MCpoint& p2, int m, int n, real sgm) {
real vy1=p1.GetEstimateVelocityY(m);
real vx1=p1.GetEstimateVelocityX(m);
real vy2=p2.GetEstimateVelocityY(n);
real vx2=p2.GetEstimateVelocityX(n);
real dd=Dist(vy1,vx1,vy2,vx2);
if(dd>2.*sgm*sgm)
return .0;
else
return exp(-dd/(2.*sgm*sgm));
}
real
InterframeCompatibilityTransform(const MCpoint& p1, const MCpoint& p2, int m, int n, real sgm){
real vy1=p1.GetEstimateVelocityY(m);
real vx1=p1.GetEstimateVelocityX(m);
real vy2=-p2.GetEstimateVelocityY(n);
real vx2=-p2.GetEstimateVelocityX(n);
real dd=Dist(vy1,vx1,vy2,vx2);
if(dd>2.*sgm*sgm)
return .0;
else
return exp(-dd/(2.*sgm*sgm));
}
vMCpoint
UpdateTransformEstimate(const vMCpoint& points, real sigma, real rate) {
int nump=points.size();
vMCpoint res=points;
real sum[MCpointMaxCandidates];
int i,m,n;
real nvy=0;
real nvx=0;
real alpha=0.5;
for(i=0; i<nump; ++i) {
real total_sum=0;
MCpoint pnt1=points[i];
for(m=0; m<pnt1.GetNumCandidates(); ++m) {
sum[m]=.0;
real evy1=pnt1.GetEstimateVelocityY(m);
real evx1=pnt1.GetEstimateVelocityX(m);
for(int j=0; j<nump; ++j) {
if(i!=j) {
MCpoint pnt2=points[j];
for(n=0; n<pnt2.GetNumCandidates(); ++n) {
real evy2=pnt2.GetEstimateVelocityY(n);
real evx2=pnt2.GetEstimateVelocityX(n);
real lnk1=pnt1.GetLink(j,m,n);
real lnk2=pnt2.GetLink(i,n,m);
real dd=CompatibilityTransform(pnt1,pnt2,m,n,sigma);
real dy=evy2-evy1;
real dx=evx2-evx1;
real pp=pnt2.GetProb(n);
nvy+=dd*pp*lnk1*lnk2*dy;
nvx+=dd*pp*lnk1*lnk2*dx;
}
}
}
res[i].SetEstimateVelocityY(m,evy1+rate*nvy);
res[i].SetEstimateVelocityX(m,evx1+rate*nvx);
}
}
return res;
}
vMCpoint
UpdateLinkWeights(const vMCpoint& points, real thres, real sigma) {
int nump=points.size();
vMCpoint res=points;
for(int i=0; i<nump; ++i) {
MCpoint p1=points[i];
int numc1=p1.GetNumCandidates();
for(int m=0; m<numc1; ++m) {
for(int j=0; j<nump; ++j) {
MCpoint p2=points[j];
int numc2=p2.GetNumCandidates();
for(int n=0; n<numc2; ++n) {
if(i!=j) {
real dd=CompatibilityTransform(p1,p2,m,n,sigma);
real lnk1=p1.GetLink(j,m,n);
real lnk2=p2.GetLink(i,n,m);
real pp=p2.GetProb(n);
#ifdef BAUM_EAGON
//real ee=pp*lnk1*lnk2;
//real pp2=ee*dd/(ee*dd+(1.-ee)*thres);
#else
real ee=pp*dd*lnk2; // for EM
real pp2=ee/(ee+thres); //for EM
#endif
res[i].SetLink(j,m,n,pp2);
}
}
}
}
}
return res;
}
vMCpoint
UpdateProbMeasure(const vMCpoint& frame1, const vMCpoint& frame2,
real thres, real sigma) {
int nump=frame1.size();
vMCpoint res=frame1;
real sum[MCpointMaxCandidates];
for(int i=0; i<nump; ++i) {
MCpoint p1=frame1[i];
int numc1=p1.GetNumCandidates();
real total_sum=0;
for(int m=0; m<numc1; ++m) { //compute fitness for each candidate
sum[m]=.0;
MCpoint p3=frame2[p1.GetIndex(m)];
real match_prob=.0;
//check if the candidate also consider it as a candidate
for(int m2=0; m2<p3.GetNumCandidates(); ++m2) {
if(p3.GetIndex(m2)==i) {
match_prob=p3.GetProb(m2);
break;
}
}
if(match_prob>0) { //mutual candidancy
for(int j=0; j<nump; ++j) {
//compute the support from other INTRA-frame points
//measured by 1. transformation similarity
// 2. strength of links
if(i!=j) {
MCpoint p2=frame1[j];
int numc2=p2.GetNumCandidates();
for(int n=0; n<numc2; ++n) {
real dd=CompatibilityTransform(p1,p2,m,n,sigma);
real lnk1=p1.GetLink(j,m,n);
real lnk2=p2.GetLink(i,n,m);
real pp=p2.GetProb(n);
real ss=pp*lnk1*lnk2;
sum[m]+=ss*match_prob;
}
}
}
#ifdef BAUM_EAGON
sum[m]*=p1.GetProb(m); //activate this for Baum-Eagon
#endif
total_sum+=sum[m];
}
}
#ifdef BAUM_EAGON
for(m=0; m<numc1; ++m)
res[i].SetProb(m,sum[m]/(total_sum+p1.GetProb(numc1)*thres));
res[i].SetProb(numc1,p1.GetProb(numc1)*thres/(total_sum+p1.GetProb(numc1)*thres));
#else
for(m=0; m<numc1; ++m)
res[i].SetProb(m,sum[m]/(total_sum+thres));
res[i].SetProb(numc1,thres/(total_sum+thres));
#endif
}
return res;
}
void main(int argc,char *argv[]) {
if(ReadArguments(argc,argv)!=0) {
Usage(argv[0]);
abort();
}
else
PrintParameters();
vMCpoint frame1(NumPoints);
vMCpoint frame2;
vMCpoint tmp_frm;
PlacePoints(frame1,Height,Width);
frame2=MovePoints(frame1,FrameRate,NoiseVar);
frame2=ShufflePoints(frame2); //to make sure the array index is not helping
EstimateTransform(frame1,frame2);
EstimateTransform(frame2,frame1);
RealImage map;
map=ShowGroundTruthLinks(frame1,Height,Width);
map.WritePnmFile("truth.ppm",IO_PPM,1);
map=ShowGroundTruthLinks(frame2,Height,Width);
map.WritePnmFile("truth2.ppm",IO_PPM,1);
map=ShowOnlyPoints(frame1,Height,Width);
map.WritePnmFile("points1.pgm",IO_PGM,1);
map=ShowOnlyPoints(frame2,Height,Width);
map.WritePnmFile("points2.pgm",IO_PGM,1);
//InteractiveImageWrite(map,"truth.pgm",1);
for(int i=0; i<NumIter; ++i) {
cout << i << endl;
frame1=UpdateLinkWeights(frame1,Threshold1,Sigma1);
frame2=UpdateLinkWeights(frame2,Threshold1,Sigma1);
frame1=UpdateTransformEstimate(frame1,Sigma1,Rate);
frame2=UpdateTransformEstimate(frame2,Sigma1,Rate);
tmp_frm=UpdateProbMeasure(frame1,frame2,Threshold2,Sigma1);
frame2=UpdateProbMeasure(frame2,tmp_frm,Threshold2,Sigma1);
frame1=tmp_frm;
map=ShowLinks(frame1,Height,Width);
//sprintf(outfile,"out%2.2d.pgm",i);
map.WritePnmFile(outfile,IO_PGM,1);
}
for(i=0; i<frame1.size(); ++i)
cout << "Point #" << i << endl << frame1[i];
} |
1673f14948e8bedfedecc85e9652bbfa2361fc6e | eb2f8b3271e8ef9c9b092fcaeff3ff8307f7af86 | /Grade 10-12/2018 autumn/NOIP/NOIP2018提高组Day1程序包/GD-Senior/answers/GD-0047/track/track.cpp | 2441748cb23515f4a37e30daa1b9f7bc55706583 | [] | no_license | Orion545/OI-Record | 0071ecde8f766c6db1f67b9c2adf07d98fd4634f | fa7d3a36c4a184fde889123d0a66d896232ef14c | refs/heads/master | 2022-01-13T19:39:22.590840 | 2019-05-26T07:50:17 | 2019-05-26T07:50:17 | 188,645,194 | 4 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 483 | cpp | track.cpp | #include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
#include<iostream>
#include<vector>
#include<queue>
#include<set>
using namespace std;
struct pic{int tonl,w;}treee[50005];
int n,m;
vector<pic> q[50005];
int main()
{
freopen("track.in","r",stdin);
freopen("track.out","w",stdout);
cin>>n>>m;int maxx=-1;
for (int i=1;i<n;i++)
{
int a,b,c;
scanf("%d %d %d",&a,&b,&c);
q[a].push_back((pic){b,c});
maxx=max(maxx,c);
}
cout<<maxx<<endl;
return 0;
}
|
acdec3f107672aad9e862650d83fd1e35d28e868 | baf873c32d8c86b71cf50d59721e8cc3db345942 | /Game/Enemy.cpp | 289decd959bf1db8c6602340c52454596278ee12 | [] | no_license | mrDIMAS/src | 6f1e0a4176e281c22d03e6766cc2719363f59e78 | cd4d0f7070359086993d544b8bea7c764f2f6d6f | refs/heads/master | 2020-04-12T01:36:42.369525 | 2016-12-17T20:20:24 | 2016-12-17T20:20:24 | 25,090,851 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 14,130 | cpp | Enemy.cpp | #include "Precompiled.h"
#include "Gate.h"
#include "Enemy.h"
#include "Menu.h"
#include "Door.h"
#include "Level.h"
Enemy::Enemy(unique_ptr<Game> & game, const vector<shared_ptr<GraphVertex>> & path, const vector<shared_ptr<GraphVertex>> & patrol) :
Actor(game, 0.5f, 0.25f),
mHitDistance(1.3),
mCurrentPatrolPoint(0),
mForceRun(false),
mAngleTo(0.0f),
mAngle(0.0f),
mRunSpeed(1.5f),
mMoveType(MoveType::Patrol),
mPathCheckTimer(120),
mCurrentPathPoint(0),
mLostTimer(0) {
mPathfinder.SetVertices(path);
mPatrolPointList = patrol;
mModel = mGame->GetEngine()->GetSceneFactory()->LoadScene("data/models/ripper/ripper0.scene");
mModel->Attach(mBody);
mModel->SetPosition(Vector3(0, -0.7f, 0));
mModel->SetBlurAmount(1.0f);
mModel->SetAnimationBlendingEnabled(false);
auto light = dynamic_pointer_cast<ISpotLight>(mModel->FindChild("Fspot001"));
light->SetShadowCastEnabled(false);
FillByNamePattern(mRightLegParts, "RightLegP?([[:digit:]]+)");
FillByNamePattern(mLeftLegParts, "LeftLegP?([[:digit:]]+)");
FillByNamePattern(mRightArmParts, "RightArmP?([[:digit:]]+)");
FillByNamePattern(mLeftArmParts, "LeftArmP?([[:digit:]]+)");
FillByNamePattern(mTorsoParts, "TorsoBoneP?([[:digit:]]+)");
mHead = mModel->FindChild("Head");
mHead->SetAnimationOverride(true);
auto soundSystem = mGame->GetEngine()->GetSoundSystem();
mHitFleshWithAxeSound = soundSystem->LoadSound3D("data/sounds/armor_axe_flesh.ogg");
mHitFleshWithAxeSound->Attach(mModel->FindChild("Weapon"));
mBreathSound = soundSystem->LoadSound3D("data/sounds/breath1.ogg");
mBreathSound->Attach(mBody);
mBreathSound->SetVolume(0.25f);
mBreathSound->SetRolloffFactor(35);
mBreathSound->SetRoomRolloffFactor(35);
mBreathSound->SetReferenceDistance(2.8);
mScreamSound = soundSystem->LoadSound3D("data/sounds/scream_creepy_1.ogg");
mScreamSound->SetVolume(1.0f);
mScreamSound->Attach(mBody);
mScreamSound->SetRolloffFactor(20);
mScreamSound->SetRoomRolloffFactor(20);
mScreamSound->SetReferenceDistance(4);
mRunAnimation = Animation(0, 33, 0.8, true);
mRunAnimation.AddFrameListener(5, [this] {EmitStepSound(); });
mRunAnimation.AddFrameListener(23, [this] {EmitStepSound(); });
mAttackAnimation = Animation(34, 48, 0.78, true);
mAttackAnimation.AddFrameListener(44, [this] { HitPlayer(); });
mWalkAnimation = Animation(49, 76, 0.7, true);
mWalkAnimation.AddFrameListener(51, [this] {EmitStepSound(); });
mWalkAnimation.AddFrameListener(67, [this] {EmitStepSound(); });
mIdleAnimation = Animation(77, 85, 1.5, true);
mSoundMaterialList.push_back(make_unique<SoundMaterial>("data/materials/stone.smat", mBody));
mSoundMaterialList.push_back(make_unique<SoundMaterial>("data/materials/metal.smat", mBody));
mSoundMaterialList.push_back(make_unique<SoundMaterial>("data/materials/wood.smat", mBody));
mSoundMaterialList.push_back(make_unique<SoundMaterial>("data/materials/gravel.smat", mBody));
mSoundMaterialList.push_back(make_unique<SoundMaterial>("data/materials/muddyrock.smat", mBody));
mSoundMaterialList.push_back(make_unique<SoundMaterial>("data/materials/rock.smat", mBody));
mSoundMaterialList.push_back(make_unique<SoundMaterial>("data/materials/grass.smat", mBody));
mSoundMaterialList.push_back(make_unique<SoundMaterial>("data/materials/soil.smat", mBody));
mSoundMaterialList.push_back(make_unique<SoundMaterial>("data/materials/chain.smat", mBody));
mSoundMaterialList.push_back(make_unique<SoundMaterial>("data/materials/mud.smat", mBody));
for(auto & pMat : mSoundMaterialList) {
for(auto & pSound : pMat->GetSoundList()) {
pSound->SetVolume(0.75f);
pSound->SetRolloffFactor(35);
pSound->SetRoomRolloffFactor(35);
pSound->SetReferenceDistance(5);
}
}
// set callback to let enemy 'hear' sounds and properly react to it
ISound::PlayCallback.PlayEvent += [this] { Listen(); };
}
void Enemy::Think() {
const auto & level = mGame->GetLevel();
const auto & player = level->GetPlayer();
// tweakable parameters
const float reachDistanceTolerance = 0.7f;
const float attackPlayerDistance = 3.0f;
const float runSpeed = 3.1f;
const float walkSpeed = 1.0f;
const float doorCheckDistance = 2.8f;
const float nearAttackPlayerDistance = 1.0f;
const float detectionDistance = 16.0f * player->mStealthFactor;
const float pathCheckTolerance = 1.0f;
const float detectionAngle = 45.0f; // in degress
const int lostTime = 5 * 60; // in frames
const bool ignorePlayer = player->IsDead();
const int pathCheckTime = 4 * 60; // in frames
const Vector3 toPlayer = player->mpCamera->mCamera->GetPosition() - (mHead->GetPosition() + mBody->GetLookVector().Normalize() * 0.4f);
const Vector3 toDestination = (mDestination - mBody->GetPosition()).Normalize();
// select move type (also see Enemy::Listen)
const bool eyeContact = player->IsVisibleFromPoint(mHead->GetPosition() + mBody->GetLookVector().Normalize() * 0.4f);
const bool flashLightHighlight = player->mFlashlightEnabled && player->mFlashlight->IsSeePoint(mBody->GetPosition());
const bool playerInSight = abs(toPlayer.Normalized().Angle(toDestination) * 180.0f / M_PI) <= detectionAngle;
const float distanceToPlayer = mBody->GetPosition().Distance(player->GetBody()->GetPosition());
const bool playerCloseEnough = distanceToPlayer <= detectionDistance;
if(!ignorePlayer && ((eyeContact || flashLightHighlight) && playerInSight && playerCloseEnough)) {
mMoveType = MoveType::ChasePlayer;
level->PlayChaseMusic();
mLostTimer = lostTime;
} else if(mLostTimer <= 0) {
if(mMoveType != MoveType::CheckSound) {
mMoveType = MoveType::Patrol;
}
}
--mLostTimer;
// select move speed
const float moveSpeed = (mMoveType == MoveType::ChasePlayer || mForceRun) ? runSpeed : walkSpeed;
// select target
switch(mMoveType) {
case MoveType::Patrol: mTarget = mPatrolPointList[mCurrentPatrolPoint]->mNode->GetPosition(); break;
case MoveType::ChasePlayer: mTarget = player->GetCurrentPosition(); break;
case MoveType::CheckSound: mTarget = mCheckSoundPosition; break;
}
// build path to target
const auto pathBegin = mPathfinder.GetVertexNearestTo(mBody->GetPosition());
const auto pathEnd = mPathfinder.GetVertexNearestTo(mTarget);
if(pathEnd != mTargetVertex) {
// rebuild path only if target vertex has changed
mPathfinder.BuildPath(pathBegin, pathEnd, mCurrentPath);
mTargetVertex = pathEnd;
mCurrentPathPoint = 0;
}
// follow path
if(!mCurrentPath.empty()) {
// if close enough to player, then follow him directly, instead of following path points
if(mCurrentPathPoint == (mCurrentPath.size() - 1) && mMoveType == MoveType::ChasePlayer) {
mDestination = mTarget;
} else {
mDestination = mCurrentPath[mCurrentPathPoint]->mNode->GetPosition();
}
LookAt(mDestination);
// if reach destination
const Vector3 destinationVector = mDestination - mBody->GetPosition();
const float distanceToDestination = destinationVector.Length();
if(distanceToDestination < reachDistanceTolerance) {
// switch to next vertex
++mCurrentPathPoint;
// if reach end of path
if(mCurrentPathPoint >= mCurrentPath.size()) {
mCurrentPathPoint = mCurrentPath.size() - 1;
if(mMoveType == MoveType::Patrol) {
// if patrolling, select next patrol point
++mCurrentPatrolPoint;
if(mCurrentPatrolPoint >= mPatrolPointList.size()) {
mCurrentPatrolPoint = 0;
}
} else if(mMoveType == MoveType::CheckSound) {
// sound checked, switch to patrolling
mMoveType = MoveType::Patrol;
mForceRun = false;
}
// stand still on end of the path
StopInstantly();
if(mMoveType != MoveType::ChasePlayer) {
SetIdleAnimation();
}
}
} else {
// check doors
bool allDoorsAreOpen = true;
for(auto & pDoor : level->GetDoorList()) {
if((pDoor->mDoorNode->GetPosition() - mBody->GetPosition()).Length() < doorCheckDistance) {
// ignore locked doors
if(pDoor->GetState() != Door::State::Opened && !pDoor->IsLocked()) {
allDoorsAreOpen = false;
}
if(pDoor->GetState() == Door::State::Closed && !pDoor->IsLocked()) {
pDoor->Open();
}
}
}
// check gates (door too)
for(auto & pGate : level->GetGateList()) {
if((pGate->GetNode()->GetPosition() - mBody->GetPosition()).Length() < doorCheckDistance) {
if(pGate->GetState() == Gate::State::Closed && !pGate->mLocked) {
pGate->Open();
}
}
}
// check for stuck when patrolling (i.e. because of locked doors)
if(mMoveType == MoveType::Patrol) {
--mPathCheckTimer;
if(mPathCheckTimer <= 0) {
if(mLastCheckPosition.Distance(mBody->GetPosition()) < pathCheckTolerance) {
// select next patrol point
++mCurrentPatrolPoint;
if(mCurrentPatrolPoint >= mPatrolPointList.size()) {
mCurrentPatrolPoint = 0;
}
}
mPathCheckTimer = pathCheckTime;
mLastCheckPosition = mBody->GetPosition();
}
}
bool allowMovement = allDoorsAreOpen;
// select animation type by distance to player
if(mMoveType == MoveType::ChasePlayer) {
if(distanceToPlayer < nearAttackPlayerDistance) {
allowMovement = false;
SetStayAndAttackAnimation();
} else if(distanceToPlayer >= nearAttackPlayerDistance && distanceToPlayer <= attackPlayerDistance) {
SetRunAndAttackAnimation();
} else {
SetRunAnimation();
}
} else {
// just walk
if(mForceRun) {
SetRunAnimation();
} else {
SetWalkAnimation();
}
}
if(allowMovement) {
Move(destinationVector.Normalized(), moveSpeed);
} else {
if(mMoveType != MoveType::ChasePlayer) {
SetIdleAnimation();
}
StopInstantly();
}
}
}
// update animations
mAttackAnimation.Update();
mIdleAnimation.Update();
mRunAnimation.Update();
mWalkAnimation.Update();
}
void Enemy::SetWalkAnimation() {
SetCommonAnimation(&mWalkAnimation);
mRunAnimation.SetEnabled(false);
mWalkAnimation.SetEnabled(true);
mAttackAnimation.SetEnabled(false);
}
void Enemy::SetStayAndAttackAnimation() {
SetCommonAnimation(&mIdleAnimation);
SetTorsoAnimation(&mAttackAnimation);
mAttackAnimation.SetEnabled(true);
}
void Enemy::SetRunAndAttackAnimation() {
SetCommonAnimation(&mAttackAnimation);
SetLegsAnimation(&mRunAnimation);
mRunAnimation.SetEnabled(true);
mWalkAnimation.SetEnabled(false);
mAttackAnimation.SetEnabled(true);
}
void Enemy::SetRunAnimation() {
SetCommonAnimation(&mRunAnimation);
mRunAnimation.SetEnabled(true);
mWalkAnimation.SetEnabled(false);
mAttackAnimation.SetEnabled(false);
}
void Enemy::SetIdleAnimation() {
SetCommonAnimation(&mIdleAnimation);
mAttackAnimation.SetEnabled(false);
}
void Enemy::SetCommonAnimation(Animation * anim) {
mModel->SetAnimation(anim);
}
void Enemy::SetTorsoAnimation(Animation * anim) {
for(auto & torsoPart : mTorsoParts) {
torsoPart->SetAnimation(anim);
}
}
void Enemy::SetLegsAnimation(Animation *pAnim) {
for(auto & rightLegPart : mRightLegParts) {
rightLegPart->SetAnimation(pAnim);
}
for(auto & leftLegPart : mLeftLegParts) {
leftLegPart->SetAnimation(pAnim);
}
}
void Enemy::HitPlayer() {
auto & player = mGame->GetLevel()->GetPlayer();
float distanceToPlayer = (player->GetCurrentPosition() - mBody->GetPosition()).Length();
if(distanceToPlayer < mHitDistance) {
player->Damage(55.0f);
mHitFleshWithAxeSound->Play(true);
}
}
void Enemy::EmitStepSound() {
RayCastResultEx result = mGame->GetEngine()->GetPhysics()->CastRayEx(mBody->GetPosition() + Vector3(0, 0.1, 0), mBody->GetPosition() - Vector3(0, mBodyHeight * 2.2, 0));
if(result.valid) {
for(auto & sMat : mSoundMaterialList) {
shared_ptr<ISound> & snd = sMat->GetRandomSoundAssociatedWith(result.textureName);
if(snd) {
snd->Play(true);
}
}
}
}
void Enemy::FillByNamePattern(vector< shared_ptr<ISceneNode> > & container, const string & pattern) {
std::regex rx(pattern);
for(int i = 0; i < mModel->GetCountChildren(); i++) {
shared_ptr<ISceneNode> child = mModel->GetChild(i);
if(regex_match(child->GetName(), rx)) {
container.push_back(child);
}
}
}
void Enemy::Listen() {
// if hear something before, then check it and only then check new sound
if(mMoveType != MoveType::ChasePlayer) {
const float hearDistance = mGame->GetLevel()->GetPlayer()->mNoiseFactor * 10.0f;
const auto sound = ISound::PlayCallback.Caller;
for(const auto & reactSound : mReactSounds) {
if(sound == reactSound) {
if(sound->GetPosition().Distance(mBody->GetPosition()) < hearDistance) {
mCheckSoundPosition = sound->GetPosition();
if(mMoveType != MoveType::ChasePlayer) {
mMoveType = MoveType::CheckSound;
}
}
}
}
}
}
void Enemy::Serialize(SaveFile & s) {
Vector3 position = mBody->GetPosition();
s & position;
s & mHealth;
s & mLostTimer;
s & mPathCheckTimer;
mBody->SetPosition(position);
}
Enemy::~Enemy() {
ISound::PlayCallback.PlayEvent.Clear();
}
void Enemy::Damage(float dmg) {
// invulnerable
}
inline float RadToDeg(float rad) {
return rad * 180.0f / M_PI;
}
void Enemy::LookAt(const Vector3 & lookAt) {
Vector3 delta = (lookAt - mBody->GetPosition()).Normalize();
mAngleTo = RadToDeg(atan2(delta.x, delta.z));
mAngleTo = mAngleTo > 0 ? mAngleTo : (360.0f + mAngleTo);
mAngle = mAngle > 0 ? mAngle : (360.0f + mAngle);
mAngleTo = fmod(mAngleTo, 360.0f);
mAngle = fmod(mAngle, 360.0f);
if((int)mAngleTo != (int)mAngle) {
float change = 0;
float diff = mAngle - mAngleTo;
if(diff < 0) {
change = 1;
} else {
change = -1;
}
if(fabs(diff) > 180) {
change = -change;
}
mAngle += change * 2;
}
mBody->SetRotation(Quaternion(Vector3(0, 1, 0), mAngle - 90.0f));
// head
//float headAngle = RadToDeg(atan2(delta.y, delta.z));
//mHead->SetRotation(Quaternion(Vector3(1, 0, 0), headAngle));
}
void Enemy::SetNextPatrolPoint() {
mCurrentPatrolPoint++;
if(mCurrentPatrolPoint >= mPatrolPointList.size()) {
mCurrentPatrolPoint = 0;
}
}
void Enemy::ForceCheckSound(Vector3 position) {
mCheckSoundPosition = position;
mMoveType = MoveType::CheckSound;
mForceRun = true;
}
shared_ptr<ISceneNode> Enemy::GetBody() {
return mBody;
}
|
ea8c02af7b4cb7070841adf3233c38334f8ec495 | d7e7ce7d4550b94f830df968e3c9ddbc347529c3 | /UVA10222.cpp | 1e8e273cb9c518735003905fc0faf10d7b396ac6 | [] | no_license | k840304/UVa | 0d9e87e3dd27fd1cb67093b7339b0cd7efde5a30 | e9c98772126b91b7ef8f6b03debe3d39938572d5 | refs/heads/master | 2021-07-19T19:05:08.399739 | 2017-10-24T08:49:18 | 2017-10-24T08:49:18 | 108,100,505 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 280 | cpp | UVA10222.cpp | #include<stdio.h>
main(){
int i;
char c,keyboard[48] = "`1234567890-=qwertyuiop[]\\asdfghjkl;'zxcvbnm,./";
while((c=getchar())>0){
if(c==' '||c=='\n'){
putchar(c);
continue;
}
for(i=0;c!=keyboard[i];i++);
printf("%c",keyboard[i-2]);
}
return 0;
}
|
7f999d3007f5cb27e924ea2483033fd5e2ff6bfd | 2c1125daddf54322ecb286e84fd7542f5715690c | /stcp_socket_tcp.h | eb0b6a20ba955b921098319bf43b6a530a96d6ad | [] | no_license | after1990s/stcp | d7c405fb2ff76d2b7ab38d4ad3ccf62f32b57c26 | 37819e1f9fcd07d97a69b56c4fa6fe21198c349f | refs/heads/master | 2021-01-10T14:55:04.512130 | 2016-03-14T07:28:02 | 2016-03-14T07:28:02 | 51,048,829 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 926 | h | stcp_socket_tcp.h | #ifndef __STCP_SOCKET_TCP_H
#define __STCP_SOCKET_TCP_H
#include "stcp_socket_base.h"
class stcp_socket_tcp: public stcp_socket_base
{
public:
stcp_socket_tcp ();
virtual ~stcp_socket_tcp();
virtual int bind(const struct sockaddr * addr, int addrlen) override;
virtual int listen(int backlog) override;
virtual int accept(struct sockaddr * addr, int addrlen) override;
virtual int connect(struct sockaddr *addr, int addrlen) override;
virtual int recv(void *buf, int size, int flag) override;
virtual int send(const void * buf, int size, int flag) override;
virtual int sendto(const void * buf, int size, int flag);
public:
virtual int on_recv() override;
virtual int on_timer() override;
private:
unsigned int m_passed_sn;//已经确认的sn
unsigned int m_current_sn;//
unsigned int m_avaiable_sn;//允许传输的最大sn
unsigned int m_rtl;
struct sockaddr_in remote_addr;
};
#endif
|
21913400473b479d2c4cf54ffe0fd17147acd6a2 | 583318dcc75237d74ed25b0394d37299d303c0df | /LQAnalysis/80X/Analyzers/ApprovedAnalyses/include/HNDiMuonOptimisation.h | a203190510b9355f3129c7f752cf9553b3261851 | [] | no_license | jalmond/LQanalyzer | 7457096ad8a90cb6e7a14e28170338c1de06cdec | 06292f3a4b46e8a00d72025ff968df1b61bc990e | refs/heads/CatAnalyzer_13TeV | 2020-04-04T07:16:53.746743 | 2018-12-07T00:08:37 | 2018-12-07T00:08:37 | 13,470,313 | 1 | 14 | null | 2018-11-12T09:55:34 | 2013-10-10T12:14:06 | C++ | UTF-8 | C++ | false | false | 1,925 | h | HNDiMuonOptimisation.h | #ifndef HNDiMuonOptimisation_h
#define HNDiMuonOptimisation_h
#include "AnalyzerCore.h"
class HNDiMuonOptimisation : public AnalyzerCore {
public:
//// constructors
HNDiMuonOptimisation();
~HNDiMuonOptimisation();
/// Functions from core
virtual void BeginCycle() throw( LQError );
virtual void BeginEvent()throw( LQError );
virtual void ExecuteEvents()throw( LQError );
virtual void EndCycle()throw( LQError );
virtual void ClearOutputVectors()throw( LQError );
void InitialiseAnalysis() throw( LQError );
void MakeHistograms();
void FillEventCutFlow(TString cut, TString label , float weight);
void RunAnalysis(TString plottag, TString tightelid, TString vetoelid, TString looseelid);
float WeightCFEvent(std::vector<snu::KElectron> electrons, bool runchargeflip);
float IsDiLep(std::vector<snu::KMuon> muons);
bool CheckSignalRegion( bool isss, std::vector<snu::KMuon> muons, std::vector<snu::KElectron> electrons, std::vector<snu::KJet> jets, std::vector<snu::KJet> alljets, TString name, float w);
bool CheckSignalRegionNN( bool isss, std::vector<snu::KMuon> muons, std::vector<snu::KJet> jets, TString name, float w);
void FillTriggerEfficiency(TString cut, float w, TString label, std::vector<TString> list);
float GetTightWeight();
float GetMediumWeight();
void GetSSSignalEfficiency(float w);
void GetOSSignalEfficiency(float w);
void GetTriggEfficiency();
void SignalValidation();
void RunAnalysis();
void OptimiseID(bool isss,bool dilep, bool removed0,float w);
private:
//
// The output variables
//
/// Vectors for output objetcs
std::vector<snu::KMuon> out_muons;
std::vector<snu::KElectron> out_electrons;
ClassDef ( HNDiMuonOptimisation, 1);
};
#endif
|
6e3bc58f285842bcbab11053f2533e3ce300964f | 5e225be17a94110d5f9fe69d7b8ffe4f783e43b5 | /Qt5.9C++/QT5.9Samp/chap06Forms/samp6_4MDI/release/qrc_res.cpp | 348cbb75602412b58e03c462d01e95a74a7fdb19 | [] | no_license | zlocker/QtBookCode | e872bc7c3aba2948f5b7da095741d224d1cddf6c | 3df1964556fbbe890d112c646dcb48e4e8dbff66 | refs/heads/master | 2020-11-27T12:07:49.161414 | 2019-12-23T12:18:00 | 2019-12-23T12:18:00 | 229,431,716 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 17,689 | cpp | qrc_res.cpp | /****************************************************************************
** Resource object code
**
** Created by: The Resource Compiler for Qt version 5.9.1
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/
static const unsigned char qt_resource_data[] = {
// G:/Qt5Book/QT5.9Samp/chap06Forms/samp6_4MDI/images/400.bmp
0x0,0x0,0x0,0x5e,
0x0,
0x0,0x4,0x36,0x78,0x9c,0x73,0xf2,0x35,0x63,0x61,0x0,0x3,0x33,0x20,0xd6,0x0,
0x62,0x1,0x28,0x66,0x64,0x50,0x80,0x48,0x40,0xe5,0x91,0xc1,0xff,0xff,0xff,0xb1,
0x63,0x63,0x6,0xe2,0x30,0x3e,0xfd,0xb8,0xe4,0x88,0x51,0x33,0x10,0xfa,0x89,0xf5,
0x1b,0x3e,0xfd,0x94,0x84,0x1f,0x31,0xfa,0xcf,0xcc,0x4,0xd3,0x69,0x69,0x4,0xec,
0x87,0xaa,0xc3,0x8b,0xb1,0xa9,0x19,0x9,0x7e,0xa6,0x76,0x3a,0xa3,0x34,0x9f,0x90,
0xea,0x67,0x64,0x4c,0x8e,0x9f,0x91,0x30,0x0,0xe,0x7d,0x2c,0xc4,
// G:/Qt5Book/QT5.9Samp/chap06Forms/samp6_4MDI/images/132.bmp
0x0,0x0,0x0,0xec,
0x0,
0x0,0x4,0x36,0x78,0x9c,0x9d,0x93,0xcd,0xd,0xc2,0x30,0xc,0x85,0x8d,0xc4,0x0,
0x8c,0xc0,0x91,0x7b,0xa5,0xe,0xc0,0x9d,0x35,0xb2,0x93,0xd7,0xe8,0x4,0x1d,0xc0,
0x53,0x20,0xf5,0x8c,0x98,0x20,0xf8,0x39,0x71,0xff,0x48,0xda,0x42,0xa5,0x27,0xbb,
0x4e,0x3e,0xbb,0x6e,0x9c,0xfb,0xa3,0x3d,0x93,0x3d,0xad,0xea,0xa6,0xba,0x64,0x9d,
0xe8,0x9a,0x16,0xf2,0xfa,0xfc,0x89,0x31,0x16,0xf5,0x7c,0xbd,0xab,0x6b,0x5b,0xcc,
0x30,0xc,0x24,0x22,0x66,0x8f,0xe6,0x70,0xae,0xeb,0x3a,0x12,0x66,0xe2,0x10,0x4c,
0xf6,0xbe,0x93,0xcb,0xea,0x65,0x6,0x16,0x42,0xdc,0x72,0x20,0xae,0x42,0x1e,0xec,
0x2b,0xf1,0xce,0x45,0x71,0xc9,0x18,0x6f,0x2,0x8f,0xaa,0xd5,0xc7,0xbe,0x89,0x5d,
0xf2,0x41,0x7d,0x88,0x38,0xc5,0x7c,0xed,0x37,0x3e,0x52,0x3,0x5e,0x7d,0x9,0xdf,
0xe7,0xe5,0x7c,0xea,0x3d,0x2c,0x78,0x56,0x9f,0x95,0x47,0xff,0x51,0xd9,0x2d,0xde,
0xec,0xec,0x1b,0x9d,0xef,0xfb,0xde,0xb8,0x92,0xd6,0xf5,0x93,0x3f,0xf1,0xb0,0x35,
0x76,0xcd,0x97,0xfa,0x37,0x1e,0x7d,0xfd,0xc9,0x63,0x76,0x70,0x6e,0x76,0xbe,0x3b,
0xfd,0x97,0x78,0x76,0x1f,0x56,0xb8,0xca,0xd7,0xe6,0x47,0xb2,0xdf,0x8c,0xe7,0xcf,
0xc5,0x19,0xb2,0x7f,0xcc,0x79,0x7e,0x65,0x9a,0x5f,0xcc,0x8d,0xeb,0xc8,0x3d,0x42,
0xbd,0xf9,0xfd,0x39,0xc2,0x7c,0x0,0xbb,0x93,0x5d,0x9d,
// G:/Qt5Book/QT5.9Samp/chap06Forms/samp6_4MDI/images/404.bmp
0x0,0x0,0x0,0x51,
0x0,
0x0,0x4,0x36,0x78,0x9c,0x73,0xf2,0x35,0x63,0x61,0x0,0x3,0x33,0x20,0xd6,0x0,
0x62,0x1,0x28,0x66,0x64,0x50,0x80,0x48,0x40,0xe5,0x91,0xc1,0xff,0xff,0xff,0x29,
0xc3,0xc6,0xc,0xe4,0x63,0x98,0x7e,0x7c,0x66,0x13,0x92,0x1b,0xd5,0x3f,0xaa,0x9f,
0x52,0xfd,0x94,0xa6,0x5f,0x64,0x7c,0x66,0x26,0x98,0x4e,0x4b,0x23,0x42,0xe,0xa4,
0x1f,0x2a,0x86,0x15,0x13,0x92,0xc3,0xe5,0x37,0x12,0x30,0x0,0x54,0xf6,0x64,0x59,
// G:/Qt5Book/QT5.9Samp/chap06Forms/samp6_4MDI/images/200.bmp
0x0,0x0,0x0,0xa1,
0x0,
0x0,0x4,0x36,0x78,0x9c,0x9d,0x52,0xc1,0xd,0x80,0x20,0xc,0xac,0x89,0x3,0x38,
0x82,0x4f,0xff,0x26,0xe,0xe0,0xdf,0x35,0xd8,0x89,0x9d,0xd8,0x9,0x29,0xda,0xd8,
0x54,0xaa,0xa7,0x24,0x17,0x4a,0xef,0xae,0x69,0x81,0x75,0x5b,0x7a,0xaa,0x6b,0x29,
0x98,0xa,0x86,0x13,0x1d,0x8d,0x7,0x71,0xf2,0x7a,0xe5,0x9c,0x29,0x5,0xa2,0x38,
0x1f,0xe0,0x98,0x73,0x2d,0xb4,0x74,0x92,0x13,0x8d,0x57,0xc3,0xd3,0xd9,0xbc,0x70,
0xd6,0xdf,0xd2,0xa0,0x3d,0x20,0x3d,0xea,0xd9,0xf4,0x8c,0x5e,0xde,0xbb,0x23,0xab,
0xb5,0xf0,0x7c,0xb7,0x1a,0x31,0x5e,0xe7,0x12,0xa3,0x5e,0xd1,0xf3,0x1e,0x42,0xa8,
0x90,0xf8,0x8b,0x37,0xa5,0x54,0x21,0x5e,0x8e,0xdf,0x6a,0x58,0x2f,0xeb,0x5b,0x39,
0xd4,0x8b,0x70,0x8,0xff,0xa4,0x41,0xfb,0x43,0xe6,0x43,0xee,0xd8,0xea,0xf5,0x5b,
0xfd,0x79,0xdf,0xfa,0x37,0xd4,0x5f,0xf9,0x52,0x83,0xb1,0x3,0x70,0xe,0x50,0xd3,
// G:/Qt5Book/QT5.9Samp/chap06Forms/samp6_4MDI/images/122.bmp
0x0,0x0,0x0,0x96,
0x0,
0x0,0x4,0x36,0x78,0x9c,0xdd,0x92,0xc1,0x9,0x80,0x30,0xc,0x45,0x2b,0x38,0x80,
0x23,0x78,0xf4,0x2e,0x74,0x0,0xef,0xae,0xd1,0x9d,0xb2,0x53,0x76,0xaa,0xf9,0xda,
0x40,0xa8,0xb5,0x2d,0x5e,0x4,0xb,0xf,0x3,0xf9,0x3f,0xf9,0x56,0xb7,0xdd,0x8f,
0xee,0x3c,0x5e,0x58,0x84,0x29,0x31,0xb8,0xf9,0x6a,0xa4,0xbe,0x3d,0x31,0xc6,0xcf,
0x59,0x89,0x9d,0xb,0xd4,0x45,0x60,0xbe,0x79,0x1,0x49,0x1d,0xb8,0x8e,0xee,0x29,
0xf9,0xd1,0xc7,0x8c,0x1a,0xd0,0xc0,0xf,0xfd,0x5b,0x3f,0xf2,0xdb,0xc,0xea,0xd5,
0x77,0x68,0xf9,0xf1,0xb4,0x19,0xd4,0x8f,0xb9,0xa0,0xc7,0x6f,0x33,0xd8,0xbb,0x43,
0xcd,0x52,0x3f,0x41,0xa6,0xce,0xfd,0x76,0x46,0xf,0xd0,0xaa,0x9f,0xb,0x59,0x4b,
0xfb,0xf3,0x6f,0x67,0xef,0x30,0xd7,0x96,0x76,0xb6,0xfe,0xc1,0x5e,0xed,0x9f,0x38,
0x0,0x46,0xd3,0x80,0x70,
// G:/Qt5Book/QT5.9Samp/chap06Forms/samp6_4MDI/images/204.bmp
0x0,0x0,0x0,0x9e,
0x0,
0x0,0x4,0x36,0x78,0x9c,0xad,0x92,0xc1,0xd,0x80,0x20,0xc,0x45,0x6b,0xe2,0x0,
0x8e,0xe0,0xd1,0xbb,0x89,0x3,0x78,0x77,0xd,0x76,0xea,0x4e,0x5d,0x83,0x39,0xb0,
0x20,0x18,0x4,0xac,0xa0,0x9a,0xbc,0x98,0xf0,0x7d,0xbf,0x9,0x76,0xdd,0x96,0x1e,
0xdc,0xb3,0x30,0x13,0x33,0x78,0x3a,0x18,0x8f,0xc0,0xe7,0xf1,0x63,0x8c,0xb9,0x85,
0x50,0x3d,0xf2,0xe4,0xd7,0xe6,0xa0,0x30,0xa3,0xd6,0x9f,0x91,0x0,0xf9,0x9d,0xd2,
0xe2,0xd3,0x47,0xdf,0x7d,0xff,0xc3,0x7c,0xfa,0x61,0x3e,0x9,0x7e,0xe9,0xff,0x95,
0xe6,0x93,0xe0,0x6b,0xad,0x2f,0xd9,0x9b,0xf9,0xf1,0x99,0x34,0xbf,0x66,0xe7,0x82,
0x5f,0xea,0x48,0xef,0xd4,0xee,0x95,0xe4,0x93,0x2,0xc0,0x39,0x87,0x1a,0x7c,0x77,
0xce,0x2b,0x1c,0x70,0x1d,0x3e,0x2f,0xf9,0xa1,0x23,0x10,0x77,0x58,0x37,0xce,0xa4,
0x7d,0xb8,0xdc,0x33,0x77,0x9c,0x3d,0x2,0x3b,0x16,0xf5,0x79,0x29,
// G:/Qt5Book/QT5.9Samp/chap06Forms/samp6_4MDI/images/100.bmp
0x0,0x0,0x0,0x55,
0x0,
0x0,0x4,0x36,0x78,0x9c,0x73,0xf2,0x35,0x63,0x61,0x0,0x3,0x33,0x20,0xd6,0x0,
0x62,0x1,0x28,0x66,0x64,0x50,0x80,0x48,0x40,0xe5,0x91,0xc1,0xff,0xff,0xff,0xa9,
0x82,0xcf,0xcc,0x4c,0x23,0x9,0x63,0xd3,0x4f,0x8a,0x5d,0xb8,0xc4,0x9e,0x3e,0x7d,
0x8a,0x17,0x13,0xd2,0x3f,0x6a,0xff,0xf0,0xb3,0x1f,0x5b,0xfa,0x24,0xd5,0x7e,0x90,
0x3c,0xc8,0x2c,0x5c,0xea,0x88,0xd1,0x8f,0x4f,0xd,0x39,0x79,0x86,0x1a,0x18,0x0,
0xa8,0x61,0xb7,0x33,
// G:/Qt5Book/QT5.9Samp/chap06Forms/samp6_4MDI/images/208.bmp
0x0,0x0,0x0,0x58,
0x0,
0x0,0x4,0x36,0x78,0x9c,0x73,0xf2,0x35,0x63,0x61,0x0,0x3,0x33,0x20,0xd6,0x0,
0x62,0x1,0x28,0x66,0x64,0x50,0x80,0x48,0x40,0xe5,0x91,0xc1,0xff,0xff,0xff,0x47,
0x31,0x95,0xf0,0x4c,0x63,0x6,0x86,0x33,0x33,0xd3,0xc8,0xd2,0xb,0xd2,0x7,0xd2,
0x8f,0xcb,0x5c,0x74,0x8c,0x4d,0xd,0x21,0xb7,0x51,0xa2,0x1f,0xdd,0xc,0x72,0xec,
0x47,0x36,0x83,0x58,0xff,0x63,0x53,0x8f,0xcb,0x2e,0x98,0x19,0xf8,0xdc,0x39,0x8a,
0x51,0x31,0x0,0xe6,0x5a,0xbc,0x67,
// G:/Qt5Book/QT5.9Samp/chap06Forms/samp6_4MDI/images/230.bmp
0x0,0x0,0x0,0x5e,
0x0,
0x0,0x4,0x36,0x78,0x9c,0x73,0xf2,0x35,0x63,0x61,0x0,0x3,0x33,0x20,0xd6,0x0,
0x62,0x1,0x28,0x66,0x64,0x50,0x80,0x48,0x40,0xe5,0x91,0xc1,0xff,0xff,0xff,0x29,
0xc2,0x67,0xd2,0xd2,0x28,0xc6,0x70,0xf3,0xce,0x9c,0x21,0x89,0x4d,0x35,0xfd,0x20,
0x31,0x32,0xf0,0x60,0x73,0x3f,0x3,0xc3,0x4c,0x14,0x4c,0xaa,0xfb,0xc1,0x7a,0xb0,
0xb0,0x89,0x75,0x3f,0xd9,0xfa,0xa9,0xe4,0xfe,0x81,0xc,0x7f,0x62,0xd3,0x12,0xd1,
0x7a,0xd0,0xf3,0x1a,0x1e,0xb3,0x28,0xc1,0x0,0xe,0x59,0x6a,0xb9,
// G:/Qt5Book/QT5.9Samp/chap06Forms/samp6_4MDI/images/506.bmp
0x0,0x0,0x0,0xab,
0x0,
0x0,0x4,0x36,0x78,0x9c,0xc5,0x92,0xc1,0xd,0xc2,0x30,0xc,0x45,0x83,0xc4,0x0,
0x1d,0x81,0x23,0xf7,0x48,0x1d,0xa0,0x77,0xd6,0xc8,0x4e,0xde,0xc9,0x6b,0x64,0xe,
0x37,0x71,0x62,0xe3,0x52,0x3,0x9,0x17,0x22,0x3d,0x55,0xaa,0xfd,0xf3,0x7f,0xbf,
0xba,0x3d,0xd6,0x6b,0xe0,0xb3,0x16,0xee,0x85,0xa5,0x73,0x9,0xb7,0x36,0xe8,0x73,
0x7b,0x88,0xe8,0xaf,0x40,0xc,0x7,0x10,0xd2,0xd7,0x1d,0xdd,0x45,0x6c,0x14,0xd,
0x26,0x5f,0x2b,0xf0,0x5c,0x89,0xac,0x93,0x59,0xce,0x59,0xdf,0x8f,0xe8,0xc9,0x68,
0x75,0x2e,0x19,0xea,0xdd,0x2f,0x0,0x3f,0x45,0xef,0x67,0x94,0xc,0xd2,0x81,0x72,
0xd0,0xfa,0xde,0xa7,0xc,0x66,0x7,0x7,0xbc,0xdf,0xf5,0xc0,0xdd,0xe,0x7a,0x7b,
0x19,0x66,0xbc,0x4f,0x3d,0x74,0x2d,0xc1,0xb8,0xb7,0xcd,0x50,0x75,0xc2,0xa7,0xff,
0xc2,0xa5,0x7f,0x37,0x41,0x9c,0xf6,0x7e,0xf6,0x9e,0x9a,0x7e,0xd6,0xdb,0x66,0xa8,
0xda,0x1f,0xbc,0x67,0xd8,0x1,0xc6,0x96,0x76,0x74,
// G:/Qt5Book/QT5.9Samp/chap06Forms/samp6_4MDI/images/104.bmp
0x0,0x0,0x0,0x72,
0x0,
0x0,0x4,0x36,0x78,0x9c,0x73,0xf2,0x35,0x63,0x61,0x0,0x3,0x33,0x20,0xd6,0x0,
0x62,0x1,0x28,0x66,0x64,0x50,0x80,0x48,0x40,0xe5,0x91,0xc1,0xff,0xff,0xff,0xa9,
0x82,0x67,0x1a,0x33,0x90,0x8c,0x91,0xf5,0x9e,0x49,0x83,0x60,0x10,0xfb,0xe9,0xd3,
0xa7,0x28,0x6c,0x18,0x46,0x57,0x37,0x98,0xf5,0x63,0xc3,0xc4,0xe8,0x87,0xc9,0x61,
0xc3,0xe8,0x6a,0x70,0xe9,0x27,0x6,0xe3,0x73,0x3f,0x3e,0x8c,0x4f,0x3f,0xb2,0x18,
0xbe,0x74,0x42,0x48,0x3f,0xbe,0xf4,0x42,0x8c,0x7e,0x72,0xec,0x87,0xc5,0xf,0x31,
0xf6,0xe3,0x4a,0xbf,0x94,0xd8,0x4f,0x49,0xfe,0xa1,0x4,0x3,0x0,0x17,0x7e,0xc7,
0xe4,
// G:/Qt5Book/QT5.9Samp/chap06Forms/samp6_4MDI/images/402.bmp
0x0,0x0,0x0,0x4e,
0x0,
0x0,0x4,0x36,0x78,0x9c,0x73,0xf2,0x35,0x63,0x61,0x0,0x3,0x33,0x20,0xd6,0x0,
0x62,0x1,0x28,0x66,0x64,0x50,0x80,0x48,0x40,0xe5,0x91,0xc1,0xff,0xff,0xff,0x29,
0xc7,0xc6,0xc,0xe4,0x63,0x98,0x7e,0x72,0xed,0x1d,0x2e,0xfa,0x29,0xd,0x3f,0x62,
0xf1,0x99,0x99,0x60,0x3a,0x2d,0xd,0xc9,0x7e,0xa8,0x18,0xc9,0x18,0xa4,0x6f,0xb0,
0x84,0xdf,0x40,0xeb,0x1f,0xa2,0xf1,0x7,0x0,0x51,0x38,0x2d,0xf6,
// G:/Qt5Book/QT5.9Samp/chap06Forms/samp6_4MDI/images/406.bmp
0x0,0x0,0x0,0x52,
0x0,
0x0,0x4,0x36,0x78,0x9c,0x73,0xf2,0x35,0x63,0x61,0x0,0x3,0x33,0x20,0xd6,0x0,
0x62,0x1,0x28,0x66,0x64,0x50,0x80,0x48,0x40,0xe5,0x91,0xc1,0xff,0xff,0xff,0x29,
0xc3,0xc6,0xc,0xe4,0x63,0x98,0x7e,0x7c,0x66,0x13,0x92,0x1b,0xe,0xfa,0x29,0xd,
0x3f,0x64,0x7c,0x66,0x26,0x98,0x4e,0x4b,0x23,0x42,0xe,0xa4,0x1f,0x2a,0x86,0x15,
0x13,0x92,0x1b,0x2c,0xe1,0x37,0xd0,0xfa,0x87,0x70,0xfc,0x1,0x0,0x7c,0x91,0x25,
0x98,
// G:/Qt5Book/QT5.9Samp/chap06Forms/samp6_4MDI/images/202.bmp
0x0,0x0,0x0,0x76,
0x0,
0x0,0x4,0x36,0x78,0x9c,0x73,0xf2,0x35,0x63,0x61,0x0,0x3,0x33,0x20,0xd6,0x0,
0x62,0x1,0x28,0x66,0x64,0x50,0x80,0x48,0x40,0xe5,0x91,0xc1,0xff,0xff,0xff,0xb1,
0x62,0xe3,0x99,0x67,0x18,0x18,0xd2,0x66,0xe2,0xc5,0xb8,0xf4,0xc2,0xf4,0xcf,0x4,
0xd2,0xb8,0xf0,0x70,0xd2,0x7f,0x66,0x66,0x1a,0x6,0x26,0x55,0x3f,0xa5,0xf6,0x13,
0xa3,0x1f,0x24,0x86,0x8c,0xc9,0xd1,0x7f,0x6,0x4b,0xd8,0x91,0xa2,0x1f,0x5b,0xb8,
0xe3,0xd2,0x8f,0xd,0x63,0x8b,0x2b,0x6c,0xfa,0x29,0x95,0x47,0x8f,0x4f,0x72,0xf4,
0x3f,0x7d,0xfa,0x94,0xa0,0x5e,0x42,0xf6,0x13,0xd2,0x8b,0x2b,0xfd,0x11,0xab,0x17,
0x0,0xda,0x4,0x87,0x4e,
// G:/Qt5Book/QT5.9Samp/chap06Forms/samp6_4MDI/images/206.bmp
0x0,0x0,0x0,0x58,
0x0,
0x0,0x4,0x36,0x78,0x9c,0x73,0xf2,0x35,0x63,0x61,0x0,0x3,0x33,0x20,0xd6,0x0,
0x62,0x1,0x28,0x66,0x64,0x50,0x80,0x48,0x40,0xe5,0x91,0xc1,0xff,0xff,0xff,0x47,
0x31,0x9d,0xf0,0x99,0x99,0x69,0xc,0x33,0x8d,0xb1,0x87,0x39,0x48,0x1c,0x1d,0xe3,
0x52,0x7,0x32,0x87,0x90,0x7e,0x7c,0xee,0xc0,0x26,0x4f,0xac,0x5e,0x42,0xfa,0x71,
0xc9,0x13,0xa3,0x1f,0x97,0x79,0xc4,0xf8,0x1f,0x9f,0x5d,0xc8,0x98,0x14,0xbd,0x23,
0x1,0x3,0x0,0x9f,0x93,0xbc,0x67,
// G:/Qt5Book/QT5.9Samp/chap06Forms/samp6_4MDI/images/128.bmp
0x0,0x0,0x0,0xa1,
0x0,
0x0,0x4,0x36,0x78,0x9c,0xd5,0x92,0xd1,0x9,0xc3,0x30,0xc,0x44,0x55,0xe8,0x0,
0x1d,0xa1,0x9f,0xfd,0xf,0x64,0x80,0xfe,0x77,0xd,0xef,0x74,0x3b,0x69,0x27,0x55,
0x67,0x49,0x90,0x9a,0xa4,0x24,0x85,0x52,0x6a,0x78,0x58,0xb6,0xef,0x6c,0x49,0xf8,
0xfe,0x98,0xcf,0xd2,0xc7,0xec,0xdc,0x9c,0x4b,0x72,0x92,0x6b,0x1c,0xe4,0xf9,0x72,
0x98,0xd9,0xcf,0x99,0xa0,0x22,0xd,0xbb,0x19,0xbd,0x4d,0x63,0x86,0xaf,0x19,0x6f,
0x51,0x9a,0xe5,0x1d,0xa3,0xff,0x1d,0xd4,0xfd,0xb3,0x1f,0xec,0x3,0x2,0xd5,0x83,
0x7e,0xd7,0xc8,0x44,0x9d,0xd3,0x22,0x6,0x5e,0x7d,0x8c,0xb7,0x80,0xa6,0x57,0x13,
0x58,0xee,0xed,0xab,0xbb,0xbf,0xe9,0x68,0xbd,0xd5,0x82,0xaa,0x61,0xf4,0xac,0xe5,
0xc0,0x9c,0xab,0x6,0xce,0xd5,0x3,0x5b,0xd1,0x8f,0x7f,0xb4,0xd7,0x9b,0x3d,0x60,
0xff,0x90,0xf9,0x1f,0xfd,0xeb,0xf4,0x7c,0xe2,0xfb,0x16,0x4f,0x43,0xcf,0x68,0xbb,
};
static const unsigned char qt_resource_name[] = {
// images
0x0,0x6,
0x7,0x3,0x7d,0xc3,
0x0,0x69,
0x0,0x6d,0x0,0x61,0x0,0x67,0x0,0x65,0x0,0x73,
// 400.bmp
0x0,0x7,
0x7,0x33,0x49,0x20,
0x0,0x34,
0x0,0x30,0x0,0x30,0x0,0x2e,0x0,0x62,0x0,0x6d,0x0,0x70,
// 132.bmp
0x0,0x7,
0x4,0x65,0x49,0x20,
0x0,0x31,
0x0,0x33,0x0,0x32,0x0,0x2e,0x0,0x62,0x0,0x6d,0x0,0x70,
// 404.bmp
0x0,0x7,
0x7,0x37,0x49,0x20,
0x0,0x34,
0x0,0x30,0x0,0x34,0x0,0x2e,0x0,0x62,0x0,0x6d,0x0,0x70,
// 200.bmp
0x0,0x7,
0x5,0x33,0x49,0x20,
0x0,0x32,
0x0,0x30,0x0,0x30,0x0,0x2e,0x0,0x62,0x0,0x6d,0x0,0x70,
// 122.bmp
0x0,0x7,
0x4,0x55,0x49,0x20,
0x0,0x31,
0x0,0x32,0x0,0x32,0x0,0x2e,0x0,0x62,0x0,0x6d,0x0,0x70,
// 204.bmp
0x0,0x7,
0x5,0x37,0x49,0x20,
0x0,0x32,
0x0,0x30,0x0,0x34,0x0,0x2e,0x0,0x62,0x0,0x6d,0x0,0x70,
// 100.bmp
0x0,0x7,
0x4,0x33,0x49,0x20,
0x0,0x31,
0x0,0x30,0x0,0x30,0x0,0x2e,0x0,0x62,0x0,0x6d,0x0,0x70,
// 208.bmp
0x0,0x7,
0x5,0x3b,0x49,0x20,
0x0,0x32,
0x0,0x30,0x0,0x38,0x0,0x2e,0x0,0x62,0x0,0x6d,0x0,0x70,
// 230.bmp
0x0,0x7,
0x5,0x63,0x49,0x20,
0x0,0x32,
0x0,0x33,0x0,0x30,0x0,0x2e,0x0,0x62,0x0,0x6d,0x0,0x70,
// 506.bmp
0x0,0x7,
0x8,0x39,0x49,0x20,
0x0,0x35,
0x0,0x30,0x0,0x36,0x0,0x2e,0x0,0x62,0x0,0x6d,0x0,0x70,
// 104.bmp
0x0,0x7,
0x4,0x37,0x49,0x20,
0x0,0x31,
0x0,0x30,0x0,0x34,0x0,0x2e,0x0,0x62,0x0,0x6d,0x0,0x70,
// 402.bmp
0x0,0x7,
0x7,0x35,0x49,0x20,
0x0,0x34,
0x0,0x30,0x0,0x32,0x0,0x2e,0x0,0x62,0x0,0x6d,0x0,0x70,
// 406.bmp
0x0,0x7,
0x7,0x39,0x49,0x20,
0x0,0x34,
0x0,0x30,0x0,0x36,0x0,0x2e,0x0,0x62,0x0,0x6d,0x0,0x70,
// 202.bmp
0x0,0x7,
0x5,0x35,0x49,0x20,
0x0,0x32,
0x0,0x30,0x0,0x32,0x0,0x2e,0x0,0x62,0x0,0x6d,0x0,0x70,
// 206.bmp
0x0,0x7,
0x5,0x39,0x49,0x20,
0x0,0x32,
0x0,0x30,0x0,0x36,0x0,0x2e,0x0,0x62,0x0,0x6d,0x0,0x70,
// 128.bmp
0x0,0x7,
0x4,0x5b,0x49,0x20,
0x0,0x31,
0x0,0x32,0x0,0x38,0x0,0x2e,0x0,0x62,0x0,0x6d,0x0,0x70,
};
static const unsigned char qt_resource_struct[] = {
// :
0x0,0x0,0x0,0x0,0x0,0x2,0x0,0x0,0x0,0x1,0x0,0x0,0x0,0x1,
0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,
// :/images
0x0,0x0,0x0,0x0,0x0,0x2,0x0,0x0,0x0,0x1,0x0,0x0,0x0,0x2,
0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,
// :/images/images
0x0,0x0,0x0,0x0,0x0,0x2,0x0,0x0,0x0,0x10,0x0,0x0,0x0,0x3,
0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,
// :/images/images/100.bmp
0x0,0x0,0x0,0x8a,0x0,0x1,0x0,0x0,0x0,0x1,0x0,0x0,0x3,0x88,
0x0,0x0,0x1,0x58,0xd1,0xf4,0x8b,0x8d,
// :/images/images/104.bmp
0x0,0x0,0x0,0xda,0x0,0x1,0x0,0x0,0x0,0x1,0x0,0x0,0x5,0x4e,
0x0,0x0,0x1,0x58,0xd1,0xf4,0xad,0xad,
// :/images/images/122.bmp
0x0,0x0,0x0,0x62,0x0,0x1,0x0,0x0,0x0,0x1,0x0,0x0,0x2,0x4c,
0x0,0x0,0x1,0x58,0xd1,0xf5,0x73,0xe,
// :/images/images/128.bmp
0x0,0x0,0x1,0x3e,0x0,0x1,0x0,0x0,0x0,0x1,0x0,0x0,0x7,0x42,
0x0,0x0,0x1,0x58,0xd1,0xf5,0x9f,0x1d,
// :/images/images/132.bmp
0x0,0x0,0x0,0x26,0x0,0x1,0x0,0x0,0x0,0x1,0x0,0x0,0x0,0x62,
0x0,0x0,0x1,0x58,0xd1,0xf5,0xbd,0x85,
// :/images/images/200.bmp
0x0,0x0,0x0,0x4e,0x0,0x1,0x0,0x0,0x0,0x1,0x0,0x0,0x1,0xa7,
0x0,0x0,0x1,0x58,0xd1,0xf6,0x5a,0x31,
// :/images/images/202.bmp
0x0,0x0,0x1,0x16,0x0,0x1,0x0,0x0,0x0,0x1,0x0,0x0,0x6,0x6c,
0x0,0x0,0x1,0x58,0xd1,0xf6,0x68,0x44,
// :/images/images/204.bmp
0x0,0x0,0x0,0x76,0x0,0x1,0x0,0x0,0x0,0x1,0x0,0x0,0x2,0xe6,
0x0,0x0,0x1,0x58,0xd1,0xf6,0x78,0xa9,
// :/images/images/206.bmp
0x0,0x0,0x1,0x2a,0x0,0x1,0x0,0x0,0x0,0x1,0x0,0x0,0x6,0xe6,
0x0,0x0,0x1,0x58,0xd1,0xf6,0x87,0x97,
// :/images/images/208.bmp
0x0,0x0,0x0,0x9e,0x0,0x1,0x0,0x0,0x0,0x1,0x0,0x0,0x3,0xe1,
0x0,0x0,0x1,0x58,0xd1,0xf6,0x98,0x97,
// :/images/images/230.bmp
0x0,0x0,0x0,0xb2,0x0,0x1,0x0,0x0,0x0,0x1,0x0,0x0,0x4,0x3d,
0x0,0x0,0x1,0x58,0xd1,0xf7,0x3b,0x5b,
// :/images/images/400.bmp
0x0,0x0,0x0,0x12,0x0,0x1,0x0,0x0,0x0,0x1,0x0,0x0,0x0,0x0,
0x0,0x0,0x1,0x58,0xd1,0xfa,0xda,0xe9,
// :/images/images/402.bmp
0x0,0x0,0x0,0xee,0x0,0x1,0x0,0x0,0x0,0x1,0x0,0x0,0x5,0xc4,
0x0,0x0,0x1,0x58,0xd1,0xfa,0xe9,0xe7,
// :/images/images/404.bmp
0x0,0x0,0x0,0x3a,0x0,0x1,0x0,0x0,0x0,0x1,0x0,0x0,0x1,0x52,
0x0,0x0,0x1,0x58,0xd1,0xfa,0xf9,0x71,
// :/images/images/406.bmp
0x0,0x0,0x1,0x2,0x0,0x1,0x0,0x0,0x0,0x1,0x0,0x0,0x6,0x16,
0x0,0x0,0x1,0x58,0xd1,0xfb,0xd,0x5e,
// :/images/images/506.bmp
0x0,0x0,0x0,0xc6,0x0,0x1,0x0,0x0,0x0,0x1,0x0,0x0,0x4,0x9f,
0x0,0x0,0x1,0x58,0xd1,0xfc,0xa8,0xf2,
};
#ifdef QT_NAMESPACE
# define QT_RCC_PREPEND_NAMESPACE(name) ::QT_NAMESPACE::name
# define QT_RCC_MANGLE_NAMESPACE0(x) x
# define QT_RCC_MANGLE_NAMESPACE1(a, b) a##_##b
# define QT_RCC_MANGLE_NAMESPACE2(a, b) QT_RCC_MANGLE_NAMESPACE1(a,b)
# define QT_RCC_MANGLE_NAMESPACE(name) QT_RCC_MANGLE_NAMESPACE2( \
QT_RCC_MANGLE_NAMESPACE0(name), QT_RCC_MANGLE_NAMESPACE0(QT_NAMESPACE))
#else
# define QT_RCC_PREPEND_NAMESPACE(name) name
# define QT_RCC_MANGLE_NAMESPACE(name) name
#endif
#ifdef QT_NAMESPACE
namespace QT_NAMESPACE {
#endif
bool qRegisterResourceData(int, const unsigned char *, const unsigned char *, const unsigned char *);
bool qUnregisterResourceData(int, const unsigned char *, const unsigned char *, const unsigned char *);
#ifdef QT_NAMESPACE
}
#endif
int QT_RCC_MANGLE_NAMESPACE(qInitResources_res)();
int QT_RCC_MANGLE_NAMESPACE(qInitResources_res)()
{
QT_RCC_PREPEND_NAMESPACE(qRegisterResourceData)
(0x2, qt_resource_struct, qt_resource_name, qt_resource_data);
return 1;
}
int QT_RCC_MANGLE_NAMESPACE(qCleanupResources_res)();
int QT_RCC_MANGLE_NAMESPACE(qCleanupResources_res)()
{
QT_RCC_PREPEND_NAMESPACE(qUnregisterResourceData)
(0x2, qt_resource_struct, qt_resource_name, qt_resource_data);
return 1;
}
namespace {
struct initializer {
initializer() { QT_RCC_MANGLE_NAMESPACE(qInitResources_res)(); }
~initializer() { QT_RCC_MANGLE_NAMESPACE(qCleanupResources_res)(); }
} dummy;
}
|
2ee709749c038f6b8271b912cc23b4c51e1e795d | 97e0a4bba7bea5689a20d019f5523d5407bc606a | /CompCoding/HackerRank/search/sherlockAndArray.cpp | cd2a127a9b1eee3ef8b84ddb5a91d1223241d737 | [] | no_license | rathore-rahul/Coding-Practice | a5fef06edaf500f337073b930b973c03ca5b5228 | 168320bb089304fb377e94053214b1aeaa80cef9 | refs/heads/master | 2020-11-24T19:00:40.241253 | 2019-12-16T04:20:09 | 2019-12-16T04:20:09 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 879 | cpp | sherlockAndArray.cpp | #include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
#define rep(i,n) for(int i = 0; i < n ;i++)
int main() {
int t,n;
cin>>t;
while(t--){
cin>>n;
vector<int> val(n);
rep(i,n){
cin>>val[i];
if(i != 0)
val[i] += val[i-1];
}
vector<int> left(n);
vector<int> right(n);
left[0] = 0;
right[n-1] = 0;
left[n-1] = val[n-2];
right[0] = val[n-1] - val[0];
for(int i = 1; i<n-1 ;i++){
left[i] = val[i-1];
right[i] = val[n-1] - val[i];
}
bool flag = false;
rep(i,n){
if(left[i] == right[i])
{flag = true; break;}
}
if(flag)
cout<<"YES\n";
else
cout<<"NO\n";
}
}
|
efd704edc332c8aef29e5065d21127b63bce83d0 | 49fbb855094bd1fc93ec7fddaec0296858474c15 | /KinectPictureSynthesis/MFC类/picture10/picture8/picture8Dlg.h | 82a10899192bc4f8a1c5a6244e73aae70d3b7060 | [] | no_license | TastSong/KinectPictureSynthesis | 714c8fe81b7507349c0eba8977c15871f22a53dd | 56a5fb2350fac4fcc7873ae45928d02c51eedc6f | refs/heads/master | 2021-08-22T23:12:45.339762 | 2017-12-01T15:22:23 | 2017-12-01T15:22:23 | 112,754,723 | 2 | 0 | null | null | null | null | GB18030 | C++ | false | false | 1,048 | h | picture8Dlg.h |
// picture8Dlg.h : 头文件
//
#pragma once
#include "Dlg2.h" //将二级窗口的头文件包括进来
#include <Kinect.h>
#include "MouseControl.h"
#include "include.h"
// Cpicture8Dlg 对话框
class Cpicture8Dlg : public CDialogEx
{
// 构造
public:
Cpicture8Dlg(CWnd* pParent = NULL); // 标准构造函数
int isPrint; //标记是否进入打印模式
//Dlg2 *myDlg; //创建二级窗口的对象
//Dlg2 myDlg;
// 对话框数据
enum { IDD = IDD_PICTURE8_DIALOG };
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 支持
// 实现
protected:
HICON m_hIcon;
// 生成的消息映射函数
virtual BOOL OnInitDialog();
afx_msg void OnSysCommand(UINT nID, LPARAM lParam);
afx_msg void OnPaint();
afx_msg HCURSOR OnQueryDragIcon();
DECLARE_MESSAGE_MAP()
public:
afx_msg void OnBnClickedCheck1();
afx_msg void OnBnClickedButton1();
// void doDrawPicture(void);
afx_msg void OnTimer(UINT_PTR nIDEvent);
public:
IKinectSensor *kinect = NULL;
CMouseControl mC;
int m_nNumberScenarios;
};
|
09504fd64cbf849ccca1e2d0604c9114d0d8f5ad | 9b21d5b495a5318f349eab3c7c8c6e979fc5b77a | /Hackerrank/ll_binary.cpp | bc8d621ea0996d0a1064f3ae7c3fa83b29229673 | [] | no_license | raokartikkumar24/CodingCompetition | 95c52f916e624ec553ed6b7666f1478269c89cb1 | 3b77f72b81d833ed56f304e5cbac70fed27da5b3 | refs/heads/master | 2021-06-03T15:35:24.314843 | 2020-09-29T07:33:39 | 2020-09-29T07:33:39 | 23,706,876 | 1 | 1 | null | 2015-07-06T11:33:39 | 2014-09-05T14:55:44 | C++ | UTF-8 | C++ | false | false | 796 | cpp | ll_binary.cpp | long long getNumber(Node *head) {
int count = 0;
long long number = 0;
Node *temp = head;
while( head )
{
count++;
head = head->next;
}
if( count == 1 ) {
if( temp->data == 0)
return 0;
else
return 2;
}
int *arr = new int[count];
for(int i = 0 ; i < count ; i++)
{
arr[i] = temp->data;
temp = temp->next;
}
int c = count ;
for(int i = 0 ; i < count ; i++)
{
long long mul = 1;
for(int j = 0 ; j < c ;j++)
mul = mul * 2;
c--;
number += arr[i]*mul;
}
return number/2;
} |
196696a5557a72083b0449c31df10ed0cfcccbda | fb8178de6cc8ff4245842e1cd4edbe4ce52b557b | /pessoa_e_cadastro/src/main.cpp | 59f0125307c340e6101600d972da088547418529 | [] | no_license | Renato-GS/LP1-2021.2-Lista2 | 523bb02a126ab138b85ef1cc42aea8a6c151a054 | f472fe85794134cea45df956a5d6b778a5cf930d | refs/heads/main | 2023-09-03T01:57:19.112243 | 2021-11-08T23:51:32 | 2021-11-08T23:51:32 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 112 | cpp | main.cpp |
#include "Pessoa.hpp"
#include "Cadastro.hpp"
int main(){
//TODO: seu programa
return EXIT_SUCCESS;
} |
26bc1b68bce6286ee093a487af38b62f6a6ca596 | 0532e09d56b586ab10fbb623c0386994e40ab87d | /Professional C++, 5th Edition/Code/c01_code/28_References/03_ReferenceParameters.cpp | 2cce5775c34f9bc0ced0de11c2864eaf1171cf12 | [] | no_license | chosungmann/book-examples | fae7245e8071f1326033971d0c108b61c7739f2f | 368597886374131856aff3ea819dd5432a8de27b | refs/heads/main | 2023-07-19T18:58:21.009598 | 2023-07-17T07:24:52 | 2023-07-17T07:24:52 | 115,195,777 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 448 | cpp | 03_ReferenceParameters.cpp | void addOneA(int i)
{
i++; // Has no real effect because this is a copy of the original
}
void addOneB(int& i)
{
i++; // Actually changes the original variable
}
void swap(int& first, int& second)
{
int temp{ first };
first = second;
second = temp;
}
int main()
{
int myInt{ 7 };
addOneA(myInt);
addOneB(myInt);
int x{ 5 }, y{ 6 };
swap(x, y);
// swap(3, 4); // DOES NOT COMPILE
int* xp{ &x }, * yp{ &y };
swap(*xp, *yp);
}
|
71aa22be998cf34d060c389f90f6c2aa6bb824f4 | 8a0811f7aa3a71f9d6aaa4bfd601a575aa9858d6 | /infomaintaindlg.cpp | 8d18c596df171f1fb4a9fd5706c4fa0334b1b687 | [] | no_license | mkw18/Crowdsourcing-translation-platform | cef05ecdc58fa750eb78a90d256cdf34a2c1790b | e5d142871982dcdef45a2485fb11c2b836ef821a | refs/heads/master | 2022-11-18T22:55:45.784856 | 2020-07-22T13:37:26 | 2020-07-22T13:37:26 | 281,687,035 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,780 | cpp | infomaintaindlg.cpp | /**********************************************************************************************************************
【文件名】 infomaintaindlg.cpp
【功能模块和目的】 InfoMaintaindlg类中成员函数的实现, 包括槽函数、接口函数
【开发者及日期】 门恺文2019.7.24
【更改记录】
**********************************************************************************************************************/
#include "infomaintaindlg.h"
#include "ui_infomaintaindlg.h"
#include <QMessageBox>
#include "depositdlg.h"
/***********************************************************************************************************************
【函数名称】 InfoMaintaindlg()
【函数功能】 类InfoMaintaindlg的构造函数,在创建对象时被调用
【参数】 QWidget *parent,输入参数
【返回值】 无
【开发者及日期】 门恺文 2019.7.24
【更改记录】
***********************************************************************************************************************/
InfoMaintaindlg::InfoMaintaindlg(QWidget *parent) :
QDialog(parent),
ui(new Ui::InfoMaintaindlg)
{
ui->setupUi(this);
}
/***********************************************************************************************************************
【函数名称】 ~InfoMaintaindlg()
【函数功能】 类InfoMaintaindlg的析构函数,在对象被销毁时调用
【参数】 ui
【返回值】 无
【开发者及日期】 门恺文2019.7.24
【更改记录】
***********************************************************************************************************************/
InfoMaintaindlg::~InfoMaintaindlg()
{
delete ui;
}
/***********************************************************************************************************************
【函数名称】 on_feedbackBtn_clicked()
【函数功能】 提交修改信息的槽函数
【参数】 无
【返回值】 无
【开发者及日期】 门恺文2019.7.24
【更改记录】
***********************************************************************************************************************/
void InfoMaintaindlg::on_acceptBtn_clicked()
{
//获取界面上的数据
//身份证号填写后不得修改
QString id;
if (userInfoList[userCode].getId().isEmpty())
{
id = ui->lineEditId->text();
}
else
{
ui->lineEditId->setFocusPolicy(Qt::NoFocus);
id = userInfoList[userCode].getId();
}
QString username = ui->lineEditUsername->text();
QString phone = ui->lineEditPhone->text();
QString name = ui->lineEditName->text();
QString email = ui->lineEditEmail->text();
QString password = ui->lineEditPassword->text();
QString comfirm = ui->lineEditComfirm->text();
for (QList<User>::iterator i = userInfoList.begin(); i < userInfoList.end(); i++)
{
//用户名,手机号,邮箱不可与他人重复,但可不改
if ((i->getUserName() == username) && (username != userInfoList[userCode].getUserName()))
{
QMessageBox::warning(this, "warning", tr("该用户名已存在"), QMessageBox::Yes);
ui->lineEditUsername->clear();
ui->lineEditUsername->setFocus();
return;
}
if ((i->getMobilePhone() == phone) && (phone != userInfoList[userCode].getMobilePhone()))
{
QMessageBox::warning(this, "warning", tr("该手机号已注册"), QMessageBox::Yes);
ui->lineEditPhone->clear();
ui->lineEditPhone->setFocus();
return;
}
if ((i->getEmail() == email) && (email != userInfoList[userCode].getEmail()))
{
QMessageBox::warning(this, "warning", tr("该邮箱已注册"), QMessageBox::Yes);
ui->lineEditEmail->clear();
ui->lineEditEmail->setFocus();
return;
}
}
//用户名,手机号,密码,确认密码为必填项
if ((username.isEmpty()) || (phone.isEmpty()) || (password.isEmpty()) || (comfirm.isEmpty()))
{
QMessageBox::warning(this, "warning", tr("您有信息尚未填写"), QMessageBox::Yes);
return;
}
if((!id.isEmpty()) && (id.length() != 18))
{
QMessageBox::warning(this, tr("warning"), tr("身份证号格式错误"), QMessageBox::Ok);
return;
}
//密码与确认密码需一致
if (password != comfirm)
{
QMessageBox::warning(this, "warning", tr("密码与确认密码不一致"), QMessageBox::Yes);
ui->lineEditComfirm->clear();
ui->lineEditComfirm->setFocus();
return;
}
//更改信息
userInfoList[userCode].setId(id);
userInfoList[userCode].setName(name);
userInfoList[userCode].setEmail(email);
userInfoList[userCode].setPassword(password);
userInfoList[userCode].setUserName(username);
userInfoList[userCode].setMobilePhone(phone);
//更改成功
QMessageBox::information(this, tr("提示"), tr("更改信息成功"), QMessageBox::Yes);
accept();
}
/***********************************************************************************************************************
【函数名称】 on_depositBtn_clicked()
【函数功能】 用户进入充值的槽函数
【参数】 无
【返回值】 无
【开发者及日期】 门恺文2019.7.24
【更改记录】
***********************************************************************************************************************/
void InfoMaintaindlg::on_depositBtn_clicked()
{
//进入充值界面
Depositdlg dlg;
dlg.setUserCode(userCode);
dlg.exec();
//实时显示余额变化
ui->lineEditBalance->setText(QString::number(userInfoList[userCode].getBalance()));
}
/***********************************************************************************************************************
【函数名称】 setUserCode()
【函数功能】 成员userCode的设置函数
【参数】 value, int, 输入参数
【返回值】 无
【开发者及日期】 门恺文2019.7.24
【更改记录】
***********************************************************************************************************************/
void InfoMaintaindlg::setUserCode(int value)
{
userCode = value;
//获取用户编号后初始化
ui->lineEditUsername->setText(userInfoList[userCode].getUserName());
ui->lineEditId->setText(userInfoList[userCode].getId());
ui->lineEditPhone->setText(userInfoList[userCode].getMobilePhone());
ui->lineEditPoints->setText(QString::number(userInfoList[userCode].getPoint()));
ui->lineEditBalance->setText(QString::number(userInfoList[userCode].getBalance()));
ui->lineEditPassword->setText(userInfoList[userCode].getPassword());
ui->lineEditComfirm->setText(userInfoList[userCode].getPassword());
ui->lineEditName->setText(userInfoList[userCode].getName());
ui->lineEditEmail->setText(userInfoList[userCode].getEmail());
//身份证号码不可更改
if (!userInfoList[userCode].getId().isEmpty())
{
ui->lineEditId->setFocusPolicy(Qt::NoFocus);
}
//显示头像
QString avatar = userInfoList[userCode].getSAvatar();
QImage* img = new QImage;
if (!img->load(avatar))
{
ui->labAvatar->setText(tr("头像加载失败"));
delete img;
}
else {
int height = ui->labAvatar->height();
int width = ui->labAvatar->width();
ui->labAvatar->setPixmap(QPixmap::fromImage(img->scaled(width, height,
Qt::IgnoreAspectRatio, Qt::SmoothTransformation)));
}
}
/***********************************************************************************************************************
【函数名称】 on_avatarBtn_clicked()
【函数功能】 更改头像的槽函数
【参数】 无
【返回值】 无
【开发者及日期】 门恺文2019.7.24
【更改记录】
***********************************************************************************************************************/
void InfoMaintaindlg::on_avatarBtn_clicked()
{
QString avatar = ui->avatarlineEdit->text();
userInfoList[userCode].setSAvatar(avatar);
QImage* img = new QImage;
if (!img->load(avatar))
{
//没能加载出头像的情况
ui->labAvatar->setText(tr("头像加载失败"));
delete img;
}
else {
int height = ui->labAvatar->height();
int width = ui->labAvatar->width();
ui->labAvatar->setPixmap(QPixmap::fromImage(img->scaled(width, height,
Qt::IgnoreAspectRatio, Qt::SmoothTransformation)));
}
}
|
02413736f83bfa606ebd1ab21625a86c2e07e252 | be62ca7d0fc62cd8d1b8a54ffe7050b2d80ba16c | /UnitTest7.1ab/UnitTest7.1ab.cpp | 3ff485d440f6277b34bb8f78c0f9057706a384b6 | [] | no_license | Senichkaa/laboratorna-7.2 | b7485f945611ad15574fee5843b7eecb79872d0f | 9419defabd1051d36a8ec2bb5c770567e863b103 | refs/heads/main | 2023-08-29T17:30:13.208278 | 2021-11-16T14:48:24 | 2021-11-16T14:48:24 | 428,676,773 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 486 | cpp | UnitTest7.1ab.cpp | #include "pch.h"
#include "CppUnitTest.h"
#include "..\pr.7.1ab\Source.cpp"
using namespace Microsoft::VisualStudio::CppUnitTestFramework;
namespace UnitTest71ab
{
TEST_CLASS(UnitTest71ab)
{
public:
TEST_METHOD(TestMethod1)
{
int** tArr = new int* [2];
for (int i = 0; i < 2;) tArr[i++] = new int[2];
{
tArr[0][0] = 1;
tArr[0][1] = 0;
tArr[1][0] = -1;
tArr[1][1] = -2;
Assert::AreEqual(0, tArr[0][1]);
}
}
};
}
|
02ed1cbdd921d6ba582d7730ff7841bd7e261bb9 | 55fd6d3a6a53f9e9a124a9d3a16eb6a9e412c705 | /warshipsBoard.h | 6e1f93711bf20e2f8abde8e340d598d4ddcf9133 | [] | no_license | is108/Warships | 031210c2420632c771f8df8bfa73f03dc72dcd26 | ad65c442c733cd698408ccb2cbfcaec5ea9fdafe | refs/heads/master | 2020-03-25T19:45:58.368535 | 2018-08-09T04:25:27 | 2018-08-09T04:25:27 | 144,099,357 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 284 | h | warshipsBoard.h | #pragma once
#include "player.h"
class warshipsBoard
{
int axisx[10];
int axisy[10];
Player index;
public:
char tab[10][10];
warshipsBoard();
void initAxis();
void addElements();
void printGame();
};
|
d537c9c1aa4b4f8b7aa54edb5ea69b5103edadb7 | f9e55f7fc2db89721e442856ba115b18d812a9e8 | /src/Scene/CubeMap.h | d3255bc15a61648f7706e52a663adf547b6b0671 | [
"MIT"
] | permissive | Jannled/J3ngine | 09932bea41bd6e3671c0d8bba2580118aff01a86 | b0a0484aa42baedc057082718e54b61b52ea1fb8 | refs/heads/master | 2021-07-14T12:50:04.940535 | 2020-07-12T17:21:38 | 2020-07-12T17:21:38 | 231,934,965 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 886 | h | CubeMap.h | #ifndef CUBEMAP_H
#define CUBEMAP_H
#include "lib/Galogen46.h"
#include "Scene/Camera/Camera.h"
#include "Shader/ShaderProgram.h"
class CubeMap
{
public:
CubeMap(const char* path);
virtual ~CubeMap();
void renderCube();
void renderQuad();
void renderSkybox(Camera& camera);
static ShaderProgram* equirectangularToCubemapShader;
static ShaderProgram* irradianceShader;
static ShaderProgram* backgroundShader;
static ShaderProgram* prefilterShader;
static ShaderProgram* brdfShader;
GLuint getIrradianceMap();
GLuint getPrefilterMap();
GLuint getBRDFLUT();
private:
static GLuint cubeVAO;
static GLuint cubeVBO;
static GLuint quadVAO;
static GLuint quadVBO;
GLuint hdrTexture;
GLuint irradianceMap;
GLuint envCubemap;
GLuint prefilterMap;
GLuint brdfLUT;
static void prepareCube();
static void prepareQuad();
};
#endif //CUBEMAP_H |
419196d4ee17cc0fac414235715df780e6b3cf61 | 2106025cd4b5242f7ef40882beae94215c6ae6f6 | /drafts/initcpp.cpp | 6a2eca05ede26b4c5544bd33512c3862d9bc801f | [] | no_license | avinash625/CodingProblems | 9ce70ec05ff69acfa66b1405928bb34094248f44 | ea2ee37be5e7f0d780b1b384af187eadfe14c982 | refs/heads/master | 2020-12-03T11:03:14.649009 | 2020-08-30T17:46:49 | 2020-08-30T17:46:49 | 66,480,637 | 2 | 1 | null | 2017-02-22T14:43:15 | 2016-08-24T16:27:34 | C++ | UTF-8 | C++ | false | false | 2,223 | cpp | initcpp.cpp | /*
"author" : "avinash bondalapati"
"date" : "26-08-2017"
"language" : "c++"
*/
#include<iostream>
#include<stdlib.h>
#include<memory.h>
#include<math.h>
#include<limits.h>
#include<cstdint>
#include<string>
#include<map>
#include<unordered_map>
#include<set>
#include<unordered_set>
#include<vector>
#include<stack>
#include<queue>
#include<deque>
#include<utility>
#include<algorithm>
using namespace std;
#define F first
#define S second
#define ll long long int
#define l long int
#define ld long double
#define pb push_back
#define pf push_front
#define pob pop_back
#define pof pop_front
#define mod 1e10+7
#define vint vector<int>
#define vchar vector<char>
#define all(a) (a.begin(),a.end())
//#define sort(a) sort(a.begin(),a.end())
#define log(text) cout<<"log:"<<" "<<text<<endl
#define forabc(a,b,c) for(int iter = (int)a; iter< (int)b;iter+=(int)c)
#define clr(a) memset((a),0,sizeof(a))
#define fill(a,value) memset((a), value, sizeof(a))
#define read(a,n) for(int iter = 0;iter< n;iter++){cin>>a[iter];}
#define print(a) for(int iter = 0;iter<(a).size();iter++ ){ cout<<a[iter]<<" ";}
bool compareWithOne(const pair<int,string> &a, const pair<int,string> &b) { if (a.first >= b.first) return false; return true; }
bool compareWithTwo(const pair<int,string> &a, const pair<int,string> &b) { if (a.second > b.second) return true; return false; }
template <class templateData> templateData maxab(templateData a, templateData b) { if (a>b) return a; return b; }
template <class templateData> templateData minab(templateData a, templateData b) { if (a<b) return a; return b; }
int main(void) {
int n;
cin>>n;
vector<vector<pair<int,string>>> superSet(100);
string value;
int x;
for(int iter = 0;iter<n;iter++){
cin>>x;
cin>>value;
if(iter >= n/2)
superSet[x].push_back(make_pair(x,value));
else
superSet[x].push_back(make_pair(x,"-"));
}
int count =0;
for(vector<vector<pair<int,string>>>::iterator st = superSet.begin(); st!= superSet.end(); st++){
for(vector<pair<int,string>>::iterator it = (*st).begin(); it != (*st).end(); it++){
cout<<it->second<<" ";
}
}
}
|
c58f31fb491400e4b92d4ac58c0983e48e767e80 | f55e86402f710d854a7520554a653a64ffcea387 | /cpp/linked_list.h | 7dc7f6d0df00f4ea4f3ad1b9327bf6fedf69c238 | [] | no_license | sinclairtarget/algorithms | 5aea8dda33960aa0159ac2b3069e7070a04fa62e | 1cd9fb56ed284d83d58ed48ba6edfc721a6a8c03 | refs/heads/master | 2021-01-23T06:45:23.742815 | 2017-06-02T18:58:11 | 2017-06-02T18:58:11 | 86,398,258 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,210 | h | linked_list.h | #ifndef LINKED_LIST_H
#define LINKED_LIST_H
#include <string>
using std::string;
template <typename T>
class ListNode
{
public:
explicit ListNode(T val) :
mStoredValue(val),
mNext(nullptr) {}
explicit ListNode(T val, ListNode* next) :
mStoredValue(val),
mNext(next) {}
// Inserts the given value before this node and returns the new list head.
ListNode* Prepend(T val);
// Inserts the given value immediately after this node. Returns the newly
// created node.
ListNode* InsertAfter(T val);
// Returns the first node with the given value, or null if the value is not
// present.
ListNode* Find(T val);
// Removes the first node with the given value. Returns the new list head,
// which may or may not be the same as the old one.
ListNode* Remove(T val);
// Returns the new list head.
ListNode* Reverse();
T GetValue() { return mStoredValue; }
ListNode* GetNext() { return mNext; }
void SetNext(ListNode* next) { mNext = next; }
string ToString(); // Prints this node.
string ListToString(); // Prints the whole list.
protected:
T mStoredValue;
ListNode* mNext;
};
#endif
|
fd2cd674929c0d1cbba5823d9357d1b393619be5 | ba7da205636d14fdb4bf2743083ba298c2c1e523 | /src/storage/istorage.h | 21b5749c05e591a485b540bea6559e5e2e3c1fd6 | [] | no_license | abbat/avalon | 732cf54090b2705026dfae2866fad907c377fc01 | b8bff997d9de6a5187177b4afd44bcd182aef5ec | refs/heads/master | 2023-02-02T20:26:44.855279 | 2023-01-08T08:11:06 | 2023-01-08T08:11:06 | 31,868,126 | 3 | 1 | null | 2023-01-08T07:21:12 | 2015-03-08T22:22:13 | C++ | UTF-8 | C++ | false | false | 20,158 | h | istorage.h | /*!
* \file
* \brief Интерфейс для работы с хранилищем данных
*/
#ifndef _avalon_istorage_h_
#define _avalon_istorage_h_
#include "model/all.h"
#include "iprogress.h"
#include "database_error.h"
/*!
* \brief Типы множеств для групповой обработки (см. IAStorage::setIDsAsRead и IAStorage::unsubscribe).
*/
typedef enum AIDSet
{
idsMessage, /*!< \brief Сообщение */
idsTopic, /*!< \brief Топик */
idsForum, /*!< \brief Форум */
idsGroup, /*!< \brief Группа форумов */
idsAll /*!< \brief Все */
} AIDSet;
/*!
* \brief Общий интерфейс для всех хранилищ (см. AStorageFactory)
* Все методы возвращают true или false в зависимости от успеха выполнения операции.
* Если метод вернул false, то сообщение об ошибке можно получить вызовом ADatabaseError::getLastError().
* Последним параметром всегда передается указатель на интерфейс IProgress для отображения прогресса выполнения операции или NULL, если отображение не требуется.
*/
class IAStorage : public ADatabaseError
{
public:
IAStorage () : ADatabaseError () {}
virtual ~IAStorage () {}
/*!
* \brief Проверка соединения с БД.
*/
virtual bool ping () = 0;
/*!
* \brief Создание новой БД.
*/
virtual bool createDatabase () = 0;
/*!
* \brief Получение информации о текущем пользователе.
* \param info Информация о пользователе, перед вызовом должно быть заполнено поле Name (логин на RSDN).
*/
virtual bool whoAmI (AUserInfo& info) = 0;
/*!
* \brief Получение версий строк (снимков).
* \param list Версии строк.
*/
virtual bool getRowVersion (ARowVersion& list) = 0;
/*!
* \brief Возвращает дерево форумов.
* \param list Список групп/форумов.
* \param subscribed_only true, для того, чтобы получить только дерево подписаных форумов, false - все форумы.
*/
virtual bool getForumList (AForumGroupInfoList& list, bool subscribed_only) = 0;
/*!
* \brief Устанавливает (сохраняет) дерево форумов.
* \param list Заполненый список описателей форумов.
*/
virtual bool setForumList (const AForumGroupInfoList& list) = 0;
/*!
* \brief Возвращает список описателей подписаных форумов.
* \param list Список описателей.
*/
virtual bool getSubscribedForumList (ASubscribedForumInfoList& list) = 0;
/*!
* \brief Устанавливает (сохраняет) список описателей подписаных форумов.
* \param list Заполненый список описателей подписаных форумов.
*/
virtual bool setSubscribedForumList (const ASubscribedForumInfoList& list) = 0;
/*!
* \brief Получение описателя форума
* \param id_forum ID форума
* \param info Описатель форума
*/
virtual bool getForumInfo (int id_forum, AForumInfo& info) = 0;
/*!
* \brief Сохраняет список пользователей добавляя новых и обновляя информацию о существующих.
* \param list Заполненый список описателей пользователей.
* \param row_version Версия снимка.
*/
virtual bool setUserList (const AUserInfoList& list, const QString& row_version) = 0;
/*!
* \brief Возвращает максимальный id для списка сообщений
* Функция полезна для работы с полной таблицей по диапазонам id
* \param max_id - максимальный id для таблицы со списком сообщений
*/
virtual bool getMaxIDMessage (int& max_id) = 0;
/*!
* \brief Возвращает минимальный id для списка сообщений
* Функция полезна для работы с полной таблицей по диапазонам id
* \param min_id - минимальный id для таблицы со списком сообщений
*/
virtual bool getMinIDMessage (int& min_id) = 0;
/*!
* \brief Возвращает параметры для получения списка сообщений.
* \param query Список форумов, поломанных веток и id сообщений для загрузки.
*/
virtual bool getMessageQuery (ADataQuery& query) = 0;
/*!
* \brief Сохраняет список сообщений добавляя новые и обновляя полученную информацию о существующих.
* \param list Список сообщений, рейтингов, модерилок.
* \param row_version Версия строки (снимка).
* \param save_row_version true, для того, чтобы сохранить версии строк,
* false, для того, чтобы игнорировать список и не считать сохраненные сообщения за новые,
* добавлен для реализации workaround при вытягивании всей базы RSDN (см. IAStorage::GetMessageIds).
*/
virtual bool setMessageList (const ADataList& list, const ARowVersion& row_version, bool save_row_version) = 0;
/*!
* \brief Возвращает количество непрочитанных сообщений для форумов
* в т.ч. и для спец-группы "Локальные" (см. константы SPECIAL_ID_FORUM_xxx в model/forum.h).
* \param list Список с количеством непрочитанных сообщений для id форумов.
* \param id_me ID текущего пользователя avalon.
*/
virtual bool getUnreadCount (AUnreadForumCountInfoList& list, int id_me) = 0;
/*!
* \brief Возвращает список id топиков (родительских веток) для форума.
* \param id_forum ID форума.
* \param count Количество топиков (0 - все).
* \param list Список id родительских сообщений (топиков).
*/
virtual bool getForumTopicList (int id_forum, int count, QList<int>& list) = 0;
/*!
* \brief Заполняет информацию о топиках в форуме
*
* Поля списка (кроме ID и Item) предполагаются заполненными значениями полей по умолчанию (см. AMessageInfoGUI::AMessageInfoGUI)
* и не меняются без необходимости.
*
* Функция ДОЛЖНА заполнить все поля AMessageInfo плюс установить флаги AMessageInfoGUI::IsRead, AMessageInfoGUI::HasUnreadChild,
* AMessageInfoGUI::HasUnreadChildMy в актуальные значения.
*
* Функция НЕ должна устанавливать флаг AMessageInfoGUI::IsInfoLoaded (устанавливается вызвающим кодом).
*
* Функция МОЖЕТ оставить некоторые поля AMessageInfo, которые не используются в текущем GUI, незаполненными в целях оптимизации
* скорости работы - в этом случае они должны иметь значения по умолчанию (к таким полям, например, может относиться поле
* AMessageInfo::LastModerated и т.д.)
*
* \param id_forum ID форума, для которого запрашивается список топиков
* (для ненулевого значения, будет произведено исключение одного лишнего преобразования из QVariant на каждый элемент,
* что положительно влияет на скорость)
* \param list Список топиков (с установленным полем ID, по которому будет производиться дальнейшее заполнение информацией).
* \param id_me ID текущего пользователя avalon.
*/
virtual bool getTopicInfoList (int id_forum, AMessageInfoGUIPtrList& list, int id_me) = 0;
/*!
* \brief Заполняет информацию о всех сообщениях в топике (родительской ветке).
*
* Функция ДОЛЖНА заполнить все поля AMessageInfo плюс установить флаги AMessageInfoGUI::IsRead, AMessageInfo::HasChild в актуальные
* значения.
*
* Функция НЕ должна устанавливать флаг AMessageInfoGUI::IsInfoLoaded (устанавливается вызвающим кодом).
*
* Функция МОЖЕТ оставить некоторые поля AMessageInfo, которые не используются в текущем GUI, незаполненными в целях оптимизации
* скорости работы - в этом случае они должны иметь значения по умолчанию (к таким полям, например, может относиться поле
* AMessageInfo::LastModerated и т.д.)
*
* \param id_forum ID форума, для которого запрашивается список топиков
* (для ненулевого значения, будет произведено исключение одного лишнего преобразования из QVariant на каждый элемент,
* что положительно влияет на скорость)
* \param id_topic ID топика (темы, родительской ветки).
* \param list Список сообщений (изначально пустой, на выходе заполненый _не_ включая сообщение id_topic).
* \param factory Фабрика для создания элементов (каждый элемент списка создается вызовом IMessageInfoGUIFactory::createItem),
* поля (кроме Item) предполагаются заполненными значениями полей по умолчанию (см. AMessageInfoGUI::AMessageInfoGUI)
* и не меняются без необходимости.
*/
virtual bool getTopicMessageList (int id_forum, int id_topic, AMessageInfoGUIPtrList& list, IMessageInfoGUIFactory* factory) = 0;
/*!
* \brief Возвращает тело сообщения.
* \param id_message ID сообщения.
* \param body Тело сообщения.
*/
virtual bool getMessageBody (int id_message, QString& body) = 0;
/*!
* \brief Пометить группу сущностей (сообщений, форумов, групп форумов) как прочитанное/непрочитанное.
* Если установлена дата (.isValid() == true), то она учитывается соответственно логике:
* read = true - до даты как прочитанные;
* read = false - после даты как непрочитанные.
* \param list Список id сущностей.
* \param type Тип сущностей.
* \param read Флаг прочитано (true) или нет (false).
* \param date До даты / После даты или все, если дата не валидна.
*/
virtual bool setIDsAsRead (const QList<int>& list, AIDSet type, bool read, QDateTime date) = 0;
/*!
* \brief Отписка от форума / группы форумов.
* \param list Список ID форумов, групп.
* \param type {idsForum | idsGroup}.
* \param clean true - очистить базу от "лишних" сообщений, false не удалять сообщения.
*/
virtual bool unsubscribe (const QList<int>& list, AIDSet type, bool clean) = 0;
/*!
* \brief Добавление сообщения в очередь на отправку.
* \param info Описатель сообщения на отправку.
*/
virtual bool addMessage2Send (const AMessage2Send& info) = 0;
/*!
* \brief Возвращает список всех сообщений к отправке.
* \param list Список сообщений к отправке.
* \param drafts Флаг выбора черновиков.
*/
virtual bool getMessage2SendList (AMessageInfoList& list, bool drafts) = 0;
/*!
* \brief Добавление рейтинга в очередь на отправку.
* \param info Описатель рейтинга на отправку.
*/
virtual bool addRating2Send (const ARating2Send& info) = 0;
/*!
* \brief Возвращает список всех рейтингов к отправке со связанными сообщениями.
* Индексы в списках сообщений и рейтингов соответствуют.
* \param message_list Список оцененых сообщений.
* \param rating_list Список оценок.
*/
virtual bool getRating2SendList (AMessageInfoList& message_list, ARating2SendList& rating_list) = 0;
/*!
* \brief Возвращает список всех рейтингов к отправке.
* \param list Список рейтингов.
*/
virtual bool getRating2SendList (ARating2SendList& list) = 0;
/*!
* \brief Смена оценки
* \param id ID оценки (локальный)
* \param new_rate Новая оценка
*/
virtual bool changeRating (int id, int new_rate) = 0;
/*!
* \brief Добавление модерилки в очередь на отправку.
* \param info Описатель модерилки.
*/
virtual bool addModerate2Send (const AModerate2Send& info) = 0;
/*!
* \brief Возвращает список всех модерилок к отправке со связанными сообщениями.
* Индексы в списках сообщений и рейтингов соответствуют.
* \param message_list Список модерируемых сообщений.
* \param moderate_list Список модерилок.
*/
virtual bool getModerate2SendList (AMessageInfoList& message_list, AModerate2SendList& moderate_list) = 0;
/*!
* \brief Возвращает список всех модерилок к отправке.
* \param list Список описателей модерилок.
*/
virtual bool getModerate2SendList (AModerate2SendList& list) = 0;
/*!
* \brief Возвращает описатель модерилки к отправке
* \param id Локальный ID модерилки
* \param info Описатель модерилки
*/
virtual bool getModerate2SendInfo (int id, AModerate2Send& info) = 0;
/*!
* \brief Коммит результата отправки.
* \param info Описатель с информацией о коммите.
*/
virtual bool setCommitResult (const ACommitInfo& info) = 0;
/*!
* \brief Удаление элементов из спец-папок.
* \param ids Список id элементов.
* \param id_special ID специального форума (см. константы SPECIAL_ID_FORUM_ххх в model/forum.h).
*/
virtual bool deleteSpecial (const QList<int>& ids, int id_special) = 0;
/*!
* \deprecated Использовался для тестирования работы с большой базой сообщений, для чего пришлось выкачать все сообщения RSDN
* \brief Возвращает существующие id сообщений в заданном интервале.
* Используется для вытягивания всей базы RSDN.
* В реализациях хранилищ, отличных от стандартного, может смело выдавать ошибку
* с сообщением "не реализованно", т.к. данная функциональность, скорее всего, будет скрыта от пользователя.
* \param from_id Начальный ID сообщения.
* \param to_id Конечный ID сообщения.
* \param list Список существующих id сообщений в заданном интервале.
*/
virtual bool getMessageIds (int from_id, int to_id, QList<int>& list) = 0;
/*!
* \brief Получение списка рейтингов для сообщения
* Дополнительно см. примечания к ARatingInfo
* \param id_message ID сообщения
* \param list Список рейтингов
*/
virtual bool getMessageRatingList (int id_message, AMessageRatingList& list) = 0;
/*!
* \brief Сжатие тел сообщений в хранилище
* \param progress Прогресс выполнения операции.
*/
virtual bool compressStorage (IProgress* progress) = 0;
/*!
* \brief Распаковка тел сообщений в хранилище
* \param progress Прогресс выполнения операции.
*/
virtual bool uncompressStorage (IProgress* progress) = 0;
/*!
* \brief Поиск пути сообщения
* \param id_message ID сообщения для поиска
* \param id_forum ID форума, в котором находится сообщение
* \param path Список, который заполняется ID сообщений от корня (корневой ID в начале списка).
* В случае, если сообщение не найдено, id_forum = 0 и список будет пуст
*/
virtual bool getMessagePath (int id_message, int& id_forum, QList<int>& path) = 0;
/*!
* \brief Добавление сообщений на дозагрузку
* \param id_message ID сообщения
* \param is_topic Является ли сообщение топиком
*/
virtual bool addBroken (int id_message, bool is_topic) = 0;
/*!
* \brief Проверка наличия поломанных веток
* \param result true, если есть поломанные ветки / сообщения
*/
virtual bool hasBroken (bool& result) = 0;
/*!
* \brief Получение ID своих сообщений
* \param id_me ID текущего пользователя avalon
* \param count Количество сообщений
* \param list Список ID сообщений
*/
virtual bool getMyMessageList (int id_me, int count, QList<int>& list) = 0;
/*!
* \brief Получение ID сообщений ответов себе
* \param id_me ID текущего пользователя avalon
* \param count Количество сообщений
* \param list Список ID сообщений
*/
virtual bool getAnswers2MeList (int id_me, int count, QList<int>& list) = 0;
};
#endif // _avalon_istorage_h_
|
0e7259ebacf63454128fce67b9e37822c8f07d28 | c68f791005359cfec81af712aae0276c70b512b0 | /September Challenge 2016/longseq.cpp | 528f5e05f51b32b622c824d729bd0bd31e58f501 | [] | no_license | luqmanarifin/cp | 83b3435ba2fdd7e4a9db33ab47c409adb088eb90 | 08c2d6b6dd8c4eb80278ec34dc64fd4db5878f9f | refs/heads/master | 2022-10-16T14:30:09.683632 | 2022-10-08T20:35:42 | 2022-10-08T20:35:42 | 51,346,488 | 106 | 46 | null | 2017-04-16T11:06:18 | 2016-02-09T04:26:58 | C++ | UTF-8 | C++ | false | false | 443 | cpp | longseq.cpp | #include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 5;
char s[N];
int main() {
int t;
scanf("%d", &t);
while (t--) {
scanf("%s", s);
int n = strlen(s);
int nol = 0, one = 0;
for (int i = 0; i < n; i++) {
if (s[i] == '0') {
nol++;
} else {
one++;
}
}
if (nol == n - 1 || one == n - 1) {
puts("Yes");
} else {
puts("No");
}
}
return 0;
}
|
4c75ebac3264d62c796800018f70155c4a78e414 | b3e525a3c48800303019adac8f9079109c88004e | /storage/offload/src/drv/test/gtests/pnso_global_ut.hpp | 09acc608b6cf0879b085e439c6772cda37a340d2 | [
"BSD-3-Clause"
] | permissive | PsymonLi/sw | d272aee23bf66ebb1143785d6cb5e6fa3927f784 | 3890a88283a4a4b4f7488f0f79698445c814ee81 | refs/heads/master | 2022-12-16T21:04:26.379534 | 2020-08-27T07:57:22 | 2020-08-28T01:15:20 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 822 | hpp | pnso_global_ut.hpp | /*
* {C} Copyright 2018 Pensando Systems Inc.
* All rights reserved.
*
*/
#ifndef __PNSO_GLOBAL_UT_H__
#define __PNSO_GLOBAL_UT_H__
/*
* NOTE:
* Some or most of the UTs may appear to be repeatitive with minor changes
* and thereby the functions may be long, and this is deliberate for the
* following reasons:
* (a) to keep the relevant pieces of a UT within the vicinity
* (b) to keep up the readability
* (c) to ease the troubleshooting
*
* TODO-chksum_ut:
* TODO-hash_ut:
* - make PNSO_BLOCK_SIZE visible via config-get, when pnso_chain.c
* comes into play
* - while code optimization is not the concern for UT, reduce the
* possible duplicates
*/
#define PNSO_BLOCK_SIZE 4096
#define PNSO_BUFFER_LEN (32 * 1024)
#define PNSO_NUM_OBJECTS 512
#endif /* __PNSO_GLOBAL_UT_H__ */
|
0f80be28a741e618e3e07499d30b7600b6ee90c3 | ce6a345839b568440c35dcd30c5a78f3af146896 | /topic08/A/main.cpp | fd29a6abdeeeb4f4eb441378564522fa67d34cca | [] | no_license | Luzhiled/ALDS | 69a25b53f483880828fac93e0b46416d7b3a6679 | 0443dbb4c35248a2872835c289d9b6ee1a454aa7 | refs/heads/master | 2023-03-05T04:02:15.496805 | 2021-02-02T10:14:02 | 2021-02-02T10:14:02 | 335,242,842 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,099 | cpp | main.cpp | #include <iostream>
#include <array>
#include <vector>
#include <string>
struct NodeBase {
NodeBase *l, *r, *p;
int key;
NodeBase() { l = r = p = nullptr; }
NodeBase(int key) : key(key) { l = r = p = nullptr; }
void set_key(int k) {
key = k;
}
};
template< typename Node, std::size_t LIM >
struct Tree {
std::size_t idx;
Node* root;
std::vector< Node > pool;
// static std::array< Node, LIM > pool;
Tree(): idx(0), pool(LIM) { root = nullptr; }
Node* create() {
return &pool[idx++];
}
Node* create(Node v) {
return &(pool[idx++] = v);
}
void insert(Node v) {
Node *z = create(v);
Node* y = nullptr;
Node* x = root;
while (x) {
y = x;
if (z->key < x->key) {
x = x->l;
} else {
x = x->r;
}
}
z->p = y;
if (!y) {
root = z;
} else if (z->key < y->key) {
y->l = z;
} else {
y->r = z;
}
}
void print() {
std::vector< int > ps;
inorder_walk(root, ps);
for (auto &p: ps) std::cout << " " << p;
std::cout << std::endl;
ps.clear();
preorder_walk(root, ps);
for (auto &p: ps) std::cout << " " << p;
std::cout << std::endl;
}
private:
void inorder_walk(Node *v, std::vector< int > &vs) {
if (v->l) inorder_walk(v->l, vs);
vs.emplace_back(v->key);
if (v->r) inorder_walk(v->r, vs);
}
void preorder_walk(Node *v, std::vector< int > &vs) {
vs.emplace_back(v->key);
if (v->l) preorder_walk(v->l, vs);
if (v->r) preorder_walk(v->r, vs);
}
};
int main() {
int q;
std::cin >> q;
Tree< NodeBase, 500000 > t;
while (q--) {
std::string s;
std::cin >> s;
if (s[0] == 'i') {
int key;
std::cin >> key;
NodeBase v(key);
t.insert(v);
} else {
t.print();
}
}
}
|
676a3cd4a961a030ffb5f39358ce423fd3a4964c | c8fcc1acf73585045a5c7213cfb9f90e4c1e809e | /HDU/3047.cpp | 38b07bceb5b8d00596587ca8fc8d1c71321cba28 | [] | no_license | Jonariguez/ACM_Code | 6db4396b20d0b0aeef30e4d47b51fb5e3ec48e03 | 465a11746d577197772f64aa11209eebd5bfcdd3 | refs/heads/master | 2020-03-24T07:09:53.482953 | 2018-11-19T09:21:33 | 2018-11-19T09:21:33 | 142,554,816 | 3 | 0 | null | null | null | null | GB18030 | C++ | false | false | 973 | cpp | 3047.cpp | /****************
*PID:hdu3047
*Auth:Jonariguez
*****************
和座位是环状的没有关系,没有影响
*/
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <vector>
#include <algorithm>
using namespace std;
typedef long long LL;
const int maxn=50000+10;
LL par[maxn],rel[maxn],n,m;
void Init(){
for(LL i=0;i<=n;i++){
par[i]=i;rel[i]=0;
}
}
LL find(LL x){
if(par[x]==x) return x;
LL y=find(par[x]);
rel[x]+=rel[par[x]];
return par[x]=y;
}
int main()
{
LL i,j,res;
while(scanf("%I64d%I64d",&n,&m)!=EOF){
Init();
res=0;
for(i=1;i<=m;i++){
LL a,b,x;
scanf("%I64d%I64d%I64d",&a,&b,&x);
LL pa=find(a),pb=find(b);
if(pa!=pb){
par[pb]=pa;
rel[pb]=rel[a]-rel[b]+x;
}else {
if(rel[b]-rel[a]!=x) res++;
}
}
printf("%I64d\n",res);
}
return 0;
}
|
6a1d4d3535c61e387664d0ed6d58e0dadfc7f70b | a2153a949214de1fa3009972a74b09ed0b80bda0 | /heapSort.cpp | 6c4154f646796ee1fefc04f2dbfc1411151d5beb | [] | no_license | msk4862/Algos | 0d93c42b874eaad3d03888939ed47ee155c68440 | 6a931ec5c0513cd16fa92b296850c8ed01de760c | refs/heads/master | 2020-03-18T23:35:59.915292 | 2018-05-30T08:36:31 | 2018-05-30T08:36:31 | 135,413,331 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,604 | cpp | heapSort.cpp | #include<iostream>
using namespace std;
void maxHeapify(int a[], int i, int s) {
int temp, largeI, left, right;
largeI = i;
if(i >= (s/2)) {
return;
}
left = 2*i+1;
right = 2*i+2;
if(right < s) {
if(a[left] > a[right]) {
largeI = left;
}
else {
largeI = right;
}
if(a[i] >= a[largeI]) {
return;
}
else {
temp = a[i];
a[i] = a[largeI];
a[largeI] = temp;
maxHeapify(a, largeI, s);
}
}
else {
if(a[left] > a[i]) {
largeI = left;
temp = a[i];
a[i] = a[largeI];
a[largeI] = temp;
maxHeapify(a, largeI, s);
}
else {
return;
}
}
}
void buildHeap(int a[], int s) {
for(int i = (s/2)-1; i >= 0; --i) {
maxHeapify(a, i, s);
}
}
void heapSort(int a[], int s) {
int temp;
int heapsize = s;
buildHeap(a, heapsize);
for(int i = heapsize-1; i >= 0; --i) {
temp = a[0];
a[0] = a[i];
a[i] = temp;
heapsize -= 1;
maxHeapify(a, 0, heapsize);
}
}
int main() {
int n = 10;
int a[n];
for(int i = 0; i < n; ++i)
a[i] = n-i;
//Isort(a, n);
heapSort(a, n);
cout<<"\n\n\n\n\nSorted array: "<<endl;
for(int i =0; i < n; ++i) {
cout<<a[i]<<" ";
}
}
|
a5a8af2df7f47584238b31bf7108134760e6f76e | ed84417478eb8e58eef53b6cf8f28976fa8d4d7a | /camera.h | a61ade44046d008905d40c1f8ea1493190e9ee84 | [] | no_license | Foxclip/GLFWTest | 7904e3eb40619fa470b557ec5cee7cf7f0bb4710 | d01bd7c7f2f62960f387b9e5c46366fb925b7706 | refs/heads/master | 2021-05-05T16:37:09.399882 | 2018-02-07T10:50:38 | 2018-02-07T10:50:38 | 117,361,741 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,522 | h | camera.h | #pragma once
#include <glad/glad.h>
#include "glm/glm.hpp"
#include "glm/gtc/matrix_transform.hpp"
const float D_YAW = -90.0f;
const float D_PITCH = 0.0f;
const float D_SLOW_SPEED = 4.0f;
const float D_FAST_SPEED = D_SLOW_SPEED * 4.0f;
const float D_SENSITIVITY = 0.1f;
const float D_FOV = 60.0f;
enum Direction {
FORWARD,
BACKWARD,
LEFT,
RIGHT,
UP,
DOWN
};
class Camera {
public:
Camera(glm::vec3 position = glm::vec3(0.0f, 0.0f, 0.0f), glm::vec3 up = glm::vec3(0.0f, 1.0f, 0.0f), float yaw = D_YAW, float pitch = D_PITCH);
Camera(float posX, float posY, float posZ, float upX, float upY, float upZ, float yaw = D_YAW, float pitch = D_PITCH);
glm::vec3 cameraPosition;
glm::vec3 cameraFront;
glm::vec3 cameraUp;
glm::vec3 cameraRight;
glm::vec3 worldUp;
float yaw;
float pitch;
float movementSpeed;
float mouseSensitivity;
float fov;
glm::mat4 getViewMatrix();
void processKeyboard(Direction direction, float deltaTime);
void processMouse(float xoffset, float yoffset, bool costraintPitch = true);
void processScroll(float yoffset);
private:
void updateCameraVectors();
};
inline Camera::Camera(glm::vec3 position, glm::vec3 up, float yaw, float pitch): cameraFront(glm::vec3(0.0f, 0.0f, -1.0f)), movementSpeed(D_SLOW_SPEED), mouseSensitivity(D_SENSITIVITY), fov(D_FOV) {
this->cameraPosition = position;
this->worldUp = up;
this->yaw = yaw;
this->pitch = pitch;
updateCameraVectors();
}
inline Camera::Camera(float posX, float posY, float posZ, float upX, float upY, float upZ, float yaw, float pitch): cameraFront(glm::vec3(0.0f, 0.0f, -1.0f)), movementSpeed(D_SLOW_SPEED), mouseSensitivity(D_SENSITIVITY), fov(D_FOV) {
cameraPosition = glm::vec3(posX, posY, posZ);
worldUp = glm::vec3(upX, upY, upZ);
this->yaw = yaw;
this->pitch = pitch;
updateCameraVectors();
}
inline glm::mat4 Camera::getViewMatrix() {
glm::mat4 mat1(cameraRight.x, cameraUp.x, -cameraFront.x, 0,
cameraRight.y, cameraUp.y, -cameraFront.y, 0,
cameraRight.z, cameraUp.z, -cameraFront.z, 0,
0, 0, 0, 1);
glm::mat4 mat2(1, 0, 0, 0,
0, 1, 0, 0,
0, 0, 1, 0,
-cameraPosition.x, -cameraPosition.y, -cameraPosition.z, 1);
return mat1 * mat2;
//return glm::lookAt(cameraPosition, cameraPosition + cameraFront, cameraUp);
}
inline void Camera::processKeyboard(Direction direction, float deltaTime) {
float velocity = movementSpeed * deltaTime;
//glm::vec3 movementDirectionFront = glm::normalize(glm::vec3(cameraFront.x, 0, cameraFront.z));
//glm::vec3 movementDirectionRight = glm::normalize(glm::vec3(cameraRight.x, 0, cameraRight.z));
if(direction == FORWARD) {
cameraPosition += cameraFront * velocity;
}
if(direction == BACKWARD) {
cameraPosition -= cameraFront * velocity;
}
if(direction == LEFT) {
cameraPosition -= cameraRight * velocity;
}
if(direction == RIGHT) {
cameraPosition += cameraRight * velocity;
}
if(direction == UP) {
cameraPosition += cameraUp * velocity;
}
if(direction == DOWN) {
cameraPosition -= cameraUp * velocity;
}
}
inline void Camera::processMouse(float xoffset, float yoffset, bool costraintPitch) {
xoffset *= mouseSensitivity;
yoffset *= mouseSensitivity;
yaw += xoffset;
pitch += yoffset;
if(costraintPitch) {
if(pitch > 89.0f) {
pitch = 89.0f;
}
if(pitch < -89.0f) {
pitch = -89.0f;
}
}
updateCameraVectors();
}
inline void Camera::processScroll(float yoffset) {
if(fov >= 1.0f && fov <= 90.0f) {
fov -= yoffset;
}
if(fov < 1.0f) {
fov = 1.0f;
}
if(fov > 90.0f) {
fov = 90.0f;
}
}
inline void Camera::updateCameraVectors() {
glm::vec3 new_front;
new_front.x = cos(glm::radians(pitch)) * cos(glm::radians(yaw));
new_front.y = sin(glm::radians(pitch));
new_front.z = cos(glm::radians(pitch)) * sin(glm::radians(yaw));
this->cameraFront = glm::normalize(new_front);
cameraRight = glm::normalize(glm::cross(cameraFront, worldUp));
cameraUp = glm::normalize(glm::cross(cameraRight, cameraFront));
}
|
87c9dcc7fa7945ea64aa3d6c56666cabf763c895 | 2e25a9b165490a525697cc2139d5808cff6f3b06 | /vehinh/tron.h | 993f53b52722c5b0c1e709794ba2f5fc541687a7 | [] | no_license | truongthihuonggiang/mfc_paint_nhom1CNTTK17 | 2b1c59b06e7a9f3c85e8ad1b059ace7b999bcbf1 | 64d2a930e40c40cee6cfd7ea49f82fed278f7335 | refs/heads/master | 2020-08-02T07:50:53.479412 | 2019-09-27T09:24:04 | 2019-09-27T09:24:04 | 211,280,066 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 250 | h | tron.h | #pragma once
#include "hinh.h"
class tron :
public hinh
{
private:
int x,y;
int S,P;
int r;
public:
tron(CPoint p1, CPoint p2);
//float chuvi();
//float dientich();
void draw(CClientDC *pdc);
tron(void);
~tron(void);
};
|
21aeb307dd3e4d627c48edd5fdc7242025ea3db3 | 0eff74b05b60098333ad66cf801bdd93becc9ea4 | /second/download/git/gumtree/git_repos_function_6140_git-2.8.2.cpp | 9aa10dde10e89cfe40409769165166234e24298f | [] | no_license | niuxu18/logTracker-old | 97543445ea7e414ed40bdc681239365d33418975 | f2b060f13a0295387fe02187543db124916eb446 | refs/heads/master | 2021-09-13T21:39:37.686481 | 2017-12-11T03:36:34 | 2017-12-11T03:36:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 147 | cpp | git_repos_function_6140_git-2.8.2.cpp | char *strdup(const char *s1)
{
char *s2 = 0;
if (s1) {
size_t len = strlen(s1) + 1;
s2 = malloc(len);
memcpy(s2, s1, len);
}
return s2;
} |
1341893612425d7b324e17225ae99b1f0ec59d10 | ab32cbf7be3dca3421015057f35c365ec763bb9e | /lib/ProjGaia/Tools/Observer.h | 56f89d99ff2a947f13826531492ff5fcd166296d | [] | no_license | ebonywolf/AgentesCataLixo | 39eeae91214a99be9e4b85ece597defeaf178717 | 602ee3067c2ffbdb7fa8808c53928dda5afa7c77 | refs/heads/master | 2021-01-21T13:57:00.560903 | 2015-05-18T01:35:37 | 2015-05-18T01:35:37 | 35,678,361 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,166 | h | Observer.h |
#ifndef OBSERVER_H
#define OBSERVER_H
#include "Listener.h"
#include <list>
namespace pg
{
template<class Tipo>
class Observer
{
public:
virtual void addListener ( Listener<Tipo>* listener );
virtual void removeListener ( Listener<Tipo>* listener );
virtual void clearListener ( );
virtual bool hasListener ( Listener<Tipo>* listener );
virtual void notifyListeners ( Tipo t );
protected:
std::list<Listener<Tipo>*> listeners = std::list<Listener<Tipo>*>();
private:
};
template <typename T>
void Observer<T>::addListener ( Listener<T>* listener )
{
listeners.push_back ( listener );
}
template <typename T>
void Observer<T>::removeListener ( Listener<T>* listener )
{
listeners.remove ( listener );
}
template <typename T>
void Observer<T>::clearListener ( )
{
listeners.clear();
}
template <typename T>
bool Observer<T>::hasListener ( Listener<T>* listener )
{
for ( auto x : listeners ) {
if ( x == listener ) { return true; }
}
return false;
}
template <typename T>
void Observer<T>::notifyListeners ( T t )
{
for ( auto x : listeners ) {
x->notify ( t );
}
}
}
#endif // OBSERVER_H
|
ce08dc3aee1aec7955d6d4ea2e3e3bc27343c310 | c13f3cb4300f453c0c8d194e9ecea645354e180e | /RayImpact/include/PlasticMaterial.hpp | 4525b82a87adf9f089539eb5806b42805ee6099f | [] | no_license | lars-frogner/RayImpact | 3d36ca1c74d866fdd4a9d663a0b3569c78c1cc4a | a7313a66ed32dc0ff7aadf604a6251f9d9de1912 | refs/heads/master | 2021-09-15T00:48:22.362863 | 2018-05-23T07:14:25 | 2018-05-23T07:14:25 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,434 | hpp | PlasticMaterial.hpp | #pragma once
#include "Material.hpp"
#include "Spectrum.hpp"
#include "Texture.hpp"
#include "ParameterSet.hpp"
#include <memory>
namespace Impact {
namespace RayImpact {
// PlasticMaterial declarations
class PlasticMaterial : public Material {
private:
std::shared_ptr< Texture<ReflectionSpectrum> > diffuse_reflectance_texture; // Texture with reflection spectra (colors) for the diffuse component of the material
std::shared_ptr< Texture<ReflectionSpectrum> > glossy_reflectance_texture; // Texture with reflection spectra (colors) for the glossy component of the material
std::shared_ptr< Texture<imp_float> > roughness_texture; // Texture with values controlling the roughness of the material
std::shared_ptr< Texture<imp_float> > bump_map; // Bump map for the material
const bool normalized_roughness; // Whether the roughness values are in the range [0, 1] (otherwise they correspond directly to slope deviations)
public:
PlasticMaterial(const std::shared_ptr< Texture<ReflectionSpectrum> >& diffuse_reflectance_texture,
const std::shared_ptr< Texture<ReflectionSpectrum> >& glossy_reflectance_texture,
const std::shared_ptr< Texture<imp_float> >& roughness_texture,
const std::shared_ptr< Texture<imp_float> >& bump_map,
bool normalized_roughness);
void generateBSDF(SurfaceScatteringEvent* scattering_event,
RegionAllocator& allocator,
TransportMode transport_mode,
bool allow_multiple_scattering_types) const;
};
// PlasticMaterial function declarations
Material* createPlasticMaterial(const TextureParameterSet& parameters);
// PlasticMaterial inline method definitions
inline PlasticMaterial::PlasticMaterial(const std::shared_ptr< Texture<ReflectionSpectrum> >& diffuse_reflectance_texture,
const std::shared_ptr< Texture<ReflectionSpectrum> >& glossy_reflectance_texture,
const std::shared_ptr< Texture<imp_float> >& roughness_texture,
const std::shared_ptr< Texture<imp_float> >& bump_map,
bool normalized_roughness)
: diffuse_reflectance_texture(diffuse_reflectance_texture),
glossy_reflectance_texture(glossy_reflectance_texture),
roughness_texture(roughness_texture),
bump_map(bump_map),
normalized_roughness(normalized_roughness)
{}
} // RayImpact
} // Impact
|
38799c2e81cac0ef8baf0554ea588f818687316f | 59af8ef7c0e71b404484aa74c0a7385c5ae87a11 | /include/LL.h | 3e3217b32b25916a7008cbd97d1b10440ad8763e | [] | no_license | SilverLining1837/LinkedListPractice | bb44c11a845b7c337723b19cf30523190d94dee9 | 34f04d58eed7a6b7ab5a9f026359205e81be00e3 | refs/heads/master | 2021-07-06T17:03:32.636238 | 2017-10-03T20:34:07 | 2017-10-03T20:34:07 | 105,700,301 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,135 | h | LL.h | #ifndef LL_H
#define LL_H
#include <iostream>
using namespace std;
class LL
{
public:
LL();
virtual ~LL();
bool isEmpty() ;
int getLength() ;
bool insert(string &newCoauthorFirstName, string &newCoauthorLastName, string &newCoauthorInstitution, string &newPaperTitle, int &newYear);
bool remove(int position, string &newCoauthorFirstName, string &newCoauthorLastName, string &newCoauthorInstitution, string &newPaperTitle, int &newYear);
void retrieve(int position, string &newCoauthorFirstName, string &newCoauthorLastName, string &newCoauthorInstitution, string &newPaperTitle, int &newYear);
void clear();
bool check(string coauthorFirstName, string coauthorLastName, string &institution, string &newPaperTitle);
protected:
private:
struct Node{
Node *next;
string coauthorFirstName;
string coauthorLastName;
string coauthorInstitution;
string paperTitle;
int year;
};
int size;
Node *find(int index);
Node *head;
};
#endif // LL_H
|
34bd83cfe30ccfc31530a67b3dff36f80295a1f7 | 1e341b74dd9ff680fc1347c1d33e2ac5fade025f | /src/include/errors.h | cece52d205f64978759906f12e99581e9ebb5b9d | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | permissive | italiangrid/voms | 908ff25b3ff5abc5442b3d1f1abc5c72229e5d65 | 92cbea9144546789d90705f160b01d116ace16d2 | refs/heads/master | 2023-07-09T02:25:51.262940 | 2021-04-01T15:56:11 | 2021-04-01T15:56:11 | 2,971,378 | 7 | 10 | Apache-2.0 | 2023-09-07T21:16:46 | 2011-12-13T10:09:43 | C | UTF-8 | C++ | false | false | 1,732 | h | errors.h | /*********************************************************************
*
* Authors: Vincenzo Ciaschini - Vincenzo.Ciaschini@cnaf.infn.it
*
* Copyright (c) Members of the EGEE Collaboration. 2004-2010.
* See http://www.eu-egee.org/partners/ for details on the copyright holders.
*
* 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.
*
* Parts of this code may be based upon or even include verbatim pieces,
* originally written by other people, in which case the original header
* follows.
*
*********************************************************************/
#ifndef VOMS_ERRORS_H
#define VOMS_ERRORS_H
#include <string>
struct errorp {
int num;
std::string message;
};
#define ERROR_OFFSET 1000
#define WARN_OFFSET 0
#define WARN_NO_FIRST_SELECT (WARN_OFFSET + 1)
#define WARN_SHORT_VALIDITY (WARN_OFFSET + 2)
#define WARN_ATTR_SUBSET (WARN_OFFSET + 3)
#define WARN_UNKNOWN_COMMAND (WARN_OFFSET + 4)
#define ERR_WITH_DB (ERROR_OFFSET + 3)
#define ERR_NOT_MEMBER (ERROR_OFFSET + 1)
#define ERR_ATTR_EMPTY (ERROR_OFFSET + 2)
#define ERR_SUSPENDED (ERROR_OFFSET + 4)
#define ERR_NO_COMMAND (ERROR_OFFSET + 5)
#define ERR_UNEXPECTED_ERROR (ERROR_OFFSET + 6)
#endif
|
013e5aed2db9736dba9415b0d8fdbe96761fc9ab | 9fb2139bf41e2301f9ee9069d649c5afe8e7735c | /folders/LeetCode C++ Solutions/partition-equal-subset-sum.cpp | 592fdf6ec349e494596b56a5952eb5941f32ef6c | [] | no_license | codewithgauri/HacktoberFest | 9bc23289b4d93f7832271644a2ded2a83aa22c87 | 8ce8f687a4fb7c3953d1e0a5b314e21e4553366e | refs/heads/master | 2023-01-02T07:20:51.634263 | 2020-10-26T07:02:34 | 2020-10-26T07:02:34 | 307,285,210 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 958 | cpp | partition-equal-subset-sum.cpp | /**
* Author: Siddhant Pandya
* Problem: 416. Partition Equal Subset Sum
*/
class Solution {
public:
int oor(int i, int j)
{
if(i==1 || j==1)
{
return 1;
}
return 0;
}
bool canPartition(vector<int>& arr) {
int n=arr.size();
sort(arr.begin(),arr.end());
int sum=0;
for(int x=0;x<n;x++)
{
sum+=arr[x];
}
if(sum%2!=0)
{
return false;
}
else
{
sum/=2;
int dp[n+1][sum+1];
//initialisation
for(int x=0;x<=sum;x++)
{
dp[0][x]=0;
}
for(int x=0;x<=n;x++)
{
dp[x][0]=1;
}
//table filling
for(int x=1;x<=n;x++)
{
for(int y=1;y<=sum;y++)
{
if(arr[x-1]<=y)
{
dp[x][y]= oor(dp[x-1][y-arr[x-1]],dp[x-1][y]);
}
else
{
dp[x][y]=dp[x-1][y];
}
}
}
if(dp[n][sum]==1)
{
return true;
}
else
{
return false;
}
}
}
}; |
13a07f82ec33478cfd206cc7e34801352d9e1637 | 7645c1224abf4465be86595e1ae76c94a6c37e40 | /14/main.cpp | 9b45ac44a0858369eb1580bc3248dc28d9000b26 | [] | no_license | Sofon/15Variant | 265d833bfb21640720d910a2459f0959fef47233 | c59450246e0306da8f4e9df5a8546f4e335785f6 | refs/heads/master | 2016-09-08T01:37:32.478462 | 2013-06-08T14:47:59 | 2013-06-08T14:47:59 | null | 0 | 0 | null | null | null | null | MacCyrillic | C++ | false | false | 1,232 | cpp | main.cpp | /*
если сумма элементов последнего столбца матрицы положительна,
присвоить каждому из элементов х1,х2,..хn
значение среднего арифметического соответсвующей стороки матрицы
*/
//---------------------------------------------------------------------------
#include <stdio.h>
#include <conio.h>
#pragma hdrstop
#include <tchar.h>
#include <H:\»Ќ‘ќ–ћј“» ј ЋјЅџ\2 семестр\14\matr.cpp>
//---------------------------------------------------------------------------
#pragma argsused
int _tmain(int argc, _TCHAR* argv[])
{
float** a;
int n,m;
int& nss=n;int& mss=m;
a=reading(nss,mss);
writing(a,n,m);
int summ=0;
for (int i = 0; i < n; i++) {
summ+=a[i][m-1];
}
if (summ>0) {
float sr=0;
for (int i = 0; i < n; i++) {
sr=0;
for (int j = 0; j < m; j++) {
sr+=a[i][j];
}
sr=sr/m;
a[i][m-1]=sr;
}
}
printf("posle vipolnenia ");
writing(a,n,m);
printf("end\n");
getch();
return 0;
}
//---------------------------------------------------------------------------
|
40835889d323b0be50e8d3b11103feefca0086b6 | 70441dcb7a8917a5574dd74c5afdeeaed3672a7a | /AtCoder Beginner Contest 097/D - Equals/main.cpp | 0739b97779a8a68a0b90298ca8c41b2e3b12def6 | [] | no_license | tmyksj/atcoder | f12ecf6255b668792d83621369194195f06c10f6 | 419165e85d8a9a0614e5544232da371d8a2f2f85 | refs/heads/master | 2023-03-05T12:14:14.945257 | 2023-02-26T10:10:20 | 2023-02-26T10:10:20 | 195,034,198 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,278 | cpp | main.cpp | #include <iostream>
#include <vector>
using namespace std;
class union_find {
vector<int> parent;
vector<int> rank;
public:
union_find(int n) {
parent = vector<int>(n);
rank = vector<int>(n);
for (int i = 0; i < n; i++) {
parent[i] = i;
rank[i] = 0;
}
}
int root(int a) {
if (parent[a] != a) {
parent[a] = this->root(parent[a]);
}
return parent[a];
}
void unite(int a, int b) {
int ra = this->root(a);
int rb = this->root(b);
if (ra == rb) {
return;
}
if (rank[ra] < rank[rb]) {
parent[ra] = rb;
} else {
parent[rb] = ra;
if (rank[ra] == rank[rb]) {
rank[ra]++;
}
}
}
};
int main() {
int n, m;
cin >> n >> m;
vector<int> p(n);
for (int i = 0; i < n; i++) {
cin >> p[i];
p[i]--;
}
union_find uf(n);
for (int i = 0; i < m; i++) {
int x, y;
cin >> x >> y;
uf.unite(x - 1, y - 1);
}
int res = 0;
for (int i = 0; i < n; i++) {
if (uf.root(i) == uf.root(p[i])) {
res++;
}
}
cout << res << endl;
}
|
2b50e0dbf3721829d01ab9d70faa94b18e86458f | 7bdb0610be5f518822ff9be66ee83107cea9c34d | /Innopolis 2017/Day 9/a.cpp | 09f8e6bc895960c66dc4b2a145470674fe8e9005 | [] | no_license | nikitonsky/olymptasks | 6024932f3479a670c9d06fb1d9a490ebfe3b9b0e | 2442efba39085a82aa197c3351a845b753502d84 | refs/heads/master | 2021-03-27T20:20:46.358261 | 2017-11-20T12:41:48 | 2017-11-20T12:41:48 | 96,989,723 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,422 | cpp | a.cpp | #include<iostream>
#include<vector>
#include<cmath>
#include<set>
#include<map>
#include<algorithm>
#include<deque>
#include<queue>
#include<string>
#include<stack>
#include<iomanip>
#include<fstream>
#include<ctime>
#define lli long long int
using namespace std;
int main() {
#ifdef _DEBUG
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#else
freopen("pathmgep.in", "r", stdin);
freopen("pathmgep.out", "w", stdout);
#endif // _DEBUG
cin.tie(0);
cout.tie(0);
ios_base::sync_with_stdio(0);
lli n, f, t;
cin >> n>>f>>t;
--f, --t;
vector < vector<pair<lli, lli>>> a(n, vector<pair<lli, lli>>());
for (lli i = 0; i < n; i++) {
for (lli j = 0; j < n; j++) {
lli c;
cin >> c;
if (c < 1) continue;
a[i].push_back({ j,c });
}
}
vector<lli> dist(n, INT64_MAX);
dist[f] = 0;
set <pair<lli, lli>> q;
q.insert({ 0,f });
while (!q.empty()) {
lli cur = q.begin()->second;
q.erase(q.begin());
for (auto now : a[cur]) {
if (dist[now.first] > dist[cur] + now.second) {
q.erase({ dist[now.first], now.first });
dist[now.first] = dist[cur] + now.second;
q.insert({ dist[now.first],now.first });
}
}
}
if (dist[t] == INT64_MAX) cout << -1;
else cout << dist[t];
} |
8f10f77997d0d2014fd9d299d4a6c39298dfb8a4 | 8292e1f6f3ff4fa0afd8aafe9aaaa5135d82d077 | /OOP Homework/Thuc hanh/Week7/Exercise 1/Worker.cpp | b6936504188313fbf90ab4b169e80a430edc4f75 | [] | no_license | lkdn3t/First-Year-In-UIT | b03abcd18506d5916bac609d536bb333e7a4f03d | ca7a5f4c1ca81bd7898176d24fb027891303321e | refs/heads/master | 2021-04-06T04:02:07.216858 | 2018-07-03T14:17:10 | 2018-07-03T14:17:10 | 123,702,504 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,239 | cpp | Worker.cpp | #include "Worker.h"
using namespace std;
//----------------- FOR WORKER-------------------- -
Worker::Worker() { }
void Worker::setName(string name) { Name = name; }
void Worker::setBirth(int d, int m, int y) {
Birth.day = d;
Birth.month = m;
Birth.year = y;
}
void Worker::setSalary(long long salary) { Salary = salary; }
string Worker::getName() const { return Name; }
int Worker::getBirthDay() const { return Birth.day; }
int Worker::getBirthMonth() const { return Birth.month; }
int Worker::getBirthYear() const { return Birth.year; }
long long Worker::getSalary() const { return Salary; }
void Worker::input()
{
cout << "Enter worker name: " ; getline(cin, Name);
cout << "Enter day of birth: " ; cin >> Birth.day;
cout << "Enter month of birth: "; cin >> Birth.month;
cout << "Enter year of birth: " ; cin >> Birth.year;
cout << "Enter salary: " ; cin >> Salary;
}
void Worker::output() const
{
cout << "Worker name: " << Name << endl;
cout << "Date of birth: " << Birth.day << "/" << Birth.month << "/" << Birth.year << endl;
cout << "Salary: " << Salary << endl;
}
void Worker::computeSalary()
{
return;
}
//-----------------FOR PRODUCTION WORKER---------------------
void ProductionWorker::input()
{
cout << "Enter worker name: " ; getline(cin, Name);
cout << "Enter day of birth: " ; cin >> Birth.day;
cout << "Enter month of birth: " ; cin >> Birth.month;
cout << "Enter year of birth: " ; cin >> Birth.year;
cout << "Enter base salary: " ; cin >> BaseSalary;
cout << "Enter number of products: "; cin >> NumProducts;
}
void ProductionWorker::output() const
{
cout << "Type of worker: Production Worker" << endl;
cout << "Worker name: " << Name << endl;
cout << "Date of birth: " << Birth.day << "/" << Birth.month << "/" << Birth.year << endl;
cout << "Number of products: " << NumProducts << endl;
cout << "Salary: " << Salary << endl;
}
void ProductionWorker::computeSalary() {
Salary = BaseSalary + NumProducts * 5000;
}
void ProductionWorker::setNumProducts(int np) { NumProducts = np; }
void ProductionWorker::setBaseSalary(long long bs) { BaseSalary = bs; }
int ProductionWorker::getNumProducts() const { return NumProducts; }
long long ProductionWorker::getBaseSalary() const { return BaseSalary; }
//-----------------FOR OFFICE WORKER---------------------
void OfficeWorker::input()
{
cout << "Enter worker name: " ; getline(cin, Name);
cout << "Enter day of birth: " ; cin >> Birth.day;
cout << "Enter month of birth: " ; cin >> Birth.month;
cout << "Enter year of birth: " ; cin >> Birth.year;
cout << "Enter number of products: "; cin >> WorkDays;
}
void OfficeWorker::output() const
{
cout << "Type of worker: Office Worker" << endl;
cout << "Worker name: " << Name << endl;
cout << "Date of birth: " << Birth.day << "/" << Birth.month << "/" << Birth.year << endl;
cout << "Number of work days: " << WorkDays << endl;
cout << "Salary: " << Salary << endl;
}
void OfficeWorker::computeSalary()
{
Salary = WorkDays * 100000;
}
int OfficeWorker::getWorkDays() const { return WorkDays; }
void OfficeWorker::setWorkDays(int wd) { WorkDays = wd; } |
2d2e1fb302108d8c1d88ae165bd3d515ec5e537b | fe75ab418adfd723f48b8eafc80515c9fd913395 | /LeetCode/!0448. Find All Numbers Disappeared in an Array.cpp | 1457b4ea280a97009dda1e46319d5abf8ec3ea8e | [] | no_license | AshkenSC/Programming-Practice | d029e9d901f51ef750ed4089f10c1f16783d2695 | 98e20c63ce1590deda6761ff2f9c8c37f3fb3c4a | refs/heads/master | 2021-07-20T06:41:12.673248 | 2021-06-25T15:44:06 | 2021-06-25T15:44:06 | 127,313,792 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,111 | cpp | !0448. Find All Numbers Disappeared in an Array.cpp | /*
0448. Find All Numbers Disappeared in an Array
给定一个整数数组,1 ≤ a[i] ≤ n(n是数组大小)。有些元素出现两次,有些只出现一次。
找到所有一次都没出现过的数。你能否在O(n)时间内,不用额外空间实现它?
思路:
遍历数组a的元素,根据元素的取值,将其作为索引找到的数组的值+n。比如遍历到a[i]=3,则将a[3]的值加n。
这样要注意的是,再往后会遇到加n以后的数组值,所以每次取数组值的时候,需要a[i] % a.size()。这样,最后哪个位置的值小于等于n,哪个位置就是没出现的数。
*/
class Solution {
public:
vector<int> findDisappearedNumbers(vector<int>& nums) {
vector<int> disappearedNumbers;
for (int i = 0; i < nums.size(); i++) {
int index = (nums[i] - 1) % nums.size();
nums[index] += nums.size();
}
for (int i = 0; i < nums.size(); i++) {
if (nums[i] <= nums.size())
disappearedNumbers.push_back(i + 1);
}
return disappearedNumbers;
}
}; |
8fc3868af3d72ffe16c6f25846ad0abf8ce6defc | a411d09be03ca3644eda3bb0e6f27a952f7c734a | /lc/mainwindow (another copy).cpp | 32906948f61b822be08cbfcc406a0b3f500f670b | [] | no_license | VasilyevGeorgy/LaunchCreator | 7bb412078aee2e8f4c55bbb42a57ed96bcfc461b | a6324279537509ce35e58512d518a19e8e662e08 | refs/heads/master | 2020-03-28T14:50:55.732486 | 2018-09-20T23:57:03 | 2018-09-20T23:57:03 | 148,528,568 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 18,041 | cpp | mainwindow (another copy).cpp | #include "mainwindow.h"
#include "ui_mainwindow.h"
#include <qfiledialog.h>
#include <qmessagebox.h>
#include <QProcess>
#include <QFile>
#include <QTextStream>
#include <QColor>
#include <QColorDialog>
#include <QDir>
#include <QList>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
setWindowTitle("Launch Creator v0.1");
ui->checkBox->setChecked(true);
ui->checkBox_2->setChecked(false);
ui->checkBox_3->setChecked(true);
ui->checkBox_4->setChecked(true);
ui->checkBox_5->setChecked(false);
ui->checkBox_6->setChecked(false);
ui->groupBox->setEnabled(false);
default_params = true;
in_gazebo_ros = false;
QStringList env = QProcess::systemEnvironment();
home_name = env.at(env.indexOf(QRegExp("^HOME=.+")));
home_name.remove(0,5);
}
MainWindow::~MainWindow()
{
delete ui;
}
QString MainWindow::boolToString(bool a){
QString result;
if (a) result = "true";
else result = "false";
return result;
}
void MainWindow::on_checkBox_8_stateChanged(int arg1)
{
// Empty world checkbox
if (ui->checkBox_8->isChecked()){
ui->lineEdit->setEnabled(false);
ui->browse->setEnabled(false);
ui->lineEdit->setText("");
empty_world = true;
}
else{
ui->lineEdit->setEnabled(true);
ui->browse->setEnabled(true);
empty_world = false;
}
}
bool MainWindow::lfname_check(){
QString launch_name = ui->lineEdit_2->text();
QRegExp lfn_check("[a-zA-Z0-9]*.launch");
lfn_check.setPatternSyntax(QRegExp::Wildcard);
if (launch_name.isEmpty() || !lfn_check.exactMatch(launch_name)){
ui->lineEdit_2->setText("Enter name of launch-file!");
//ui->lineEdit_2->setStyleSheet("color: red;");
return false;
}
//lfname = launch_name;
return true;
}
bool MainWindow::lfpath_check(){
QString launch_path = ui->lineEdit_3->text();
QRegExp lfp_check("[/][a-zA-Z0-9_/]*"); // [^/]*
//lfp_check.setPatternSyntax(QRegExp::Wildcard);
if (launch_path.isEmpty() || !lfp_check.exactMatch(launch_path)){
ui->lineEdit_3->setText("Enter path of launch-file!");
//ui->lineEdit_2->setStyleSheet("color: red;");
return false;
}
//lfolder_path = launch_path;
return true;
}
bool MainWindow::world_check(){
QString world_name = ui->lineEdit->text();
QRegExp wn_check("*.launch");
wn_check.setPatternSyntax(QRegExp::Wildcard);
QRegExp wn_check1("*.world");
wn_check1.setPatternSyntax(QRegExp::Wildcard);
if(world_name.isEmpty() || (!wn_check.exactMatch(world_name) && !wn_check1.exactMatch(world_name))){
ui->lineEdit->setText("Enter name of world or launch file!");
//ui->lineEdit_4->setText(boolToString(wn_check1.exactMatch(world_name)));
return false;
}
//world = world_name;
return true;
}
bool MainWindow::nname_check(){
QString node_name = ui->lineEdit_5->text();
QRegExp nn_check("(\\w+)");
//nn_check.setPatternSyntax(QRegExp::Wildcard);
if(node_name.isEmpty() || !nn_check.exactMatch(node_name)){
ui->lineEdit_5->setText("Enter node name!");
ui->lineEdit_4->setText(boolToString(nn_check.exactMatch(node_name)));
return false;
}
return true;
}
void MainWindow::add_params(QStringList &list_name){
list_name << " <!-- these are the arguments you can pass this launch file -->";
list_name << " <arg name=\"paused\" default=\"" + boolToString(paused) + "\" />";
list_name << " <arg name=\"use_sim_time\" default=\"" + boolToString(use_sim_time) + "\" />";
list_name << " <arg name=\"gui\" default=\"" + boolToString(gui) + "\" />";
list_name << " <arg name=\"respawn_gazebo\" default=\"" + boolToString(respawn_gazebo) + "\" />";
list_name << " <arg name=\"debug\" default=\"" + boolToString(debug) + "\" />";
list_name << "";
}
void MainWindow::add_args(QStringList& list_name){
list_name << " <arg name=\"paused\" value=\"$(arg paused)\" />";
list_name << " <arg name=\"use_sim_time\" value=\"$(arg use_sim_time)\" />";
list_name << " <arg name=\"gui\" value=\"$(arg gui)\" />";
list_name << " <arg name=\"respawn_gazebo\" value=\"$(arg respawn_gazebo)\" />";
list_name << " <arg name=\"debug\" value=\"$(arg debug)\" />";
}
void MainWindow::write_file(QString folder_path, QString file_path, QStringList& list_name){
if (!QDir(folder_path).exists())
QDir().mkdir(folder_path);
QFile file_out(file_path);
if (file_out.open(QIODevice::ReadWrite))
{
QTextStream out(&file_out);
for (QStringList::Iterator it = list_name.begin();
it != list_name.end(); ++it)
out << *it << "\n";
}
file_out.close();
file_out.setPermissions(QFile::ReadOwner | QFile::ReadUser | QFile::ReadGroup);
}
//Launch file generation thru empty_world.launch
void MainWindow::thru_empty(QString launch_name, bool is_default_params){
QStringList launch;
launch << "<launch>";
QStringList& flref = launch;
if (!is_default_params){
add_params(flref);
launch << " <!-- Launch empty_world with parameters -->";
launch << " <include file=\"$(find gazebo_ros)/launch/empty_world.launch\">";
}
else{
launch << " <!-- Launch empty_world with -->";
launch << " <include file=\"$(find gazebo_ros)/launch/empty_world.launch\">";
}
if (in_gazebo_ros){
//Get world name
QStringList list = world.split('/',QString::SkipEmptyParts);
QString world_name = list.at(list.indexOf(QRegExp("[a-zA-Z0-9_]*.launch")));
world_name = world_name.left(world_name.lastIndexOf(QChar('.')));
world_name = world_name.replace('_','.');
launch << " <arg name=\"world_name\" value=\"worlds/" + world_name + "\" />";
}
else{
//Filename extension check
QStringList list = world.split('.',QString::SkipEmptyParts);
QString world_extension = list.at(1);
if (world_extension == "launch"){
ui->lineEdit->setText("Choose it properly!");
return;
}
launch << " <arg name=\"world_name\" value=\"" + world + "\" />";
}
if (default_params)
launch << " </include>";
else{
add_args(flref);
launch << " </include>";
}
launch << "</launch>";
write_file(lfolder_path, lfolder_path + "/" + launch_name, launch);
}
//Overloading
void MainWindow::thru_empty(QString launch_name, bool is_default_params, QString node_name, QString package_name){
QStringList launch;
launch << "<launch>";
QStringList& flref1 = launch;
if (!is_default_params){
add_params(flref1);
launch << " <!-- Launch empty_world with parameters -->";
launch << " <include file=\"$(find gazebo_ros)/launch/empty_world.launch\">";
}
else{
launch << " <!-- Launch empty_world with -->";
launch << " <include file=\"$(find gazebo_ros)/launch/empty_world.launch\">";
}
if (in_gazebo_ros){
//Get world name
QStringList list = world.split('/',QString::SkipEmptyParts);
QString world_name = list.at(list.indexOf(QRegExp("[a-zA-Z0-9_]*.launch")));
world_name = world_name.left(world_name.lastIndexOf(QChar('.')));
world_name = world_name.replace('_','.');
launch << " <arg name=\"world_name\" value=\"worlds/" + world_name + "\" />";
}
else{
//Filename extension check
QStringList list = world.split('.',QString::SkipEmptyParts);
QString world_extension = list.at(1);
if (world_extension == "launch"){
ui->lineEdit->setText("Choose it properly!");
return;
}
launch << " <arg name=\"world_name\" value=\"" + world + "\" />";
}
if (default_params)
launch << " </include>";
else{
add_args(flref1);
launch << " </include>";
}
launch << "";
launch << " <node name =\""+node_name+"\" pkg=\""+package_name+"\" type=\""+node_name+"\" output=\"screen\" />";
launch << "</launch>";
write_file(lfolder_path, lfolder_path + "/" + launch_name, launch);
//QStringList name_list = launch_name.split('.',QString::SkipEmptyParts);
//launch_name = name_list.at(0) + "_1.launch";
}
void MainWindow::on_browse_clicked()
{
QString world_name = QFileDialog::getOpenFileName(
this,
tr("Choose World"),
"/opt/ros/kinetic/share/gazebo_ros/launch",
"launch files (*.launch);; world files (*.world)"
);
//world = "/opt/ros/kinetic/share/gazebo_ros/launch" + world_name;
ui->lineEdit->setText("");
ui->lineEdit->setText(world_name);
}
void MainWindow::on_browse1_clicked()
{
if(!lfname_check())
return;
QString create_in = QFileDialog::getExistingDirectory(
this,
tr("Choose package"),
home_name,
QFileDialog::ShowDirsOnly
);
//lfolder_path = create_in;
//lfile_path = lfolder_path +"/"+lfname;
ui->lineEdit_3->setText(create_in);
}
void MainWindow::on_checkBox_stateChanged(int arg1)
{
ui->groupBox->setEnabled(true);
default_params = false;
if (ui->checkBox->isChecked()){
ui->checkBox_2->setChecked(false);
ui->checkBox_3->setChecked(true);
ui->checkBox_4->setChecked(true);
ui->checkBox_5->setChecked(false);
ui->checkBox_6->setChecked(false);
ui->groupBox->setEnabled(false);
}
}
void MainWindow::on_buttonBox_2_accepted()
{
//Check empty fields
if( !((!world_check() && empty_world) || (world_check() && !empty_world))
|| !lfname_check() || !lfpath_check()
|| (ui->lineEdit_3->text().isEmpty()) || !nname_check()){
return;
}
//Empty && TurtleBot check
turtlebot_world = ui->checkBox_9->isChecked();
//Get file name and directory path
world = ui->lineEdit->text();
lfolder_path = ui->lineEdit_3->text() + "/launch";
lfile_path = lfolder_path + "/" + ui->lineEdit_2->text();
//Get args
paused = ui->checkBox_2->isChecked();
use_sim_time = ui->checkBox_3->isChecked();
gui = ui->checkBox_4->isChecked();
respawn_gazebo = ui->checkBox_5->isChecked();
debug = ui->checkBox_6->isChecked();
//gazebo_ros check
QRegExp type_check("/opt/ros/kinetic/share/gazebo_ros/launch/[a-zA-Z0-9_]*.launch");
type_check.setPatternSyntax(QRegExp::Wildcard);
in_gazebo_ros = type_check.exactMatch(world);
//Get node
node = ui->lineEdit_5->text();
//Get package
QStringList p_list = (ui->lineEdit_3->text()).split('/',QString::SkipEmptyParts);
QString package = p_list.last();
//ui->lineEdit_4->setText(package);
//Compose launch-list
QStringList& flref = final_launch;
/// (in_gazebo_ros && default_params) && (in_gazebo_ros && !default_params)
if (empty_world && turtlebot_world){
final_launch << "<launch>";
if (default_params){
final_launch << " <!-- Launch turtlebot_world -->";
final_launch << " <include file=\"$(find turtlebot_gazebo)/launch/turtlebot_world.launch\" />";
}
else{
add_params(flref);
final_launch << " <!-- Launch turtlebot_world with parameters -->";
final_launch << " <include file=\"$(find turtlebot_gazebo)/launch/turtlebot_world.launch\" >";
add_args(flref);
final_launch << " </include>";
}
final_launch << "";
final_launch << " <!-- Launch node -->";
final_launch << " <node name =\""+node+"\" pkg=\""+package+"\" type=\""+node+"\" output=\"screen\" />";
final_launch << "</launch>";
write_file(lfolder_path, lfile_path, flref);
}
if (empty_world && !turtlebot_world){
final_launch << "<launch>";
if (default_params){
final_launch << " <!-- launch empty_world -->";
final_launch << " <include file=\"$(find gazebo_ros)/launch/empty_world.launch\" />";
}
else{
add_params(flref);
final_launch << " <!-- launch empty_world with parameters -->";
final_launch << " <include file=\"$(find gazebo_ros)/launch/empty_world.launch\" >";
add_args(flref);
final_launch << " </include>";
}
final_launch << "";
final_launch << " <!-- Launch node -->";
final_launch << " <node name =\""+node+"\" pkg=\""+package+"\" type=\""+node+"\" output=\"screen\" />";
final_launch << "</launch>";
write_file(lfolder_path, lfile_path, flref);
}
if (!empty_world && !turtlebot_world){
thru_empty(ui->lineEdit_2->text(), default_params, node, package);
}
if (!empty_world && turtlebot_world){
//world thru emty
QStringList name_list = ui->lineEdit_2->text().split('.',QString::SkipEmptyParts);
//thru_empty(name_list.at(0) + "_1.launch", true);
//turtlebot launch file
QStringList tb_launch;
tb_launch << "<launch>";
tb_launch << " <arg name=\"world_file\" default=\"$(env TURTLEBOT_GAZEBO_WORLD_FILE)\"/>";
tb_launch << " <arg name=\"base\" value=\"$(optenv TURTLEBOT_BASE kobuki)\"/>";
tb_launch << " <arg name=\"battery\" value=\"$(optenv TURTLEBOT_BATTERY /proc/acpi/battery/BAT0)\"/>";
tb_launch << " <arg name=\"stacks\" value=\"$(optenv TURTLEBOT_STACKS hexagons)\"/>";
tb_launch << " <arg name=\"3d_sensor\" value=\"$(optenv TURTLEBOT_3D_SENSOR kinect)\"/>";
tb_launch << " <arg name=\"gui\" default=\"true\"/>";
tb_launch << "";
///tb_launch << " <include file=\""+lfolder_path+"/"+name_list.at(0)+"_1.launch\">";
tb_launch << " <include file=\"$(find gazebo_ros)/launch/empty_world.launch\">";
tb_launch << " <arg name=\"world_name\" value=\"$(arg world_file)\"/>";
tb_launch << " </include>";
tb_launch << "";
tb_launch << " <include file=\"$(find turtlebot_gazebo)/launch/includes/$(arg base).launch.xml\">";
tb_launch << " <arg name=\"base\" value=\"$(arg base)\"/>";
tb_launch << " <arg name=\"stacks\" value=\"$(arg stacks)\"/>";
tb_launch << " <arg name=\"3d_sensor\" value=\"$(arg 3d_sensor)\"/>";
tb_launch << " </include>";
tb_launch << "";
tb_launch << " <node pkg=\"robot_state_publisher\" type=\"robot_state_publisher\" name=\"robot_state_publisher\">";
tb_launch << " <param name=\"publish_frequency\" type=\"double\" value=\"30.0\" />";
tb_launch << " </node>";
tb_launch << "";
tb_launch << " <!-- Fake laser -->";
tb_launch << " <node pkg=\"nodelet\" type=\"nodelet\" name=\"laserscan_nodelet_manager\" args=\"manager\"/>";
tb_launch << " <node pkg=\"nodelet\" type=\"nodelet\" name=\"depthimage_to_laserscan\"";
tb_launch << " args=\"load depthimage_to_laserscan/DepthImageToLaserScanNodelet laserscan_nodelet_manager\">";
tb_launch << " <param name=\"scan_height\" value=\"10\"/>";
tb_launch << " <param name=\"output_frame_id\" value=\"/camera_depth_frame\"/>";
tb_launch << " <param name=\"range_min\" value=\"0.45\"/>";
tb_launch << " <remap from=\"image\" to=\"/camera/depth/image_raw\"/>";
tb_launch << " <remap from=\"scan\" to=\"/scan\"/>";
tb_launch << " </node>";
tb_launch << "</launch>";
QStringList &tbref = tb_launch;
QString tb_name = lfolder_path+"/"+name_list.at(0)+"_1.launch";
write_file(lfolder_path, tb_name, tbref);
//executable file
final_launch << "<launch>";
if (!default_params){
add_params(flref);
final_launch << " <!-- Launch turtlebot_world with parameters -->";
final_launch << " <include file=\"" + tb_name +"\">";
}
else{
final_launch << " <!-- Launch turtlebot_world -->";
final_launch << " <include file=\"" + tb_name +"\">";
}
if (in_gazebo_ros){
//Get world name
QStringList list = world.split('/',QString::SkipEmptyParts);
QString world_name = list.at(list.indexOf(QRegExp("[a-zA-Z0-9_]*.launch")));
world_name = world_name.left(world_name.lastIndexOf(QChar('.')));
world_name = world_name.replace('_','.');
final_launch << " <arg name=\"world_file\" value=\"worlds/" + world_name + "\" />";
}
else{
//Filename extension check
QStringList list = world.split('.',QString::SkipEmptyParts);
QString world_extension = list.at(1);
if (world_extension == "launch"){
ui->lineEdit->setText("Choose it properly!");
return;
}
final_launch << " <arg name=\"world_name\" value=\"" + world + "\" />";
}
if (default_params)
final_launch << " </include>";
else{
add_args(flref);
final_launch << " </include>";
}
final_launch << "";
final_launch << " <!-- Launch node -->";
final_launch << " <node name =\""+node+"\" pkg=\""+package+"\" type=\""+node+"\" output=\"screen\" />";
final_launch << "</launch>";
write_file(lfolder_path, lfile_path, flref);
}
//<node name="spawn_urdf"pkg="gazebo_ros" type="spawn_model" respawn="false" args="-param robot_description -urdf -model hobo" />
if(QFile(lfile_path).exists())
QMessageBox::information(0, "LaunchCreatorMessage", "Launch file is created!");
}
void MainWindow::on_buttonBox_2_rejected()
{
QApplication::quit();
}
|
933dcf694f25a337e37a34c7e481a47a2e8f4af8 | cf5d980e9b37daebc95d088b3ad3d3ba34c65249 | /pkg-config-0.28/pixman-0.30.0/cairo-1.12.18/test/extend-reflect.c | 16b08c1550ff3582aae60e0fbaa5b8bfe0ae4ebd | [
"MIT",
"FSFUL",
"LicenseRef-scancode-public-domain",
"MPL-1.1",
"MPL-1.0",
"LGPL-2.1-only",
"LGPL-2.1-or-later",
"GPL-1.0-or-later",
"LicenseRef-scancode-other-permissive",
"GPL-2.0-only"
] | permissive | hbzhang/inventorymanagement | 6bd800c26e39763364f0cd919caeacf731cb2f1f | 93cb8608545fd2bae71ac8632368594ffa3ab040 | refs/heads/master | 2023-01-28T18:03:06.185315 | 2019-09-25T14:51:44 | 2019-09-25T14:51:44 | 210,862,224 | 0 | 0 | MIT | 2023-01-11T05:53:53 | 2019-09-25T14:13:42 | null | UTF-8 | C++ | false | false | 766 | c | extend-reflect.c | #include <math.h>
#include "cairo-test.h"
#include <stdio.h>
static const char *png_filename = "romedalen.png";
static cairo_test_status_t
draw (cairo_t *cr, int width, int height)
{
const cairo_test_context_t *ctx = cairo_test_get_context (cr);
cairo_surface_t *surface;
surface = cairo_test_create_surface_from_png (ctx, png_filename);
cairo_set_source_surface (cr, surface, 32, 32);
cairo_pattern_set_extend (cairo_get_source (cr), CAIRO_EXTEND_REFLECT);
cairo_paint (cr);
cairo_surface_destroy (surface);
return CAIRO_TEST_SUCCESS;
}
CAIRO_TEST (extend_reflect,
"Test CAIRO_EXTEND_REFLECT for surface patterns",
"extend", /* keywords */
NULL, /* requirements */
256 + 32*2, 192 + 32*2,
NULL, draw)
|
48ae4f3f91178a423bc12dd149211e893c12b99e | e0beee526a664c376597bca5320b40d8b698770b | /Homeworks/HW-1/Task-4/task-4.cpp | 712819e4b257b7174d0a5c92fc54fe0a5ce5679a | [
"MIT"
] | permissive | kgolov/uni-data-structures | c74ea00d36c1139c0e02ca94219fd7249645d4ac | 8d8b2ff75ffa0ceed3ebe7bbc294680134b7d1c1 | refs/heads/master | 2021-03-10T00:41:00.619457 | 2020-04-18T21:41:55 | 2020-04-18T21:41:55 | 246,399,607 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,092 | cpp | task-4.cpp | #include <iostream>
#include <vector>
bool cloningSocks(int normalTarget, int copiesTarget) {
int normal = 1;
int copies = 0;
while (normal < normalTarget) {
// Run normal copying
normal++;
copies++;
}
// We now get the exact number of normal socks
// See if we can get the number of copies
if (copies > 0) {
while (copiesTarget > copies) {
copies += 2;
}
}
// Check if we have enough or more
if (normal == normalTarget && copies == copiesTarget) {
return true;
}
else {
return false;
}
}
int main() {
int t;
std::cin >> t;
std::vector<bool> output;
for (int i = 0; i < t; i++) {
int n;
int m;
std::cin >> n;
std::cin >> m;
bool result = cloningSocks(m, n);
output.push_back(result);
}
for (int i = 0; i < t; i++) {
if (output[i]) {
std::cout << "yes" << std::endl;
}
else {
std::cout << "no" << std::endl;
}
}
return 0;
}
|
a0d154c959bb3f2dc1428b9b924ea3158c0be99f | 8e3b4c1c6c4d5eeefd0bcbb9f7d5c8439c84677f | /第三章作业/shan/Cpp1.cpp | 006035665625e9bf9c43fa0c1fc11402bd7b2015 | [] | no_license | DomainMiller/c- | 358af1ce0976c150d089be0ec442abcb730ba5f2 | 2f06d321444a171ca20069c19112add62cf72bd0 | refs/heads/main | 2023-07-26T10:36:38.904065 | 2021-09-03T14:14:05 | 2021-09-03T14:14:05 | 402,793,833 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 440 | cpp | Cpp1.cpp | #include <stdio.h>
int main()
{
int a[8];
while (1) {
for (int i = 0; i < 8; i++) {
int mountain_h;
scanf("%d", &mountain_h);
a[i]=mountain_h;
}
int max=0;
for(int j=0;j<=7;j++)
{
for(int k=0;k<=7;k++)
{
if(a[k]>a[max]) max=k;
}
printf("%d\n",max);
a[max]=a[max]-3;
}
return 0;
}
}
|
6682def1fd0a9f58eb8acaff3c2da0af4d3038ad | 4d8c1f32ba90390b8be3cc872453de02ab164246 | /krypton/jni/krypton_notification.h | 2171ce2c0a4fc58629948342b6fbbee52346d631 | [
"Apache-2.0"
] | permissive | torebal/vpn-libraries | 5b9c2cf50a4b1b1b3fdc10f46e5067ac26f2de82 | aa741f31c98f25e81e76fb5306c30233dd872598 | refs/heads/main | 2023-06-29T02:57:15.493717 | 2021-07-30T18:37:21 | 2021-07-30T18:37:21 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,975 | h | krypton_notification.h | // Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the );
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an 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 PRIVACY_NET_KRYPTON_JNI_KRYPTON_NOTIFICATION_H_
#define PRIVACY_NET_KRYPTON_JNI_KRYPTON_NOTIFICATION_H_
#include <cstdint>
#include "privacy/net/krypton/pal/krypton_notification_interface.h"
#include "privacy/net/krypton/proto/connection_status.proto.h"
#include "third_party/absl/status/status.h"
namespace privacy {
namespace krypton {
namespace jni {
// All krypton notifications that are eventually plumbed through JNI.
class KryptonNotification : public KryptonNotificationInterface {
public:
KryptonNotification() = default;
~KryptonNotification() override = default;
void Connected(const ConnectionStatus& status) override;
void Connecting(const ConnectingStatus& status) override;
void ControlPlaneConnected() override;
void StatusUpdated(const ConnectionStatus& status) override;
void Disconnected(const DisconnectionStatus& status) override;
void PermanentFailure(const absl::Status& status) override;
void NetworkDisconnected(const NetworkInfo& network_info,
const absl::Status& status) override;
void Crashed() override;
void WaitingToReconnect(const ReconnectionStatus& status) override;
void Snoozed(const SnoozeStatus& status) override;
void Resumed(const ResumeStatus& status) override;
};
} // namespace jni
} // namespace krypton
} // namespace privacy
#endif // PRIVACY_NET_KRYPTON_JNI_KRYPTON_NOTIFICATION_H_
|
e95ea75de76dd7f3fccee37a17c7205c29a8f021 | d812f329fe15093e621cb34b76bb0ff0f886c394 | /shooter_version1/bipyramid/bipyramid.cpp | b0cf41d80b0ce8d557113aec6087c166b49fd883 | [] | no_license | Anastasia-98Moiseeva/shooter | 3bc8b457d0ea8b67219aaa281c635f41ae020c6c | 8c433380c67e9228f4b6b5b34407877a5dbfd543 | refs/heads/master | 2022-04-23T02:01:57.188219 | 2020-04-15T18:34:56 | 2020-04-15T18:34:56 | 255,323,127 | 2 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 2,352 | cpp | bipyramid.cpp | #include "shooter_version1/tools/tools.cpp"
GLuint getBipyramidVertex(float k, glm::vec3 offset) {
GLfloat g_vertex_buffer_data[] = {
0, 2, 0,
0, 0, -1,
1, 0, 0,
0, 2, 0,
0, 0, 1,
1, 0, 0,
0, 2, 0,
0, 0, 1,
-1, 0, 0,
0, 2, 0,
0, 0, -1,
-1, 0, 0,
0, -2, 0,
0, 0, -1,
1, 0, 0,
0, -2, 0,
0, 0, 1,
1, 0, 0,
0, -2, 0,
0, 0, 1,
-1, 0, 0,
0, -2, 0,
0, 0, -1,
-1, 0, 0,
};
Tools tools = Tools();
tools.changeConfiguration(*g_vertex_buffer_data, (sizeof(g_vertex_buffer_data)) / (sizeof(g_vertex_buffer_data[0])), k, offset);
GLuint vertexbuffer;
glGenBuffers(1, &vertexbuffer);
glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer);
glBufferData(GL_ARRAY_BUFFER, sizeof(g_vertex_buffer_data), g_vertex_buffer_data, GL_STATIC_DRAW);
return vertexbuffer;
}
GLuint getBipyramidColor() {
// One color for each vertex.
static const GLfloat g_color_buffer_data[] = {
0.822f, 0.569f, 0.201f,
0.409f, 0.115f, 0.436f,
0.427f, 0.483f, 0.644f,
0.783f, 0.506f, 0.389f,
0.395f, 0.548f, 0.759f,
0.559f, 0.361f, 0.639f,
0.683f, 0.596f, 0.289f,
0.195f, 0.548f, 0.759f,
0.559f, 0.281f, 0.639f,
0.597f, 0.270f, 0.361f,
0.559f, 0.436f, 0.630f,
0.359f, 0.583f, 0.552f,
0.597f, 0.770f, 0.361f,
0.559f, 0.436f, 0.330f,
0.359f, 0.583f, 0.152f,
0.014f, 0.184f, 0.176f,
0.771f, 0.328f, 0.570f,
0.406f, 0.615f, 0.116f,
0.676f, 0.777f, 0.133f,
0.971f, 0.572f, 0.433f,
0.140f, 0.416f, 0.489f,
0.797f, 0.513f, 0.064f,
0.745f, 0.719f, 0.192f,
0.543f, 0.021f, 0.578f,
};
GLuint colorbuffer;
glGenBuffers(1, &colorbuffer);
glBindBuffer(GL_ARRAY_BUFFER, colorbuffer);
glBufferData(GL_ARRAY_BUFFER, sizeof(g_color_buffer_data), g_color_buffer_data, GL_STATIC_DRAW);
return colorbuffer;
}
|
eeeb70afad47fc0de695246ff5bb38574d9481ab | 170ab6daedec4a8f107203b6eb5cd8bed1f4ed81 | /OJ-SPOJ/SPOJ DETER3 Find The Determinant III.cpp | 5017a048c3a0f20a9473904988c7b8f3a0a5c248 | [] | no_license | sfailsthy/ACM-ICPC | 4a15930c06c5ba35ca54a5ecb0acd7de63ebe7f7 | 7e32bfc49010c55d24b68c074c800a2d492abbfd | refs/heads/master | 2021-01-11T06:07:58.598819 | 2017-01-18T13:04:23 | 2017-01-18T13:04:23 | 71,685,224 | 3 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 1,087 | cpp | SPOJ DETER3 Find The Determinant III.cpp | //created by sfailsthy 2016/12/22 13:06
#include <cstdio>
#include <iostream>
#include <cstring>
#include <algorithm>
#include <cmath>
using namespace std;
const int maxn =200+10;
typedef long long LL;
LL C[maxn][maxn];
int n;
LL Mod;
LL det(LL a[][maxn],int n){
LL ret=1;
for(int i=0;i<n;i++){
for(int j=i+1;j<n;j++){
while(a[j][i]){
LL t=a[i][i]/a[j][i];
for(int k=i;k<n;k++){
a[i][k]=(a[i][k]-a[j][k]*t)%Mod;
}
for(int k=i;k<n;k++){
swap(a[i][k],a[j][k]);
}
ret=-ret;
}
}
if(a[i][i]==0){
return 0;
}
ret=(ret*a[i][i])%Mod;
}
/*if(ret<0){
ret=-ret;
}
return ret%Mod;*/
return (ret+Mod)%Mod;
}
int main(){
while(scanf("%d%lld",&n,&Mod)==2){
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
scanf("%lld",&C[i][j]);
}
}
printf("%lld\n",det(C,n));
}
return 0;
}
|
e0db25e62dbaa14bac08bb3c2f67e383b19d0816 | 2e315c77a6dff56a9efe2d5903b15219685b62ce | /Parser.cpp | 78a664ecca02d2823e07ffd26b437eb9c0a9e44f | [] | no_license | alohashc/avm | ef3124631a9d8f2c59f92ead8a1df510089d45d9 | 83d2f4593b264471ca99998ffdefa733091ea983 | refs/heads/master | 2020-03-21T16:16:27.579458 | 2018-08-30T18:04:00 | 2018-08-30T18:04:00 | 132,354,358 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,829 | cpp | Parser.cpp | //
// Created by aloha on 6/14/18.
//
#include "Parser.hpp"
#include <regex>
Parser::Parser(std::list<Token> &tokens) : _tokens(tokens){
_instr[PUSH] = &Parser::push;
_instr[POP] = &Parser::pop;
_instr[ASSERT] = &Parser::assert;
_instr[ADD] = &Parser::add;
_instr[SUB] = &Parser::sub;
_instr[MUL] = &Parser::mul;
_instr[DIV] = &Parser::div;
_instr[MOD] = &Parser::mod;
_instr[PRINT] = &Parser::print;
_instr[DUMP] = &Parser::dump;
_instr[EXIT] = &Parser::exit;
}
Parser::~Parser() {}
void Parser::start() {
std::string tmp;
bool isExit = false;
for (auto &_token : _tokens) {
if (_token._type > COMMENT) {
tmp = _token._value;
tmp.resize(tmp.size() - 1);
size_t found = tmp.find('(') + 1;
_token._value = tmp.substr(found);
}
}
for (auto it = _tokens.begin(); it != _tokens.end(); ++it) {
if (it->_value == "exit")
isExit = true;
void (Parser::*func)(std::list<Token>::iterator& it);
func = _instr.at(it->_type);
try {
(this->*func)(it);
}
catch (AvmExcept &e) {
std::cerr << e.what() << std::endl;
}
}
if (!isExit)
throw AvmExcept("ERROR: exit instruction not found");
}
void Parser::push(std::list<Token>::iterator &it) {
auto next = ++it;
_stack.push_front(_factory.createOperand(static_cast<eOperandType>(next->_type - INT8), next->_value));
}
void Parser::pop(std::list<Token>::iterator &it) {
(void)it;
if (_stack.empty())
throw AvmExcept("ERROR: stack is empty");
_stack.pop_front();
}
void Parser::assert(std::list<Token>::iterator &it) {
auto next = ++it;
if (_stack.empty())
throw AvmExcept("ERROR: stack is empty");
const IOperand* first = *(_stack.begin());
if (next->_value != first->toString())
throw AvmExcept("ASSERT ERROR: different values");
if (next->_type - INT8 != first->getType())
throw AvmExcept("ASSERT ERROR: different values");
}
void Parser::dump(std::list<Token>::iterator &it) {
(void)it;
if (_stack.empty())
throw AvmExcept("ERROR: stack is empty");
for (auto &iter : _stack)
std::cout << iter->toString() << std::endl;
}
void Parser::add(std::list<Token>::iterator &it) {
(void)it;
if (_stack.size() < 2)
throw AvmExcept("ERROR: less than 2 elements");
const IOperand* first = *(_stack.begin());
_stack.pop_front();
const IOperand* second = *(_stack.begin());
_stack.pop_front();
_stack.push_front(*first + *second);
delete first;
delete second;
}
void Parser::mul(std::list<Token>::iterator &it) {
(void)it;
if (_stack.size() < 2)
throw AvmExcept("ERROR: less than 2 elements");
const IOperand* first = *(_stack.begin());
_stack.pop_front();
const IOperand* second = *(_stack.begin());
_stack.pop_front();
_stack.push_front(*first * *second);
delete first;
delete second;
}
void Parser::sub(std::list<Token>::iterator &it) {
(void)it;
if (_stack.size() < 2)
throw AvmExcept("ERROR: less than 2 elements");
const IOperand* first = *(_stack.begin());
_stack.pop_front();
const IOperand* second = *(_stack.begin());
_stack.pop_front();
_stack.push_front(*first - *second);
delete first;
delete second;
}
void Parser::div(std::list<Token>::iterator &it) {
(void)it;
if (_stack.size() < 2)
throw AvmExcept("ERROR: less than 2 elements");
const IOperand* first = *(_stack.begin());
_stack.pop_front();
const IOperand* second = *(_stack.begin());
if (first->toString() == "0")
throw AvmExcept("ERROR: division on 0");
_stack.pop_front();
_stack.push_front(*second / *first);
delete first;
delete second;
}
void Parser::mod(std::list<Token>::iterator &it) {
(void)it;
if (_stack.size() < 2)
throw AvmExcept("ERROR: less than 2 elements");
const IOperand* first = *(_stack.begin());
_stack.pop_front();
const IOperand* second = *(_stack.begin());
if (first->toString() == "0")
throw AvmExcept("ERROR: division on 0");
std::cout << 5 % 7 << std::endl;
_stack.pop_front();
_stack.push_front(*second % *first);
delete first;
delete second;
}
void Parser::print(std::list<Token>::iterator &it) {
(void)it;
if (_stack.empty())
throw AvmExcept("Print instruction on empty stack");
const IOperand* first = *(_stack.begin());
if (first->getType() != Int8)
throw AvmExcept("Print instruction on no 8-bit integer");
std::cout << static_cast<char>(std::stoi(first->toString())) << std::endl;
}
void Parser::exit(std::list<Token>::iterator &it) {
(void)it;
std::exit(0);
} |
e7157642f8a1ee1b3627e348c8aed38501664233 | 00da6f58fff4964f18fea36e29849220ceffe545 | /TC3CPP-OC-FourierSignals/TC3CPP-OC-FourierSignals/CPPVP1/CPPVP1Main.cpp | 2a90eb0e47e1ca90c257c182de10d186cf7dd84c | [
"MIT"
] | permissive | 0w8States/TwinCAT-CPP---Fourier-Series-Online-Changeable | fd77b5458bed632fb4a529d0eeafe9c5a3933997 | d3837f39d256d0c5a6ca7e82a207009c77dd2722 | refs/heads/master | 2023-03-04T01:00:36.663581 | 2020-04-24T17:39:11 | 2020-04-24T17:39:11 | 338,688,308 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,488 | cpp | CPPVP1Main.cpp | // dllmain.cpp : Defines the entry point for the DLL application.
#include "TcPch.h"
#pragma hdrstop
#include "TcBase.h"
#include "CPPVP1ClassFactory.h"
#include "TcOCFCtrlImpl.h"
#include "CrtInit.h"
class CCPPVP1Ctrl : public ITcOCFCtrlImpl<CCPPVP1Ctrl, CCPPVP1ClassFactory>
{
public:
CCPPVP1Ctrl() {};
virtual ~CCPPVP1Ctrl() {};
};
// Entry point for loaders like FreeBSD in Kernel loader, which is
// operating on an already relocated DLL. For these loaders we need
// an explicitly "dllexported" symbol.
extern "C"
__declspec(dllexport)
BOOL APIENTRY DllMain(HMODULE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
cppInit();
break;
case DLL_THREAD_ATTACH:
break;
case DLL_THREAD_DETACH:
break;
case DLL_PROCESS_DETACH:
cppShutdown();
break;
}
return TRUE;
}
// Entry point for Windows loader (implicit lookup, not by name)
BOOL APIENTRY DllMainWin(HMODULE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
return DllMain(hModule, ul_reason_for_call, lpReserved);
}
extern "C"
__declspec(dllexport)
HRESULT APIENTRY DllGetTcCtrl(ITcCtrl** ppTcCtrl)
{
HRESULT hr = E_FAIL;
TRACE("CPPVP1: DllGetTcCtrl(ITcCtrl** ppTcCtrl) \n");
if (ppTcCtrl != NULL)
{
ITcCtrl* pTcCtrl = new IUnknownImpl<CCPPVP1Ctrl>;
pTcCtrl->AddRef();
*ppTcCtrl = pTcCtrl;
hr = S_OK;
}
else
hr = E_POINTER;
return hr;
}
|
c9520061114b1e1e1a335c59527a25a008569379 | 8030bae5b1e6d29492c933ebfc622f8a831d32cc | /rush00/incl/Enemy.hpp | db90e97029a9a77867669f46cd5d0231a85ea3cb | [] | no_license | rhohls/CPP_Bootcamp | 6bb9e007deda8661f159b259db11cbecece9939d | 4daf970110f837259a8cb5dabfa12ac854e49f91 | refs/heads/master | 2020-05-31T06:39:56.719160 | 2019-06-13T05:25:37 | 2019-06-13T05:25:37 | 190,146,666 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,077 | hpp | Enemy.hpp | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* Enemy.hpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: rhohls <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/06/09 09/01/13 by rhohls #+# #+# */
/* Updated: 2019/06/09 09/01/13 by rhohls ### ########.fr */
/* */
/* ************************************************************************** */
#ifndef ENEMY_HPP
# define ENEMY_HPP
class Enemy {
public:
Enemy();
Enemy(Enemy const & src);
~Enemy();
Enemy & operator=(Enemy const & src);
private:
protected:
};
#endif
|
c6531b840b945d2279e2ad27f280d8536dfa0319 | 0b9178ff7d3db16e6d28106f33c52298d8c04f81 | /source/problem/Green-Naghdi/discretization_EHDG/kernels_processor/ehdg_gn_proc_derivatives_ompi.hpp | 620cb32d96d55f36e27979cd5af5cb532a09282c | [
"Apache-2.0",
"MIT"
] | permissive | bremerm31/dgswemv2 | 440d3999fd76632e2631d0993509a0adde090762 | 5ddddfdf1b5f51e9dbc348f2e69f187546649957 | refs/heads/master | 2021-07-13T05:59:42.005455 | 2020-04-06T13:45:34 | 2020-04-06T13:45:34 | 132,520,141 | 0 | 0 | MIT | 2018-06-27T13:53:49 | 2018-05-07T21:50:47 | C++ | UTF-8 | C++ | false | false | 631 | hpp | ehdg_gn_proc_derivatives_ompi.hpp | #ifndef EHDG_GN_PROC_DERIVATIVES_OMPI_HPP
#define EHDG_GN_PROC_DERIVATIVES_OMPI_HPP
#ifdef D_RECON_INT
#include "grad_methods/recon_int_derivatives.hpp"
#endif
#ifdef D_RECON_LS
#include "grad_methods/recon_ls_derivatives.hpp"
#endif
#ifdef D_RECON_AVG
#include "grad_methods/recon_avg_derivatives.hpp"
#include "grad_methods/recon_avg_derivatives_ompi.hpp"
#endif
#ifdef D_PROJECTION
#include "grad_methods/projection_derivatives_ompi.hpp"
#endif
#ifdef D_GREENGAUSS
#include "grad_methods/greengauss_derivatives_ompi.hpp"
#endif
#ifdef D_LEASTSQUARES
#include "grad_methods/leastsquares_derivatives_ompi.hpp"
#endif
#endif |
89200be392a1ea92c4adedb848767331da82dbdb | ebcb68cfe233f45d0126c2ebfd353acfbe8ac358 | /asteroids/src/model.cpp | ddace94d5d262fdc41e02a5bc4cd311b79d1ffdf | [] | no_license | Small-Embedded-Systems/assignment-2-asteroids-abdul-uk | ca13b7720dbbd076386c3e52ad90bba12cba7041 | 9c31b2c45aaad737a274a4e3d0e8ef7185b48e28 | refs/heads/master | 2021-01-18T15:42:38.548932 | 2017-05-14T16:40:55 | 2017-05-14T16:40:55 | 86,674,766 | 0 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 6,101 | cpp | model.cpp | /* Asteroids model */
#include <stdbool.h>
#include <stdint.h>
#include <stdlib.h>
#include <math.h>
#include "model.h"
#include "view.h"
#include "utils.h"
#include "asteroids.h"
static const size_t MAXSize = 10;
static missile missile_data[MAXSize];
static missile *freeMissileNodes;
void new_missile(struct missile *r);
static rock rock_data[MAXSize];
static rock *freeRockNodes;
void new_asteroid(struct rock *r);
//functions
ship move_ship(ship, float Dt);
void shoot_missile();
void move_missiles(struct missile *r);
static void move_missiles(struct missile *l);
static void update_missile_list(struct missile *l);
static void move_asteroids(struct rock *l, float x);
static void update_rock_list(struct rock *l);
static bool ship_hits(struct rock *l);
static void missile_hit_rocks(struct missile *l, struct rock *k);
struct rock * new_asteroids();
void physics(void)
{
if(!paused){
elapsed_time += Dt;
player = move_ship(player, Dt);
move_missiles(shots);
asteroids = new_asteroids();
move_asteroids(asteroids, Dt);
missile_hit_rocks(shots, asteroids);
if(ship_hits(asteroids)){
inPlay = false;
score += (int) elapsed_time;
elapsed_time = 0;
lives--;
}
update_missile_list(shots);
update_rock_list(asteroids);
}
}
//moving the ship
ship move_ship(ship, float time){
//ship's accelration
player.p.x += player.v.x*time;
player.p.y += player.v.y*time;
//ship's drag
player.v.x -= (player.v.x*player.drag)*0.01f;
player.v.y -= (player.v.y*player.drag)*0.01f;
//screen wrap-around
if(player.p.x < 0){
player.p.x += 390;
}
if(player.p.x >= 390){
player.p.x -= 390;
}
if(player.p.y < 0){
player.p.y += 272;
}
if(player.p.y >= 272){
player.p.y -= 272;
}
return player;
}
void shoot_missile(){
struct missile *newMissile = allocate_missile_node();
if(newMissile){
newMissile->next = shots;
shots = newMissile;
new_missile(newMissile);
}
update_missile_list(shots);
}
void new_missile(struct missile *r){
r->heading = player.heading;
r->p.x = player.p.x;
r->p.y = player.p.y;
//adjusting position of missiles
r->v.x = sin(radians(r->heading));
r->v.y = -cos(radians(r->heading));
//adjusting position of missiles
r->p.x += r->v.x * 10;
r->p.y += r->v.y * 10;
//setting up the speed
r->v.x *=50;
r->v.y *=50;
//time to live
r->ttl = 10;
}
void initialise_missiles(){
int n;
for(n=0; n<(MAXSize-1) ; n++){
missile_data[n].next = &missile_data[n+1];
}
missile_data[n].next = NULL;
freeMissileNodes = &missile_data[0];
}
missile *allocate_missile_node(void){
missile *node = NULL;
if (freeMissileNodes){
node = freeMissileNodes;
freeMissileNodes = freeMissileNodes->next;
}
return node;
}
void free_missile_node(missile *n){
n->next = freeMissileNodes;
freeMissileNodes = n;
}
void update_missile_list(struct missile *l){
for ( ; l ; l = l->next){
if (l->next->ttl <= 0){
struct missile *expiredM = l->next;
l->next = l->next->next;
free_missile_node(expiredM);
}
}
}
void move_missiles(struct missile *l){
for ( ; l ; l = l->next){
l->p.x += l->v.x * Dt;
l->p.y += l->v.y * Dt;
if (l->p.y >= 272){
l->ttl = 0;
}
if (l->p.y < 0){
l->ttl = 0;
}
if (l->p.x >= 400){
l->ttl = 0;
}
if (l->p.x < 0){
l->ttl = 0;
}
l->ttl -= Dt;
}
}
struct rock * new_asteroids(){
int i;
for(i = 0; i < MAXSize-1; i++){
struct rock *newRock = allocate_rock_node();
if(newRock){
newRock->next = asteroids;
asteroids = newRock;
int initAstPos = randrange(1,5);
switch (initAstPos){
case 1 :
newRock->p.x = randrange(0,100);
newRock->p.y = randrange(0,272);
newRock->v.x = 1;
if(newRock->p.y > 136) newRock->v.y = -10;
if(newRock->p.y <= 136) newRock->v.y = 10;
break;
case 2 :
newRock->p.x = randrange(280,380);
newRock->p.y = randrange(0,272);
newRock->v.x = -1;
if(newRock->p.y > 136) newRock->v.y = -10;
if(newRock->p.y <= 136) newRock->v.y = 10;
break;
case 3 :
newRock->p.x = randrange(0,380);
newRock->p.y = randrange(0,100);
newRock->v.y = 1;
if(newRock->p.x > 200) newRock->v.x = -10;
if(newRock->p.y <= 200) newRock->v.x = 10;
break;
case 4 :
newRock->p.x = randrange(0,380);
newRock->p.y = randrange(172,272);
newRock->v.y = 1;
if(newRock->p.x > 200) newRock->v.x = -10;
if(newRock->p.y <= 200) newRock->v.x = 10;
break;
}
newRock->ttl = 2000;
}
update_rock_list(asteroids);
}
return asteroids;
}
void initialise_asteroids(){
int n;
for(n=0; n<(MAXSize-1) ; n++){
rock_data[n].next = &rock_data[n+1];
}
rock_data[n].next = NULL;
freeRockNodes = &rock_data[0];
}
rock *allocate_rock_node(void){
rock *node = NULL;
if (freeRockNodes){
node = freeRockNodes;
freeRockNodes = freeRockNodes->next;
}
return node;
}
void update_rock_list(struct rock *l){
for ( ; l ; l = l->next){
if (l->next->ttl <= 0){
struct rock *expiredR = l->next;
l->next = l->next->next;
free_rock_node(expiredR);
}
}
}
void free_rock_node(rock *n){
n->next = freeRockNodes;
freeRockNodes = n;
}
void move_asteroids(struct rock *l, float x){
for ( ; l ; l = l->next){
l->p.x += l->v.x * x;
l->p.y += l->v.y * x;
if (l->p.y >= 272){
l->p.y -= 272;
}
if (l->p.y < 0){
l->p.y += 272;
}
if (l->p.x >= 380){
l->p.x -= 380;
}
if (l->p.x < 0){
l->p.x += 380;
}
l->ttl -= Dt;
}
}
void missile_hit_rocks(struct missile *l, struct rock *k){
for ( ; l ; l = l->next){
for( ; k ; k =k->next){
float r1 = 1;
float r2 = 20;
float dx = l->p.x - k->p.x; float dy = l->p.y - k->p.y;
float distance = sqrt(dx*dx + dy*dy);
if (distance < (r1 + r2)){
l->ttl = 0;
k->ttl = 0;
}
}
}
}
bool ship_hits(struct rock *l){
for( ; l ; l =l->next){
float r1 = 7.9;
float r2 = 20;
float dx = l->p.x - player.p.x; float dy = l->p.y - player.p.y;
float distance = sqrt(dx*dx + dy*dy);
if (distance < (r1 + r2)){
l->ttl = 0;
return true;
}
}
return false;
}
|
e818beb7d3770130cc094b7d8eed26fde391aae2 | ac140a854c180f0c6c0ff0f35518c18e32a43758 | /BoostLibrary/example_9_1.cpp | 2559b31fc59392fac2bf08484aef7402be6f1492 | [] | no_license | klasing/MnistExample | 53bd4e6316b513889acd77a5549082863c643435 | 720479f6768c15fa6e63fafd415b5a2bcff3dfa9 | refs/heads/master | 2020-04-22T00:29:18.102857 | 2019-06-30T18:41:17 | 2019-06-30T18:41:17 | 169,981,063 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 73 | cpp | example_9_1.cpp | // Example 9.1
// Comparing strings with boost::xpressive::regex_match()
|
0f9a77d1f07be65a8170eadeef158e3e10859ee9 | c60bc44b3cb7620c87af0a49e7b907b5c553f9a5 | /ular/fibonaci.cpp | a4b123d14683569bdcd0c5c0b77125ab028d77d3 | [] | no_license | jasonchan117/ularProject | c7117de399377704d5171d2097b96a8510836f01 | 1bf53a2c7ef56b3dd11156ab2f431787f298c593 | refs/heads/master | 2021-06-21T01:44:35.218327 | 2020-12-11T19:37:51 | 2020-12-11T19:37:51 | 141,500,199 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 265 | cpp | fibonaci.cpp | #include<stdio.h>
int main(){
long long a[3];
a[0]=1;
a[1]=1;
a[2]=2;
int i=0;
int count =3;
long long sum=0;
while(1){
a[i%3]=a[(i+1)%3]+a[(i+2)%3];
sum=a[i%3];
i++;
count++;
if(count==58) break;
}
printf("%lld",sum);
return 0;
}
|
aee0dc7c17f347222c6549604cf2e84f0a1b25ad | b77b470762df293be67877b484bb53b9d87b346a | /game/MaterialManager.h | e3531c90651f0235dca54779a73770b27a183787 | [
"BSD-3-Clause"
] | permissive | Sheph/af3d | 9b8b8ea41f4e439623116d70d14ce5f1ee1fae25 | 4697fbc5f9a5cfb5d54b06738de9dc44b9f7755f | refs/heads/master | 2023-08-28T16:41:43.989585 | 2021-09-11T19:09:45 | 2021-09-11T19:09:45 | 238,231,399 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 4,143 | h | MaterialManager.h | /*
* Copyright (c) 2020, Stanislav Vorobiov
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE 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.
*/
#ifndef _MATERIAL_MANAGER_H_
#define _MATERIAL_MANAGER_H_
#include "ResourceManager.h"
#include "Material.h"
#include "af3d/Single.h"
#include <unordered_map>
#include <unordered_set>
namespace af3d
{
class MaterialManager : public ResourceManager,
public Single<MaterialManager>
{
public:
MaterialManager() = default;
~MaterialManager();
bool init() override;
void shutdown() override;
void reload() override;
bool renderReload(HardwareContext& ctx) override;
MaterialTypePtr getMaterialType(MaterialTypeName name);
MaterialPtr getMaterial(const std::string& name);
MaterialPtr loadImmMaterial(const TexturePtr& tex, const SamplerParams& params, bool depthTest);
MaterialPtr createMaterial(MaterialTypeName typeName, const std::string& name = "");
bool onMaterialClone(const MaterialPtr& material);
void onMaterialDestroy(Material* material);
inline const MaterialPtr& matImmDefault(bool depthTest, bool cullFace) const { return matImmDefault_[(int)depthTest][(int)cullFace]; }
inline const MaterialPtr& matUnlitVCDefault() const { return matUnlitVCDefault_; }
inline const MaterialPtr& matOutlineInactive() const { return matOutlineInactive_; }
inline const MaterialPtr& matOutlineHovered() const { return matOutlineHovered_; }
inline const MaterialPtr& matOutlineSelected() const { return matOutlineSelected_; }
inline const MaterialPtr& matClusterCull() const { return matClusterCull_; }
inline const MaterialPtr& matPrepassWS() const { return matPrepassWS_; }
inline const MaterialPtr& matPrepass(int i) const { return matPrepass_[i]; }
inline const MaterialPtr& matShadowWS() const { return matShadowWS_; }
inline const MaterialPtr& matShadow(int i) const { return matShadow_[i]; }
private:
using MaterialTypes = std::array<MaterialTypePtr, MaterialTypeMax + 1>;
using CachedMaterials = std::unordered_map<std::string, MaterialPtr>;
using ImmediateMaterials = std::unordered_set<Material*>;
std::string glslCommonHeader_;
MaterialTypes materialTypes_;
CachedMaterials cachedMaterials_;
ImmediateMaterials immediateMaterials_;
MaterialPtr matImmDefault_[2][2];
MaterialPtr matUnlitVCDefault_;
MaterialPtr matOutlineInactive_;
MaterialPtr matOutlineHovered_;
MaterialPtr matOutlineSelected_;
MaterialPtr matClusterCull_;
MaterialPtr matPrepassWS_;
MaterialPtr matPrepass_[2];
MaterialPtr matShadowWS_;
MaterialPtr matShadow_[2];
};
extern MaterialManager materialManager;
}
#endif
|
fa1163bc01ecf26b52e37e1c20fc84ca1292df30 | bb2edea55ac82eca75ea1e23ada87d66c146c2a1 | /src/problems/parabola_test_problem_5d.h | db19aeff2f3bd6d572a5dfdfd7f6f4aabe8c9938 | [] | no_license | mjoseland/particle_swarm_optimisation_parallel | 7a922cb47b0a85f94c4bb92b4b34049dd79771a5 | c9332b2653990f302af06dc2f7959b9339dac579 | refs/heads/master | 2022-12-08T21:47:18.912151 | 2022-11-22T09:32:59 | 2022-11-22T09:32:59 | 68,461,979 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 593 | h | parabola_test_problem_5d.h | //
// Created by Malcolm Joseland on 4/08/2016.
//
#ifndef PARTICLE_SWARM_OPTIMISATION_SPHERE_TEST_PROBLEM_H
#define PARTICLE_SWARM_OPTIMISATION_SPHERE_TEST_PROBLEM_H
#include <cmath>
#include "../problem.h"
using namespace std;
// Finds the minimal point in a 5-dimensional parabola
class ParabolaTestProblem5d : public Problem {
public:
ParabolaTestProblem5d();
// find the sum of the value at all dimensions squared (not sigma value)
REAL getOutput(const vector<REAL> &dimension_values) const;
//Problem *getCopy();
};
#endif //PARTICLE_SWARM_OPTIMISATION_SPHERE_TEST_PROBLEM_H
|
94477b61b67a25dc5041a47ad2d5f9ea24e63667 | e94559835dec204537927865800f95b81a191b7f | /Tympan/models/business/TYPointControl.h | f89b52f61aa357c17960b720ff20879731c81a97 | [] | no_license | FDiot/code_tympan3 | 64530a3fc8a392cdbe26f478a9ea9ce03abab051 | cf4383c4a162962b68df470e2bf757ad534880b9 | refs/heads/master | 2022-04-07T10:54:05.711913 | 2019-10-24T13:27:42 | 2019-10-24T13:27:42 | 239,812,326 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 6,158 | h | TYPointControl.h | /*
* Copyright (C) <2012> <EDF-R&D> <FRANCE>
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#ifndef __TY_POINTCONTROL__
#define __TY_POINTCONTROL__
#include "Tympan/models/business/geometry/TYGeometryNode.h"
#include "Tympan/models/business/TYColorInterface.h"
#include "Tympan/models/business/TYPointCalcul.h"
/**
* \file TYPointControl.h
* \class TYPointControl
* \brief Classe de definition d'un point de controle.Le point de controle est un point de calcul avec une hauteur par rapport a l'altitude.
* \date 2008/01/21
* \version v 1.1
* \author Projet_Tympan
*/
class TYPointControl: public TYPointCalcul, public TYColorInterface
{
OPROTODECL(TYPointControl)
TY_EXTENSION_DECL_ONLY(TYPointControl)
TY_EXT_GRAPHIC_DECL_ONLY(TYPointControl)
// Methodes
public:
/**
* \fn TYPointControl()
* \brief Constructeur par defaut.
* Constructeur par defaut de la classe TYPointControl
*/
TYPointControl();
/**
* \fn TYPointControl(const TYPoint& other)
* \brief Constructeur a partir d'un TYPoint.
* Le constructeur a partir d'un TYPoint de la classe TYPointControl .
*/
TYPointControl(const TYPoint& other);
/**
* \fn TYPointControl(const TYPointControl& other
* \brief Constructeur par copie.
* Le constructeur par copie de la classe TYPointControl.
*/
TYPointControl(const TYPointControl& other);
/**
* \fn virtual ~TYPointControl()
* \brief Destructeur
* Destructeur de la classe TYPointControl .
*/
virtual ~TYPointControl();
///Operateur =.
TYPointControl& operator=(const TYPointControl& other);
///Operateur =.
TYPointControl& operator=(const TYPoint& other);
///Operateur ==.
bool operator==(const TYPointControl& other) const;
///Operateur !=.
bool operator!=(const TYPointControl& other) const;
virtual bool deepCopy(const TYElement* pOther, bool copyId = true);
virtual std::string toString() const;
virtual DOM_Element toXML(DOM_Element& domElement);
virtual int fromXML(DOM_Element domElement);
/**
* \fn int getObject()
* \brief Set/Get de l'objet a afficher.
* \return _object
*/
int getObject() const { return _object; }
/**
* \fn void setObject(int object)
* \brief Set/Get de l'objet a afficher.
*/
void setObject(int object) { _object = object; }
/**
* \fn void setHauteur(double hauteur)
* \brief Set de la hauteur de ce point par rapport au sol (a l'altimetrie en fait).
*/
void setHauteur(double hauteur) { _hauteur = hauteur; setIsGeometryModified(true); }
/**
* \fn double getHauteur()
* \brief Get de la hauteur de ce point par rapport au sol (a l'altimetrie en fait).
* \return _hauteur
*/
double getHauteur() const { return _hauteur; }
/**
* \param objectCube, objectPyramid, objectSphere, objectStar
* Les differents types d'objet graphique que l'on peut afficher.
*/
enum
{
objectCube,
objectPyramid,
objectSphere,
objectStar
};
/**
* \fn void toSIG()
* void fromSIG()
* \brief Conversion dans le repere du Systeme d'Information Geographique
*/
void toSIG();
void fromSIG();
/**
* \fn void setStatusSIG(const bool& statusSIG)
* bool getStatusSIG()
* const bool getStatusSIG()
* \brief Get/Set du statut des coordonnees par rapport au SIG
* \return _statusSIG
*/
void setStatusSIG(const bool& statusSIG) { _statusSIG = statusSIG; }
bool getStatusSIG() { return _statusSIG; }
const bool getStatusSIG() const { return _statusSIG; }
/**
* \fn int getSIGType())
* \brief Retourne le type de SIG
*/
int getSIGType();
virtual LPTYSpectre getSpectre();
/**
* Set/Get de l'etat de ce point de calcul.
*/
virtual void setEtat(const TYUUID& id_calc, bool etat);
virtual bool etat();
virtual bool etat(const TYUUID& id_calc);
virtual bool etat(const TYCalcul* pCalc);
/// Copie du map calcul-etat
void copyEtats(TYPointControl* pOther);
/// Remove calcul from "etat" map
bool remEtat(TYCalcul* pCalcul);
/*!
* \brief Duplique l'etat defini pour un calcul pour un autre calcul
* \param idCalculRef : Identifiant unique du calcul referent
* \param idCalculNew : Identifiant unique du calcul a recopier
*/
void duplicateEtat(const TYUUID& idCalculRef, const TYUUID& idCalculNew);
void* getCompatibilityVector();
// Membres
protected:
///L'etat du point pour un calcul donne
TYMapIdBool _tabEtats;
///shape of the point in GUI
int _object;
///La hauteur du point par rapport a l'altitude.
double _hauteur;
/// Etat des coordonnees par rapport au SIG (position dans le repere SIG ou pas)
bool _statusSIG;
};
///Smart Pointer sur TYPointControl.
typedef SmartPtr<TYPointControl> LPTYPointControl;
///Collection de Smart Pointer sur TYPointControl.
typedef std::vector<LPTYPointControl> TYTabLPPointControl;
///Noeud geometrique de type TYPointControl.
typedef TYGeometryNode TYPointControlGeoNode;
///Smart Pointer sur TYPointControlGeoNode.
typedef SmartPtr<TYPointControlGeoNode> LPTYPointControlGeoNode;
///Collection de noeuds geometriques de type TYPointControl.
typedef std::vector<LPTYPointControlGeoNode> TYTabLPPointControlGeoNode;
#endif // __TY_POINTCONTROL__
|
d881be7e6ca8d85554fc0d532e85370248648577 | 5bf67a8e12a670f4fdb52d043dec84e04a1cb67c | /sequence_alignment/sequence_alignment/assignment_write.hpp | 20311e0e5b96c74a49e985da3ac3eb015ac71240 | [] | no_license | mfileman/DNA-Pairwise-Alignment | 57b991407e15513385799224d985e5417202d28f | 547692b8206e66713f9475f5d4d888e672934efb | refs/heads/main | 2023-01-14T17:27:41.402113 | 2020-11-24T05:46:18 | 2020-11-24T05:57:15 | 315,532,522 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 301 | hpp | assignment_write.hpp | //
// assignment_write.hpp
// sequence_alignment
//
// Created by madison on 10/13/20.
//
#ifndef assignment_write_hpp
#define assignment_write_hpp
class Assignment {
public:
static void assignment_write(const char* file_path, const char* text);
};
#endif /* assignment_write_hpp */
|
c0c6bec56bc77d3e8f162b10bc667a886a46e89f | b8211e577353e4658b8ab1848774665e6fc7974f | /webdev.cpp | de915a5a980996c4435bad631def472f0bcc1fa9 | [] | no_license | srflorea/Webdev-CPlusPlus | c99b0f56f94add0ffe10ed2f3a1d9f1cd1f9136a | d86fc83df24b9f4220e4a1a9344f0a7175484904 | refs/heads/master | 2021-01-16T07:08:43.821446 | 2013-10-06T20:49:01 | 2013-10-06T20:49:01 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,925 | cpp | webdev.cpp | /* Florea Stefan - Razvan
* 341C3
* This file contains the main function and some additional functions.
* The program take
*/
#include <iostream>
#include "examples.hpp"
using namespace std;
vector<string> example;
map<string, func_type> functions_map;
/*Function that populates the dictionary with all the available functions.
*/
void populate_map()
{
functions_map["add_one"] = add_one;
functions_map["add_two"] = add_two;
functions_map["add_three"] = add_three;
functions_map["add_four"] = add_four;
functions_map["add_five"] = add_five;
functions_map["multiply_by_one"] = multiply_by_one;
functions_map["multiply_by_two"] = multiply_by_two;
functions_map["multiply_by_three"] = multiply_by_three;
functions_map["multiply_by_four"] = multiply_by_four;
functions_map["multiply_by_five"] = multiply_by_five;
functions_map["subtract_one"] = subtract_one;
functions_map["subtract_two"] = subtract_two;
functions_map["subtract_three"] = subtract_three;
functions_map["subtract_four"] = subtract_four;
functions_map["subtract_five"] = subtract_five;
}
/*Function that populates the list with names of the functions that will be used
*/
void populate_example(int no_functions_map)
{
int k = 0;
map<string, func_type>::iterator it = functions_map.begin();
for( ; it != functions_map.end() && k < no_functions_map; it++, k++) {
example.push_back(it->first);
}
}
int main(int argc, char *argv[])
{
string function;
int integer_used, no_functions_map;
if(argc < 3) {
cout << "./webdev 'integer used' 'number of used functions_map'" << endl;
return -1;
}
populate_map();
integer_used = atoi(argv[1]);
no_functions_map = atoi(argv[2]);
populate_example(no_functions_map);
cout << "integer used: " << integer_used << endl;
for(int k = 0; k < no_functions_map; k++) {
function = example[k];
cout << function << ": " << functions_map[function](integer_used) << endl;
}
return 0;
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.