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
5f94973fb358882eb52b80820b267b6b7be692b9
da289d5f618b676def2ef5cda2f7e10042a3bb1a
/Bulk Club Project/FillMemberList.cpp
0646dc809255cf4413ad28474a06b34138f23534
[]
no_license
stewartjustind/Bulk-Club-Project
9936537da18768d582be3914c2e46f5cfbb32dd0
2ae8aa590c22c68b3c1e7fad646f5a61ce93d642
refs/heads/master
2021-05-30T19:44:03.663058
2014-05-13T02:03:07
2014-05-13T02:03:07
19,219,967
0
1
null
null
null
null
UTF-8
C++
false
false
2,940
cpp
FillMemberList.cpp
/************************************************************************* * AUTHOR : Andrea Velazquez & Justin Stewart * STUDENT ID : 994759 * FINAL PROJECT: Super Warehouse Store * CLASS : CS1C * SECTION : TTH: 8:30a - 9:50a * DUE DATE : May 13th, 2014 ************************************************************************/ #include "header.h" /************************************************************************* * FUNCTION FillMemberList * _______________________________________________________________________ * This function receives a basic members vector list and a * preferred members vector list. It then uses the file name to populate * these lists. -returns nothing * _______________________________________________________________________ * PRE-CONDITIONS * fileName : File name has to be previously defined * basicList : Basic member vector has to be previously defined * prefList : Preferred member vector has to be previously defined * * POST-CONDTIONS * This function returns nothing ************************************************************************/ void FillMemberList(vector<Basic>& basicList, // IN - Basic list vector<Preferred> & prefList)// IN - Preferred list { ifstream inFile; //IN - Input file variable Basic tempBasic; //IN - Temporary basic list Preferred tempPref; //IN - Temporary preferred list string tempName; //IN - Temporary name variable int tempId; //IN - Temporary id variable string tempStatus; //IN - Temporary status variable string tempMo; //IN - Temporary month variable string tempDa; //IN - Temporary day variable string tempYe; //IN - Temporary year variable int monthExp; //CALC - Month variable post string conversion int dayExp; //CALC - Day variable post string conversion int yearExp; //CALC - Year variable post string conversion inFile.open("warehouse shoppers.txt"); //WHILE - Loops through file until no longer in file boundary while(getline(inFile, tempName)) { inFile >> tempId; inFile.ignore(numeric_limits<streamsize>::max(), '\n'); getline(inFile, tempStatus); getline(inFile, tempMo, '/'); getline(inFile, tempDa, '/'); getline(inFile, tempYe); monthExp = atoi(tempMo.c_str()); dayExp = atoi(tempDa.c_str()); yearExp = atoi(tempYe.c_str()); //IF - Checks if status is preferred or basic, inputs into correct // list. if(tempStatus == "Preferred") { tempPref.setName(tempName); tempPref.setNumber(tempId); tempPref.setMemType(1); tempPref.setExp(monthExp, dayExp, yearExp); prefList.push_back(tempPref); } else if(tempStatus == "Basic") { tempBasic.setName(tempName); tempBasic.setNumber(tempId); tempBasic.setMemType(0); tempBasic.setExp(monthExp, dayExp, yearExp); basicList.push_back(tempBasic); }//END IF }//END WHILE inFile.close(); }
33558ef19d3ee4cdb05f197eaba923fb2e53d70a
ee669f4df44f2f241bd9a2c7c348e0c78183d414
/数据结构算法/一元稀疏多项式.cpp
6867c1e944a98aae26ef81f4cca1bc8ad6f85ad6
[]
no_license
totoroKalic/Practice
bd3f23f53c89e42041b6714f3eeda6a1d953cd44
5b57080d54be2b66bb38df6b289d94557252ace1
refs/heads/master
2020-06-14T10:30:22.151827
2019-07-03T05:03:00
2019-07-03T05:03:00
194,982,082
1
0
null
null
null
null
GB18030
C++
false
false
2,381
cpp
一元稀疏多项式.cpp
/* 一元稀疏方程组的计算 */ /* 该程序存在问题!还需要调试 */ #include <stdio.h> #include <stdlib.h> typedef struct LNode{ int down; int up; struct LNode *next; }LNode,*LNodeList; void creatLNode(LNodeList &hp, int m) { LNodeList p; hp = (LNodeList)malloc(sizeof(LNode)); p = hp; for (int i = 0; i < m; i++) { p->next = (LNodeList)malloc(sizeof(LNode)); scanf("%d %d", &p->next->down, &p->next->up); p = p->next; } p->next = NULL; } void add(LNodeList pa, LNodeList pb) { LNodeList t_a, t_b; t_a = pa->next; t_b = pb->next; while (pb != NULL) { if (pa == NULL) { pa->next = pb; break; } if (t_a->up == t_b->up) { t_a->down += t_b->down; if (t_a->down == 0) pa->next = t_a->next; else pa = pa->next; t_a = t_a->next; t_b = t_b->next; } if (t_a->up < t_b->up) { t_a = t_a->next; pa = pa->next; } if (t_a->up > t_b->up) { pa->next = t_b; pb = t_b->next; t_b->next = t_a; t_b = pb; pa = pa->next; } } } void sub(LNodeList pa, LNodeList pb) { LNodeList t_a, t_b; t_a = pa->next; t_b = pb->next; while (pa != NULL&&pb != NULL) { if (t_a->up == t_b->up) { t_a->down -= t_b->down; if (t_a->down == 0) pa->next = t_a->next; else pa = pa->next; t_a = t_a->next; t_b = t_b->next; } else if (t_a->up < t_b->up) { t_a = t_a->next; pa = pa->next; } else if (t_a->up > t_b->up) { pa->next = t_b; pb = t_b->next; t_b->next = t_a; t_b->down = -1 * t_b->down; t_b = pb; pa = pa->next; } } if (t_b != NULL) { pa->next = t_b; while (t_b) { t_b->down *= -1; t_b = t_b->next; } } } void printLNode(LNodeList pa) { LNodeList hp; int flag = 1; hp = pa; while(hp->next!=NULL) { hp = hp->next; if (hp->down) { if (flag != 0 && hp->down > 0) { printf("+"); } flag = 0; if (hp->up == 0) printf("%d", hp->down); else { if (hp->down == -1) printf("-"); else if (hp->down != 1) printf("%d", hp->down); if (hp->up != 1) printf("x^%d", hp->up); else printf("x"); } } } if (flag == 0) printf("0"); } int main() { int m, n, a; scanf("%d %d %d", &m, &n, &a); LNodeList pa, pb; creatLNode(pa, m); creatLNode(pb, n); if (a == 0) add(pa, pb); else sub(pa, pb); printLNode(pa); printf("\n"); return 0; }
dac09e91b1871afc60dd4e6ec726739cc051f294
6db40efe5c45bbb8f0ca609c81c42131e999d6d4
/tp1/codigo/sched_rr2.h
f84991460bac1e664f76df966a748be10a225f51
[]
no_license
svilerino/Sistemas-Operativos
483d4566a63428796a07cae22d86839c98aa9ba7
97999e058647fbbc06331d859a7413ab1e755a13
refs/heads/master
2016-09-06T02:53:13.808347
2014-07-27T14:13:47
2014-07-27T14:13:47
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,218
h
sched_rr2.h
#ifndef __SCHED_RR2__ #define __SCHED_RR2__ #include <vector> #include <queue> #include <unordered_map> #include <algorithm> #include <stdint.h> #include <iostream> #include "basesched.h" using namespace std; /** Sea n_cores la cantidad de cores: Estructuras de datos: - Una tabla vector de n_cores core_entry - Un mapa de <pid_t, PCB_ENTRY> denotando * PCB_ENTRY: - operador == comparacion por pid - int pid: denota el PID del proceso - uint core_affinity: denota el core fijo asignado a este proceso durante su ciclo de vida * CORE_ENTRY: - operador < comparacion por load - uint id: id del core, sirve para identificar el core al asignar afinidades a los procesos - uint default_quantum: quantum por default para cada proceso en este core - uint remaining_quantum: quantum restante en este core - CORE_LOAD load: cantidad de procesos entre BLOCKED + RUNNING + READY en este core - queue<PCB_ENTRY> *ready_queue: cola de procesos ready asociada al core - PCB_ENTRY running_process: running process actual de este core Funcionamiento del load balancing: Cuando una tarea es cargada mediante el metodo load(...); el scheduler se fija cual es el core con menor carga de trabajo (operador < del struct CORE_ENTRY) y admite el proceso en la cola FIFO del core elegido, aumentando el load en dicho core. Inicializacion: Todos los cores comienzan con load 0, los quantums completos y running_process en la IDLE_PCB(atributo estatico de clase) Finalizacion: Al finalizar un proceso se le resta una unidad al load de su core asociado Desbloqueo: Se mueven las tareas de la tabla global waiting_table a la cola ready de su core asociado. Consumo de procesos: Cada core selecciona con modelo round robin un proceso y lo asigna a running_process mientras corre, en la cola de cada core quedan SOLAMENTE procesos READY, ni RUNNING ni BLOCKED por IO. Cuando se termina el quantum, o cuando un proceso pide IO, o termina con EXIT son desalojados del core y este toma un nuevo proceso o IDLE_PCB si no hay ninguno en su cola ready. */ typedef uint32_t uint; typedef uint CORE_LOAD; typedef struct pcb_entry { bool operator == (const struct pcb_entry other) const { return pid == other.pid; } //necesario para indexar el map de waiting con la PK pid. int pid; //necerario para indexar la tabla de cores cuando se desbloquea de waiting y debe ser encolado //o cuando se modifica el load de un core uint core_affinity; } PCB_ENTRY; typedef struct core_entry { //sirve para obtener el core con menos carga con la funcion min_element de c++ bool operator<(struct core_entry &other) const { return load < other.load; } //id del core, sirve para identificar el core al asignar afinidades a los procesos uint id; //quantum por default para cada proceso en este core uint default_quantum; //quantum restante en este core uint remaining_quantum; //cantidad de procesos entre BLOCKED + RUNNING + READY en este core CORE_LOAD load; //cola de procesos ready asociada al core queue<PCB_ENTRY> *ready_queue; //running process PCB_ENTRY running_process; } CORE_ENTRY; class SchedRR2 : public SchedBase { public: //constructor y destructor SchedRR2(std::vector<int> argn); ~SchedRR2(); //metodos publicos que deben implementarse por interfaz virtual void load(int pid); virtual void unblock(int pid); virtual int tick(int core, const enum Motivo m); private: //atributos vector<CORE_ENTRY> *core_table; //tabla comun de procesos en espera unordered_map<int, PCB_ENTRY> *waiting_table;//<pid, PCB_ENTRY> //IDLE_PCB static template static PCB_ENTRY IDLE_PCB; //metodos privados void admitProcess(int pid, CORE_ENTRY assignedCore); void finalizeProcess(PCB_ENTRY targetProcess); }; #endif
ebf5749c68bc9793b65fd1dd7964f2c754eea0aa
1ad0c6f4927808f313cfcd29f149c20d26ad7887
/QTDistribute/main.cpp
977d6303cf37d6f23fd8a49b7ae34d6ed9a514ae
[]
no_license
hustyouyou/ADT-MultCS
c68ccd251e4e4566acae98642dd77dd1417f891c
0f6f82e2f17831f27bf767e16a5c867924fd1db2
refs/heads/master
2020-04-06T11:05:08.673887
2018-11-13T08:09:35
2018-11-13T08:09:35
null
0
0
null
null
null
null
UTF-8
C++
false
false
183
cpp
main.cpp
#include <QtCore/QCoreApplication> #include "Distribute.h" int main(int argc, char *argv[]) { QCoreApplication q(argc, argv); Distribute distribute; distribute.Run(); return 0; }
99a711a56a33bc4062b1e34856c755247423678c
9b543466a27511d77ce59e3c50367323705e6569
/src/replica/backup/test/replica_backup_manager_test.cpp
09a2ea423523a5c812257da102f198f830501601
[ "MIT" ]
permissive
satanson/rdsn
17e7d87b7312a357f766ac107e072c0c5e681c84
646a8b1ff31fd38e870bb7708c76a8c172825c5e
refs/heads/master
2023-03-31T13:03:28.452245
2021-04-08T03:28:46
2021-04-08T03:28:46
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,081
cpp
replica_backup_manager_test.cpp
// Copyright (c) 2017-present, Xiaomi, Inc. All rights reserved. // This source code is licensed under the Apache License Version 2.0, which // can be found in the LICENSE file in the root directory of this source tree. #include "replica/test/replica_test_base.h" #include "replica/backup/replica_backup_manager.h" namespace dsn { namespace replication { class replica_backup_manager_test : public replica_test_base { public: void clear_backup_checkpoint(const std::string &policy_name) { _replica->get_backup_manager()->clear_backup_checkpoint(policy_name); } }; TEST_F(replica_backup_manager_test, clear_cold_backup) { std::string policy_name = "test_policy"; // create policy dir: <backup_dir>/backup.<policy_name>.* std::string policy_dir = _replica->get_app()->backup_dir() + "/backup." + policy_name; utils::filesystem::create_directory(policy_dir); // clear policy dir clear_backup_checkpoint(policy_name); ASSERT_FALSE(utils::filesystem::directory_exists(policy_dir)); } } // namespace replication } // namespace dsn
b47d9dec9a68de13d1c148a10dc1e28d282361e8
36aff955b9d38c47f5b613755001aa6b3a8c4110
/Block.h
0da1792a21a05f1c91103b53fc46162e1773ab30
[]
no_license
JohnalKhow/CPECOG2-Project
31111421e8d5221cd4a79ffe65c2a2e1d8262fa3
804eb29c629e9a12e7cdb87e2571319fca554dcb
refs/heads/main
2023-07-18T12:12:51.446917
2021-09-07T05:56:16
2021-09-07T05:56:16
403,853,230
0
0
null
null
null
null
UTF-8
C++
false
false
668
h
Block.h
#pragma once #include <stdio.h> #include <stdlib.h> #include <iostream> class Block { public: Block(uint32_t* sprite_tracker, int width, int height, int x, int y, float factor, int type); int getWidth(); int getHeight(); int getX(); int getY(); float getFactor(); int getType(); uint32_t* getSpriteTracker(); void setWidth(int width); void setHeight(int height); void setX(int x); void setY(int y); void setSpriteTracker(uint32_t* sprite_tracker); void setFactor(float factor); void setType(int type); private: int type; uint32_t* sprite_tracker; float factor; int x, y; int width, height; };
7d196e904a0448798ac86872244585890d7175b4
0a902acd23482e6e0666f5a3f3de5e07fb6056e3
/include/iterator.hpp
b29c9bf7fa756a6779b6d92726786f07ea1b3a2f
[ "MIT" ]
permissive
subhasis256/opencvpp11
4a004781ca9ee702da6d669982d6306a743fe3a3
cad4ec61cccd1c3814594a01cb869e1239f25e47
refs/heads/master
2016-09-15T17:29:54.845937
2014-06-13T02:13:06
2014-06-13T02:13:06
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,978
hpp
iterator.hpp
#ifndef __OPENCVPP11_ITERATOR__ #define __OPENCVPP11_ITERATOR__ #include <opencv2/opencv.hpp> #include <common_checker.hpp> using namespace cv; using namespace std; /** * This is a wrapper over MatIterator_ to make it consistent with * range based for loops in C++11. * The IterableMat<T> class has a begin() and an end() iterator * that function similarly to MatIterator_<T> class. Also, while * creating the IterableMat, a warning is issued if the type of * the matrix is not the same as T * * A simple way to get an IterableMat<T> from a Mat is to do * iterate<T>(mat). Thus, an easy range based for loop would look * like: * * for(T elem : iterate<T>(mat)) {...} */ template<class Element> class IterableMat : public Mat { public: struct Iterator { MatIterator_<Element> it; Iterator& operator++ () { ++it; return *this; } Iterator(MatIterator_<Element> _it): it(_it) {} bool operator != (const Iterator &other) { return it != other.it; } Element &operator*() { return *it; } }; Iterator begin() { return Iterator(Mat::begin<Element>()); } Iterator end() { return Iterator(Mat::end<Element>()); } IterableMat(Mat &x) : Mat(x) {} }; template<class Element> IterableMat<Element> iterate(Mat &x) { CHECKER_ASSERT(DataType<Element>::type == x.type(), "WARNING: Data type mismatch in iterable, may lead to wrong results\n"); return IterableMat<Element>(x); } /** * This is another wrapper over MatIterator_ but it also gives the * (x,y) coordinates of the current loop instance. * The EnumerableMat<T> class has an EnumerationIterator * that gives back an Enumeration object upon dereference. The * Enumeration object has three fields: x, y, T& val, which are * set according to the current iteration. * * A simple way to get an EnumerableMat<T> from a Mat is to do * enumerate<T>(mat). Thus, an easy range based for loop would look * like: * * for(auto en : enumerate<float>(mat)) { * printf("%d %d %f", en.x, en.y, en.val); * } */ template<class Element> class EnumerableMat : public Mat { public: struct Enumeration { int x; int y; Element &val; Enumeration(int _x, int _y, Element &_val): x(_x), y(_y), val(_val) {} }; struct EnumerationIterator { int x; int y; int rows; int cols; MatIterator_<Element> it; EnumerationIterator& operator++ () { if(x < cols-1) ++x; else { x = 0; ++y; } ++it; return *this; } EnumerationIterator(MatIterator_<Element> _it, int _x, int _y, int _rows, int _cols): it(_it), x(_x), y(_y), rows(_rows), cols(_cols) {} bool operator != (const EnumerationIterator &other) { return it != other.it; } Enumeration operator*() { return Enumeration(x, y, *it); } }; EnumerationIterator begin() { return EnumerationIterator(Mat::begin<Element>(), 0, 0, Mat::rows, Mat::cols); } EnumerationIterator end() { return EnumerationIterator(Mat::end<Element>(), Mat::cols, Mat::rows, Mat::rows, Mat::cols); } EnumerableMat(Mat &x) : Mat(x) {} }; template<class Element> EnumerableMat<Element> enumerate(Mat &x) { CHECKER_ASSERT(DataType<Element>::type == x.type(), "WARNING: Data type mismatch in enumerable, may lead to wrong results\n"); return EnumerableMat<Element>(x); } #endif
c2cb4119f11e3a2e11fc43c557d286decd9900d4
d30a102c2bd54a2bdb9f6d7e51e53483d5b19bd6
/test_spuce/plot_fft.h
619acafb2995f56013ecf5f061ecaf198584440f
[ "BSL-1.0" ]
permissive
kevinl8890/spuce
56f1454970a4e1877965bd965d1ceedde9f81e5c
1fb0d26e8a09f3b6a43fff9f279ca202f03b6294
refs/heads/master
2020-04-11T06:02:24.825693
2017-10-30T00:39:54
2017-10-30T00:39:54
null
0
0
null
null
null
null
UTF-8
C++
false
false
265
h
plot_fft.h
#pragma once #include <vector> #include <complex> void plot_fft(std::vector<double>& data); void plot_fft(std::vector<std::complex<double>>& data); void plot_data(std::vector<double>& data); void compare_fft(std::vector<double>& data1, std::vector<double>& data2);
5f75777ea32be74d1cfe9092369d7ad2f89b258e
36fb616092b30a25df027ca2a4b91d9bf327641a
/ex05/PromoteForm.cpp
d0f61d901571e5b0305764a9f116a8bd301fe26b
[]
no_license
2LeoCode/CPP_Module_05
e6b41dca7d8cdac2f4bd09817e672ddb54c5f066
4241e32b0cac9616079db66c3d39957e5dab25b2
refs/heads/master
2023-02-23T04:58:32.669996
2021-01-27T18:06:39
2021-01-27T18:06:39
333,516,068
0
0
null
null
null
null
UTF-8
C++
false
false
1,081
cpp
PromoteForm.cpp
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* PromoteForm.cpp :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: lsuardi <lsuardi@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/01/26 16:35:48 by lsuardi #+# #+# */ /* Updated: 2021/01/26 16:51:38 by lsuardi ### ########.fr */ /* */ /* ************************************************************************** */ #include "PromoteForm.hpp" void PromoteForm::execute(Bureaucrat const & b) const { Form::execute(b); std::cout << '<' << _target << "> has been promoted to Bureaucrat++" << std::endl; }
bf553164fcc3bac98ce4d4645ff36ef99694c0f7
94f0ce8cc713c0fcb50821996d46d583214a9164
/Sources/hoaRecomposerProcessor/AmbisonicsRecomposer.cpp
6f80689cd40d9bf645925fb75730f586263138c5
[]
no_license
dimibil/HoaLibrary
6329e58a70274f7a5f196eaf43aa79cb94921200
f0f5513081c4d77b7fe53b36daf47552fe3e6420
refs/heads/master
2021-01-17T05:52:43.949051
2013-05-28T10:31:26
2013-05-28T10:31:26
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,116
cpp
AmbisonicsRecomposer.cpp
/* * * Copyright (C) 2012 Julien Colafrancesco & Pierre Guillot, Universite Paris 8 * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Library General Public License as published * by the Free Software Foundation; either version 2 of the License. * * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public * License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * */ #include "AmbisonicsRecomposer.h" ambisonicRecomposer::ambisonicRecomposer(int anOrder, int aNumberOfChannels, int aVectorSize) { m_order = anOrder; m_number_of_harmonics = m_order * 2 + 1; m_number_of_inputs = aNumberOfChannels; m_number_of_outputs = m_number_of_harmonics; m_fishEyeFactor = 1.; m_input_vector = gsl_vector_alloc(m_number_of_inputs); m_output_vector = gsl_vector_alloc(m_number_of_outputs); m_recompMicCoefs = gsl_matrix_alloc(m_number_of_inputs, m_number_of_outputs); m_recompMicCoefsSet = new gsl_matrix*[NUMBEROFCIRCLEPOINTS]; for (int i = 0; i < NUMBEROFCIRCLEPOINTS; i++) m_recompMicCoefsSet[i] = gsl_matrix_alloc(m_number_of_inputs, m_number_of_outputs); computeIndex(); computeAngles(); computeMicMatrixSet(); setVectorSize(aVectorSize); } int ambisonicRecomposer::getParameters(std::string aParameter) const { int value = 0; if (aParameter == "order") value = m_order; else if (aParameter == "samplingRate") value = m_sampling_rate; else if (aParameter == "vectorSize") value = m_vector_size; else if (aParameter == "numberOfInputs") value = m_number_of_inputs; else if (aParameter == "numberOfOutputs") value = m_number_of_outputs; return value; } void ambisonicRecomposer::computeIndex() { m_index_of_harmonics = new int[m_number_of_harmonics ]; m_index_of_harmonics[0] = 0; for(int i = 1; i < m_number_of_harmonics; i++) { m_index_of_harmonics[i] = (i - 1) / 2 + 1; if (i % 2 == 1) m_index_of_harmonics[i] = - m_index_of_harmonics[i]; } } void ambisonicRecomposer::computeAngles() { m_speakers_angles = new double[m_number_of_inputs]; for(int i = 0; i < m_number_of_inputs; i++) { m_speakers_angles[i] = (2. * PI / (double)m_number_of_inputs) * (double)i; if(m_speakers_angles[i] > PI) m_speakers_angles[i] -= 2. * PI; } } void ambisonicRecomposer::computeMicMatrix(gsl_matrix* resMatrix, double aFishFactor) { for (int micIndex = 0; micIndex < m_number_of_inputs; micIndex++) { gsl_matrix_set(resMatrix, micIndex, 0, 1); for (int orderIndex = 1; orderIndex <= m_order; orderIndex++) { gsl_matrix_set(resMatrix, micIndex, orderIndex * 2 -1, sin(orderIndex * m_speakers_angles[micIndex] * aFishFactor)); gsl_matrix_set(resMatrix, micIndex, orderIndex * 2 , cos(orderIndex * m_speakers_angles[micIndex] * aFishFactor)); } } } void ambisonicRecomposer::computeMicMatrixSet() { double tmpFishEyeFactor; for (int matIndex = 0; matIndex < NUMBEROFCIRCLEPOINTS; matIndex++) { tmpFishEyeFactor = (float)matIndex/float(NUMBEROFCIRCLEPOINTS-1); computeMicMatrix(m_recompMicCoefsSet[matIndex], tmpFishEyeFactor); } } void ambisonicRecomposer::setVectorSize(int aVectorSize) { m_vector_size = aVectorSize; } void ambisonicRecomposer::setFishEyeFactor(double aFishEyeFactor) { if (aFishEyeFactor > 1.) aFishEyeFactor = 1.; else if (aFishEyeFactor < 0.) aFishEyeFactor = 0.; m_fishEyeFactor = aFishEyeFactor; } ambisonicRecomposer::~ambisonicRecomposer() { gsl_matrix_free(m_recompMicCoefs); for (int i = 0; i < NUMBEROFCIRCLEPOINTS; i++) gsl_matrix_free(m_recompMicCoefsSet[i]); delete[] m_recompMicCoefsSet; gsl_vector_free(m_output_vector); gsl_vector_free(m_input_vector); delete[] m_speakers_angles; delete[] m_index_of_harmonics; }
d0a7baf0a2e2e324e6d6a3de18f6cd7c2e935118
87ecb0545391aa1217843c9348fec455836ff017
/DataStructure/Map/HashMap.cc
b9758ac3f03cbd970a79c840ca83eace103e6464
[]
no_license
MarkAureliy/software-engineer
fff34b0c909e2cb0f7ea88470e684f2e12d9acd0
20d63e2489c104ea39fdc67d2861ecb868d5e63e
refs/heads/master
2023-04-05T08:35:35.805347
2021-04-13T15:04:59
2021-04-13T15:04:59
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,381
cc
HashMap.cc
/* Author: Jemmy * Date: 2020-03-22 */ #include <iostream> #include <vector> #include <utility> #include <optional> template<typename KeyT, typename ValT, typename HashT = std::hash<KeyT>> class HashMap { public: using key_type = KeyT; using mapped_type = ValT; using value_type = std::pair<const key_type, mapped_type>; using size_type = size_t; using hash_type = HashT; using element_type = std::shared_ptr<value_type>; public: HashMap() { mContainer = new element_type[mCapacity]; } ~HashMap() { delete [] mContainer; } bool empty() { return mSize == 0; } size_type size() { return mSize; } size_type capacity() { return mCapacity; } using optional_type = std::optional<std::reference_wrapper<mapped_type>>; optional_type find (const key_type& key) const { auto idx = index(key); auto result = mContainer[idx]; return result ? optional_type(std::ref(result->second)) : std::nullopt; } mapped_type& operator[](const key_type& key) { auto idx = index(key); if (!mContainer[idx] && insertAt(idx, key) && loadFactor() >= mLoadFactor) { expand(); idx = index(key); // mCapacity changed } return mContainer[idx]->second; } void insert(const key_type& key, const mapped_type& val) { operator[](key) = val; } private: size_type index(const key_type& key) const { auto idx = mHasher(key) % mCapacity; auto count = 1; while (mContainer[idx] != nullptr && mContainer[idx]->first != key) { idx = (idx + count++) % mCapacity; } return idx; } double loadFactor() const { return static_cast<double>(mSize / mCapacity); } bool insertAt(size_t idx, const key_type& key) { ++mSize; mContainer[idx] = std::make_shared<value_type>(std::make_pair(key, mapped_type())); return true; } void expand() { auto preCapacity = mCapacity; mCapacity *= 2; element_type* tmp = new element_type[mCapacity]; for (auto idx = 0; idx < preCapacity; ++idx) { if (auto val = mContainer[idx]) { tmp[index(val->first)] = val; } } delete [] mContainer; mContainer = tmp; } private: size_t mSize = 0; size_t mCapacity = 4; double mLoadFactor = 0.75; const hash_type mHasher = hash_type(); element_type *mContainer; }; template<typename KeyT, typename ValT> void TestHashMap(HashMap<KeyT, ValT>& map, const KeyT& key, const ValT& val) { map.insert(key, val); std::cout << "Size: " << map.size() << " Capacity: " << map.capacity() << " Key: " << key << " val: " << map[key] << std::endl << std::endl; } int main() { HashMap<int, int> map; TestHashMap(map, 1, 1); TestHashMap(map, 2, 2); TestHashMap(map, 3, 3); TestHashMap(map, 4, 4); TestHashMap(map, 5, 5); TestHashMap(map, 6, 6); TestHashMap(map, 7, 7); TestHashMap(map, 8, 8); TestHashMap(map, 9, 9); TestHashMap(map, 10, 10); if (auto opt = map.find(4)) { std::cout << "find key = 4, valu = " << *opt << std::endl; } if (auto opt = map.find(20)) { } else { std::cout << "Oops, not find key = 20" << std::endl; } return 0; }
94b52d61fa54edd1e1bf45d7912436b4bcae3577
83c0ed11b4d229d02907042c3b2ded2f96205269
/c++_code(dirty)/rmse.h
f2aa1d9467c13404cde8b1a0228fbb9e5bcdac89
[]
no_license
AdamGabrys/Time_series_prediction_FCM_IG_PSO
54b753dd168bb0db18fc34bfa956458df639cd0c
7f4e2b812f1f24f2421aeff6aefe19eab6520312
refs/heads/master
2021-05-30T21:45:39.534058
2016-04-08T21:49:57
2016-04-08T21:49:57
55,811,559
2
0
null
null
null
null
UTF-8
C++
false
false
398
h
rmse.h
#ifndef RMSE_H_INCLUDED #define RMSE_H_INCLUDED #include <cmath> #include <vector> inline double rmse(double* dat, std::vector<double> dat_or ,int t){ //double dat_s=0; double dif=0; double ret; /*for(int i=0; i<t; i++){ dat_s+=dat[i]; } dat_s=dat_s/(double)t;*/ for(int i=0; i<t; i++){ dif+=pow(dat[i]-dat_or[i],2); } ret=sqrt(dif/(double)t); return ret; } #endif // RMSE_H_INCLUDED
a8483d07b9fe8b77577ad3c769677594e40a8c5f
1ecb45de29ec256a367b1d441c69158e63f1f280
/Session 2/representation.cpp
ec8aaff987a7b3aa64ab264cb8fc4a76b54b0784
[]
no_license
safwankdb/WnCC-Competitive-Coding
2c2e1591d7693524a8c4d34c99e562f65ff20487
de04e5d99b7e61ee983797cb5a92fe0522d0cf21
refs/heads/master
2021-06-30T17:48:58.851327
2019-02-11T11:32:40
2019-02-11T11:32:40
165,313,442
5
2
null
2020-10-01T18:47:26
2019-01-11T21:35:55
C++
UTF-8
C++
false
false
251
cpp
representation.cpp
#include<bits/stdc++.h> using namespace std ; const int N=100010; vector<int> adj[N] ; int main() { int n,m ; cin >> n >> m ; for(int i=0 ; i<m ; i++){ int u,v ; cin >> u >> v ; adj[u].push_back(v); adj[v].push_back(u) ; } return 0 ; }
e441b16c97c61871633d8414faa7c2e62959c9fc
e0983d33e0d60dd00eb3aa4858ff2f36a6d51f67
/coreless_motor_tutorial/coreless_motor_tutorial.ino
e29d5d7b2477c630a63a2f708af5b73393161e2e
[]
no_license
prashant9316/Coreless--Motor
a41bd26e0a3242bb8532db87d7379fd4d8cca1b6
968d1225202ed502bfd7bfb600d41d7356787e75
refs/heads/master
2022-05-29T04:39:38.768779
2020-05-03T04:23:34
2020-05-03T04:23:34
260,827,253
0
0
null
null
null
null
UTF-8
C++
false
false
502
ino
coreless_motor_tutorial.ino
int turns = 10; int turnAmount = 10; const int m = 9; void setup() { pinMode(m,OUTPUT); pinMode(LED_BUILTIN,OUTPUT); delay(1000); } void loop() { analogWrite(m,turns); delay(1000); turns += turnAmount; if(turns > 255){ turnAmount = -10; digitalWrite(LED_BUILTIN,HIGH); delay(100); digitalWrite(LED_BUILTIN,LOW); } else if (turns <= 0) { turnAmount = 10; digitalWrite(LED_BUILTIN,HIGH); delay(100); digitalWrite(LED_BUILTIN,LOW); } }
623cd0a18e955782a521e1eea3e569ec8995237a
a3d6556180e74af7b555f8d47d3fea55b94bcbda
/ui/views/accessibility/ax_virtual_view_unittest.cc
95e35d7866414e8d6bb64df0f92471d2aafe16cd
[ "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
34,733
cc
ax_virtual_view_unittest.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 "ui/views/accessibility/ax_virtual_view.h" #include <utility> #include <vector> #include "base/functional/callback.h" #include "base/memory/ptr_util.h" #include "base/memory/raw_ptr.h" #include "build/build_config.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" #include "ui/accessibility/ax_enums.mojom.h" #include "ui/accessibility/ax_node_data.h" #include "ui/accessibility/platform/ax_platform_node.h" #include "ui/accessibility/platform/ax_platform_node_delegate.h" #include "ui/gfx/geometry/rect.h" #include "ui/gfx/geometry/size.h" #include "ui/views/accessibility/view_accessibility.h" #include "ui/views/accessibility/view_ax_platform_node_delegate.h" #include "ui/views/controls/button/button.h" #include "ui/views/test/views_test_base.h" #include "ui/views/view.h" #include "ui/views/widget/widget.h" #if BUILDFLAG(IS_WIN) #include "ui/views/win/hwnd_util.h" #endif namespace views::test { namespace { class TestButton : public Button { public: TestButton() : Button(Button::PressedCallback()) {} TestButton(const TestButton&) = delete; TestButton& operator=(const TestButton&) = delete; ~TestButton() override = default; }; } // namespace class AXVirtualViewTest : public ViewsTestBase { public: AXVirtualViewTest() : ax_mode_setter_(ui::kAXModeComplete) {} AXVirtualViewTest(const AXVirtualViewTest&) = delete; AXVirtualViewTest& operator=(const AXVirtualViewTest&) = delete; ~AXVirtualViewTest() override = default; void SetUp() override { ViewsTestBase::SetUp(); widget_ = new Widget; Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_WINDOW); params.bounds = gfx::Rect(0, 0, 200, 200); widget_->Init(std::move(params)); button_ = new TestButton; button_->SetSize(gfx::Size(20, 20)); button_->SetAccessibleName(u"Button"); widget_->GetContentsView()->AddChildView(button_.get()); virtual_label_ = new AXVirtualView; virtual_label_->GetCustomData().role = ax::mojom::Role::kStaticText; virtual_label_->GetCustomData().SetNameChecked("Label"); button_->GetViewAccessibility().AddVirtualChildView( base::WrapUnique(virtual_label_.get())); widget_->Show(); ViewAccessibility::AccessibilityEventsCallback accessibility_events_callback = base::BindRepeating( [](std::vector<std::pair<const ui::AXPlatformNodeDelegate*, const ax::mojom::Event>>* accessibility_events, const ui::AXPlatformNodeDelegate* delegate, const ax::mojom::Event event_type) { DCHECK(accessibility_events); accessibility_events->push_back({delegate, event_type}); }, &accessibility_events_); button_->GetViewAccessibility().set_accessibility_events_callback( std::move(accessibility_events_callback)); } void TearDown() override { if (!widget_->IsClosed()) widget_->Close(); ViewsTestBase::TearDown(); } protected: ViewAXPlatformNodeDelegate* GetButtonAccessibility() const { return static_cast<ViewAXPlatformNodeDelegate*>( &button_->GetViewAccessibility()); } #if defined(USE_AURA) void SetCache(AXVirtualView& virtual_view, AXAuraObjCache& cache) const { virtual_view.set_cache(&cache); } #endif // defined(USE_AURA) void ExpectReceivedAccessibilityEvents( const std::vector<std::pair<const ui::AXPlatformNodeDelegate*, const ax::mojom::Event>>& expected_events) { EXPECT_THAT(accessibility_events_, testing::ContainerEq(expected_events)); accessibility_events_.clear(); } raw_ptr<Widget, AcrossTasksDanglingUntriaged> widget_; raw_ptr<Button, AcrossTasksDanglingUntriaged> button_; // Weak, |button_| owns this. raw_ptr<AXVirtualView, AcrossTasksDanglingUntriaged> virtual_label_; private: std::vector< std::pair<const ui::AXPlatformNodeDelegate*, const ax::mojom::Event>> accessibility_events_; ScopedAXModeSetter ax_mode_setter_; }; TEST_F(AXVirtualViewTest, AccessibilityRoleAndName) { EXPECT_EQ(ax::mojom::Role::kButton, GetButtonAccessibility()->GetRole()); EXPECT_EQ(ax::mojom::Role::kStaticText, virtual_label_->GetRole()); EXPECT_EQ("Label", virtual_label_->GetStringAttribute( ax::mojom::StringAttribute::kName)); } // The focusable state of a virtual view should not depend on the focusable // state of the real view ancestor, however the enabled state should. TEST_F(AXVirtualViewTest, FocusableAndEnabledState) { virtual_label_->GetCustomData().AddState(ax::mojom::State::kFocusable); EXPECT_TRUE(GetButtonAccessibility()->HasState(ax::mojom::State::kFocusable)); EXPECT_TRUE(virtual_label_->HasState(ax::mojom::State::kFocusable)); EXPECT_EQ(ax::mojom::Restriction::kNone, GetButtonAccessibility()->GetData().GetRestriction()); EXPECT_EQ(ax::mojom::Restriction::kNone, virtual_label_->GetData().GetRestriction()); button_->SetFocusBehavior(View::FocusBehavior::NEVER); EXPECT_FALSE( GetButtonAccessibility()->HasState(ax::mojom::State::kFocusable)); EXPECT_TRUE(virtual_label_->HasState(ax::mojom::State::kFocusable)); EXPECT_EQ(ax::mojom::Restriction::kNone, GetButtonAccessibility()->GetData().GetRestriction()); EXPECT_EQ(ax::mojom::Restriction::kNone, virtual_label_->GetData().GetRestriction()); button_->SetEnabled(false); EXPECT_FALSE( GetButtonAccessibility()->HasState(ax::mojom::State::kFocusable)); EXPECT_TRUE(virtual_label_->HasState(ax::mojom::State::kFocusable)); EXPECT_EQ(ax::mojom::Restriction::kDisabled, GetButtonAccessibility()->GetData().GetRestriction()); EXPECT_EQ(ax::mojom::Restriction::kDisabled, virtual_label_->GetData().GetRestriction()); button_->SetEnabled(true); button_->SetFocusBehavior(View::FocusBehavior::ALWAYS); virtual_label_->GetCustomData().RemoveState(ax::mojom::State::kFocusable); EXPECT_TRUE(GetButtonAccessibility()->HasState(ax::mojom::State::kFocusable)); EXPECT_FALSE(virtual_label_->HasState(ax::mojom::State::kFocusable)); EXPECT_EQ(ax::mojom::Restriction::kNone, GetButtonAccessibility()->GetData().GetRestriction()); EXPECT_EQ(ax::mojom::Restriction::kNone, virtual_label_->GetData().GetRestriction()); } TEST_F(AXVirtualViewTest, VirtualLabelIsChildOfButton) { EXPECT_EQ(1u, GetButtonAccessibility()->GetChildCount()); EXPECT_EQ(0u, virtual_label_->GetChildCount()); ASSERT_NE(nullptr, virtual_label_->GetParent()); EXPECT_EQ(button_->GetNativeViewAccessible(), virtual_label_->GetParent()); ASSERT_NE(nullptr, GetButtonAccessibility()->ChildAtIndex(0)); EXPECT_EQ(virtual_label_->GetNativeObject(), GetButtonAccessibility()->ChildAtIndex(0)); } TEST_F(AXVirtualViewTest, RemoveFromParentView) { ASSERT_EQ(1u, GetButtonAccessibility()->GetChildCount()); std::unique_ptr<AXVirtualView> removed_label = virtual_label_->RemoveFromParentView(); EXPECT_EQ(nullptr, removed_label->GetParent()); EXPECT_TRUE(GetButtonAccessibility()->virtual_children().empty()); AXVirtualView* virtual_child_1 = new AXVirtualView; removed_label->AddChildView(base::WrapUnique(virtual_child_1)); ASSERT_EQ(1u, removed_label->GetChildCount()); ASSERT_NE(nullptr, virtual_child_1->GetParent()); std::unique_ptr<AXVirtualView> removed_child_1 = virtual_child_1->RemoveFromParentView(); EXPECT_EQ(nullptr, removed_child_1->GetParent()); EXPECT_EQ(0u, removed_label->GetChildCount()); } #if defined(USE_AURA) TEST_F(AXVirtualViewTest, MultipleCaches) { // This test ensures that AXVirtualView objects remove themselves from an // existing cache (if present) when |set_cache| is called. std::unique_ptr<AXAuraObjCache> cache = std::make_unique<AXAuraObjCache>(); std::unique_ptr<AXAuraObjCache> second_cache = std::make_unique<AXAuraObjCache>(); // Store |virtual_label_| in |cache|. SetCache(*virtual_label_, *cache); AXVirtualViewWrapper* wrapper = virtual_label_->GetOrCreateWrapper(cache.get()); EXPECT_NE(wrapper, nullptr); EXPECT_NE(wrapper->GetUniqueId(), ui::kInvalidAXNodeID); EXPECT_NE(wrapper->GetParent(), nullptr); EXPECT_NE(cache->GetID(virtual_label_.get()), ui::kInvalidAXNodeID); // Store |virtual_label_| in |second_cache|. SetCache(*virtual_label_, *second_cache); AXVirtualViewWrapper* second_wrapper = virtual_label_->GetOrCreateWrapper(second_cache.get()); EXPECT_NE(second_wrapper, nullptr); EXPECT_NE(second_wrapper->GetUniqueId(), ui::kInvalidAXNodeID); // |virtual_label_| should only exist in |second_cache|. EXPECT_NE(second_cache->GetID(virtual_label_.get()), ui::kInvalidAXNodeID); EXPECT_EQ(cache->GetID(virtual_label_.get()), ui::kInvalidAXNodeID); } #endif // defined(USE_AURA) TEST_F(AXVirtualViewTest, AddingAndRemovingVirtualChildren) { ASSERT_EQ(0u, virtual_label_->GetChildCount()); ExpectReceivedAccessibilityEvents({}); AXVirtualView* virtual_child_1 = new AXVirtualView; virtual_label_->AddChildView(base::WrapUnique(virtual_child_1)); EXPECT_EQ(1u, virtual_label_->GetChildCount()); ASSERT_NE(nullptr, virtual_child_1->GetParent()); EXPECT_EQ(virtual_label_->GetNativeObject(), virtual_child_1->GetParent()); ASSERT_NE(nullptr, virtual_label_->ChildAtIndex(0)); EXPECT_EQ(virtual_child_1->GetNativeObject(), virtual_label_->ChildAtIndex(0)); ExpectReceivedAccessibilityEvents({std::make_pair( GetButtonAccessibility(), ax::mojom::Event::kChildrenChanged)}); AXVirtualView* virtual_child_2 = new AXVirtualView; virtual_label_->AddChildView(base::WrapUnique(virtual_child_2)); EXPECT_EQ(2u, virtual_label_->GetChildCount()); ASSERT_NE(nullptr, virtual_child_2->GetParent()); EXPECT_EQ(virtual_label_->GetNativeObject(), virtual_child_2->GetParent()); ASSERT_NE(nullptr, virtual_label_->ChildAtIndex(1)); EXPECT_EQ(virtual_child_2->GetNativeObject(), virtual_label_->ChildAtIndex(1)); ExpectReceivedAccessibilityEvents({std::make_pair( GetButtonAccessibility(), ax::mojom::Event::kChildrenChanged)}); AXVirtualView* virtual_child_3 = new AXVirtualView; virtual_child_2->AddChildView(base::WrapUnique(virtual_child_3)); EXPECT_EQ(2u, virtual_label_->GetChildCount()); EXPECT_EQ(0u, virtual_child_1->GetChildCount()); EXPECT_EQ(1u, virtual_child_2->GetChildCount()); ASSERT_NE(nullptr, virtual_child_3->GetParent()); EXPECT_EQ(virtual_child_2->GetNativeObject(), virtual_child_3->GetParent()); ASSERT_NE(nullptr, virtual_child_2->ChildAtIndex(0)); EXPECT_EQ(virtual_child_3->GetNativeObject(), virtual_child_2->ChildAtIndex(0)); ExpectReceivedAccessibilityEvents({std::make_pair( GetButtonAccessibility(), ax::mojom::Event::kChildrenChanged)}); virtual_child_2->RemoveChildView(virtual_child_3); EXPECT_EQ(0u, virtual_child_2->GetChildCount()); EXPECT_EQ(2u, virtual_label_->GetChildCount()); ExpectReceivedAccessibilityEvents({std::make_pair( GetButtonAccessibility(), ax::mojom::Event::kChildrenChanged)}); virtual_label_->RemoveAllChildViews(); EXPECT_EQ(0u, virtual_label_->GetChildCount()); // There should be two "kChildrenChanged" events because Two virtual child // views are removed in total. ExpectReceivedAccessibilityEvents( {std::make_pair(GetButtonAccessibility(), ax::mojom::Event::kChildrenChanged), std::make_pair(GetButtonAccessibility(), ax::mojom::Event::kChildrenChanged)}); } TEST_F(AXVirtualViewTest, ReorderingVirtualChildren) { ASSERT_EQ(0u, virtual_label_->GetChildCount()); AXVirtualView* virtual_child_1 = new AXVirtualView; virtual_label_->AddChildView(base::WrapUnique(virtual_child_1)); ASSERT_EQ(1u, virtual_label_->GetChildCount()); AXVirtualView* virtual_child_2 = new AXVirtualView; virtual_label_->AddChildView(base::WrapUnique(virtual_child_2)); ASSERT_EQ(2u, virtual_label_->GetChildCount()); virtual_label_->ReorderChildView(virtual_child_1, 100); ASSERT_EQ(2u, virtual_label_->GetChildCount()); EXPECT_EQ(virtual_label_->GetNativeObject(), virtual_child_2->GetParent()); ASSERT_NE(nullptr, virtual_label_->ChildAtIndex(0)); EXPECT_EQ(virtual_child_2->GetNativeObject(), virtual_label_->ChildAtIndex(0)); ASSERT_NE(nullptr, virtual_label_->ChildAtIndex(1)); EXPECT_EQ(virtual_child_1->GetNativeObject(), virtual_label_->ChildAtIndex(1)); virtual_label_->ReorderChildView(virtual_child_1, 0); ASSERT_EQ(2u, virtual_label_->GetChildCount()); EXPECT_EQ(virtual_label_->GetNativeObject(), virtual_child_1->GetParent()); ASSERT_NE(nullptr, virtual_label_->ChildAtIndex(0)); EXPECT_EQ(virtual_child_1->GetNativeObject(), virtual_label_->ChildAtIndex(0)); ASSERT_NE(nullptr, virtual_label_->ChildAtIndex(1)); EXPECT_EQ(virtual_child_2->GetNativeObject(), virtual_label_->ChildAtIndex(1)); virtual_label_->RemoveAllChildViews(); ASSERT_EQ(0u, virtual_label_->GetChildCount()); } TEST_F(AXVirtualViewTest, ContainsVirtualChild) { ASSERT_EQ(0u, virtual_label_->GetChildCount()); AXVirtualView* virtual_child_1 = new AXVirtualView; virtual_label_->AddChildView(base::WrapUnique(virtual_child_1)); ASSERT_EQ(1u, virtual_label_->GetChildCount()); AXVirtualView* virtual_child_2 = new AXVirtualView; virtual_label_->AddChildView(base::WrapUnique(virtual_child_2)); ASSERT_EQ(2u, virtual_label_->GetChildCount()); AXVirtualView* virtual_child_3 = new AXVirtualView; virtual_child_2->AddChildView(base::WrapUnique(virtual_child_3)); ASSERT_EQ(1u, virtual_child_2->GetChildCount()); EXPECT_TRUE(button_->GetViewAccessibility().Contains(virtual_label_)); EXPECT_TRUE(virtual_label_->Contains(virtual_label_)); EXPECT_TRUE(virtual_label_->Contains(virtual_child_1)); EXPECT_TRUE(virtual_label_->Contains(virtual_child_2)); EXPECT_TRUE(virtual_label_->Contains(virtual_child_3)); EXPECT_TRUE(virtual_child_2->Contains(virtual_child_2)); EXPECT_TRUE(virtual_child_2->Contains(virtual_child_3)); EXPECT_FALSE(virtual_child_1->Contains(virtual_label_)); EXPECT_FALSE(virtual_child_2->Contains(virtual_label_)); EXPECT_FALSE(virtual_child_3->Contains(virtual_child_2)); virtual_label_->RemoveAllChildViews(); ASSERT_EQ(0u, virtual_label_->GetChildCount()); } TEST_F(AXVirtualViewTest, GetIndexOfVirtualChild) { ASSERT_EQ(0u, virtual_label_->GetChildCount()); AXVirtualView* virtual_child_1 = new AXVirtualView; virtual_label_->AddChildView(base::WrapUnique(virtual_child_1)); ASSERT_EQ(1u, virtual_label_->GetChildCount()); AXVirtualView* virtual_child_2 = new AXVirtualView; virtual_label_->AddChildView(base::WrapUnique(virtual_child_2)); ASSERT_EQ(2u, virtual_label_->GetChildCount()); AXVirtualView* virtual_child_3 = new AXVirtualView; virtual_child_2->AddChildView(base::WrapUnique(virtual_child_3)); ASSERT_EQ(1u, virtual_child_2->GetChildCount()); EXPECT_FALSE(virtual_label_->GetIndexOf(virtual_label_).has_value()); EXPECT_EQ(0u, virtual_label_->GetIndexOf(virtual_child_1).value()); EXPECT_EQ(1u, virtual_label_->GetIndexOf(virtual_child_2).value()); EXPECT_FALSE(virtual_label_->GetIndexOf(virtual_child_3).has_value()); EXPECT_EQ(0u, virtual_child_2->GetIndexOf(virtual_child_3).value()); virtual_label_->RemoveAllChildViews(); ASSERT_EQ(0u, virtual_label_->GetChildCount()); } // Verify that virtual views with invisible ancestors inherit the // ax::mojom::State::kInvisible state. TEST_F(AXVirtualViewTest, InvisibleVirtualViews) { EXPECT_TRUE(widget_->IsVisible()); EXPECT_FALSE( GetButtonAccessibility()->HasState(ax::mojom::State::kInvisible)); EXPECT_FALSE(virtual_label_->HasState(ax::mojom::State::kInvisible)); button_->SetVisible(false); EXPECT_TRUE(GetButtonAccessibility()->HasState(ax::mojom::State::kInvisible)); EXPECT_TRUE(virtual_label_->HasState(ax::mojom::State::kInvisible)); button_->SetVisible(true); } TEST_F(AXVirtualViewTest, OverrideFocus) { ViewAccessibility& button_accessibility = button_->GetViewAccessibility(); ASSERT_NE(nullptr, button_accessibility.GetNativeObject()); ASSERT_NE(nullptr, virtual_label_->GetNativeObject()); ExpectReceivedAccessibilityEvents({}); button_->SetFocusBehavior(View::FocusBehavior::ALWAYS); button_->RequestFocus(); ExpectReceivedAccessibilityEvents( {std::make_pair(GetButtonAccessibility(), ax::mojom::Event::kFocus)}); EXPECT_EQ(button_accessibility.GetNativeObject(), button_accessibility.GetFocusedDescendant()); button_accessibility.OverrideFocus(virtual_label_); EXPECT_EQ(virtual_label_->GetNativeObject(), button_accessibility.GetFocusedDescendant()); ExpectReceivedAccessibilityEvents( {std::make_pair(virtual_label_, ax::mojom::Event::kFocus)}); button_accessibility.OverrideFocus(nullptr); EXPECT_EQ(button_accessibility.GetNativeObject(), button_accessibility.GetFocusedDescendant()); ExpectReceivedAccessibilityEvents( {std::make_pair(GetButtonAccessibility(), ax::mojom::Event::kFocus)}); ASSERT_EQ(0u, virtual_label_->GetChildCount()); AXVirtualView* virtual_child_1 = new AXVirtualView; virtual_label_->AddChildView(base::WrapUnique(virtual_child_1)); ASSERT_EQ(1u, virtual_label_->GetChildCount()); ExpectReceivedAccessibilityEvents({std::make_pair( GetButtonAccessibility(), ax::mojom::Event::kChildrenChanged)}); AXVirtualView* virtual_child_2 = new AXVirtualView; virtual_label_->AddChildView(base::WrapUnique(virtual_child_2)); ASSERT_EQ(2u, virtual_label_->GetChildCount()); ExpectReceivedAccessibilityEvents({std::make_pair( GetButtonAccessibility(), ax::mojom::Event::kChildrenChanged)}); button_accessibility.OverrideFocus(virtual_child_1); EXPECT_EQ(virtual_child_1->GetNativeObject(), button_accessibility.GetFocusedDescendant()); ExpectReceivedAccessibilityEvents( {std::make_pair(virtual_child_1, ax::mojom::Event::kFocus)}); AXVirtualView* virtual_child_3 = new AXVirtualView; virtual_child_2->AddChildView(base::WrapUnique(virtual_child_3)); ASSERT_EQ(1u, virtual_child_2->GetChildCount()); ExpectReceivedAccessibilityEvents({std::make_pair( GetButtonAccessibility(), ax::mojom::Event::kChildrenChanged)}); EXPECT_EQ(virtual_child_1->GetNativeObject(), button_accessibility.GetFocusedDescendant()); button_accessibility.OverrideFocus(virtual_child_3); EXPECT_EQ(virtual_child_3->GetNativeObject(), button_accessibility.GetFocusedDescendant()); ExpectReceivedAccessibilityEvents( {std::make_pair(virtual_child_3, ax::mojom::Event::kFocus)}); // Test that calling GetFocus() while the owner view is not focused will // return nullptr. button_->SetFocusBehavior(View::FocusBehavior::NEVER); button_->RequestFocus(); ExpectReceivedAccessibilityEvents({}); EXPECT_EQ(nullptr, virtual_label_->GetFocus()); EXPECT_EQ(nullptr, virtual_child_1->GetFocus()); EXPECT_EQ(nullptr, virtual_child_2->GetFocus()); EXPECT_EQ(nullptr, virtual_child_3->GetFocus()); button_->SetFocusBehavior(View::FocusBehavior::ALWAYS); button_->RequestFocus(); ExpectReceivedAccessibilityEvents( {std::make_pair(virtual_child_3, ax::mojom::Event::kFocus)}); // Test that calling GetFocus() from any object in the tree will return the // same result. EXPECT_EQ(virtual_child_3->GetNativeObject(), virtual_label_->GetFocus()); EXPECT_EQ(virtual_child_3->GetNativeObject(), virtual_child_1->GetFocus()); EXPECT_EQ(virtual_child_3->GetNativeObject(), virtual_child_2->GetFocus()); EXPECT_EQ(virtual_child_3->GetNativeObject(), virtual_child_3->GetFocus()); virtual_label_->RemoveChildView(virtual_child_2); ASSERT_EQ(1u, virtual_label_->GetChildCount()); ExpectReceivedAccessibilityEvents( {std::make_pair(GetButtonAccessibility(), ax::mojom::Event::kFocus), std::make_pair(GetButtonAccessibility(), ax::mojom::Event::kChildrenChanged)}); EXPECT_EQ(button_accessibility.GetNativeObject(), button_accessibility.GetFocusedDescendant()); EXPECT_EQ(button_accessibility.GetNativeObject(), virtual_label_->GetFocus()); EXPECT_EQ(button_accessibility.GetNativeObject(), virtual_child_1->GetFocus()); button_accessibility.OverrideFocus(virtual_child_1); EXPECT_EQ(virtual_child_1->GetNativeObject(), button_accessibility.GetFocusedDescendant()); ExpectReceivedAccessibilityEvents( {std::make_pair(virtual_child_1, ax::mojom::Event::kFocus)}); virtual_label_->RemoveAllChildViews(); ASSERT_EQ(0u, virtual_label_->GetChildCount()); EXPECT_EQ(button_accessibility.GetNativeObject(), button_accessibility.GetFocusedDescendant()); ExpectReceivedAccessibilityEvents( {std::make_pair(GetButtonAccessibility(), ax::mojom::Event::kFocus), std::make_pair(GetButtonAccessibility(), ax::mojom::Event::kChildrenChanged)}); } TEST_F(AXVirtualViewTest, TreeNavigation) { ASSERT_EQ(0u, virtual_label_->GetChildCount()); AXVirtualView* virtual_child_1 = new AXVirtualView; virtual_label_->AddChildView(base::WrapUnique(virtual_child_1)); AXVirtualView* virtual_child_2 = new AXVirtualView; virtual_label_->AddChildView(base::WrapUnique(virtual_child_2)); AXVirtualView* virtual_child_3 = new AXVirtualView; virtual_label_->AddChildView(base::WrapUnique(virtual_child_3)); AXVirtualView* virtual_child_4 = new AXVirtualView; virtual_child_2->AddChildView(base::WrapUnique(virtual_child_4)); EXPECT_EQ(button_->GetNativeViewAccessible(), virtual_label_->GetParent()); EXPECT_EQ(virtual_label_->GetNativeObject(), virtual_child_1->GetParent()); EXPECT_EQ(virtual_label_->GetNativeObject(), virtual_child_2->GetParent()); EXPECT_EQ(virtual_label_->GetNativeObject(), virtual_child_3->GetParent()); EXPECT_EQ(virtual_child_2->GetNativeObject(), virtual_child_4->GetParent()); EXPECT_EQ(0u, virtual_label_->GetIndexInParent()); EXPECT_EQ(0u, virtual_child_1->GetIndexInParent()); EXPECT_EQ(1u, virtual_child_2->GetIndexInParent()); EXPECT_EQ(2u, virtual_child_3->GetIndexInParent()); EXPECT_EQ(0u, virtual_child_4->GetIndexInParent()); EXPECT_EQ(3u, virtual_label_->GetChildCount()); EXPECT_EQ(0u, virtual_child_1->GetChildCount()); EXPECT_EQ(1u, virtual_child_2->GetChildCount()); EXPECT_EQ(0u, virtual_child_3->GetChildCount()); EXPECT_EQ(0u, virtual_child_4->GetChildCount()); EXPECT_EQ(virtual_child_1->GetNativeObject(), virtual_label_->ChildAtIndex(0)); EXPECT_EQ(virtual_child_2->GetNativeObject(), virtual_label_->ChildAtIndex(1)); EXPECT_EQ(virtual_child_3->GetNativeObject(), virtual_label_->ChildAtIndex(2)); EXPECT_EQ(virtual_child_4->GetNativeObject(), virtual_child_2->ChildAtIndex(0)); EXPECT_EQ(virtual_child_1->GetNativeObject(), virtual_label_->GetFirstChild()); EXPECT_EQ(virtual_child_3->GetNativeObject(), virtual_label_->GetLastChild()); EXPECT_EQ(nullptr, virtual_child_1->GetFirstChild()); EXPECT_EQ(nullptr, virtual_child_1->GetLastChild()); EXPECT_EQ(virtual_child_4->GetNativeObject(), virtual_child_2->GetFirstChild()); EXPECT_EQ(virtual_child_4->GetNativeObject(), virtual_child_2->GetLastChild()); EXPECT_EQ(nullptr, virtual_child_4->GetFirstChild()); EXPECT_EQ(nullptr, virtual_child_4->GetLastChild()); EXPECT_EQ(nullptr, virtual_label_->GetNextSibling()); EXPECT_EQ(nullptr, virtual_label_->GetPreviousSibling()); EXPECT_EQ(virtual_child_2->GetNativeObject(), virtual_child_1->GetNextSibling()); EXPECT_EQ(nullptr, virtual_child_1->GetPreviousSibling()); EXPECT_EQ(virtual_child_3->GetNativeObject(), virtual_child_2->GetNextSibling()); EXPECT_EQ(virtual_child_1->GetNativeObject(), virtual_child_2->GetPreviousSibling()); EXPECT_EQ(nullptr, virtual_child_3->GetNextSibling()); EXPECT_EQ(virtual_child_2->GetNativeObject(), virtual_child_3->GetPreviousSibling()); EXPECT_EQ(nullptr, virtual_child_4->GetNextSibling()); EXPECT_EQ(nullptr, virtual_child_4->GetPreviousSibling()); } TEST_F(AXVirtualViewTest, TreeNavigationWithIgnoredVirtualViews) { ASSERT_EQ(0u, virtual_label_->GetChildCount()); AXVirtualView* virtual_child_1 = new AXVirtualView; virtual_label_->AddChildView(base::WrapUnique(virtual_child_1)); virtual_child_1->GetCustomData().AddState(ax::mojom::State::kIgnored); EXPECT_EQ(0u, virtual_label_->GetChildCount()); EXPECT_EQ(0u, virtual_child_1->GetChildCount()); AXVirtualView* virtual_child_2 = new AXVirtualView; virtual_child_1->AddChildView(base::WrapUnique(virtual_child_2)); AXVirtualView* virtual_child_3 = new AXVirtualView; virtual_child_2->AddChildView(base::WrapUnique(virtual_child_3)); AXVirtualView* virtual_child_4 = new AXVirtualView; virtual_child_2->AddChildView(base::WrapUnique(virtual_child_4)); // While ignored nodes should not be accessible via any of the tree navigation // methods, their descendants should be. EXPECT_EQ(button_->GetNativeViewAccessible(), virtual_label_->GetParent()); EXPECT_EQ(virtual_label_->GetNativeObject(), virtual_child_1->GetParent()); EXPECT_EQ(virtual_label_->GetNativeObject(), virtual_child_2->GetParent()); EXPECT_EQ(virtual_child_2->GetNativeObject(), virtual_child_3->GetParent()); EXPECT_EQ(virtual_child_2->GetNativeObject(), virtual_child_4->GetParent()); EXPECT_EQ(0u, virtual_label_->GetIndexInParent()); EXPECT_FALSE(virtual_child_1->GetIndexInParent().has_value()); EXPECT_EQ(0u, virtual_child_2->GetIndexInParent()); EXPECT_EQ(0u, virtual_child_3->GetIndexInParent()); EXPECT_EQ(1u, virtual_child_4->GetIndexInParent()); EXPECT_EQ(1u, virtual_label_->GetChildCount()); EXPECT_EQ(1u, virtual_child_1->GetChildCount()); EXPECT_EQ(2u, virtual_child_2->GetChildCount()); EXPECT_EQ(0u, virtual_child_3->GetChildCount()); EXPECT_EQ(0u, virtual_child_4->GetChildCount()); EXPECT_EQ(virtual_child_2->GetNativeObject(), virtual_label_->ChildAtIndex(0)); EXPECT_EQ(virtual_child_2->GetNativeObject(), virtual_child_1->ChildAtIndex(0)); EXPECT_EQ(virtual_child_3->GetNativeObject(), virtual_child_2->ChildAtIndex(0)); EXPECT_EQ(virtual_child_4->GetNativeObject(), virtual_child_2->ChildAtIndex(1)); // Try ignoring a node by changing its role, instead of its state. virtual_child_2->GetCustomData().role = ax::mojom::Role::kNone; EXPECT_EQ(button_->GetNativeViewAccessible(), virtual_label_->GetParent()); EXPECT_EQ(virtual_label_->GetNativeObject(), virtual_child_1->GetParent()); EXPECT_EQ(virtual_label_->GetNativeObject(), virtual_child_2->GetParent()); EXPECT_EQ(virtual_label_->GetNativeObject(), virtual_child_3->GetParent()); EXPECT_EQ(virtual_label_->GetNativeObject(), virtual_child_4->GetParent()); EXPECT_EQ(2u, virtual_label_->GetChildCount()); EXPECT_EQ(2u, virtual_child_1->GetChildCount()); EXPECT_EQ(2u, virtual_child_2->GetChildCount()); EXPECT_EQ(0u, virtual_child_3->GetChildCount()); EXPECT_EQ(0u, virtual_child_4->GetChildCount()); EXPECT_EQ(0u, virtual_label_->GetIndexInParent()); EXPECT_FALSE(virtual_child_1->GetIndexInParent().has_value()); EXPECT_FALSE(virtual_child_2->GetIndexInParent().has_value()); EXPECT_EQ(0u, virtual_child_3->GetIndexInParent()); EXPECT_EQ(1u, virtual_child_4->GetIndexInParent()); EXPECT_EQ(virtual_child_3->GetNativeObject(), virtual_label_->ChildAtIndex(0)); EXPECT_EQ(virtual_child_4->GetNativeObject(), virtual_label_->ChildAtIndex(1)); EXPECT_EQ(virtual_child_3->GetNativeObject(), virtual_child_1->ChildAtIndex(0)); EXPECT_EQ(virtual_child_4->GetNativeObject(), virtual_child_1->ChildAtIndex(1)); EXPECT_EQ(virtual_child_3->GetNativeObject(), virtual_child_2->ChildAtIndex(0)); EXPECT_EQ(virtual_child_4->GetNativeObject(), virtual_child_2->ChildAtIndex(1)); // Test for mixed ignored and unignored virtual children. AXVirtualView* virtual_child_5 = new AXVirtualView; virtual_child_1->AddChildView(base::WrapUnique(virtual_child_5)); EXPECT_EQ(button_->GetNativeViewAccessible(), virtual_label_->GetParent()); EXPECT_EQ(virtual_label_->GetNativeObject(), virtual_child_1->GetParent()); EXPECT_EQ(virtual_label_->GetNativeObject(), virtual_child_2->GetParent()); EXPECT_EQ(virtual_label_->GetNativeObject(), virtual_child_3->GetParent()); EXPECT_EQ(virtual_label_->GetNativeObject(), virtual_child_4->GetParent()); EXPECT_EQ(virtual_label_->GetNativeObject(), virtual_child_5->GetParent()); EXPECT_EQ(3u, virtual_label_->GetChildCount()); EXPECT_EQ(3u, virtual_child_1->GetChildCount()); EXPECT_EQ(2u, virtual_child_2->GetChildCount()); EXPECT_EQ(0u, virtual_child_3->GetChildCount()); EXPECT_EQ(0u, virtual_child_4->GetChildCount()); EXPECT_EQ(0u, virtual_child_5->GetChildCount()); EXPECT_EQ(0u, virtual_label_->GetIndexInParent()); EXPECT_FALSE(virtual_child_1->GetIndexInParent().has_value()); EXPECT_FALSE(virtual_child_2->GetIndexInParent().has_value()); EXPECT_EQ(0u, virtual_child_3->GetIndexInParent()); EXPECT_EQ(1u, virtual_child_4->GetIndexInParent()); EXPECT_EQ(2u, virtual_child_5->GetIndexInParent()); EXPECT_EQ(virtual_child_3->GetNativeObject(), virtual_label_->ChildAtIndex(0)); EXPECT_EQ(virtual_child_4->GetNativeObject(), virtual_label_->ChildAtIndex(1)); EXPECT_EQ(virtual_child_5->GetNativeObject(), virtual_label_->ChildAtIndex(2)); // An ignored root node should not be exposed. virtual_label_->GetCustomData().AddState(ax::mojom::State::kIgnored); EXPECT_EQ(button_->GetNativeViewAccessible(), virtual_label_->GetParent()); EXPECT_EQ(button_->GetNativeViewAccessible(), virtual_child_1->GetParent()); EXPECT_EQ(button_->GetNativeViewAccessible(), virtual_child_2->GetParent()); EXPECT_EQ(button_->GetNativeViewAccessible(), virtual_child_3->GetParent()); EXPECT_EQ(button_->GetNativeViewAccessible(), virtual_child_4->GetParent()); EXPECT_EQ(button_->GetNativeViewAccessible(), virtual_child_5->GetParent()); EXPECT_EQ(3u, GetButtonAccessibility()->GetChildCount()); EXPECT_EQ(0u, virtual_child_3->GetIndexInParent()); EXPECT_EQ(1u, virtual_child_4->GetIndexInParent()); EXPECT_EQ(2u, virtual_child_5->GetIndexInParent()); EXPECT_EQ(virtual_child_3->GetNativeObject(), GetButtonAccessibility()->ChildAtIndex(0)); EXPECT_EQ(virtual_child_4->GetNativeObject(), GetButtonAccessibility()->ChildAtIndex(1)); EXPECT_EQ(virtual_child_5->GetNativeObject(), GetButtonAccessibility()->ChildAtIndex(2)); // Test for mixed ignored and unignored root nodes. AXVirtualView* virtual_label_2 = new AXVirtualView; virtual_label_2->GetCustomData().role = ax::mojom::Role::kStaticText; virtual_label_2->GetCustomData().SetNameChecked("Label"); button_->GetViewAccessibility().AddVirtualChildView( base::WrapUnique(virtual_label_2)); EXPECT_EQ(button_->GetNativeViewAccessible(), virtual_label_2->GetParent()); EXPECT_EQ(4u, GetButtonAccessibility()->GetChildCount()); EXPECT_EQ(0u, virtual_label_2->GetChildCount()); EXPECT_EQ(virtual_label_2->GetNativeObject(), GetButtonAccessibility()->ChildAtIndex(3)); // A focusable node should not be ignored. virtual_child_1->GetCustomData().AddState(ax::mojom::State::kFocusable); EXPECT_EQ(2u, GetButtonAccessibility()->GetChildCount()); EXPECT_EQ(1u, virtual_label_->GetChildCount()); EXPECT_EQ(virtual_child_1->GetNativeObject(), GetButtonAccessibility()->ChildAtIndex(0)); EXPECT_EQ(virtual_label_2->GetNativeObject(), GetButtonAccessibility()->ChildAtIndex(1)); } TEST_F(AXVirtualViewTest, HitTesting) { ASSERT_EQ(0u, virtual_label_->GetChildCount()); const gfx::Vector2d offset_from_origin = button_->GetBoundsInScreen().OffsetFromOrigin(); // Test that hit testing is recursive. AXVirtualView* virtual_child_1 = new AXVirtualView; virtual_child_1->GetCustomData().relative_bounds.bounds = gfx::RectF(0, 0, 10, 10); virtual_label_->AddChildView(base::WrapUnique(virtual_child_1)); AXVirtualView* virtual_child_2 = new AXVirtualView; virtual_child_2->GetCustomData().relative_bounds.bounds = gfx::RectF(5, 5, 5, 5); virtual_child_1->AddChildView(base::WrapUnique(virtual_child_2)); gfx::Point point_1 = gfx::Point(2, 2) + offset_from_origin; EXPECT_EQ(virtual_child_1->GetNativeObject(), virtual_child_1->HitTestSync(point_1.x(), point_1.y())); gfx::Point point_2 = gfx::Point(7, 7) + offset_from_origin; EXPECT_EQ(virtual_child_2->GetNativeObject(), virtual_label_->HitTestSync(point_2.x(), point_2.y())); // Test that hit testing follows the z-order. AXVirtualView* virtual_child_3 = new AXVirtualView; virtual_child_3->GetCustomData().relative_bounds.bounds = gfx::RectF(5, 5, 10, 10); virtual_label_->AddChildView(base::WrapUnique(virtual_child_3)); AXVirtualView* virtual_child_4 = new AXVirtualView; virtual_child_4->GetCustomData().relative_bounds.bounds = gfx::RectF(10, 10, 10, 10); virtual_child_3->AddChildView(base::WrapUnique(virtual_child_4)); EXPECT_EQ(virtual_child_3->GetNativeObject(), virtual_label_->HitTestSync(point_2.x(), point_2.y())); gfx::Point point_3 = gfx::Point(12, 12) + offset_from_origin; EXPECT_EQ(virtual_child_4->GetNativeObject(), virtual_label_->HitTestSync(point_3.x(), point_3.y())); // Test that hit testing skips ignored nodes but not their descendants. virtual_child_3->GetCustomData().AddState(ax::mojom::State::kIgnored); EXPECT_EQ(virtual_child_2->GetNativeObject(), virtual_label_->HitTestSync(point_2.x(), point_2.y())); EXPECT_EQ(virtual_child_4->GetNativeObject(), virtual_label_->HitTestSync(point_3.x(), point_3.y())); } // Test for GetTargetForNativeAccessibilityEvent(). #if BUILDFLAG(IS_WIN) TEST_F(AXVirtualViewTest, GetTargetForEvents) { EXPECT_EQ(button_, virtual_label_->GetOwnerView()); EXPECT_NE(nullptr, HWNDForView(virtual_label_->GetOwnerView())); EXPECT_EQ(HWNDForView(button_), virtual_label_->GetTargetForNativeAccessibilityEvent()); } #endif // BUILDFLAG(IS_WIN) } // namespace views::test
c3e8002e1cddbe681c2a7e53523280d87bf94436
ac45b5a1f9f357d14d7f290ff767d2bb849b657a
/src/WorkingTree.cpp
0c53f9f4bca98c10b121b42421831cf4c54c1969
[]
no_license
SimoneMSR/gentree
bbaf522c60fa7f030472112592eb2ce85e0b0654
12a12a02214f8bdae3f758485f39de28dad18375
refs/heads/master
2021-04-03T08:42:05.406362
2018-03-12T11:30:41
2018-03-12T11:30:41
124,876,722
0
0
null
null
null
null
UTF-8
C++
false
false
10,945
cpp
WorkingTree.cpp
/* * WorkingTree.cpp * * Created on: 05/nov/2010 * Author: simonemsr */ using namespace std; #include "WorkingTree.h" #include <iostream> #include "errors.h" extern int VERBOSE_LEVEL; WorkingTree_c::WorkingTree_c(P_GTMsd gtm, Tree t) : Tree_c(t) { int n, i; Nu = new double[nodes]; E1 = new_matrix(nodes, gtm->C, 0); b = new_matrix(nodes, gtm->C); P_N = new_matrix(nodes, gtm->C, 0); Beta1 = new_matrix(nodes, gtm->C, 0); Beta2 = new_matrix(nodes, gtm->C, 0); E2nor = new_matrix(nodes, gtm->C, 0); for (n = 0; n < nodes; n++) //initialize b for (i = 0; i < gtm->C; i++) b[n][i] = gtm->get_emission(labels[n], i); } WorkingTree_c::~WorkingTree_c() { delete (Nu); free_matrix(E1, nodes); free_matrix(b, nodes); free_matrix(P_N, nodes); free_matrix(Beta1, nodes); free_matrix(Beta2, nodes); free_matrix(E2nor, nodes); } void WorkingTree_c::calculate_Beta1(P_GTMsd gtm, int node) { int i, j, l, child; double Nn = 0, temp = 0; if (is_leaf(node)) { //calculate Nu and then Beta1 for leaves if (gtm->stationary) { if (Nu[node] < FLT_MIN) { Nu[node] = 1; for (i = 0; i < gtm->C; i++) Beta1[node][i] = gtm->get_P_L(i); } else for (i = 0; i < gtm->C; i++) Beta1[node][i] = b[node][i] * gtm->get_P_L(i) / Nu[node]; } else { l = parents[node][1]; if (Nu[node] < FLT_MIN) { Nu[node] = 1; for (i = 0; i < gtm->C; i++) Beta1[node][i] = gtm->get_P_L(l, i); } else for (i = 0; i < gtm->C; i++) Beta1[node][i] = b[node][i] * gtm->get_P_L(l, i) / Nu[node]; } } else { Nn = 0; //calculate Nu for internal nodes for (j = 0; j < gtm->C; j++) { temp = 0; for (l = 0; l < gtm->L; l++) { child = get_child(node, l); if (child > 0) temp += gtm->get_phi(l) * Beta2[child][j]; else { if (gtm->stationary) temp += gtm->get_phi(l) * gtm->get_Astar(j); else temp += gtm->get_phi(l) * gtm->get_Astar(l, j); } } Nn += b[node][j] * temp; } Nu[node] = Nn; //calculate the Beta1 values for internal nodes for (i = 0; i < gtm->C; i++) { temp = 0; for (l = 0; l < gtm->L; l++) { child = children[node][l]; if (child > 0) temp += gtm->get_phi(l) * Beta2[child][i]; else { if (gtm->stationary) temp += gtm->get_phi(l) * gtm->get_Astar(i); else temp += gtm->get_phi(l) * gtm->get_Astar(l, i); } } if (Nu[node] < FLT_MIN) Beta1[node][i] = 1.0 / gtm->C; else Beta1[node][i] = b[node][i] * temp / Nu[node]; } } } void WorkingTree_c::calculate_P_N(P_GTMsd gtm, int node) { int i, j, l, child; if (is_leaf(node)) { //calculate P_N for leaves if (gtm->stationary) { for (i = 0; i < gtm->C; i++) { P_N[node][i] = gtm->get_P_L(i); } } else { l=parents[node][1]; for (i = 0; i < gtm->C; i++) { P_N[node][i] = gtm->get_P_L(l, i); } } } else { //calculate P_N for internal nodes for (i = 0; i < gtm->C; i++) { for (l = 0; l < gtm->L; l++) { child = children[node][l]; if (child > 0) { //real child contribute for (j = 0; j < gtm->C; j++) { if (gtm->stationary) { P_N[node][i] += gtm->get_phi(l) * gtm->get_A(i, j) * P_N[child][j]; } else P_N[node][i] += gtm->get_phi(l) * gtm->get_A(l, i, j) * P_N[child][j]; } } else { //ghost child contribute if (gtm->stationary) P_N[node][i] += gtm->get_phi(l) * gtm->get_Astar(i); else P_N[node][i] += gtm->get_phi(l) * gtm->get_Astar(l, i); } } } } } NPosWorkingTree_c::NPosWorkingTree_c(P_GTMsd gtm, Tree tree) : WorkingTree_c(gtm, tree) { int i, n; for (n = 0; n < nodes; n++) { //calculate Nu for leaves Nu[n] = 0; if (is_leaf(n)) for (i = 0; i < gtm->C; i++) Nu[n] += b[n][i] * gtm->get_P_L(i); } } void NPosWorkingTree_c::calculate_Beta2(P_GTMsd gtm, int parent) { int i, j, l, child; for (l = 0; l < arity; l++) { child = children[parent][l]; if (child > 0) { for (i = 0; i < gtm->C; i++) { for (j = 0; j < gtm->C; j++) { Beta2[child][i] += gtm->get_A(i, j) * Beta1[child][j]; } // Beta2[child][i] = Beta2[child][i] / P_N[parent][i]; } } } } void NPosWorkingTree_c::calculate_E1_E2_update_S_E(GTMsd gtm) { int i, j, position, l, l2, parent, child, child2, u; double temp = 0, normalize; double **E2_u; //calculate E1 and E2nor for the root for (i = 0; i < gtm->C; i++) { E1[0][i] = Beta1[0][i]; for (l = 0; l < gtm->L; l++) { child = children[0][l]; if (child > 0) E2nor[0][i] += gtm->get_phi(l) * Beta2[child][i]; else E2nor[0][i] += gtm->get_phi(l) * gtm->get_Astar(i); } if (E2nor[0][i] < FLT_MIN) { E2nor[0][i] = 1.0 / gtm->C; if (VERBOSE_LEVEL == 2) my_cerr(OR_E2N); } } //initialize the temporary matrix useful in S_E2 calculus E2_u = new_matrix(gtm->C, gtm->C, 0); for (u = 1; u < nodes; u++) { //calculate E2nor for a node for (i = 0; i < gtm->C; i++) { for (l = 0; l < gtm->L; l++) { child = children[u][l]; if (child > 0) E2nor[u][i] += gtm->get_phi(l) * Beta2[child][i]; else E2nor[u][i] += gtm->get_phi(l) * gtm->get_Astar(i); } if (E2nor[u][i] < FLT_MIN) { E2nor[u][i] = 1.0 / gtm->C; if (VERBOSE_LEVEL == 2) my_cerr(OR_E2N); } } parent = parents[u][0]; position = parents[u][1]; for (i = 0; i < gtm->C; i++) { for (j = 0; j < gtm->C; j++) { E2_u[i][j] = E1[parent][i] * Beta1[u][j] * gtm->get_phi( position) * gtm->get_A(i, j) / E2nor[parent][i]; } } //normalize E2 normalize = 0; for (i = 0; i < gtm->C; i++) for (j = 0; j < gtm->C; j++) normalize += E2_u[i][j]; for (i = 0; i < gtm->C; i++) { for (j = 0; j < gtm->C; j++) { E2_u[i][j] = E2_u[i][j] / normalize; } } //update temp_phi for (i = 0; i < gtm->C; i++) for (j = 0; j < gtm->C; j++) gtm->add_temp_phi(position, E2_u[i][j]); //calculate and normalize E1 for (j = 0; j < gtm->C; j++) { for (i = 0; i < gtm->C; i++) E1[u][j] += E2_u[i][j]; } normalize = 0; for (i = 0; i < gtm->C; i++) normalize += E1[u][i]; for (i = 0; i < gtm->C; i++) E1[u][i] = E1[u][i] / normalize; //update accumulator S_E1 and S_E2, using real child of node for (i = 0; i < gtm->C; i++) { if (is_leaf(u)) gtm->train_param-> S_E0[i] += E1[u][i]; gtm->train_param-> S_E1[i] += E1[u][i]; for (j = 0; j < gtm->C; j++) { gtm->train_param-> S_E2[i][j] += E2_u[i][j]; } } //updates accumulator S_Estar, using ghost child of node normalize = 0; if (!is_leaf(u)) { for (l = 0; l < gtm->L; l++) { child =children[u][l]; if (child < 0) { for (i = 0; i < gtm->C; i++) { temp = 0; for (l2 = 0; l2 < gtm->L; l2++) { child2 = children[u][l2]; if (child2 > 0) temp += gtm->get_phi(l2) * Beta2[child2][i]; else temp += gtm->get_phi(l2) * gtm->get_Astar(i); } gtm->train_param-> S_Estar[i] += E1[u][i] * gtm->get_phi(l) * gtm->get_Astar(i) / temp; if ((E1[u][i] * gtm->get_phi(l) * gtm->get_Astar(i)) < FLT_MIN) { gtm->train_param->S_Estar[i] = 1.0 / gtm->C; if (VERBOSE_LEVEL == 2) my_cerr(OR_Estar); } } } } } } free_matrix(E2_u, gtm->C); } PosWorkingTree_c::PosWorkingTree_c(P_GTMsd gtm, Tree tree) : WorkingTree_c(gtm, tree) { int i, n, l; for (n = 0; n < nodes; n++) { //calculate N for leaves Nu[n] = 0; if (is_leaf(n)) { l = parents[n][1]; for (i = 0; i < gtm->C; i++) Nu[n] += b[n][i] * gtm->get_P_L(l, i); } } } void PosWorkingTree_c::calculate_Beta2(P_GTMsd gtm, int parent) { int i, j, l, child; for (l = 0; l < arity; l++) { child = children[parent][l]; if (child > 0) { for (i = 0; i < gtm->C; i++) { for (j = 0; j < gtm->C; j++) { Beta2[child][i] += gtm->get_A(l, i, j) * Beta1[child][j]; } } } } } void PosWorkingTree_c::calculate_E1_E2_update_S_E(GTMsd gtm) { int i, j, position, l, l2, parent, child2,child, u; double **E2_u, normalize, temp = 0; //calculate E1 and E2nor for the root for (i = 0; i < gtm->C; i++) { E1[0][i] = Beta1[0][i]; for (l = 0; l < gtm->L; l++) { child = children[0][l]; if (child > 0) E2nor[0][i] += gtm->get_phi(l) * Beta2[child][i]; else E2nor[0][i] += gtm->get_phi(l) * gtm->get_Astar(l, i); } if (E2nor[0][i] < FLT_MIN) { E2nor[0][i] = 1.0 / gtm->C; if (VERBOSE_LEVEL == 2) my_cerr(OR_E2N); } } //initialize the temporary matrix useful in S_E2 calculus containing the values of E2(parent(u),u,i,j) for all i j E2_u = new_matrix(gtm->C, gtm->C); //start to calculate for (u = 1; u < nodes; u++) { //calculate E2nor for the node for (i = 0; i < gtm->C; i++) { for (l = 0; l < gtm->L; l++) { child = children[u][l]; if (child > 0) E2nor[u][i] += gtm->get_phi(l) * Beta2[child][i]; else E2nor[u][i] += gtm->get_phi(l) * gtm->get_Astar(l, i); } if (E2nor[u][i] < FLT_MIN) { E2nor[u][i] = 1.0 / gtm->C; if (VERBOSE_LEVEL == 2) my_cerr(OR_E2N); } } parent = parents[u][0]; position = parents[u][1]; for (i = 0; i < gtm->C; i++) { for (j = 0; j < gtm->C; j++) { E2_u[i][j] = E1[parent][i] * Beta1[u][j] * gtm->get_phi( position) * gtm->get_A(position, i, j) / E2nor[parent][i]; } } //normalize E2 normalize = 0; for (i = 0; i < gtm->C; i++) for (j = 0; j < gtm->C; j++) normalize += E2_u[i][j]; for (i = 0; i < gtm->C; i++) { for (j = 0; j < gtm->C; j++) E2_u[i][j] = E2_u[i][j] / normalize; } //calculate and normalize E1 for (j = 0; j < gtm->C; j++) for (i = 0; i < gtm->C; i++) E1[u][j] += E2_u[i][j]; normalize = 0; for (i = 0; i < gtm->C; i++) normalize += E1[u][i]; for (i = 0; i < gtm->C; i++) E1[u][i] = E1[u][i] / normalize; //update accumulator S_E1 and S_E2, using real child of node for (i = 0; i < gtm->C; i++) { gtm->train_param->ns_S_E1[position][i] += E1[u][i]; if (is_leaf(u)) gtm->train_param->ns_S_E0[position][i] += E1[u][i]; for (j = 0; j < gtm->C; j++) gtm->train_param->ns_S_E2[position][i][j] += E2_u[i][j]; } //update accumulator S_Estar, using ghost child of node for (l = 0; l < gtm->L; l++) { if (children[u][l] < 0) { for (i = 0; i < gtm->C; i++) { temp = 0; for (l2 = 0; l2 < gtm->L; l2++) { child2 = children[u][l2]; if (child2 > 0) temp += gtm->get_phi(l2) * Beta2[child2][i]; else temp += gtm->get_phi(l2) * gtm->get_Astar(l2, i); } gtm->train_param->ns_S_Estar[l][i] += E1[u][i] * gtm->get_phi(l) * gtm->get_Astar(l, i) / temp; if ((E1[u][i] * gtm->get_phi(l) * gtm->get_Astar(l, i)) < FLT_MIN) { gtm->train_param->ns_S_Estar[l][i] = 1.0 / gtm->C; if (VERBOSE_LEVEL == 2) my_cerr(OR_Estar); } } } } } free_matrix(E2_u, gtm->C); }
526a9d4303fafa74ad132ae8ca9e9851f4980c8f
07379707c774efb53e2239bce50c8c81a326f8e2
/include/game/Reinforce.h
eb504bbb0f68a9b0de640b16df019f43d09a2ca1
[]
no_license
dizedel/Risk
b25e59b43ab6e4192a5409805620c35abd42ce44
5e76c8d1b1dd4d8966d7343a09112dcd34ec7d56
refs/heads/master
2020-04-10T10:49:57.223328
2018-12-05T19:57:22
2018-12-05T19:57:22
null
0
0
null
null
null
null
UTF-8
C++
false
false
582
h
Reinforce.h
// // Created by pamel on 2018-10-11. // #pragma once #ifndef REINFORCE_H #define REINFORCE_H #include <string> #include <vector> #include <Map.h> #include <Hand.h> #include <Player.h> #include <MainGame.h> using namespace std; class Reinforce{ public: Reinforce(); Reinforce(Player*, int, string, Map); Reinforce(Player*, Map); ~Reinforce(); bool reinforce(); void setCountryToReinforce(string); void setNumOfArmiesToPutDown(int); private: string countryToReinforce; int numOfArmiesToPutDown; Player* player; Map map; }; #endif
1cf7e0bbf1471fd0feafbe95c6712d2e2f57e5bc
4022138df061a13beab618e5fcbaedca9b195b31
/include/Tree/BiTNode.h
b320195298546dca6cb302b90f57c67afac8e470
[ "Apache-2.0" ]
permissive
CedarVGC/Data-Structure-CPlusPlus
a6876e95583d4dc04ca98c138eeb0e7055ea8c85
cf9969aba575ebc21dbdac40dda08bb29e421ab6
refs/heads/master
2022-11-24T14:33:38.650768
2020-08-01T15:06:05
2020-08-01T15:06:05
277,577,510
1
0
null
null
null
null
UTF-8
C++
false
false
1,263
h
BiTNode.h
// // Created by Administrator on 2020/7/12. // #ifndef DATA_STRUCTURE_C_BITNODE_H #define DATA_STRUCTURE_C_BITNODE_H #include <iostream> #include "..\StackQueue\Queue.h" #include "..\StackQueue\Stack.h" template <typename T> class BiTNode{ public: T data; BiTNode<T>* lchild=NULL; BiTNode<T>* rchild=NULL; BiTNode(){}; BiTNode(const T& a){ data=a; } ~BiTNode()=default; }; template <typename T> class BinaryTree{ public: BiTNode<T>* root=NULL; BinaryTree()= default; BinaryTree(T* data,int size); BinaryTree(BiTNode<T>* t){root=t;} }; template <typename T> BinaryTree<T>::BinaryTree(T* data,int size) { Queue<BiTNode<T> *> q; int i=0; root=new BiTNode<T>(data[i++]); q.EnQueue(root); BiTNode<T>* pointer=NULL; while(!q.QueueEmpty()&&i<size){ pointer=q.GetHead(); q.DeQueue(); if(pointer!=NULL){ if(data[i]!=0){ pointer->lchild=new BiTNode<T>(data[i]); } i++; if(data[i]!=0){ pointer->rchild=new BiTNode<T>(data[i]); } i++; q.EnQueue(pointer->lchild); q.EnQueue(pointer->rchild); } } } #endif //DATA_STRUCTURE_C_BITNODE_H
b23d6b4269e210d6fc58cba50cdf932ea210a8fa
471a19c9b6a7eb297a18fa287011724991179f4a
/Lab2/kthsmallestElement.cpp
dbbe5ef02ccad3f90f7a8c83812352e71dbc502e
[]
no_license
gunishmatta/Data-Structures-College-Lab
4e5020aacb3d5ecfcdc7edda17687e5a7b7420a5
1e6745ca095d4f4a77d886530738543b9c8f6dcc
refs/heads/master
2022-12-30T07:34:30.892352
2020-10-20T11:36:06
2020-10-20T11:36:06
305,687,577
2
0
null
null
null
null
UTF-8
C++
false
false
607
cpp
kthsmallestElement.cpp
#include<iostream> using namespace std; void sort(int a[],int n) { int temp; for (int i = 1; i <= n-1; i++) { for(int j =1;j<=(n-i)-1;j++) { if(a[j]>a[j+1]) { temp=a[j]; a[j]=a[j+1]; a[j+1]=temp; } } } } int findksmallest(int a[],int k,int n) { sort(a,n); return a[k-1]; } int main() { int n,k; cout<<"Enter Size of array "; cin>>n; int a[n]; cout<<"Enter Elements of array "; for (int i = 0; i < n; i++) { cin>>a[i]; } cout<<"Enter k for which you want smallest number"; cin>>k; cout<<findksmallest(a,k,n); return 0; }
f03cf6ab946f8b11a859e7f1eec39e083a8fd4f3
0f7b0683c7ecb51f3a3b10a72b382fcf162e6306
/Final.ino
da79505f52377a660bb8d5658493b8dcc6594d58
[]
no_license
kimhao97/BLE_ESP32_MPU6050
15ab1f4543335d18d0382e3d83cae149d383dd92
997e3d1af60a415e44e7e69a89f94e0b1b22b07a
refs/heads/master
2020-07-06T01:02:31.618805
2019-08-17T05:33:42
2019-08-17T05:33:42
null
0
0
null
null
null
null
UTF-8
C++
false
false
11,981
ino
Final.ino
#include <BLEDevice.h> #include <BLEUtils.h> #include <BLEServer.h> #include <BLE2902.h> #include "MPU6050_tockn.h" #include <Wire.h> BLECharacteristic *pCharacteristic; bool deviceConnected = false; uint8_t txValue = 0; std::string rxValue; #define SERVICE_UUID "4fafc201-1fb5-459e-8fcc-c5c9c331914b" // #define CHARACTERISTIC_UUID "beb5483e-36e1-4688-b7f5-ea07361b26a8" #define CHARACTERISTIC_UUID_RX "582adc94-2eab-4735-b821-293883e26762" #define CHARACTERISTIC_UUID_TX "0da69903-6d69-4810-bccc-4c56d2880188" MPU6050 mpu6050(Wire); const int endstop1_Pin = 27; //IO2 const int endstop2_Pin = 15; const int motor_Pin1 = 18; const int motor_Pin2 = 19; const int Led1_4_Pin = 17; //IO0 const int Led2_5_Pin = 4; const int Led3_6_Pin = 16; bool button1_state = false; bool button2_state = false; bool button3_state = false; bool led_state = true; unsigned long timePressButton3 = 0; unsigned long timePressButton2 = 0; unsigned long timePressButton1 = 0; #define STOP 0 #define RUN_FORWARD 1 #define RUN_BACKWARD 2 int motorState = STOP; bool accelCheck = false; long timeAccel = 0; float accelAverage; /* BLE */ class MyServerCallbacks: public BLEServerCallbacks { void onConnect(BLEServer* pServer) { deviceConnected = true; }; void onDisconnect(BLEServer* pServer) { deviceConnected = false; } }; class MyCallbacks: public BLECharacteristicCallbacks { void onWrite(BLECharacteristic *pCharacteristic) { rxValue = pCharacteristic->getValue(); /* my iOS app sends a 5 byte payload so thisis how it is listened for */ // Serial.print("Data: "); // Serial.println((String)rxValue); if (rxValue.length() == 1) { byte data0 = (uint8_t)rxValue[0]; // byte data1 = (uint8_t)rxValue[1]; // byte data2 = (uint8_t)rxValue[2]; // byte data3 = (uint8_t)rxValue[3]; // byte data4 = (uint8_t)rxValue[4]; Serial.println(data0); // Serial.print(", "); // Serial.print(data1); // Serial.print(", "); // Serial.print(data2); // Serial.print(", "); // Serial.print(data3); // Serial.print(", "); // Serial.println(data4); } } }; class MySecurity : public BLESecurityCallbacks { bool onConfirmPIN(uint32_t pin) { return false; } uint32_t onPassKeyRequest() { ESP_LOGI(LOG_TAG, "PassKeyRequest"); return 199720; } void onPassKeyNotify(uint32_t pass_key) { ESP_LOGI(LOG_TAG, "On passkey Notify number:%d", pass_key); } bool onSecurityRequest() { ESP_LOGI(LOG_TAG, "On Security Request"); return true; } void onAuthenticationComplete(esp_ble_auth_cmpl_t cmpl) { ESP_LOGI(LOG_TAG, "Starting BLE work!"); if (cmpl.success) { uint16_t length; esp_ble_gap_get_whitelist_size(&length); ESP_LOGD(LOG_TAG, "size: %d", length); } } }; void setup() { Serial.begin(115200); Serial.println("Starting BLE work!"); BLEDevice::init("ESP32"); BLEDevice::setEncryptionLevel(ESP_BLE_SEC_ENCRYPT); /* Required in authentication process to provide displaying and/or input passkey or yes/no butttons confirmation */ BLEDevice::setSecurityCallbacks(new MySecurity()); BLEServer *pServer = BLEDevice::createServer(); BLEService *pService = pServer->createService(SERVICE_UUID); // BLECharacteristic *pCharacteristic = pService->createCharacteristic( // CHARACTERISTIC_UUID, // BLECharacteristic::PROPERTY_READ | // BLECharacteristic::PROPERTY_WRITE // ); // Create a BLE Characteristic pCharacteristic = pService->createCharacteristic( CHARACTERISTIC_UUID_TX, BLECharacteristic::PROPERTY_NOTIFY ); pCharacteristic->addDescriptor(new BLE2902()); BLECharacteristic *pCharacteristic = pService->createCharacteristic( CHARACTERISTIC_UUID_RX, BLECharacteristic::PROPERTY_WRITE | BLECharacteristic::PROPERTY_WRITE_NR /* the redbear library explicitly does not listen for a write response so this needs to be here */ ); pCharacteristic->setCallbacks(new MyCallbacks()); pCharacteristic->setValue("Hello World says Neil"); pService->start(); BLEAdvertising *pAdvertising = pServer->getAdvertising(); pAdvertising->start(); BLESecurity *pSecurity = new BLESecurity(); pSecurity->setAuthenticationMode(ESP_LE_AUTH_REQ_SC_ONLY); pSecurity->setCapability(ESP_IO_CAP_OUT); pSecurity->setInitEncryptionKey(ESP_BLE_ENC_KEY_MASK | ESP_BLE_ID_KEY_MASK); esp_ble_auth_req_t auth_req = ESP_LE_AUTH_REQ_SC_MITM_BOND; //bonding with peer device after authentication esp_ble_io_cap_t iocap = ESP_IO_CAP_OUT; //set the IO capability to No output No input uint8_t key_size = 16; //the key size should be 7~16 bytes uint8_t init_key = ESP_BLE_ENC_KEY_MASK | ESP_BLE_ID_KEY_MASK; uint8_t rsp_key = ESP_BLE_ENC_KEY_MASK | ESP_BLE_ID_KEY_MASK; //set static passkey uint32_t passkey = 199720; uint8_t auth_option = ESP_BLE_ONLY_ACCEPT_SPECIFIED_AUTH_DISABLE; uint8_t oob_support = ESP_BLE_OOB_DISABLE; esp_ble_gap_set_security_param(ESP_BLE_SM_SET_STATIC_PASSKEY, &passkey, sizeof(uint32_t)); esp_ble_gap_set_security_param(ESP_BLE_SM_AUTHEN_REQ_MODE, &auth_req, sizeof(uint8_t)); esp_ble_gap_set_security_param(ESP_BLE_SM_IOCAP_MODE, &iocap, sizeof(uint8_t)); esp_ble_gap_set_security_param(ESP_BLE_SM_MAX_KEY_SIZE, &key_size, sizeof(uint8_t)); esp_ble_gap_set_security_param(ESP_BLE_SM_ONLY_ACCEPT_SPECIFIED_SEC_AUTH, &auth_option, sizeof(uint8_t)); // esp_ble_gap_set_security_param(ESP_BLE_SM_OOB_SUPPORT, &oob_support, sizeof(uint8_t)); /* If your BLE device act as a Slave, the init_key means you hope which types of key of the master should distribut to you, and the response key means which key you can distribut to the Master; If your BLE device act as a master, the response key means you hope which types of key of the slave should distribut to you, and the init key means which key you can distribut to the slave. */ esp_ble_gap_set_security_param(ESP_BLE_SM_SET_INIT_KEY, &init_key, sizeof(uint8_t)); esp_ble_gap_set_security_param(ESP_BLE_SM_SET_RSP_KEY, &rsp_key, sizeof(uint8_t)); pinMode(endstop1_Pin, INPUT); pinMode(endstop2_Pin, INPUT); pinMode(motor_Pin1, OUTPUT); pinMode(motor_Pin2, OUTPUT); pinMode(Led1_4_Pin, OUTPUT); pinMode(Led2_5_Pin, OUTPUT); pinMode(Led3_6_Pin, OUTPUT); Wire.begin(); mpu6050.begin(); mpu6050.calcGyroOffsets(true); Serial.println("START" ); } void loop() { Serial.print("button1_state: "); Serial.println(button1_state); Serial.print("button2_state: "); Serial.println(button2_state); Serial.print("button3_state: "); Serial.println(button3_state); accelAverage = calAccelerator(50); Serial.println(accelAverage); if (accelAverage > 1.5 && !accelCheck) { accelCheck = true; } if (accelCheck) { if (accelAverage < 1.5) { turnOnLed(Led1_4_Pin); turnOnLed(Led2_5_Pin); turnOnLed(Led3_6_Pin); delay(2000); turnOffLed(Led1_4_Pin); turnOffLed(Led2_5_Pin); turnOffLed(Led3_6_Pin); accelCheck = false; } } readBLE(); if (button2_state) { if (motorState == STOP) { Serial.println("RUN FORWARD" ); motor_FORWARD(); pCharacteristic->setValue("2"); pCharacteristic->notify(); } else if (motorState == RUN_FORWARD) { if (readStatusEndstop(endstop1_Pin) == HIGH) { Serial.println("RUN BACKWARD" ); motor_BACKWARD(); pCharacteristic->setValue("3"); pCharacteristic->notify(); } } else if (motorState == RUN_BACKWARD) { if (readStatusEndstop(endstop2_Pin) == HIGH) { Serial.println("Stop" ); motor_Stop(); pCharacteristic->setValue("4"); pCharacteristic->notify(); button2_state = false; } } } if (button3_state) { if ((unsigned long)(millis() - timePressButton3) < 200) { turnOnLed(Led1_4_Pin); turnOnLed(Led2_5_Pin); turnOnLed(Led3_6_Pin); } else if ((unsigned long)(millis() - timePressButton3) < 400) { turnOffLed(Led1_4_Pin); turnOffLed(Led2_5_Pin); turnOffLed(Led3_6_Pin); } else { timePressButton3 = millis(); } } if (button1_state) { if ((unsigned long)(millis() - timePressButton1) < (150 * 1)) { turnOnLed(Led1_4_Pin); } else if ((unsigned long)(millis() - timePressButton1) < (150 * 2)) { turnOffLed(Led1_4_Pin); } else if ((unsigned long)(millis() - timePressButton1) < (150 * 3)) { turnOnLed(Led2_5_Pin); } else if ((unsigned long)(millis() - timePressButton1) < (150 * 4)) { turnOffLed(Led2_5_Pin); } else if ((unsigned long)(millis() - timePressButton1) < (150 * 5)) { turnOnLed(Led3_6_Pin); } else if ((unsigned long)(millis() - timePressButton1) < (150 * 6)) { turnOffLed(Led3_6_Pin); } else { timePressButton1 = millis(); } } if ((button1_state || button3_state) && led_state ) { pCharacteristic->setValue("1"); pCharacteristic->notify(); led_state = false; } else if (!(button1_state || button3_state)) { pCharacteristic->setValue("0"); pCharacteristic->notify(); led_state = true; } } void motor_FORWARD() { motorState = RUN_FORWARD; digitalWrite(motor_Pin1, HIGH); digitalWrite(motor_Pin2, LOW); } void motor_BACKWARD() { motorState = RUN_BACKWARD; digitalWrite(motor_Pin1, LOW); digitalWrite(motor_Pin2, HIGH); } void motor_Stop() { motorState = STOP; digitalWrite(motor_Pin1, LOW); digitalWrite(motor_Pin2, LOW); } int readStatusEndstop(int pin) { delay(50); return digitalRead(pin); } void turnOnLed(int pin) { digitalWrite(pin, HIGH); } void turnOffLed(int pin) { digitalWrite(pin, LOW); } int readBLE() { if ((uint8_t)rxValue[0] == 49) // ON/OFF ROW { //while(digitalRead(RF_D0) == HIGH){}; button1_state = !(button1_state); timePressButton1 = millis(); { turnOffLed(Led1_4_Pin); turnOffLed(Led2_5_Pin); turnOffLed(Led3_6_Pin); } button3_state = false; rxValue = -1; return 0; } if ((uint8_t)rxValue[0] == 51) // Motor { button2_state = !(button2_state); timePressButton2 = millis(); rxValue = -1; return 2; } if ((uint8_t)rxValue[0] == 50) // ON/OFF ALL { Serial.println("////////////"); button3_state = !(button3_state); { turnOffLed(Led1_4_Pin); turnOffLed(Led2_5_Pin); turnOffLed(Led3_6_Pin); } timePressButton3 = millis(); button1_state = false; rxValue = -1; return 3; } //} } float calAccelerator(int N) { float accelTotal[100], vAverage = 0; unsigned long timeCheck = millis(); // for (int i = 0; i < N; i++) { // mpu6050.update(); // accelTotal[i] = sqrt(pow(mpu6050.getAccX(), 2) + pow(mpu6050.getAccY(), 2) + pow(mpu6050.getAccZ(), 2)); // } // for (int i = 0; i < N; i++) { // vAverage += accelTotal[i] / N; // } for (int i = 0; i < N; i++) { mpu6050.update(); vAverage += sqrt(pow(mpu6050.getAccX(), 2) + pow(mpu6050.getAccY(), 2) + pow(mpu6050.getAccZ(), 2)); } vAverage = vAverage / N; Serial.print("Times: "); Serial.println(millis() - timeCheck); return vAverage; }
d383e12dfddf1cbec9725c2ba0033119b2fab889
fceae18adcb683fe5826b096598c44c1d8ae3d3e
/1033.cpp
f03f06389da5128ae7b4ac48a1ada4b13c6aa5a5
[]
no_license
Kerorohu/PAT_Code
48ee1162b2836a41b92cfe9a61439ffd8136e382
df70b80d7e6e7eb51f96361d9dd806de6ce81946
refs/heads/master
2023-01-25T04:05:03.497326
2020-12-03T07:32:25
2020-12-03T07:32:25
295,098,225
1
0
null
null
null
null
UTF-8
C++
false
false
1,007
cpp
1033.cpp
#include <iostream> #include <map> #include <string> using namespace std; int main() { string err, str, res; getline(cin, err); getline(cin, str); int t = 0; if (!err.empty()) { if (err.find('+') != string::npos) { err.erase(err.find('+'), 1); for (int i = 0; i < str.size(); i++) { if (str[i] > 90 || str[i] < 65) { for (int j = 0; j < err.size(); j++) { if (str[i] == err[j]) t = 1; else if (str[i] == (err[j] + 32)) { t = 1; } } if (t == 0) res.push_back(str[i]); t = 0; } } } else { for (int i = 0; i < str.size(); i++) { for (int j = 0; j < err.size(); j++) { if (str[i] == err[j]) t = 1; else if (str[i] == (err[j] + 32)) { t = 1; } else if (str[i] == (err[j] - 32)) { t = 1; } } if (t == 0) res.push_back(str[i]); t = 0; } } } else { res = str; } if (res.empty()) { cout << endl; } else { cout << res; } }
740d08a1ad45a471feb199cbf3f9cb910e3d4eb0
24286fa2ae71d36ec43cbf61f17b88ce0ba6c8f4
/test5-5.cpp
de7d6ed2e1960e097d145a83ec2f0bc557043fce
[]
no_license
wanghuqiang123/testopencv
b2c6fda08f7eef3ea1b4f0ffd22391c44bd98f8e
c2dd0369273d48afbba36ddf7506078b05338941
refs/heads/master
2021-09-10T23:23:31.705271
2018-04-04T08:05:29
2018-04-04T08:05:29
111,551,861
0
0
null
null
null
null
GB18030
C++
false
false
1,651
cpp
test5-5.cpp
/********** <learning opencv>test5-4.cpp *********/ #include <iostream> #include <cv.h> #include <highgui.h> using namespace std; using namespace cv; int main(int argc, char* argv[]) { IplImage* src_image1=cvLoadImage("imdata/glass1.bmp",CV_LOAD_IMAGE_GRAYSCALE); assert(src_image1!=NULL); IplImage* src_image2=cvLoadImage("imdata/glass2.bmp",CV_LOAD_IMAGE_GRAYSCALE); assert(src_image2!=NULL); IplImage *dst_a=cvCloneImage(src_image1); assert(dst_a!=NULL); IplImage *dst_b=cvCloneImage(src_image1); assert(dst_b!=NULL); IplImage *dst_c=cvCloneImage(src_image1); assert(dst_c!=NULL); //a :取其差的绝对值并显示出来,带有噪声的水杯掩码 cvSub(src_image1,src_image2,dst_a,NULL); cvAbs(dst_a,dst_a); //b :对图像进行二值化阈值操作, cvThreshold(dst_a,dst_b,15,255,CV_THRESH_BINARY_INV); //c :对图像进行 CV_MOP_OPEN 操作,进一步清除噪声 IplConvKernel* temp=cvCreateStructuringElementEx(3,3,1,1,CV_SHAPE_RECT,NULL); cvMorphologyEx(dst_b,dst_c,NULL,temp,CV_MOP_OPEN); cvReleaseStructuringElement(&temp); cvNamedWindow("未放水杯"); cvNamedWindow("放水杯后"); cvNamedWindow("取差的绝对值"); cvNamedWindow("二值化阈值"); cvNamedWindow("开运算"); cvShowImage("未放水杯",src_image1); cvShowImage("放水杯后",src_image2); cvShowImage("取差的绝对值",dst_a); cvShowImage("二值化阈值",dst_b); cvShowImage("开运算",dst_c); cvWaitKey(); cvReleaseImage(&src_image1); cvReleaseImage(&src_image2); cvReleaseImage(&dst_a); cvReleaseImage(&dst_b); cvReleaseImage(&dst_c); cvDestroyAllWindows(); return 0; }
0bba27aaab4af39569abe711cecc9ac559a8da6f
839b6264763a5fd20863fc79232059a625d79d91
/Hmwk/Assignment 1/Gaddis_7thEd_Chap2_Problem7/main.cpp
adb1cf749bca7fe5185b40dbe6dc114c601ebddf
[]
no_license
Kevirz/kr2437797
f9c119f4ce909bec49a5d372e2c055e7e7acf497
53b0f5216658a36e1fdc9633a6a6d1bb22cf236e
refs/heads/master
2021-01-23T06:34:22.026973
2014-07-31T13:13:25
2014-07-31T13:13:25
null
0
0
null
null
null
null
UTF-8
C++
false
false
868
cpp
main.cpp
/* * File: main.cpp * Author: Kevin Rivas * * Created on June 25, 2014, 10:12 PM */ //System Libraries #include <iostream> //Defines the standard input/output stream objects //User Defined Library //Global Constants //Function Prototypes //Execution begins here using namespace std; int main(int argc, char** argv) { //Variable Declaration float oshn=1.5f; //the rise of the ocean level is 1.5 millimeters //Calculating 5 year rise and output simple text cout<<"After 5 Years, the ocean will be "<<oshn*5<<"mm higher."<<endl; //Calculating 7 Year rise and output simple text cout<<"After 7 Years, the ocean will be "<<oshn*7<<"mm higher."<<endl; //Calculating 10 year rise and output simple text cout<<"After 10 Years, the ocean will be "<<oshn*10<<"mm higher."<<endl; return 0; }
40fddb1160bbaf6f456e4cc77d5e8154d08eac4c
f54478bdc7ccc93052c3af14bf573d9434f15197
/src-tex/ktx_writer.cpp
7c3e9cfd848dcc9bf48ae3944db28a1b3ae2f3f8
[ "MIT" ]
permissive
radtek/bengine-gfx
609669ee8e31ab84b9e757f8dc513086bc8abe7e
e7a6f476ccb85262db8958e39674bc9570956bbe
refs/heads/master
2022-02-22T22:17:59.880921
2018-05-23T05:34:38
2018-05-23T05:34:38
null
0
0
null
null
null
null
UTF-8
C++
false
false
8,903
cpp
ktx_writer.cpp
#include "pch.hpp" #include "ktx_header_.hpp" #include "tex/ktx_writer.hpp" #include "tex/texture.hpp" #include "tex/duplicate_texture.hpp" #include "tex/byte_order.hpp" #include "tex/texture_file_error.hpp" #include "tex/image_format_gl.hpp" #include <be/util/put_file_contents.hpp> #include <be/util/zlib.hpp> #include <be/core/exceptions.hpp> namespace be::gfx::tex { ////////////////////////////////////////////////////////////////////////////// KtxWriter::KtxWriter(Log& log) : log_(log), endianness_(bo::Host::value) { } ////////////////////////////////////////////////////////////////////////////// void KtxWriter::reset() { tex_ = ConstTextureView(); endianness_ = bo::Host::value; metadata_entries_.clear(); } ////////////////////////////////////////////////////////////////////////////// void KtxWriter::texture(const ConstTextureView& view) noexcept { tex_ = view; } ////////////////////////////////////////////////////////////////////////////// void KtxWriter::image(const ConstImageView& view) noexcept { TextureClass tc; if (view.dim().z == 1) { if (view.dim().y == 1) { tc = TextureClass::lineal; } else { tc = TextureClass::planar; } } else { tc = TextureClass::volumetric; } tex_ = ConstTextureView(view.format(), tc, view.storage(), view.layer(), 1, view.face(), 1, view.level(), 1); } ////////////////////////////////////////////////////////////////////////////// void KtxWriter::endianness(ByteOrderType endianness) noexcept { endianness_ = endianness; } ////////////////////////////////////////////////////////////////////////////// void KtxWriter::metadata(SV key, SV value) { assert(key.find('\0') == SV::npos); // otherwise part of the key will be prepended to the value when read metadata_entries_.push_back(std::make_pair(key, value)); } ////////////////////////////////////////////////////////////////////////////// Buf<UC> KtxWriter::write() { Buf<UC> result; std::error_code ec; result = write(ec); if (ec) { throw RecoverableError(ec); } return result; } ////////////////////////////////////////////////////////////////////////////// Buf<UC> KtxWriter::write(std::error_code& ec) noexcept { using namespace gl; using err = TextureFileError; using sig = detail::KtxSignature; Buf<UC> result; if (!tex_) { ec = make_error_code(err::image_unavailable); return result; } if (endianness_ != bo::Big::value && endianness_ != bo::Little::value) { ec = make_error_code(err::unsupported); return result; } std::error_code ec2; ImageFormatGl gl_fmt = to_gl_format(tex_.format(), ec2); if (ec2) { ec = ec2; return result; } constexpr GLenum std_swizzle[4] = { GL_RED, GL_GREEN, GL_BLUE, GL_ALPHA }; for (glm::length_t c = 0; c < 4; ++c) { auto s = gl_fmt.swizzle[c]; if (s == std_swizzle[c]) { continue; } if (c >= tex_.format().components()) { if (c == 3) { if (s == GL_ONE) { continue; } } else if (s == GL_ZERO) { continue; } } ec = make_error_code(err::unsupported); // This is a soft error; we can still generate a valid KTX file, it just might not map color channels correctly // so no return here. } detail::KtxHeader header; static_assert(sizeof(header.signature) == sizeof(detail::KtxSignature::full)); std::memcpy(header.signature, detail::KtxSignature::full, sizeof(header.signature)); header.endianness = 0x04030201; header.gl_type = gl_fmt.data_type; header.gl_type_size = block_word_size(tex_.format().packing()); header.gl_format = gl_fmt.data_format; header.gl_internal_format = gl_fmt.internal_format; header.gl_base_internal_format = gl_fmt.base_internal_format; header.pixel_width = tex_.dim(0).x; header.pixel_height = tex_.dim(0).y; header.pixel_depth = tex_.dim(0).z; auto dimensionality = tex::dimensionality(tex_.texture_class()); if (dimensionality < 3) { header.pixel_depth = 0; if (dimensionality < 2) { header.pixel_height = 0; } } if (!is_array(tex_.texture_class())) { header.number_of_array_elements = 0; } else { header.number_of_array_elements = tex_.layers(); } header.number_of_faces = tex_.faces(); header.number_of_mipmap_levels = tex_.levels(); header.bytes_of_key_value_data = 0; for (const auto& p : metadata_entries_) { U32 raw_size = U32(sizeof(U32) + p.first.size() + 1 + p.second.size()); U32 padded_size = aligned_size<sizeof(U32)>(raw_size); header.bytes_of_key_value_data += padded_size; } ConstTextureView t; Texture tmp_tex; if (tex_.format().block_size() != tex_.block_span() || tex_.storage().alignment().line() != 4 || tex_.storage().alignment().plane() != 4) { try { tmp_tex = duplicate_texture(tex_, tex_.format().block_size(), TextureAlignment(2)); } catch (const std::bad_alloc&) { ec = std::make_error_code(std::errc::not_enough_memory); return result; } t = tmp_tex.view; if (endianness_ != bo::Host::value) { reverse_endianness(*tmp_tex.storage, t.format().packing()); } } else if (endianness_ != bo::Host::value) { try { tmp_tex = duplicate_texture(tex_); } catch (const std::bad_alloc&) { ec = std::make_error_code(std::errc::not_enough_memory); return result; } t = tmp_tex.view; reverse_endianness(*tmp_tex.storage, t.format().packing()); } else { t = tex_; } ec2 = std::error_code(); std::size_t payload_size = calculate_required_texture_storage(t.layers(), t.faces(), t.levels(), t.dim(0), t.block_dim(), t.block_span(), ec2, TextureAlignment(2)); payload_size = aligned_size<sizeof(U32)>(payload_size + sizeof(U32) * t.levels()); if (ec2) { ec = ec2; return result; } U32 metadata_size = header.bytes_of_key_value_data; // we know this is aligned to U32 already const std::size_t buffer_size = sizeof(header) + metadata_size + payload_size; try { result = make_buf<UC>(buffer_size); } catch (const std::bad_alloc&) { ec = std::make_error_code(std::errc::not_enough_memory); return result; } if (endianness_ == ByteOrderType::big_endian) { bo::static_to_big<>(header); } else { bo::static_to_little<>(header); } std::memcpy(result.get(), &header, sizeof(header)); std::size_t offset = sizeof(header); for (const auto& p : metadata_entries_) { std::size_t o = offset; U32 raw_size = U32(p.first.size() + 1 + p.second.size()); U32 endian_size; if (endianness_ == ByteOrderType::big_endian) { endian_size = bo::to_big<>(raw_size); } else { endian_size = bo::to_little<>(raw_size); } std::memcpy(result.get() + o, &endian_size, sizeof(U32)); o += sizeof(U32); std::memcpy(result.get() + o, p.first.data(), p.first.size()); o += p.first.size(); result[o] = '\0'; ++o; std::memcpy(result.get() + o, p.second.data(), p.second.size()); o += p.second.size(); std::size_t padded_size = sizeof(U32) + aligned_size<sizeof(U32)>(raw_size); offset += padded_size; while (o < offset) { result[o] = '\0'; ++o; } } offset = sizeof(header) + metadata_size; for (auto level = 0; level < t.levels(); ++level) { U32 level_size = 0; std::size_t level_size_offset = offset; offset += sizeof(U32); for (auto layer = 0; layer < t.layers(); ++layer) { for (auto face = 0; face < t.faces(); ++face) { auto v = t.image(layer, face, level); std::memcpy(result.get() + offset, v.data(), v.size()); offset += v.size(); level_size += (U32)v.size(); } } if (t.layers() == 1 && t.faces() == 6) { // weird edge case in KTX spec for non-array cubemaps level_size = (U32)t.image(0, 0, level).size(); } if (endianness_ == ByteOrderType::big_endian) { bo::static_to_big<>(level_size); } else { bo::static_to_little<>(level_size); } std::memcpy(result.get() + level_size_offset, &level_size, sizeof(U32)); } return result; } ////////////////////////////////////////////////////////////////////////////// void KtxWriter::write(const Path& path) { util::put_file_contents(path, write()); } ////////////////////////////////////////////////////////////////////////////// void KtxWriter::write(const Path& path, std::error_code& ec) noexcept { Buf<UC> data = write(ec); if (data) { util::put_file_contents(path, std::move(data), ec); } } } // be::gfx::tex
5a72faf665dcc68694d67cc97dfdbddb3547bff3
ad43f4f7ef95e78c5f280ce39cacc83635fc92ec
/C++/scope/initializer/LegInitializer.h
70de63e339454b6e20d030b011225cc64d226cc1
[ "MIT" ]
permissive
PeterZhouSZ/SCOPE
bfebe2d40516983326cb4751874f421bfdfadb04
982785b7c10dc71774e151eabc2f7d4af4e1adfb
refs/heads/master
2023-08-10T15:31:33.666994
2021-10-11T09:48:10
2021-10-11T09:48:10
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,361
h
LegInitializer.h
#pragma once #include <memory> #include <vector> #include <scope/initializer/Initializer.h> namespace scope { namespace Initializer { class LegInitializer : public Initializer { public: std::array<Vector3, 2> mRelJointLocations; mutable Vector6 mDRootPoseChange; mutable Pose mRootPoseChange; mutable Vector3 mDJointChange; mutable Matrix3 mJointChange; mutable Scalar mKneeJoint[2]; mutable Matrix63 mB0; mutable Vector6 mB1; mutable Vector<9> mS; mutable Vector<9> ms; mutable Scalar mA; mutable Scalar ma; public: EIGEN_MAKE_ALIGNED_OPERATOR_NEW LegInitializer(const Options &options, const std::array<Vector3, 2> &RelJointLocations); LegInitializer(const LegInitializer &) = delete; LegInitializer &operator=(const LegInitializer &) = delete; virtual int initialize(const Pose &T0, const AlignedVector<Matrix3> &joints) const override; public: virtual int FKintree(int n) const override; virtual int DFKintree() const override; virtual int updateGaussNewton() const override; virtual int solveGaussNewton() const override; virtual int update(Scalar stepsize) const override; virtual int accept() const override; protected: const Scalar KneeLowerBnd = 0; const Scalar KneeUpperBnd = 0.85 * M_PI; }; } // namespace Initializer } // namespace scope
384690e01b8887ec7873997a8bfc4252074a3ee8
ba1061443f83d65033347c8e8896618005fbb32e
/69A/69A.cpp
993098f3ea9c0ee70925cd9fd8ab7f57ab5f60f8
[]
no_license
epidersis/olymps
9388f690d4cc282bb5af2b8f57094a5bacce77eb
ff22f97d8cc7e6779dc8533e246d0d651e96033e
refs/heads/master
2022-07-31T01:50:42.950753
2022-07-18T21:51:47
2022-07-18T21:51:47
130,722,706
0
0
null
null
null
null
UTF-8
C++
false
false
422
cpp
69A.cpp
#include <bits/stdc++.h> using namespace std; int main() { short n, num; short x, y, z; x = y = z = 0; cin >> n; for (short i = 0; i < n; i++) { cin >> num; x += num; cin >> num; y += num; cin >> num; z += num; } if (x != 0 || y != 0 || z != 0) cout << "NO"; else cout << "YES"; return 0; }
f4b5d394d23b088f1c86be1acc686dcc1763e4b5
c7cb991e314b7c470966e24124ce739b2f1d65a0
/Bit-masking/Bitwise-AND-from-m-to-n.cpp
162339e7c566d0dac7ed81fb86decd8271adc2cc
[]
no_license
JamiYashwanth/Concepts
30b94df4a775a1a6fc96721f8e2d3c84c2f11650
20d25ed1149fabfa36091c11ebbeb695dcbe77d4
refs/heads/main
2023-05-15T07:50:46.929970
2021-06-16T18:26:33
2021-06-16T18:26:33
377,589,612
1
0
null
null
null
null
UTF-8
C++
false
false
740
cpp
Bitwise-AND-from-m-to-n.cpp
class Solution { public: int rangeBitwiseAnd(int left, int right) { int count=0,result; while(left!=right){ // Iterate the loop till left == right and copy and resultant value to result left=left>>1; right=right>>1; count+=1; } result=left<<count; // Left shift the number for how many times right shift has been performed return result; } }; /* Time - Complexity equals to O(1) Why?? -> while loop iteration takes place for Atmost 32 times (32 bits). Hence, Constant time Observations :- -> If any bit is ZERO in one coloumn. Then, the resultant bit will be ZERO for sure (Therefore, Reason for left shifting count times) */
c3c253340908eea61040bc0b120d8dfa33bdab3d
b0bd3af542ad93bc06f13348692256265433ee33
/test.cpp
ce8e724b1382673f66b08555d3c4d0c5e9ded403
[]
no_license
tczengming/kdtree
880fcda9cb7e4ac5e869fc2d8053e05316bc1aa9
b340b9b920c572f1631828785565feec14e213eb
refs/heads/master
2020-04-08T22:53:06.830471
2018-12-06T02:36:52
2018-12-06T02:36:52
159,803,742
0
0
null
null
null
null
UTF-8
C++
false
false
1,065
cpp
test.cpp
// Last Update:2018-12-05 16:52:30 /** * @file test.cpp * @brief * @author tczengming@163.com www.benewtech.cn * @version 0.1.00 * @date 2018-11-29 */ #include <unistd.h> #include "kdtree.h" int main( int argc, char **argv ) { struct KdTree tree; float m[7][2] = {{6, 2}, {6, 3}, {3, 5}, {5, 0}, {1, 2}, {4, 9}, {8, 1}}; for ( size_t i = 0; i < sizeof(m) / sizeof(m[0]); ++i ) { struct Kdata data(&(m[i][0]), 1, sizeof(m[0]) / sizeof(m[0][0])); tree.Add(data); } tree.Train(); tree.Print(); float query[] = {5, 6}; struct Kdata data(query, 1, 2); struct Kdata nearest; double dist; if (tree.NearestSearch(data, &nearest, &dist)) { printf( "dist;%lf\n", dist ); tree.PrintData(nearest); } std::vector<struct Match> matchs; tree.Knearest(data, 2, &matchs); for ( int i = 0; i < matchs.size(); ++i ) { printf( "i %d imgidx;%d trainidx:%d distance:%f\n", i, matchs[i].imgIdx, matchs[i].trainIdx, matchs[i].distance ); } return 0; }
33ba50de408e5659758ae90b957b4f7f8e6e691d
d6f0b898329384a12bb79851f6de7e92ae058da3
/ProcessingTrafic/IpTcp.cpp
863f907c920cb1f45425fef552a8cb845c9cde79
[]
no_license
yurayolkin/Processing
da0e26c4571f14930605f8f47912d9e357ebc4ee
346077dcc907d4a242f544e5f24619fbd688fa4d
refs/heads/master
2016-09-06T14:36:58.620009
2014-08-04T18:20:07
2014-08-04T18:20:07
null
0
0
null
null
null
null
UTF-8
C++
false
false
62
cpp
IpTcp.cpp
#include "IpTcp.h" IpTcp::IpTcp() { } IpTcp::~IpTcp() { }
a854a888e75752004a1044403c58b1ba6f00c042
d327e106285776f28ef1d6c8a7f561b7f05763a6
/SDL_EngineProject/AlienAttack/Classes/GameOverLayer.h
1285a7619dde7c1b06438b93dab3b6f31a36e7ec
[]
no_license
sky94520/old-code
a4bb7b6826906ffa02f57151af2dc21471cf2106
6b37cc7a9338d283a330b4afae2c7fbd8aa63683
refs/heads/master
2020-05-03T12:37:48.443045
2019-07-23T00:38:16
2019-07-23T00:38:16
178,631,201
0
0
null
null
null
null
UTF-8
C++
false
false
473
h
GameOverLayer.h
#ifndef __GameOverLayer_H__ #define __GameOverLayer_H__ #include "SDL_Engine/SDL_Engine.h" using namespace SDL; class GameOverDelegate { public: virtual ~GameOverDelegate(){} virtual void gameRestart()=0; }; class GameOverLayer:public Layer { private: GameOverDelegate*m_pDelegate; public: GameOverLayer(); ~GameOverLayer(); CREATE_FUNC(GameOverLayer); bool init(); void setDelegate(GameOverDelegate*pDelegate); private: void gameRestart(Object*sender); }; #endif
82c46f0521d74f43c58d5e436a5163dc34f2aca2
a6f7d6627a9dc410b1d75e43b3285db1f17b2eea
/C programming/knight.cpp
2e9ec5f45a11b524210a7ef371ec02a4d8095630
[ "MIT" ]
permissive
Tiiberiu/misc
60dbc8c3372e0b771f4b3f14cf7a65f278c80f96
8284d5f117c0ac2fa1ef08aea50c0503be7cf24b
refs/heads/master
2021-06-27T02:22:28.868826
2020-09-27T08:15:29
2020-09-27T08:15:29
152,137,343
0
0
null
null
null
null
UTF-8
C++
false
false
2,048
cpp
knight.cpp
#include "stdafx.h" #include "stdafx.cpp" int PathMatrix[100][100],moves = 1; /* int x, y; bool InMatrix(int M[100][100], int x, int y, int n) { return(x>-1 && x<n && y>-1 && y<n && M[x][y] == 1); } vector<string> printPath(int m[MAX][MAX], int n) { int x_path[4] = { -1,0,1,-1 }; int y_path[4] = { 0,1,0,-1 }; string path[4] = { "U","R","D","L" }; for (int i = 0; i<n; i++) { x += x_path[i]; y += y_path[i]; if (InMatrix(m, x, y, n)) { cout << (path[i]); printPath(m, n); } } }*/ int DigitCntMax(long long i); void PrintSpaces(int n); void MatrixFixed(int M[100][100], int n); bool MoveOK(int m[100][100],int x, int y, int n) { return (x >= 0 && x < n && y >= 0 && y < n && m[x][y] == 0); } void KnightTraversal(int M[100][100],int n,int knight_x, int knight_y){ int xMove[8] = { 2, 1, -1, -2, -2, -1, 1, 2 }; int yMove[8] = { 1, 2, 2, 1, -1, -2, -2, -1 }; int next_y, next_x; for (int i = 0; i < 8; i++) { next_x = knight_x + xMove[i]; next_y = knight_y + yMove[i]; if (MoveOK(M,next_x, next_y, n)) { M[next_x][next_y] = moves++; KnightTraversal(M, n, next_x, next_y); } } } void MatrixInit(int M[100][100]) { for (int i = 0; i < 8; i++) for (int j = 0; j < 8; j++) M[i][j] = 0; } void MatrixPrint(int M[100][100]) { for (int i = 0; i < 8; i++) { for (int j = 0; j < 8; j++) cout << M[i][j] << " "; cout << endl; } } void Knight() { int M[100][100], n = 8, x = 0, y = 0; MatrixInit(M); KnightTraversal(M, n, x, y); MatrixFixed(M,n); } int DigitCntMax(long long i) { return i > 0 ? (int)log10((double)i) + 1 : 1; } void PrintSpaces(int n) { while (n) { cout << " "; n--; } } void MatrixFixed(int M[100][100],int n) { int max = 0; for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) if (DigitCntMax(M[i][j])> max) max = DigitCntMax(M[i][j]); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { PrintSpaces(max - DigitCntMax(M[i][j])); cout << M[i][j] << " "; } cout << endl; } } int main() { Knight(); cin.get(); return 0; }
6af59250a7c237a80e4fde19b26a389c2a38fd22
94f74fbe1377bb617c588500b4f37aec43dabf05
/Depot.cpp
ca3083d5a2f683439a536183be43fda716377987
[]
no_license
TheBeastwood/CEIS400
146bc42ee2d95d591098947dd97b0d091219f6b3
dcba1a83bad56b871541dc0c62bb8e0a8654e1a8
refs/heads/master
2021-08-23T05:53:58.047994
2017-12-03T18:58:38
2017-12-03T18:58:38
null
0
0
null
null
null
null
UTF-8
C++
false
false
396
cpp
Depot.cpp
#include "Depot.h" Depot::Depot() { } void Depot::orderEquipment(int id, std::string name) { } bool Depot::checkInventory(std::string name) { //check inventory for equipment name return false; } void Depot::addEquipment(std::string name) { } void Depot::removeEquipment(std::string name) { } void Depot::printInventory() { } void Depot::notifyEmployee() { }
cbb8f34712f625edd8d5f6304f8febebac3cd172
ef37f289aad930639dff9807517751135533e482
/component/zookeeper/ServiceDiscoveryListenner.h
cd7d09af22c9936c358112fca8ce740f6128a0b6
[ "Apache-2.0" ]
permissive
wenii/libnetwork
f1a9eb354efb9ab79588fdc1348f33c38361ba30
afb0d90307efe83dbb5e4594aca130af7f7a7b80
refs/heads/master
2021-08-16T15:57:49.814949
2020-09-28T10:45:10
2020-09-28T10:45:10
225,009,797
0
0
null
null
null
null
WINDOWS-1252
C++
false
false
750
h
ServiceDiscoveryListenner.h
#ifndef __SERVICE_DISCOVERY_LISTENNER_H__ #define __SERVICE_DISCOVERY_LISTENNER_H__ #include <string> #include <list> class ZookeeperClient; // ·þÎñ·¢ÏÖ¼àÌýÆ÷ class ServiceDiscoveryListenner { public: ServiceDiscoveryListenner(ZookeeperClient* zkClient, const std::string& servicePath, void* target); virtual ~ServiceDiscoveryListenner(); public: virtual void notify(const std::list<std::string>& serviceInfoArray, void* target) = 0; public: void getService(); const std::string& getPath() const; private: bool isNewService(const std::string& serviceInfo); private: ZookeeperClient* _zkClient; std::string _servicePath; void* _target; std::list<std::string> _serviceList; }; #endif // !__SERVICE_DISCOVERY_LISTENNER_H__
de45fc043437e8fe5eff52209dc5d6727e214467
807315581299c7dd9896a13b0ad56a1d678623ec
/src/modules/emotions/src/emotion_handle.cpp
4d7699558efd2868e62cd485329bb1992f89dc33
[ "MIT" ]
permissive
P8P-7/core
4b68bf5980883422f48045fd6fb47c1aa520b094
820873e7da867392729b2e65922205afe98e41d8
refs/heads/master
2020-03-12T14:19:57.499223
2018-07-04T13:58:01
2018-07-04T13:58:01
130,664,669
3
1
MIT
2018-07-05T20:34:25
2018-04-23T08:26:54
C++
UTF-8
C++
false
false
452
cpp
emotion_handle.cpp
#include <goliath/emotions/emotion_handle.h> using namespace goliath; handles::EmotionHandle::EmotionHandle(const size_t &handleId, const std::shared_ptr<goliath::repositories::EmotionRepository> &emotionRepository) : Handle(handleId), emotionRepository(emotionRepository) {} std::shared_ptr<goliath::repositories::EmotionRepository> handles::EmotionHandle::getEmotionRepository() { return emotionRepository; }
192f9c043f97ff1d64e66e791688d674c04e95fa
9a06328e1ebab3a094193f61dc7e0081ba0054bd
/Projekt PK4 Statki/Projekt PK4 Statki.cpp
5cc83986cf5672315f2b3a419c9973257ae4cc0a
[]
no_license
sylwiamolitor/Statki-PK4
16c3261fe4c6616a973fdd455e4fde317e3b3251
5a10e5127a1c1294b713f71d872c1f0e9e3dddf5
refs/heads/master
2022-06-05T11:21:45.546651
2020-05-04T18:42:53
2020-05-04T18:42:53
257,845,317
0
0
null
null
null
null
UTF-8
C++
false
false
4,403
cpp
Projekt PK4 Statki.cpp
 #include <SFML/Graphics.hpp> #include <iostream> #include "Interface.h" #include "GraphicObject.h" #include "GameLogic.h" #include <Windows.h> #include <list> #include <fstream> //lista do zapisu std::list<Button>ButtonList; int main() { std::ifstream plikWej("Zapis_Rozgrywki.txt"); Create_Board my_board; Create_Board enemy_board; if (plikWej) { //dodac tablice zestrzeleń std::string linijka; for (int i = 0; i < 10; i++) { std::getline(plikWej, linijka); for (int j = 0; j < 10; j++) { if(linijka[j] == '1') my_board.set_ship(i, j); }//wczytuj do planszy swojej } std::getline(plikWej, linijka); for (int i = 0; i < 10; i++) { std::getline(plikWej, linijka); for (int j = 0; j < 10; j++) { if (linijka[j] == '1') my_board.shoot_ship(i, j); }//wczytuj do planszy swojej } std::getline(plikWej, linijka); for (int i = 0; i < 10; i++) { std::getline(plikWej, linijka); for (int j = 0; j < 10; j++) { if (linijka[j] == '1') enemy_board.set_ship(i, j); } } std::getline(plikWej, linijka); for (int i = 0; i < 10; i++) { std::getline(plikWej, linijka); for (int j = 0; j < 10; j++) { if (linijka[j] == '1') enemy_board.shoot_ship(i, j); } } plikWej.close(); } sf::RenderWindow window(sf::VideoMode(1880, 1000), "Statki!");//, sf::Style::Fullscreen); // O - trafiony , X puste, . nic //rozgrywka ty-komputer - komputer strzela randem window.clear(sf::Color(0, 0, 0)); sf::RectangleShape rectangle(sf::Vector2f(225,100)); // tworzymy prostokąt rectangle.setPosition(200, 200); rectangle.setFillColor(sf::Color(255,255,255)); sf::Font font; if (!font.loadFromFile("arial.ttf")) { // error... } Button przycisk_wyjscia("EXIT", font, 40, sf::Vector2f(1100, 100)); Button przycisk_nowa_rozgrywka("NOWA ROZGRYWKA", font, 40, sf::Vector2f(1100, 300)); Button przycisk_wynik_przeciwnika("WYNIK PRZECIWNIKA:", font, 40, sf::Vector2f(1100, 500)); Button przycisk_twoj_wynik("TWOJ WYNIK:", font, 40, sf::Vector2f(1100, 700)); ButtonList.push_back(przycisk_nowa_rozgrywka); ButtonList.push_back(przycisk_twoj_wynik); ButtonList.push_back(przycisk_wyjscia); ButtonList.push_back(przycisk_wynik_przeciwnika); Board plansza1(font, sf::Vector2f(0, 0)); Board plansza2(font, sf::Vector2f(0, 500)); sf::Event event; sf::Mouse mouse; while (window.isOpen()) { while (window.pollEvent(event)) { float mouse_x=0; float mouse_y=0; if (event.type == sf::Event::Closed) window.close(); if (mouse.isButtonPressed(sf::Mouse::Left)) { mouse_x = mouse.getPosition(window).x; mouse_y = mouse.getPosition(window).y; if (mouse_x > 1100 && mouse_y > 100 && mouse_x < 1600 && mouse_y < 200) //na sztywno window.close(); } if (sf::Keyboard::isKeyPressed(sf::Keyboard::Escape)) //wciśnięto klawisz ESC window.close(); //zakończ aplikację } window.draw(plansza1); window.draw(plansza2); for (Button a : ButtonList) { window.draw(a); } window.display(); window.clear(); } //komunikat kto wygral i zapis do pliku //dzwieki? std::ofstream plikWyj("Zapis_Rozgrywki.txt"); if (plikWyj) { for (int i = 0; i < 10; i++) { for (int j = 0; j < 10; j++) { if (my_board.is_ship_there(i, j) == 1) plikWyj << 1; else plikWyj << 0; } plikWyj << std::endl; } plikWyj << std::endl; for (int i = 0; i < 10; i++) { for (int j = 0; j < 10; j++) { if (my_board.is_ship_there_shot(i, j) == 1) plikWyj << 1; else plikWyj << 0; } plikWyj << std::endl; } plikWyj << std::endl; for (int i = 0; i < 10; i++) { for (int j = 0; j < 10; j++) { if (enemy_board.is_ship_there(i, j) == 1) plikWyj << 1; else plikWyj << 0; } plikWyj << std::endl; } plikWyj << std::endl; for (int i = 0; i < 10; i++) { for (int j = 0; j < 10; j++) { if (enemy_board.is_ship_there_shot(i, j) == 1) plikWyj << 1; else plikWyj << 0; } plikWyj << std::endl; } plikWyj.close(); } return 0; }
92fcaf973b4df46b8152ac62d2495db7db229aa3
2c0e82962eb9b70c5afd542166e4bad69d982abc
/03-functions/factorial.cc
c32371a2d792c67ce7997cefaba9c302ba3cb0cd
[]
no_license
ishaandhamija/LP-Fasttrack-Summer18
e1cb6e37752501e32e50a8722b66ef11e4c639bf
f915327bf63074c1a5ef16f2d3ce55d7419b0a6e
refs/heads/master
2020-03-22T17:23:26.563687
2018-07-07T08:05:08
2018-07-07T08:05:08
null
0
0
null
null
null
null
UTF-8
C++
false
false
591
cc
factorial.cc
// Deepak Aggarwal, Coding Blocks // deepak@codingblocks.com #include <iostream> using namespace std; int main() { // n!, r!, n-r! int n, r; cin >> n >> r; // n! int nFact = 1; for (int curNum = 1; curNum <= n; ++curNum) { nFact = nFact * curNum; } // r ! int rFact = 1; for(int curNum = 1; curNum <= r; ++curNum){ rFact = rFact* curNum; } // n - r ! int nrFact = 1; for(int curNum = 1; curNum <= (n-r); ++curNum){ nrFact = nrFact * curNum; } int ans = nFact / (rFact * nrFact); cout << ans; }
2f387127d1f63aca47ec6bbc5180a588bd794699
0932a1d94a15ef74294acde30e1bc3267084e3f4
/OJ/POJ1/POJ2769.cpp
cd89f3474e54fd7a9f70f6d9f10958d7252b175c
[]
no_license
wuzhen247/ACM-ICPC
9e585cb425cb0a5d2698f4c603f04a04ade84b88
65b5ab5e86c07e9f1d7c5c8e42f704bbabc8c20d
refs/heads/master
2020-05-17T19:51:48.804361
2016-09-03T12:21:59
2016-09-03T12:21:59
33,580,771
0
0
null
null
null
null
UTF-8
C++
false
false
544
cpp
POJ2769.cpp
#include<iostream> #include<cstdio> #include<cstring> using namespace std; bool b[10000001],flag; int t,n,a[305],c[1000000],n1,i,j; int main() { scanf("%d",&t); while(t--) { scanf("%d",&n); for(i=0;i<n;i++) scanf("%d",&a[i]); memset(b,0,sizeof(b)); for(i=1;;i++) { n1=0; flag=false; for(j=0;j<n;j++) { c[++n1]=a[j]%i; if(b[c[n1]]) { flag=true; break; } b[c[n1]]=true; } if(flag==false) break; for(j=1;j<=n1;j++) b[c[j]]=0; } printf("%d\n",i); } return 0; }
e4562296b4e746637041686572fc5bddeee68c32
13295aacaae3d206fcbd0ae03b82207b240d20a8
/c++ ELAL project/Passenger/Passenger_t.h
8d54a7223c7852542d11af0e9f2c5cdd4b3bbfda
[]
no_license
paveln1234/Projects
d2b778a5a3a0cdc8106424ed27db552f08f38298
05ea7e19c847ac41c6d9871b8c0a891a6464678c
refs/heads/master
2021-08-14T10:10:40.694863
2017-11-15T10:41:28
2017-11-15T10:41:28
109,574,151
0
0
null
null
null
null
UTF-8
C++
false
false
2,177
h
Passenger_t.h
#ifndef PASSENGER_T_H #define PASSENGER_T_H #include <string> #include <vector> class Customer_t; class Ticket_t; using namespace std; class Passenger_t { public: /** Default constructor */ Passenger_t(); /** Default destructor */ virtual ~Passenger_t(); /** set Passenger id * \param size_t - _passengerId */ void SetPassengerId(size_t _passengerId){m_passengerId = _passengerId;} /** Get Passenger Id * \return size_t - passenger id */ size_t GetPassengerId()const {return m_passengerId;} /** Add Ticket to Passenger * \param const string& _ticketId */ virtual void AddTicket(const string& _ticketId); /** Remove Ticket to Passenger * \param const string& _ticketId * \return bool - true if success , fail if wrong ticket id given */ virtual bool RemoveTicket(const string& _ticketId); /** Set Customer for passenger * \param const Customer_t* _customer - Costumer to set */ virtual void SetCustomer(const Customer_t* _customer) {m_coustumer = _customer;} /** Get Customer from Passenger * \return const Customer_t* _customer - Costumer to set1 */ virtual const Customer_t* GetCustomer() const {return m_coustumer;} /** Get Passenger Ditals * \return const string whit passengers ditals */ virtual const string GetPassengerDitals(); /** Set Borded Passenger after Passenger make Check In * \param bool _status - Passenger new status */ void SetBorded(bool _status) {m_isBorded = _status;} /** Get Passenger borded status * \return bool */ const bool IsBorded()const {return m_isBorded;} /** Get Passenger tickets list * \return const vector<string> whit passengers tikets */ virtual const vector<string> GetTicketList()const; private: Customer_t const* m_coustumer; vector<string> m_tickets; bool m_isBorded; size_t m_passengerId; }; #endif // PASSENGER_T_H
40da8855615c9b37d861f07d199cc0f61c307e0d
4ed3043deea4e9d8f2a43169d9f40c9a3abeb46d
/q24.cpp
5c88c705dc1f87d04c158eb9d7ce8f450ae08200
[]
no_license
dyrroth-11/A2OJ-B-Ladder-Solutions
a2fa326b57ad9ba1e5c5a4f13e1f3f4bebf5fb76
122c09339953aa2bef9eaf5115d5b85de629bb4b
refs/heads/master
2022-11-21T11:58:15.633484
2020-07-26T20:38:43
2020-07-26T20:38:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
486
cpp
q24.cpp
#include <bits/stdc++.h> using namespace std; int main(){ ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); int n,k,ma=0,mi=101; cin>>n>>k; int arr[n]; for(int i=0;i<n;i++){ cin>>arr[i]; mi=min(mi,arr[i]); ma=max(ma,arr[i]); } if((ma-mi)>k){cout<<"NO";return 0;} cout<<"YES\n"; for(int i=0;i<n;i++){ for(int j=1;j<=arr[i];j++){ if(j%k==0)cout<<k<<" "; else cout<<j%k<<" "; } cout<<"\n"; } return 0; }
09b2f2e5dfbce1a160280909211e45d9df005f5e
d0fb46aecc3b69983e7f6244331a81dff42d9595
/httpdns/include/alibabacloud/httpdns/model/GetResolveStatisticsRequest.h
55962ccb323c6771ff72c991f227bb1df075dff0
[ "Apache-2.0" ]
permissive
aliyun/aliyun-openapi-cpp-sdk
3d8d051d44ad00753a429817dd03957614c0c66a
e862bd03c844bcb7ccaa90571bceaa2802c7f135
refs/heads/master
2023-08-29T11:54:00.525102
2023-08-29T03:32:48
2023-08-29T03:32:48
115,379,460
104
82
NOASSERTION
2023-09-14T06:13:33
2017-12-26T02:53:27
C++
UTF-8
C++
false
false
1,853
h
GetResolveStatisticsRequest.h
/* * Copyright 2009-2017 Alibaba Cloud All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef ALIBABACLOUD_HTTPDNS_MODEL_GETRESOLVESTATISTICSREQUEST_H_ #define ALIBABACLOUD_HTTPDNS_MODEL_GETRESOLVESTATISTICSREQUEST_H_ #include <string> #include <vector> #include <alibabacloud/core/RpcServiceRequest.h> #include <alibabacloud/httpdns/HttpdnsExport.h> namespace AlibabaCloud { namespace Httpdns { namespace Model { class ALIBABACLOUD_HTTPDNS_EXPORT GetResolveStatisticsRequest : public RpcServiceRequest { public: GetResolveStatisticsRequest(); ~GetResolveStatisticsRequest(); std::string getProtocolName()const; void setProtocolName(const std::string& protocolName); std::string getDomainName()const; void setDomainName(const std::string& domainName); int getTimeSpan()const; void setTimeSpan(int timeSpan); std::string getAccessKeyId()const; void setAccessKeyId(const std::string& accessKeyId); std::string getGranularity()const; void setGranularity(const std::string& granularity); private: std::string protocolName_; std::string domainName_; int timeSpan_; std::string accessKeyId_; std::string granularity_; }; } } } #endif // !ALIBABACLOUD_HTTPDNS_MODEL_GETRESOLVESTATISTICSREQUEST_H_
047c421a9a9c5ab5137d6dbef05a6a5163376020
a29e024320cb08d6f7ce2931376bf80745fb935f
/include/eva/journal.hpp
c2930942990745ac98acd96706837b55a8b06bb4
[]
no_license
mmcilroy/gma_cpp
6c4e5d59f91146f6c102d3651ae9e84dc1e5f39b
2280f731691a59745cf771f02054e93fb901acc4
refs/heads/master
2021-01-17T11:52:18.000447
2015-10-11T21:42:37
2015-10-11T21:42:37
42,574,934
0
0
null
null
null
null
UTF-8
C++
false
false
388
hpp
journal.hpp
#pragma once #include "eva/event.hpp" #include <fstream> #include <iostream> namespace eva { class journal { public: journal( const std::string&, bool ); void write( const eva::event& ); void flush(); template< typename F > void recover( F ); private: std::fstream file_; std::string filename_; }; #include "journal.inl" }
9b20626b46a1ec7a0a9cc3ec9cc771dd997e6fa3
9939aab9b0bd1dcf8f37d4ec315ded474076b322
/libs/core/execution_base/src/spinlock_deadlock_detection.cpp
01b03855050be9034e6ecb0cf285cef93a0cc872
[ "BSL-1.0", "LicenseRef-scancode-free-unknown" ]
permissive
STEllAR-GROUP/hpx
1068d7c3c4a941c74d9c548d217fb82702053379
c435525b4631c5028a9cb085fc0d27012adaab8c
refs/heads/master
2023-08-30T00:46:26.910504
2023-08-29T14:59:39
2023-08-29T14:59:39
4,455,628
2,244
500
BSL-1.0
2023-09-14T13:54:12
2012-05-26T15:02:39
C++
UTF-8
C++
false
false
1,398
cpp
spinlock_deadlock_detection.cpp
//////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2013 Thomas Heller // Copyright (c) 2008 Peter Dimov // Copyright (c) 2018 Hartmut Kaiser // // SPDX-License-Identifier: BSL-1.0 // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) //////////////////////////////////////////////////////////////////////////////// #include <hpx/config.hpp> #ifdef HPX_HAVE_SPINLOCK_DEADLOCK_DETECTION #include <hpx/execution_base/detail/spinlock_deadlock_detection.hpp> #include <cstddef> namespace hpx::util::detail { static bool spinlock_break_on_deadlock_enabled = false; static std::size_t spinlock_deadlock_detection_limit = HPX_SPINLOCK_DEADLOCK_DETECTION_LIMIT; void set_spinlock_break_on_deadlock_enabled(bool enabled) noexcept { spinlock_break_on_deadlock_enabled = enabled; } bool get_spinlock_break_on_deadlock_enabled() noexcept { return spinlock_break_on_deadlock_enabled; } void set_spinlock_deadlock_detection_limit(std::size_t limit) noexcept { spinlock_deadlock_detection_limit = limit; } std::size_t get_spinlock_deadlock_detection_limit() noexcept { return spinlock_deadlock_detection_limit; } } // namespace hpx::util::detail #endif
6411602cd545199d46841768f7243787b526401f
4a4693db3d0716c0f94bcc6829e80b217a96ca89
/CountingSort.cpp
09fb8082b0a0380cfd432e7ff4405e314abc7136
[]
no_license
sunnylee7/Algorithm_Sorting
65c98731dc7e08fa28bc613f62a26a676fed29c7
38e64a53e1da6f607f271d7af8d04fb44e40d2de
refs/heads/master
2022-10-15T19:25:55.219084
2020-06-10T12:50:04
2020-06-10T12:50:04
null
0
0
null
null
null
null
UHC
C++
false
false
4,040
cpp
CountingSort.cpp
#include "pch.h" #include <iostream> #include <stdio.h> #include <stdlib.h> #include <time.h> #define NUMOFNUMBERS 500000 // 5만개, 7.5만개, 10만개, 12.5만개, ..., 50만개까지 증가시키며 시간 측정할 것 #define COUNTINGNUMBER 10000 // n은 -COUNTINGNUMBER~COUNTINGNUMBER 값 사이에 있어야 countingSort 를 쓸 수 있음 //COUNTINGNUMBER는 A[]의 원소가 등장하는 횟수 long *randNumbers = (long*)malloc(sizeof(long)* NUMOFNUMBERS); long resultNumber[NUMOFNUMBERS]; void countingSort(long A[], long B[], long n); int main(int argc, char* argv[]) { register long n, i; clock_t before; double elapsed_time; std::cout << "알고리즘입문 소팅 프로젝트 시작합니다.\n\n"; srand((unsigned)time(NULL)); before = clock(); //k값 범위 이내여야하므로, 10000개로 잡겠습니다. //for (i = NUMOFNUMBERS - 1; i >= 0; i--) { for (i = NUMOFNUMBERS - 1; i >= 0; i--) { n = rand()%COUNTINGNUMBER; // n은 -k~k 값 사이에 있어야 countingSort 를 쓸 수 있음 n += ((i + 1) / RAND_MAX) * RAND_MAX; if (n > COUNTINGNUMBER) n = rand() % COUNTINGNUMBER; //n은 COUNTINGNUMBER 범위 내에 있어야 하므로 조건을 변경하였습니다. randNumbers[NUMOFNUMBERS - 1 - i] = n; } elapsed_time = (double)(clock() - before) / CLOCKS_PER_SEC; // 초 단위의 경과 시간을 측정함. fprintf(stdout, "%d 개의 랜덤 넘버 생성에 걸린 시간(초): %10.2f\n\n", NUMOFNUMBERS, elapsed_time); //후에 지우고 실행할 것 //std::cout << "정렬전 숫자 입력 값들 출력:\n\n"; //for (i = 0; i < NUMOFNUMBERS; i++) //std::cout << randNumbers[i]<<"\n\n"; // 여기에 각종 정렬 알고리즘을 구현해서 실행시키고 그 실행 시간을 출력합니다. before = clock(); countingSort(randNumbers, resultNumber, NUMOFNUMBERS); std::cout << "countingSort실행"; elapsed_time = (double)(clock() - before) / CLOCKS_PER_SEC; // 초 단위의 경과 시간을 측정함. std::cout << " COUNTINGNUMBER은" << COUNTINGNUMBER << "\n"; fprintf(stdout, "%d 개의 랜덤 넘버를 count sort 하는 데에 걸린 시간(초): %10.3f\n\n", NUMOFNUMBERS, elapsed_time); //countingsort의 수행시간이 너무 빨라서 더 세밀한 단위로 나타내도록 하였습니다. //std::cout << "정렬 결과 출력:\n\n"; //for (i = 0; i < NUMOFNUMBERS; i++) //std::cout << resultNumber[i]<< "\n\n"; return 0; } void countingSort(long A[], long B[], long n) { //B배열 초기화 for (int i = 0; i < n; i++) B[i] = 0; long *C = (long*)malloc(sizeof(long)* COUNTINGNUMBER); for (int i = 0; i < COUNTINGNUMBER; i++) C[i] = 0; //C배열을 초기화함 for (int j = 0; j < n; j++) C[A[j]]++; //A[j]를 index로 설정 for (int i = 1; i < COUNTINGNUMBER; i++) C[i] = C[i] + C[i - 1]; //C[i]에는 누적횟수가 저장됨(i의 값이 몇번 나왔는 지 그 횟수+ i보다 작은 값이 등장한 횟수)-> 결과: i값의 자리 결정 // i보다 큰 값 { i(i의 횟수=i의 갯수이므로, i의 횟수만큼 들어감) } i보다 작은 값들 <-이런 식으로 들어감 //이 시점에서 C[i] : i보다 작거나 같은 원소의 총수 for (int j = n-1; j >= 0; j--) { B[C[A[j]]-1] = A[j]; //B[C[A[j]]] : B배열의 j보다 작은 원소들의 총개수 ---> 배열의 뒤부터 채워줌(결과배열은 오름차순정렬이므로, 현재는 내림차순 정렬이므로) //B[C[A[j]]-1] 인 이유: C[]가 0부터 시작인데, 위의 루프에서는 1부터 시작하였으므로, C[0]값이 출력이 안됨, 결과적으로 값이 하나씩 누락됨 //=> 해결: 정렬된 값들을 한 칸씩 이동시켜서 저장함-> 값 손실 잃어나지 않고 제대로 정렬됨 C[A[j]]--; //자신의 개수를 빼줌(A[j]에는 j보다 작은 원소개수 뿐아니라 j의 개수도 들어있으므로) } free(C); free(randNumbers); }
6a06c4e3d96c40f74047ee4283656db279629db8
7499c8c3390214f0fea9cfbfb4f3f515edfe6f6f
/2Cycle/14장/p361-q25.cpp
1672fb1e8f84e01190814e71012c57a0b31df050
[]
no_license
jrucl2d/Python_Coding_Test
cd3032ea2b5c0df29650bbc1dfca169a4f8d91c4
0249893b463dfc78f033e2067b137add8f989fe6
refs/heads/master
2023-03-03T16:51:33.387077
2021-02-22T06:50:25
2021-02-22T06:50:25
287,958,302
0
0
null
null
null
null
UTF-8
C++
false
false
880
cpp
p361-q25.cpp
#include <algorithm> #include <string> #include <vector> using namespace std; typedef pair<double, int> pdi; bool comp(pdi a, pdi b) { if (a.first == b.first) { return a.second < b.second; } return a.first > b.first; } vector<int> solution(int N, vector<int> stages) { vector<int> answer; vector<pdi> tmp; int num = stages.size(); int count[510] = { 0, }; for (int i = 0; i < num; i++) { count[stages[i]] += 1; } int cnt = num; for (int i = 1; i <= N; i++) { double first; if (count[i] != 0) first = double(count[i]) / cnt; else first = 0; tmp.push_back({first, i}); cnt -= count[i]; } sort(tmp.begin(), tmp.end(), comp); for (int i = 0; i < tmp.size(); i++) { answer.push_back(tmp[i].second); } return answer; }
24a67fb877198c0b85737c109b747d951c2c4e18
10482826e4b50289d25e19d214e360964a68c99f
/codeblock_parse/node_modules/tree-sitter/vendor/tree-sitter/src/compiler/lex_table.h
9317c818c36466fe14999946bce903565d679db5
[ "MIT" ]
permissive
ZachEddy/IssueLabeler
85cfb28cc7f592739aae7af672bcef3f96d653e1
e0d9f8e33382c46d902dc8d8d22044953ca4a3cf
refs/heads/master
2020-06-11T12:21:04.279108
2017-05-24T22:12:14
2017-05-24T22:12:14
75,671,208
2
0
null
null
null
null
UTF-8
C++
false
false
1,008
h
lex_table.h
#ifndef COMPILER_LEX_TABLE_H_ #define COMPILER_LEX_TABLE_H_ #include <map> #include <vector> #include <set> #include <string> #include "compiler/precedence_range.h" #include "compiler/rule.h" namespace tree_sitter { typedef int64_t LexStateId; struct AdvanceAction { AdvanceAction(); AdvanceAction(size_t, PrecedenceRange, bool); bool operator==(const AdvanceAction &other) const; LexStateId state_index; PrecedenceRange precedence_range; bool in_main_token; }; struct AcceptTokenAction { AcceptTokenAction(); AcceptTokenAction(rules::Symbol, int, bool); bool is_present() const; bool operator==(const AcceptTokenAction &action) const; rules::Symbol symbol; int precedence; bool is_string; }; struct LexState { bool operator==(const LexState &) const; std::map<rules::CharacterSet, AdvanceAction> advance_actions; AcceptTokenAction accept_action; }; struct LexTable { std::vector<LexState> states; }; } // namespace tree_sitter #endif // COMPILER_LEX_TABLE_H_
e8e57d827ac988fc4c292986dfef431501af037e
5b1df9018826179d50bc5b2eb4825a60551fec6e
/Search/BinarySearch/CounterOfNumber.cpp
c0c3404daa787a6014de0eafe2390fb95c267463
[]
no_license
whybfq/Kehan-Academy-algorithm
a9c61458b24cfc870a3c8b39384ae67a548830e6
c80e1d56afe327cf373807fd086f1b19fe0e9081
refs/heads/master
2022-02-16T01:07:19.376063
2019-09-13T14:43:16
2019-09-13T14:43:16
109,346,298
1
0
null
2017-11-06T03:26:20
2017-11-03T03:10:27
null
UTF-8
C++
false
false
1,871
cpp
CounterOfNumber.cpp
/********************************************************************************* * @copyright (C) 2018 sanner All Rights Reserved * @file: BinarySearch2.cpp / CounterOfNumber.cpp * @brief: Counter of n, assume the array is sorted first and some elements will appear multiple times * * @date: Nov 2018 * @bug : * @author: sanner * * @CMAKE_CXX_STANDARD 14 * @IDE: Clion 2018.2 * @OS: macOS 10.14 * * @function_lists: * 1. fg: void Swap(int A[] , int i, int j -- exchange A[i] and A[j],dtype=int 2. * @history: 1.@date: @author: @modification: 2.@date: @author: @modification: **********************************************************************************/ #include <iostream> using std:: cin ; using std:: cout; using std:: endl; int BinarySearch(int A[], int n, int x,bool searchFirst) { int low = 0, high = n - 1; int result = -1; while (low <= high) // attention <= { int mid = low + (high - low) / 2; // int mid = (low + high) / 2; (low+high) may overflow if(x == A[mid]) { result = mid; if(searchFirst) high = mid - 1; // go on searching towards left else low = mid + 1; // go on searching towards right } else if(x < A[mid]) high = mid - 1; else low = mid + 1; } // cout << " not found " << x << " in A[] " << endl; return result; } int main() { int A[] = {1,1,3,3,5,5,5,5,9,9,11}; int n; cout << "Enter a number: "; cin >> n; int Firstindex = BinarySearch(A,sizeof(A)/sizeof(A[0]),n,true); if(Firstindex == -1) { cout << "can't found " << n << endl; } else { int lastIndex = BinarySearch(A,sizeof(A)/sizeof(A[0]),n,false); cout << "Count of " << n << " is " << (lastIndex-Firstindex+1) << endl; } }
d667ab17ea9d4834671eacc55071f12c09e1e2c5
6bd8361a48483349696013979dcff4f857c6f9c4
/cFish.cpp
a2a453bf14dea64128c9421d0ddf52a655c1e516
[]
no_license
seodaun/DX9_2D_ShootingGame
c0edb26d0abd888198c1c6fb10c05a905b1e251c
f5b30b9ca29758321ee4107cce470dbc6a21bc99
refs/heads/master
2020-12-19T17:01:03.993647
2020-01-23T12:56:36
2020-01-23T12:56:36
235,789,644
0
0
null
null
null
null
UTF-8
C++
false
false
1,735
cpp
cFish.cpp
#include "DXUT.h" #include "cFish.h" #include "cEnemyBullet.h" #include "cBullet.h" #include <string> cFish::cFish(const D3DXVECTOR2& pos, const D3DXVECTOR2& playerPos, const float speed) : cEnemy(pos, 300, 2), m_playerpos(playerPos), m_PlayerBullet(GAMEMANAGER->getPBulletAd()->GetPBullet()) { m_image = IMAGEMANAGER->FindImage("IdleFish_0"); m_speed = speed; m_EnemyAni[eIDLE] = new cAnimation("IdleFish", 0.08f, true); m_EnemyAni[eDAMAGE] = new cAnimation("DamageFish", 0.08f, true); m_EnemyAni[eDIE] = new cAnimation("DieFish", 0.08f, false); m_State = eIDLE; m_rColl = { 0,0,(LONG)m_image->info.Width / 2,(LONG)m_image->info.Height / 2 }; } cFish::~cFish() { for (int j = 0; j < STATE_KIND; j++) SAFE_DELETE(m_EnemyAni[j]); } void cFish::Update() { if (m_State != eDIE)m_pos.x -= 100 * DXUTGetElapsedTime()* m_speed; switch (m_State) { case CHARACTER_STATE::eIDLE: if (m_EnemyAni[eIDLE]->Update()) m_State = eIDLE; break; case CHARACTER_STATE::eDIE: if (m_EnemyAni[eDIE]->Update()) m_dead = true; break; } m_rEnemy = { (LONG)(m_pos.x - m_image->info.Width / 2 + 150), (LONG)(m_pos.y - m_image->info.Height / 2 ), (LONG)(m_pos.x + m_image->info.Width / 2 -100), (LONG)(m_pos.y + m_image->info.Height / 2 ) }; for (auto iter = m_PlayerBullet.begin(); iter != m_PlayerBullet.end();) { RECT rPBullet = { (LONG)((*iter)->m_pos.x - (*iter)->m_image->info.Width / 2), (LONG)((*iter)->m_pos.y - (*iter)->m_image->info.Height / 2), (LONG)((*iter)->m_pos.x + (*iter)->m_image->info.Width / 2), (LONG)((*iter)->m_pos.y + (*iter)->m_image->info.Height / 2) }; if (IntersectRect(&m_rColl, &m_rEnemy, &rPBullet)) { if (!(*iter)->m_die) Damage(); (*iter)->m_die = true; } iter++; } }
4b08cf17d94d4fb819ef0b917df277dac6700f7c
692e27eb86c6c8f24c49eb83746d6be3d4f86eed
/modulo_11((AxB)%c).cpp
9b99a65f51e40146bd6889f9d97225229a9430c8
[]
no_license
docongban/zcode_C-
335b8f6521eef512dbb131e0cfda139fd81851f3
bfb50a37748cd50eb2e3fb3e56eea95218c70d9f
refs/heads/main
2023-06-06T02:10:47.656463
2021-07-01T14:36:00
2021-07-01T14:36:00
null
0
0
null
null
null
null
UTF-8
C++
false
false
367
cpp
modulo_11((AxB)%c).cpp
#include<bits/stdc++.h> using namespace std; long long Modulo(long long a,long long b,long long c) { if(b==0) { return 0; } long long x=Modulo(a,b/2,c); if(b%2==1) { return ((a%c)+2*(x%c))%c; } else { return (2*(x%c))%c; } } int main() { int t; cin>>t; while(t--) { long long a,b,c; cin>>a>>b>>c; cout<<Modulo(a,b,c)<<endl; } return 0; }
7cb294e6ae0e7f8bfd5e3a121465c667e94858a5
6c4bd0d5f1e2c8902bfdeebe5d3d6931e60c028b
/ga4/doublylinkedlist.h
adf9d61e1d47355c9ad188644047fafad2124f61
[]
no_license
bpham-work/cosc2430
1097fb9619d23134edc71f179f2f149edc0617f2
15be977e0cce0bfb8dd483ea1a830ef2492bfdf9
refs/heads/master
2021-05-05T11:35:59.809944
2018-05-06T22:37:08
2018-05-06T22:37:08
118,179,397
0
0
null
null
null
null
UTF-8
C++
false
false
4,330
h
doublylinkedlist.h
#ifndef DOUBLY_LINKED_LIST_H #define DOUBLY_LINKED_LIST_H #include "doublynode.h" #include <string> #include <iostream> using namespace std; template <class T> class DoublyLinkedList { DoublyNode<T>* head; DoublyNode<T>* tail; public: DoublyLinkedList(); ~DoublyLinkedList(); void append(T& val); void push(T& val); T* peekTail(); T* peekHead(); T* popFromLeft(int position); T* popHead(); T* popFromRight(int position); void deleteNode(DoublyNode<T>* node); void clear(); void print(); string toString(); class iterator; iterator begin(); }; template <class T> DoublyLinkedList<T>::DoublyLinkedList() { this->head = nullptr; } template <class T> DoublyLinkedList<T>::~DoublyLinkedList() { delete this->head; } template <class T> void DoublyLinkedList<T>::append(T& val) { DoublyNode<T>* newNode = new DoublyNode<T>(val); if (this->head == nullptr) { this->head = newNode; this->tail = newNode; } else { DoublyNode<T>* temp = this->tail; temp->next = newNode; newNode->prev = temp; this->tail = newNode; } } template <class T> void DoublyLinkedList<T>::push(T& val) { DoublyNode<T>* newNode = new DoublyNode<T>(val); if (this->head == nullptr) { this->head = newNode; this->tail = newNode; } else { DoublyNode<T>* temp = this->head; newNode->next = temp; this->head = newNode; } } template <class T> T* DoublyLinkedList<T>::peekTail() { if (this->tail != nullptr) return this->tail->val; return nullptr; } template <class T> T* DoublyLinkedList<T>::peekHead() { if (this->head != nullptr) return this->head->val; return nullptr; } template <class T> T* DoublyLinkedList<T>::popHead() { return this->popFromLeft(0); } template <class T> T* DoublyLinkedList<T>::popFromLeft(int index) { //if (this->head == nullptr) return NULL; int counter = 0; DoublyNode<T>* node = this->head; while (counter < index) { node = node->next; counter++; } T* val = node->val; this->deleteNode(node); return val; } template <class T> T* DoublyLinkedList<T>::popFromRight(int index) { //if (this->tail == nullptr) return NULL; int counter = 0; DoublyNode<T>* node = this->tail; while (counter < index) { node = node->prev; counter++; } T* val = node->val; this->deleteNode(node); return val; } template <class T> void DoublyLinkedList<T>::deleteNode(DoublyNode<T>* node) { if (node->prev == nullptr) { this->head = node->next; this->head->prev = nullptr; } else if (node->next == nullptr) { this->tail = node->prev; this->tail->next = nullptr; } else { DoublyNode<T>* prevNode = node->prev; DoublyNode<T>* nextNode = node->next; prevNode->next = nextNode; nextNode->prev = prevNode; } node->clearLinks(); delete node; } template <class T> void DoublyLinkedList<T>::clear() { delete this->head; this->head = nullptr; } template <class T> void DoublyLinkedList<T>::print() { DoublyNode<T>* node = this->head; while (node != nullptr) { cout << node->val; node = node->next; } cout << endl; } template <class T> string DoublyLinkedList<T>::toString() { string result; DoublyNode<T>* node = this->head; while (node != nullptr) { result += node->val; node = node->next; } return result; } template <typename T> typename DoublyLinkedList<T>::iterator DoublyLinkedList<T>::begin() { return typename DoublyLinkedList<T>::iterator(this->head); } template <class T> class DoublyLinkedList<T>::iterator { DoublyNode<T>* current; public: iterator(DoublyNode<T>* head) { this->current = head; } iterator& operator++() { current = current->next; return *this; } iterator& operator++(int a) { current = current->next; return *this; } T* operator*() { return current->val; } bool operator!=(bool end) { return end; } bool end() { return current == nullptr; } }; #endif
bbb716c380d52c713608c70ce6a452268b89b027
2315e5da2da28b454eb0a5d7bf9c5881650c84a6
/Task/assignment3/main.cpp
69cf843b2faab4982814dc2b34dda4a69b00c2ff
[]
no_license
SAMIUL98SIAM/Computer-graphics
c34451f3dde3e35af680bc908b4592c7150af07c
acc7afda553190a02c68cf7f79ef3c58cf664bc7
refs/heads/master
2023-06-02T08:14:39.792171
2021-06-23T18:49:23
2021-06-23T18:49:23
379,700,382
0
1
null
null
null
null
UTF-8
C++
false
false
1,507
cpp
main.cpp
#include<iostream> #include <stdio.h> #include <GL/gl.h> #include <GL/glut.h> #include <cmath> using namespace std; double xi=0; double yi=0; double xn=0; double yb=0; void myDisplay(void) { double max,m,cel,cel2,a; double difference_x= xn-xi; double difference_y= yb-yi; if(difference_x>difference_y){ max=difference_x; } else{ max= difference_y; } m= (yb-yi)/(xn-xi); glClearColor(0,0,0,0); glClear(GL_COLOR_BUFFER_BIT); for(int i=0;i<max;i++){ xi=xi+1; yi=yi+m; cel=ceil(yi); a=cel-yi; if(a>=0.5){ glPointSize(4.0); glColor3f(1,1,1); glBegin(GL_POINT); glVertex2i(xi,cel); glEnd(); glFlush(); } else{ glPointSize(4.0); cel2=floor(yi); glColor3f(1,1,1); glBegin(GL_POINT); glVertex2i(xi,cel2); glEnd(); glFlush(); } } } void myInit (void) { glClearColor(0.0,0.0,0.0,0.0); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); gluOrtho2D(0.0,800.0,0.0,800.0); } int main(int argc,char** argv) { cin>>xi; cin>>yi; cin>>xn; cin>>yb; glutInit( &argc , argv); glutInitDisplayMode(GLUT_SINGLE |GLUT_RGB); glutInitWindowSize(800,800); glutInitWindowPosition(0,0); glutCreateWindow("CHESS"); glutDisplayFunc(myDisplay); myInit(); glutMainLoop(); }
232b1c8925215f26badff00e93e7d20078cf1302
fe479340153355e43d3ce3f3c3d058b7764d2a98
/Projects/Plasma/DataFlow/DFNode.h
524ac2b9f60b766f14a92c8f250c1260c44f917d
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
LudoSapiens/Dev
8496490eda1c4ca4288a841c8cbabb8449135125
8ad0be9088d2001ecb13a86d4e47e6c8c38f0f2d
refs/heads/master
2016-09-16T11:11:56.224090
2013-04-17T01:55:59
2013-04-17T01:55:59
9,486,806
4
1
null
null
null
null
UTF-8
C++
false
false
9,035
h
DFNode.h
/*============================================================================= Copyright (c) 2012, Ludo Sapiens Inc. and contributors. See accompanying file LICENSE.txt for details. =============================================================================*/ #ifndef PLASMA_DFNODE_H #define PLASMA_DFNODE_H #include <Plasma/StdDefs.h> #include <Fusion/VM/VM.h> #include <CGMath/Vec2.h> #include <Base/ADT/ConstString.h> #include <Base/ADT/String.h> #include <Base/ADT/Vector.h> #include <Base/ADT/Set.h> #include <Base/IO/StreamIndent.h> #include <Base/Util/RCObject.h> NAMESPACE_BEGIN class DFGraph; class DFInput; class DFNode; class DFNodeAttrList; class DFNodeAttrStates; class DFNodeSpec; class Manipulator; /*============================================================================== CLASS DFSocket ==============================================================================*/ class DFSocket { public: /*----- types and enumerations -----*/ enum Type { FLOAT, VEC2, VEC3, VEC4, SOUND, IMAGE, GEOMETRY, ANIMATION, WORLD, STROKES, POLYGON }; /*----- static methods -----*/ static PLASMA_DLL_API const char* toStr( Type type ); /*----- methods -----*/ PLASMA_DLL_API virtual Type type() const = 0; inline const char* typeAsStr() const { return toStr(type()); } }; /*============================================================================== CLASS DFOutput ==============================================================================*/ class DFOutput: public DFSocket { public: inline bool isConnected() const { return !_inputs.empty(); } inline uint numInputs() const { return uint(_inputs.size()); } inline const Vector<DFInput*>& inputs() const { return _inputs; } protected: /*----- friends -----*/ friend class DFGraph; friend class DFInput; /*----- methods -----*/ void connect( DFInput* input ) { _inputs.pushBack( input ); } void disconnect( DFInput* input ) { _inputs.removeSwap( input ); } /*----- data members -----*/ Vector<DFInput*> _inputs; }; /*============================================================================== CLASS DFInput ==============================================================================*/ class DFInput: public DFSocket { public: DFInput( DFNode* n ): _node( n ) {} DFNode* node() const { return _node; } virtual bool isConnected() const = 0; virtual bool isMulti() const { return false; } protected: /*----- friends -----*/ friend class DFGraph; /*----- methods -----*/ virtual void connect( DFOutput* ) = 0; virtual void disconnect( DFOutput* ) = 0; virtual void disconnect() = 0; void disconnectFrom( DFOutput* output ) { output->disconnect( this ); } /*----- data members -----*/ DFNode* _node; }; /*============================================================================== CLASS DFNodeEditor ==============================================================================*/ //! An editing context for a particular edit node. //! This is meant to be subclassed in order to offer a more complete //! interface. class DFNodeEditor: public RCObject { public: /*----- methods -----*/ PLASMA_DLL_API DFNodeEditor(); PLASMA_DLL_API virtual ~DFNodeEditor(); // UI. PLASMA_DLL_API virtual RCP<Manipulator> manipulator(); PLASMA_DLL_API virtual RCP<DFNodeAttrList> attributes() const; PLASMA_DLL_API virtual RCP<DFNodeAttrStates> attributesStates() const; PLASMA_DLL_API virtual void updateAttributes( const DFNodeAttrStates& ); }; //class DFNodeEditor /*============================================================================== CLASS DFNode ==============================================================================*/ class DFNode: public RCObject { public: /*----- methods -----*/ PLASMA_DLL_API DFNode(); DFGraph* graph() const { return _graph; } DFSocket::Type type() const { return output()->type(); } // Attributes. PLASMA_DLL_API virtual const ConstString& name() const = 0; PLASMA_DLL_API const String& label() const; PLASMA_DLL_API const DFNodeSpec& spec() const; PLASMA_DLL_API virtual bool isGraph() const; // Input/output. PLASMA_DLL_API virtual uint numInputs() const; PLASMA_DLL_API virtual DFOutput* output(); PLASMA_DLL_API virtual DFInput* input( uint ); const DFOutput* output() const { return const_cast<DFNode*>(this)->output(); } const DFInput* input( uint i ) const { return const_cast<DFNode*>(this)->input(i); } PLASMA_DLL_API bool hasConnectedInput(); PLASMA_DLL_API bool hasConnectedOutput(); // Editor. PLASMA_DLL_API virtual RCP<DFNodeEditor> edit(); // Appearence. const Vec2i& position() const { return _position; } int width() const { return _width; } // Dumping. PLASMA_DLL_API bool dump ( TextStream& os, StreamIndent& indent ) const; PLASMA_DLL_API bool dumpBegin ( TextStream& os, StreamIndent& indent ) const; PLASMA_DLL_API virtual bool dumpCustom( TextStream& os, StreamIndent& indent ) const; PLASMA_DLL_API bool dumpEnd ( TextStream& os, StreamIndent& indent ) const; protected: /*----- friends -----*/ friend class DFGraph; /*----- data members -----*/ DFGraph* _graph; Vec2i _position; int _width; }; /*============================================================================== CLASS DFNodeSpec ==============================================================================*/ class DFNodeSpec: public RCObject { public: /*----- types -----*/ typedef RCP<DFNode> (*CreateVMFunc)( VMState* vm, int idx ); /*----- static methods -----*/ PLASMA_DLL_API static const DFNodeSpec* get( const ConstString& name ); PLASMA_DLL_API static void getAll( Vector<const DFNodeSpec*>& dst ); PLASMA_DLL_API static bool registerNode( DFSocket::Type type, const ConstString& name, CreateVMFunc createFunc, const String& label, const String& info, const String& icon ); PLASMA_DLL_API static bool unregisterNode( const ConstString& name ); PLASMA_DLL_API static void unregisterAll(); /*----- methods -----*/ inline const char* typeName() const { return DFSocket::toStr( _type ); } inline DFSocket::Type type() const { return _type; } inline const ConstString& name() const { return _name; } inline const String& label() const { return _label; } inline const String& info() const { return _info; } inline const String& icon() const { return _icon; } inline RCP<DFNode> create( VMState* vm, int idx ) const { return _createFunc( vm, idx ); } protected: /*----- data members -----*/ DFSocket::Type _type; //!< Output type. ConstString _name; //!< A unique type name. CreateVMFunc _createFunc; //!< A creation callback routine. String _label; //!< The node's label. String _info; //!< An information string (optional). String _icon; //!< The resource ID of an icon (optional). }; //class DFNodeSpec /*============================================================================== CLASS DFSelection ==============================================================================*/ template< typename T > class DFSelection { public: /*----- types -----*/ typedef Set<T> EntryContainer; typedef typename EntryContainer::ConstIterator ConstIterator; /*----- methods -----*/ inline DFSelection() {} inline void clear() { _entries.clear(); _last = T(); } inline bool empty() const { return _entries.empty(); } inline uint numEntries() const { return uint(_entries.size()); } inline const T& last() const { return _last; } inline ConstIterator begin() const { return _entries.begin(); } inline ConstIterator end() const { return _entries.end(); } inline bool has( const T& p ) const { return _entries.has(p); } inline void add( const T& p ) { _entries.add(p); _last = p; } inline void set( const T& p ) { clear(); add(p); _last = p; } inline void remove( const T& p ) { _entries.remove(p); if( p == _last ) { // Choose one arbitrarily. if( _entries.empty() ) _last = T(); else _last = *begin(); } } inline bool toggle( const T& p ) { if( _entries.has(p) ) { remove(p); return false; } else { add(p); return true; } } protected: /*----- data members -----*/ T _last; EntryContainer _entries; }; NAMESPACE_END #endif
5e4688d985c5a29202feab00f9ffae1d227a7a1d
043d7fb043a1469681f070cad1b3e96786b4f0df
/Shared/Source/Game/BaseScene.cpp
41f1dfcb2c5494802665354df53a7c32cf8e2f73
[]
no_license
Anolog/Game_Engine
b2a37f7a25679e911142922f26ab729c208f97f8
67ccdf9cf2f6dc476bd223374f4ddbf695b980d4
refs/heads/master
2021-08-14T23:06:34.325803
2017-11-17T00:30:07
2017-11-17T00:30:07
111,037,557
1
0
null
null
null
null
UTF-8
C++
false
false
10,034
cpp
BaseScene.cpp
#include "pch.h" #include "BaseScene.h" //Use this num to create unique names for all the turret bullets for multiple turrets static int TURRET_NUM = 0; BaseScene::BaseScene(GameCore* pGame, ResourceManager* pResources) : Scene(pGame, pResources) { SaveManager = new SaveScene(this); m_pSoundGuy = new SoundManager(); m_UpdatingWhileInStack = true; m_Score = 0; m_ScoreTimer = 0; m_ButtonTimer = 0; m_MusicChannel = 0; m_Muted = false; m_MutedMusic = false; } BaseScene::~BaseScene() { if (SaveManager != nullptr) { delete SaveManager; SaveManager = nullptr; } if (m_pSoundGuy != nullptr) { delete m_pSoundGuy; m_pSoundGuy = nullptr; } } void BaseScene::LoadContent() { Scene::LoadContent(); m_pSoundGuy->initialize(); //debugdraw -> Change to toggle key later m_pGame->SetDebugDrawEnabled(true); m_MusicChannel = m_pSoundGuy->playSound(Sound_Music); //comment this out to stop music //SoundGuy->stopSound(musicChannel); // create our shaders. m_pResources->AddShader("White", new ShaderProgram("Data/Shaders/white.vert", "Data/Shaders/white.frag")); m_pResources->AddShader("Lighting", new ShaderProgram("Data/Shaders/Lighting.vert", "Data/Shaders/Lighting.frag")); //CubeMap Shader m_pResources->AddShader("CubeS", new ShaderProgram("Data/Shaders/Cube.vert", "Data/Shaders/Cube.frag")); //Cube Reflection m_pResources->AddShader("CubeReflection", new ShaderProgram("Data/Shaders/CubeReflection.vert", "Data/Shaders/CubeReflection.frag")); //Number Shader m_pResources->AddShader("Font", new ShaderProgram("Data/Shaders/font.vert", "Data/Shaders/font.frag")); // create meshes. //inverted faced cube mesh m_pResources->AddMesh("Cube", Mesh::SkyCube(vec3(5, 5, 5), vec2(1.0f, 1.0f), true)); //reflection m_pResources->AddMesh("Reflection", Mesh::CreateCube(vec3(5, 5, 5))); // name, location // load our textures. m_pResources->AddTexture("Megaman", LoadTexture("Data/Textures/Megaman.png")); m_pResources->AddTexture("TestPlayer", LoadTexture("Data/Textures/Player.png")); m_pResources->AddTexture("JumpingEnemy", LoadTexture("Data/Textures/JumpingEnemy.png")); m_pResources->AddTexture("Bullet", LoadTexture("Data/Textures/Meteor.png")); m_pResources->AddTexture("Numbers", LoadTexture("Data/Textures/Numbers.png")); m_pResources->AddTexture("Turret", LoadTexture("Data/Textures/Turret.png")); m_pResources->AddTexture("Floor", LoadTexture("Data/Textures/Floor1.png")); m_pResources->AddTexture("Pizza", LoadTexture("Data/Textures/Pizza.png")); //cube map textures //order //#define GL_TEXTURE_CUBE_MAP_POSITIVE_X 0x8515 //#define GL_TEXTURE_CUBE_MAP_NEGATIVE_X 0x8516 //#define GL_TEXTURE_CUBE_MAP_POSITIVE_Y 0x8517 //#define GL_TEXTURE_CUBE_MAP_NEGATIVE_Y 0x8518 //#define GL_TEXTURE_CUBE_MAP_POSITIVE_Z 0x8519 //#define GL_TEXTURE_CUBE_MAP_NEGATIVE_Z 0x851A const char* CubeFileNames[6]; CubeFileNames[0] = "Data/Textures/posx.png"; CubeFileNames[1] = "Data/Textures/negx.png"; CubeFileNames[2] = "Data/Textures/posy.png"; CubeFileNames[3] = "Data/Textures/negy.png"; CubeFileNames[4] = "Data/Textures/posz.png"; CubeFileNames[5] = "Data/Textures/negz.png"; m_pResources->AddTexture("CubeTexture", LoadTextureCubemap(CubeFileNames)); // create some game objects. { //create the game's skybox. m_pGameObjects["Skybox"] = new GameObject(this, "Skybox", vec3(0, 0, 0), vec3(0, 0, 0), vec3(1, 1, 1), "Cube", "CubeS", "CubeTexture"); m_pGameObjects["Skybox"]->setType("Skybox"); m_pGameObjects["Skybox"]->SetRenderOrder(0); m_pGameObjects["Reflection1"] = new Collectable(this, "Reflection1", vec3(0,1, 0), vec3(0, 0, 0), vec3(0.2, 0.2, 0.2), "Reflection", "CubeReflection", "CubeTexture",500); m_pGameObjects["Reflection1"]->AddPhysicsBox(vec2(0.75f, 0.75f), false, true, 1.0f, CATEGORY_PICKUP, MASK_PICKUP, true); m_pGameObjects["Reflection1"]->SetRenderOrder(1); // Camera //Swap to follow camera - Copy previous files over m_pGameObjects["Camera"] = new WindowCameraObject(this, "Camera", Vector3(0, 0, -15), Vector3(0, 0, 0), Vector3(1, 1, 1), 0, 0, 0); m_pGameObjects["Camera"]->SetPosition(vec3(0, 0, -15)); // player m_pGameObjects["Player"] = new PlayerObject(this, "Player", vec3(-5, 0, 0), vec3(0, 0, 0), vec3(1, 1, 1), "Sprite", "Font", "TestPlayer"); ((PlayerObject*)m_pGameObjects["Player"])->SetController(m_pGame->GetController(0)); m_pGameObjects["Player"]->AddPhysicsBox(vec2(0.75f, 0.75f), true, true, 1.0f, CATEGORY_PLAYER, MASK_PLAYER); //Make player unable to rotate m_pGameObjects["Player"]->GetPhysicsBody()->SetFixedRotation(true); m_pGameObjects["Player"]->SetRenderOrder(2); m_pGameObjects["Turret"] = new TurretEnemy(this, "Turret", vec3(6, 0, 0), vec3(0, 0, 0), vec3(1, 1, 1), "Sprite", "Texture", "Turret", TURRET_NUM); TURRET_NUM++; m_pGameObjects["Turret"]->SetRenderOrder(1); m_pGameObjects["Jumper"] = new JumpingEnemy(this, "Jumper", vec3(3.5, 0.5, 0), vec3(0, 0, 0), vec3(1, 1, 1), "Sprite", "Font", "JumpingEnemy"); m_pGameObjects["Jumper"]->AddPhysicsBox(vec2(0.75f, 0.75f), true, true, 1.0f, CATEGORY_ENEMY, MASK_ENEMY); m_pGameObjects["Jumper"]->GetPhysicsBody()->SetFixedRotation(true); m_pGameObjects["Jumper"]->SetRenderOrder(2); m_pGameObjects["Coin"] = new Collectable(this, "Coin", vec3(-1, 0.5, 0), vec3(0, 0, 0), vec3(1, 1, 1), "Sprite", "Lighting", "Pizza", 300); m_pGameObjects["Coin"] = new Collectable(this, "Coin", vec3(-1, 0.5, 0), vec3(0, 0, 0), vec3(1, 1, 1), "Sprite", "Lighting", "Pizza", 1111); m_pGameObjects["Coin"] = new Collectable(this, "Coin", vec3(-1, 0.5, 0), vec3(0, 0, 0), vec3(1, 1, 1), "Sprite", "Texture", "Pizza", 1111); m_pGameObjects["Coin"]->AddPhysicsCircle(0.5f, false, true, 1.0f, CATEGORY_PICKUP, MASK_PICKUP, true); //Create base ground m_pGameObjects["Ground"] = new GameObject(this, "Ground", vec3(0, -5, 0), vec3(0, 0, 0), vec3(50, 1, 1), "Sprite", "Lighting", "Floor"); m_pGameObjects["Ground"]->AddPhysicsBox(vec2(50, 1), false, true, 1.0f, CATEGORY_GROUND, MASK_GROUND_NO_BULLETS); m_pGameObjects["Ground"]->SetRenderOrder(1); // UI m_pGameObjects["Number1000s"] = new GameObject(this, "Number1000s", vec3(-3, -1, -5), vec3(0, 0, 0), vec3(0.5, 0.5, 0.5), "Sprite", "Font", "Numbers"); //pushed forward in z m_pGameObjects["Number100s"] = new GameObject(this, "Number100s", vec3(-1, -1, -5), vec3(0, 0, 0), vec3(0.5, 0.5, 0.5), "Sprite", "Font", "Numbers"); m_pGameObjects["Number10s"] = new GameObject(this, "Number10s", vec3(1, -1, -5), vec3(0, 0, 0), vec3(0.5, 0.5, 0.5), "Sprite", "Font", "Numbers"); m_pGameObjects["Number1s"] = new GameObject(this, "Number1s", vec3(3, -1, -5), vec3(0, 0, 0), vec3(0.5, 0.5, 0.5), "Sprite", "Font", "Numbers"); m_pGameObjects["Number1000s"]->SetRenderOrder(2); m_pGameObjects["Number100s"]->SetRenderOrder(2); m_pGameObjects["Number10s"]->SetRenderOrder(2); m_pGameObjects["Number1s"]->SetRenderOrder(2); /* m_pGameObjects["Wall"] = new GameObject(this, "Wall", vec3(5, -2, 0), vec3(0, 0, 90), vec3(10, 1, 1), "Sprite", "Lighting", "Player"); m_pGameObjects["Wall"]->AddPhysicsBox(vec2(10, 1), false, true, 1.0f, CATEGORY_GROUND, MASK_GROUND_NO_BULLETS); m_pGameObjects["Wall"]->SetRenderOrder(1); */ } CheckForGLErrors(); } void BaseScene::RebuildOpenGLContent() { Scene::RebuildOpenGLContent(); m_pResources->GetShader("Texture")->Reload(); Mesh::CreateBox(vec2(1, 1), false, m_pResources->GetMesh("Sprite")); Mesh::CreateBox(vec2(1, 1), true, m_pResources->GetMesh("SpriteReversed)")); } void BaseScene::Update(float deltatime) { if (m_UpdatingWhileInStack) { Scene::Update(deltatime); { int temp1000s = (int)GetScore() / 1000; int temp100s = (int)(GetScore() - (temp1000s * 1000)) / 100; int temp10s = (int)((GetScore() - (temp1000s * 1000) - (temp100s * 100)) / 10); int temp1s = (int)(GetScore() - (temp1000s * 1000) - (temp100s * 100) - temp10s * 10); m_pGameObjects["Number1000s"]->SetFrame(temp1000s); m_pGameObjects["Number100s"]->SetFrame(temp100s); m_pGameObjects["Number10s"]->SetFrame(temp10s); m_pGameObjects["Number1s"]->SetFrame(temp1s); //update UI movement m_pGameObjects["Number1000s"]->SetPosition(vec3(m_pGameObjects["Camera"]->GetPosition().x + 2 - 1.0f, m_pGameObjects["Camera"]->GetPosition().y + 3.5f, m_pGameObjects["Number1000s"]->GetPosition().z)); m_pGameObjects["Number100s"]->SetPosition(vec3(m_pGameObjects["Camera"]->GetPosition().x + 2 - 0.5f, m_pGameObjects["Camera"]->GetPosition().y + 3.5f, m_pGameObjects["Number1000s"]->GetPosition().z)); m_pGameObjects["Number10s"]->SetPosition(vec3(m_pGameObjects["Camera"]->GetPosition().x + 2 + 0.0f, m_pGameObjects["Camera"]->GetPosition().y + 3.5f, m_pGameObjects["Number1000s"]->GetPosition().z)); m_pGameObjects["Number1s"]->SetPosition(vec3(m_pGameObjects["Camera"]->GetPosition().x + 2 + 0.5f, m_pGameObjects["Camera"]->GetPosition().y + 3.5f, m_pGameObjects["Number1000s"]->GetPosition().z)); } //load and save if (g_KeyStates['N']) { m_ButtonTimer += deltatime; if (m_ButtonTimer >= 0.1) { if (m_Muted == false) { m_pSoundGuy->MuteSound(); m_Muted = true; m_MutedMusic = true; } else { m_pSoundGuy->UnMuteSound(); m_Muted = false; m_MutedMusic = false; } m_ButtonTimer = 0; } } if (g_KeyStates['M']) { m_ButtonTimer += deltatime; if (m_ButtonTimer >= 0.1) { if (m_MutedMusic == false) { m_pSoundGuy->MuteMusic(m_MusicChannel); m_MutedMusic = true; } else { m_pSoundGuy->UnMuteMusic(m_MusicChannel); m_MutedMusic = false; } m_ButtonTimer = 0; } } if (g_KeyStates['Z']) SaveManager->LoadState(); if (g_KeyStates['X']) SaveManager->SaveState(); //OutputMessage("Camera pos: %f , %f \n", m_pGameObjects["Camera"]->GetPosition().x, m_pGameObjects["Camera"]->GetPosition().y); } } void BaseScene::Draw() { Scene::Draw(); CheckForGLErrors(); }
eaa55931c3b9996355ccf2357da49895b45ced94
33fd37df43086fa8a5f1942c5e3ab70cbe00614b
/code/graphics_uniform_buffer.cpp
57e970821060cdde72d993aaa3dfd1fe02f40530
[]
no_license
aod6060/vulkan_ping
0ed2f24665f527a7e2ce24ee3e5aba9c78b20e82
7b2db39a2a7235c8fce7d030689958c9371b0df4
refs/heads/master
2022-08-04T02:05:08.344010
2020-05-21T07:33:13
2020-05-21T07:33:13
265,483,209
0
0
null
null
null
null
UTF-8
C++
false
false
3,026
cpp
graphics_uniform_buffer.cpp
#include "sys.h" // Uniform Buffer void VulkanRender::createUniformBuffer() { VkResult r; // Size size_t s = sizeof(UniformVS); // Buffer // Create Buffer this->createBuffer( &this->uniformBuffer, &this->uniformDeviceMemory, s, VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_TRANSFER_SRC_BIT, VK_SHARING_MODE_EXCLUSIVE, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT ); // Upload Buffer this->uploadBufferData(&this->uniformDeviceMemory, &this->uniformVS, sizeof(UniformVS)); // uniform desc layout set // Vertex Shader UBOs VkDescriptorSetLayoutBinding descSetLayoutBinding = {}; descSetLayoutBinding.binding = 0; descSetLayoutBinding.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER; descSetLayoutBinding.descriptorCount = 1; descSetLayoutBinding.stageFlags = VK_SHADER_STAGE_VERTEX_BIT; // Vertex Descriptor Create Info VkDescriptorSetLayoutCreateInfo createInfo = {}; createInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO; createInfo.bindingCount = 1; createInfo.pBindings = &descSetLayoutBinding; r = vkCreateDescriptorSetLayout(this->device, &createInfo, nullptr, &this->uniformDescLayoutSet); if (r != VK_SUCCESS) { std::runtime_error("failed to create vertex desc set layout"); } // uniform desc set // Uniform Allocation VkDescriptorSetAllocateInfo descSetAllocInfo = {}; descSetAllocInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO; descSetAllocInfo.descriptorPool = this->descPool; descSetAllocInfo.descriptorSetCount = 1; descSetAllocInfo.pSetLayouts = &this->uniformDescLayoutSet; r = vkAllocateDescriptorSets(this->device, &descSetAllocInfo, &this->uniformDescSet); if (r != VK_SUCCESS) { std::runtime_error("failed to allocate desc set"); } // Update Desc Sets // Descriptor Buffer Info VkDescriptorBufferInfo bufferInfo = {}; bufferInfo.buffer = uniformBuffer; bufferInfo.offset = 0; bufferInfo.range = sizeof(UniformVS); // Uniform Write Desc Set VkWriteDescriptorSet uniformDescWrite = {}; uniformDescWrite.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; uniformDescWrite.dstSet = this->uniformDescSet; uniformDescWrite.dstBinding = 0; uniformDescWrite.dstArrayElement = 0; uniformDescWrite.descriptorCount = 1; uniformDescWrite.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER; uniformDescWrite.pBufferInfo = &bufferInfo; std::vector<VkWriteDescriptorSet> writes = { uniformDescWrite }; vkUpdateDescriptorSets(device, writes.size(), writes.data(), 0, nullptr); } void VulkanRender::destroyUniformBuffer() { vkFreeDescriptorSets(this->device, this->descPool, 1, &this->uniformDescSet); vkDestroyDescriptorSetLayout(device, this->uniformDescLayoutSet, nullptr); vkFreeMemory(this->device, this->uniformDeviceMemory, nullptr); vkDestroyBuffer(this->device, this->uniformBuffer, nullptr); } void VulkanRender::updateUniformBuffer() { this->uploadBufferData( &this->uniformDeviceMemory, &this->uniformVS, sizeof(UniformVS) ); }
e1f24047eaa128083f5fdfd7f6e8d001f276d465
599f210e9a3aee1628eec9d853223b01cb06f9e2
/addons/zylann.hterrain/src/height_map_mesher.h
e253810d84b13fab338565bf3aca9fde2e1e33d2
[ "MIT" ]
permissive
blockspacer/GodotMonoVoxel
ee9fa31061bf595de9f08f6dd9949e2170c0be19
615dfb1cdf97a6ce5faaad0685dfea7043d90231
refs/heads/master
2020-12-19T23:23:33.783242
2019-04-23T04:17:20
2019-04-23T04:17:20
235,882,639
1
1
null
2020-01-23T20:42:24
2020-01-23T20:42:23
null
UTF-8
C++
false
false
956
h
height_map_mesher.h
#ifndef HEIGHT_MAP_MESHER_H #define HEIGHT_MAP_MESHER_H #include <core/Ref.hpp> #include <core/PoolArrays.hpp> #include <Mesh.hpp> #include <ArrayMesh.hpp> #include "util/point2i.h" class HeightMapMesher { public: enum SeamFlag { SEAM_LEFT = 1, SEAM_RIGHT = 2, SEAM_BOTTOM = 4, SEAM_TOP = 8, SEAM_CONFIG_COUNT = 16 }; HeightMapMesher(); void configure(Point2i chunk_size, int lod_count); godot::Ref<godot::ArrayMesh> get_chunk(int lod, int seams); private: void precalculate(); godot::Ref<godot::ArrayMesh> make_flat_chunk(Point2i chunk_size, int stride, int seams); godot::PoolIntArray make_indices(Point2i chunk_size, unsigned int seams); private: // TODO This is an internal limit. Need vector for non-POD types heh static const size_t MAX_LODS = 16; // [seams_mask][lod] godot::Ref<godot::ArrayMesh> _mesh_cache[SEAM_CONFIG_COUNT][MAX_LODS]; int _mesh_cache_size; Point2i _chunk_size; }; #endif // HEIGHT_MAP_MESHER_H
2328119c0a9448655c67c1ced1019720846fad07
1fe10ee5e34cd76067c720ef4b4a054f6107b286
/mobile/mobile/src/chill/common/opera_switches.h
1dcf8c699c8b3771c8c4e27c1006f9e6fd953a3d
[ "BSD-2-Clause" ]
permissive
bopopescu/ofa
9f001c4f36b07fa27347ade37337422fd6719dcc
84e319101d4a1200657337dcdf9ed3857fc59e03
refs/heads/master
2021-06-14T08:53:05.865737
2017-04-03T12:50:44
2017-04-03T12:50:44
null
0
0
null
null
null
null
UTF-8
C++
false
false
871
h
opera_switches.h
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // // Modified by Opera Software ASA // @copied-from chromium/src/content/shell/shell_switches.h // @final-synchronized // Defines all the opera mobile command-line switches. #ifndef CHILL_COMMON_OPERA_SWITCHES_H_ #define CHILL_COMMON_OPERA_SWITCHES_H_ namespace switches { extern const char kEnableRemoteDebugging[]; extern const char kNetLogLevel[]; extern const char kUserAgent[]; extern const char kBypassAppBannerEngagementChecks[]; // Duplicated in src/com/opera/android/BrowserSwitches.java as // CUSTOM_ARTICLE_PAGE_SERVER extern const char kCustomArticleTranscodingServer[]; extern const char kDisableTileCompression[]; } // namespace switches #endif // CHILL_COMMON_OPERA_SWITCHES_H_
bc951905c8d357aa6050c974e596042abb5cc403
360f5513b6059bc2ec7baf24e1349d6225798665
/examples/cpp/stl_export.cpp
40da058e2e00bfda19223d382f1c537c00642fee
[ "Zlib" ]
permissive
theoathanasiadis/archmind
d188ca44eb656923a41b823f772e8243ac670a23
8bd3ed7448f052698e0ce599fb2ce96611b9f708
refs/heads/master
2020-05-19T11:48:57.234546
2014-10-17T18:07:51
2014-10-17T18:07:51
33,659,073
0
1
null
null
null
null
UTF-8
C++
false
false
2,790
cpp
stl_export.cpp
/* Archmind Non-manifold Geometric Kernel Copyright (C) 2010 Athanasiadis Theodoros This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ //Custom stl exporter example #include "Geometry/Geometry.h" #include "Io/Io.h" using namespace arch::geometry; typedef mesh<> mesh_t; //Stl exporter class template<typename mesh_t> struct Stl { bool can_read(const std::string &filename)const { return filename.find(".stl") != std::string::npos || filename.find(".STL") != std::string::npos; } bool write(const std::string &filename, const mesh_t &m) { std::ofstream Stream(filename.c_str()); if( !Stream ) { std::cerr << "Failed to open : " << filename << " for parsing\n"; return false; } Stream << "solid Archmind\n"; for( typename mesh_t::face_iterator_t f = m.faces_begin(); f != m.faces_end(); ++f ) { Stream << " facet normal " << (*f)->normal() << "\n"; Stream << " outer loop\n"; for( typename mesh_t::face_t::vertex_iterator_t v = (*f)->verts_begin(); v != (*f)->verts_end(); ++v ) Stream << " vertex " << (*v)->point() << "\n"; Stream << " endloop\n"; Stream << " endfacet\n"; } Stream << "endsolid Archmind\n"; return true; } }; //Register custom stl exporter, classes are expected to implement can_read,write namespace arch{ namespace io{ template<> struct writer_traits<mesh_t> { typedef boost::mpl::vector< Stl<mesh_t> > type; }; }} int main(int argc, char **argv) { mesh_t mymesh; if( argc != 3 ) { std::cout << argv[0] << " : " << "[input] [output.stl] \n"; return 1; } arch::io::load_from_file(argv[1],mymesh); arch::io::save_to_file(argv[2],mymesh); return 0; }
8bc835e8c3bfe25af3144b7521fd291cb38ffcd5
b34039a3a8f159c1f6d896fd77d0d9400edd391f
/Informatik 1/Praktikum/Blatt 2/ostern.cpp
9894e92a08957233f82b11dfbec2662678e17ecf
[]
no_license
Nirusu/uni_assignments
82ab2482bbc7bd528510f131d3b568d2d4f1c6a2
e4a8616e75fc5e8ec53bbb29d87fae5dac892717
refs/heads/master
2021-10-08T09:43:41.801666
2018-12-06T16:45:15
2018-12-06T16:45:15
85,975,706
0
0
null
null
null
null
UTF-8
C++
false
false
1,101
cpp
ostern.cpp
/* * ostern.cpp * Ein Programm zur Berechnung des Datums des Ostersonntags * fuer ein vorgegebenes Jahr */ #include<iostream> using namespace std; int main() { // Variablen nach http://de.wikipedia.org/wiki/Gau%C3%9Fsche_Osterformel // (Gregorianischer Kalender) int Jahr = 2084; int Ostern; int a, b, c, d, e, k, p, q, N, M; //++++++++++++++++++++++++++++++++++++++++++++ // Hier bitte die Berechnungsfolge einfuegen: a = Jahr % 19; b = Jahr % 4; c = Jahr % 7; k = Jahr / 100; p = (8*k + 13) / 25; q = k / 4; M = (15 + k - p - q) % 30; d = (19*a + M) % 30; N = (4 + k - q) % 7; e = (2*b + 4*c + 6*d + N) % 7; Ostern = (22 + d + e); //++++++++++++++++++++++++++++++++++++++++++++ cout << "Der Ostersonntag ist am "; if (Ostern <= 31) cout << Ostern << ". Maerz " << Jahr << endl; else cout << (Ostern - 31) << ". April " << Jahr << endl; return 0; }
235a3bc1708076111669d143607b50f808a204b1
d1b19a18a2181b9a1897569aba2633552fbc0e93
/Training/LeetCode/ProblemSet/0528/yuange528.cpp
a58770194d7268e8cfb876a6a76d2db3fdcb2458
[]
no_license
ygtxr1997/AlgorithmLearningTraining
bf20702a929d886652cb7691f4f791aadd8a0c2a
dacefc52161ecac1632963ae43ccffa7b94e9889
refs/heads/master
2021-05-19T05:15:32.493999
2020-06-15T08:40:56
2020-06-15T08:40:56
251,542,778
0
0
null
null
null
null
UTF-8
C++
false
false
539
cpp
yuange528.cpp
class Solution { public: int mx = 0; vector<int> hash; Solution(vector<int>& w) { for (int num : w) { mx += num; hash.push_back(mx - 1); } srand((unsigned)time(NULL)); } int pickIndex() { int r = rand() % mx; int pos = lower_bound(hash.begin(), hash.end(), r) - hash.begin(); return pos; } }; /** * Your Solution object will be instantiated and called as such: * Solution* obj = new Solution(w); * int param_1 = obj->pickIndex(); */
cdda72647f7ebc2cfc149bb9f2ef5774b4e0ef0b
568fe4582d34a2f7e0e16a2eed26502b70b7aeb5
/DocumentFile.h
fe40bb2e313f7d72ec9951432f4314c78a5ebf82
[]
no_license
zhitaop/DocumentDialogApp
5d128c460a3a07caab78e97110e90035dbf9509d
bac93dfc61ae81a3ef362f7d80d0557b10abaf9c
refs/heads/master
2022-11-20T04:25:55.485149
2020-06-25T01:02:22
2020-06-25T01:02:22
279,491,736
0
0
null
2020-07-14T05:32:08
2020-07-14T05:32:07
null
UTF-8
C++
false
false
1,998
h
DocumentFile.h
//---------------------------------------------------------------------- // //---------------------------------------------------------------------- #ifndef __DocumentFile__ #define __DocumentFile__ //---------------------------------------------------------------------- // //---------------------------------------------------------------------- #include "AndroidObject.h" //---------------------------------------------------------------------- // //---------------------------------------------------------------------- class DocumentFile : public AndroidObject { public: DocumentFile(QAndroidJniEnvironment& env, QAndroidJniObject obj = QAndroidJniObject()); DocumentFile(DocumentFile&& other); DocumentFile(DocumentFile& other); virtual ~DocumentFile(); static const char* JCLASS; static DocumentFile fromSingleUri(QAndroidJniEnvironment& env, const QString& uri); static DocumentFile fromTreeUri(QAndroidJniEnvironment& env, const QString& treeUri); static DocumentFile fromUri(QAndroidJniEnvironment& env, const QString& uri); static bool isDocumentUri(QAndroidJniEnvironment& env, const QString& uri); DocumentFile createFile(const QString& mimeType, const QString& displayName) const; DocumentFile createDirectory(const QString& displayName) const; QString getUri() const; QString getName() const; QString getType() const; DocumentFile getParentFile() const; bool isDirectory() const; bool isFile() const; bool isVirtual() const; qint64 lastModified() const; qint64 length() const; bool canRead() const; bool canWrite() const; bool deleteFile() const; bool exists() const; QStringList listFiles() const; DocumentFile findFile(const QString& displayName) const; bool renameTo(const QString& displayName) const; }; #endif //---------------------------------------------------------------------- // //----------------------------------------------------------------------
788186678db1686cd2e55f7a342223b4ff7e71eb
407f7e43dd3b41a24b414ca018ada6cfbcd0ff8d
/数学/二次剩余.cpp
1986915844e1161e2e301a3497d31c1813910f7f
[]
no_license
cddchen/algorithm
1661447fdede32de22854f5623132504cf5272bb
fb1d8a08dc44b42e105a95a97064668ef223e6d4
refs/heads/master
2020-12-01T09:11:52.135525
2020-02-29T14:54:15
2020-02-29T14:54:15
230,598,939
0
0
null
null
null
null
UTF-8
C++
false
false
1,614
cpp
二次剩余.cpp
#include <bits/stdc++.h> using namespace std; typedef long long ll; #define random(a,b) (rand()%(b-a+1)+a) ll quickmod(ll a, ll b, ll c) { ll ans = 1; while (b) { if (b & 1) ans = ans * a % c; b >>= 1; a = a * a % c; } return ans; } ll p, w; struct QuadraticField { ll x, y; QuadraticField operator *(QuadraticField T) { QuadraticField rhs; rhs.x = (this->x * T.x % p + this->y * T.y % p * w % p) % p; rhs.x = (rhs.x + p) % p; rhs.y = (this->x * T.y % p + this->y * T.x % p) % p; rhs.y = (rhs.y + p) % p; return rhs; } QuadraticField operator ^(ll b) { QuadraticField rhs; QuadraticField a = *this; rhs.x = 1; rhs.y = 0; while (b) { if (b & 1) rhs = rhs * a; b >>= 1; a = a * a; } return rhs; } }; ll Legender(ll a) { ll rhs = quickmod(a, (p - 1) / 2, p); if (rhs + 1 == p) return -1; else return rhs; } ll get_w(ll n, ll a) { return ((a * a % p - n) % p + p) % p; } ll solve(ll n) { ll a; if (p == 2) return n; if (Legender(n) == -1) return -1; srand((unsigned)time(NULL)); while (true) { a = random(0, p - 1); w = get_w(n, a); if (Legender(w) == -1) break; } QuadraticField ans, rhs; rhs.x = a; rhs.y = 1; ans = rhs ^ ((p + 1) / 2); return ans.x; } int main() { int t; scanf("%d", &t); while (t--) { ll n; scanf("%lld%lld", &n, &p); n %= p; if (n == 0) printf("0\n"); else { ll ans1 = solve(n), ans2; if (ans1 == -1) printf("Hola!\n"); else { ans2 = p - ans1; if (ans1 == ans2) printf("%lld\n", ans1); else printf("%lld %lld\n", min(ans1, ans2), max(ans1, ans2)); } } } }
abfa246759a0fbaea81c8b41627716c05f7dd786
f90547b3689474a9d97143f90c3ddfc965c583da
/Sorting/sort.cpp
ab9714c73591e027185b987792f9ae857a922549
[]
no_license
lindsay0416/DSA
fbe4716d4c295ca6e66c1de870ca0740460cd2c4
d6961f70c29be0c695573c66a87297a2e355de80
refs/heads/master
2020-06-18T01:20:50.256568
2019-07-10T02:59:47
2019-07-10T02:59:47
196,113,634
0
0
null
null
null
null
UTF-8
C++
false
false
2,944
cpp
sort.cpp
// Example program #include <iostream> #include <string> void swap(int *a, int *b) { int temp = *a; *a = *b; *b = temp; } void printOut(const char* sortType, int array[], int iteration) { printf("%s iterations: %d\n", sortType, iteration); printf("Sorted array: \n"); for (int i = 0; i < 1000; i++) { printf("array[%d] =%d \n", i, array[i]); } printf("============================\n"); } // bubble sort int* bubbleSort(int array[], int len) { int i, j; for (i = 0; i < len - 1; i++) { for (j = i + 1; j < len; j++) { if (array[i] > array[j]) { swap(&array[i], &array[j]); } } } return array; } int bubbleSortIteration(int array[], int len) { int i, j, iteration; for (i = 0; i < len - 1; i++) { for (j = i + 1; j < len; j++) { if (array[i] > array[j]) { swap(&array[i], &array[j]); } iteration++; } } return iteration; } // insertion sort int* insertionSort(int array[], int len) { int i, j, num; for (i = 1; i < len; i++) { num = array[i]; j = i-1; while (j >= 0 && array[j] > num) { array[j+1] = array[j]; j = j-1; } array[j+1] = num; } return array; } int insertionSortIteration(int array[], int len) { int i, j, num, iteration; for (i = 1; i < len; i++) { num = array[i]; j = i-1; while (j >= 0 && array[j] > num) { array[j+1] = array[j]; j = j-1; } array[j+1] = num; iteration++; } return iteration; } // selection sort int* selectionSort(int array[], int len) { int i, j, min_idx; for (i = 0; i < len-1; i++) { min_idx = i; for (j = i+1; j < len; j++) { if (array[j] < array[min_idx]) { min_idx = j; } } swap(&array[min_idx], &array[i]); } return array; } int selectionSortIteration(int array[], int len) { int i, j, min_idx, iteration; for (i = 0; i < len-1; i++) { min_idx = i; for (j = i+1; j < len; j++) { if (array[j] < array[min_idx]) { min_idx = j; } iteration++; } swap(&array[min_idx], &array[i]); } return iteration; } int main() { int ranInt[1000]; for (int i = 0; i < 1000; i++) { ranInt[i] = rand() % 900 - 200; } int arrayLen = sizeof(ranInt) / sizeof(ranInt[0]); // bubble sort int* bubbleSortA = bubbleSort(ranInt, arrayLen); int bubbleSortI = bubbleSortIteration(ranInt, arrayLen); printOut("bubble sort", bubbleSortA, bubbleSortI); // insertion sort int* insertionSortA = insertionSort(ranInt, arrayLen); int insertionSortI = insertionSortIteration(ranInt, arrayLen); printOut("insertion sort", insertionSortA, insertionSortI); // selection sort int* selectionSortA = selectionSort(ranInt, arrayLen); int selectionSortI = selectionSortIteration(ranInt, arrayLen); printOut("selection sort", selectionSortA, selectionSortI); }
b0e85269be51af55bb2d8621cb5499716ad75219
8be083e9fbf15606201217d6c4b87c929e418065
/branches/editable-raster-objects/util/iter.hh
6db448142676914bc3f0998ece5080f0bb3ca9c2
[ "Apache-2.0" ]
permissive
BGCX067/faint-graphics-editor-svn-to-git
430768d441f3e9b353fbc128e132f7406ee48c0e
dad252f820d29ab336bcfa57138625dae6dfed60
refs/heads/master
2021-01-13T00:56:26.685520
2015-12-28T14:22:44
2015-12-28T14:22:44
48,752,914
1
1
null
null
null
null
UTF-8
C++
false
false
3,260
hh
iter.hh
// Copyright 2012 Lukas Kemmer // // Licensed under the Apache License, Version 2.0 (the "License"); you // may not use this file except in compliance with the License. You // may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or // implied. See the License for the specific language governing // permissions and limitations under the License. #ifndef FAINT_ITER_HH #define FAINT_ITER_HH #include "util/commonfwd.hh" template<typename Container> class reversed_t { private: const Container& m_container; public: reversed_t(const Container& c) : m_container(c) {} auto begin() -> decltype(m_container.rbegin()) { return m_container.rbegin(); } auto end() -> decltype(m_container.rend()) { return m_container.rend(); } private: reversed_t& operator=(const reversed_t&); }; template<typename Container> reversed_t<Container> reversed(const Container& container) { return reversed_t<Container>(container); } inline reversed_t<objects_t> top_to_bottom(const objects_t& objects){ return reversed_t<objects_t>(objects); } template<typename Container> class but_first_t { private: const Container& m_container; public: but_first_t(const Container& c) : m_container(c) {} auto begin() -> decltype(m_container.begin()) { return m_container.empty() ? m_container.end() : m_container.begin() + 1; } auto end() -> decltype(m_container.end()) { return m_container.end(); } private: but_first_t& operator=(const but_first_t&); }; template<typename Container> but_first_t<Container> but_first(const Container& container) { return but_first_t<Container>(container); } template<typename Container> class but_last_t { private: const Container& m_container; public: but_last_t(const Container& c) : m_container(c) {} auto begin() -> decltype(m_container.begin()) { return m_container.begin(); } auto end() -> decltype(m_container.end()) { return m_container.empty() ? m_container.end() : m_container.begin() + m_container.size() - 1; } private: but_last_t& operator=(const but_last_t&); }; template<typename Container> but_last_t<Container> but_last(const Container& container) { return but_last_t<Container>(container); } template<typename T> class enum_iter_t{ public: enum_iter_t(T value) : m_value(static_cast<int>(value)) // Fixme: use underlying_type {} T operator*() const{ return static_cast<T>(m_value); } void operator++(){ m_value++; } bool operator!=( const enum_iter_t& rhs ) const{ return m_value != rhs.m_value; } private: int m_value; }; template<typename T> class iterable{ public: iterable() : m_value(static_cast<int>(T::BEGIN)) {} enum_iter_t<T> begin(){ return enum_iter_t<T>(T::BEGIN); } enum_iter_t<T> end(){ return enum_iter_t<T>(T::END); } private: int m_value; // Fixme: Use underlying type }; #endif
008104287bf191524b689c728d42ee7dbc963083
e629c53a4930a844785759a9653916172348a88b
/OOP_ADT_Class_1.0/mod1.cpp
07185b43cc4fb9d40fd856295ba42fb12bdba32e
[]
no_license
DemVD/OOP
ca807473e2eb5063c97a8a3d1960f133711cfd5e
990e3be41c98ffbe70b4f6f8be6b85316ddfb1ea
refs/heads/master
2020-03-31T15:55:04.353756
2019-12-27T06:24:42
2019-12-27T06:24:42
152,356,089
0
0
null
2018-10-10T03:39:04
2018-10-10T03:13:03
null
UTF-8
C++
false
false
590
cpp
mod1.cpp
#include <math.h> #include <vector> #include "header.h" using namespace std; class Time{ public: int setHours(Hnum){ Hours = Hnum; return Hours; } int setMinutes(Mnum){ Minutes = Mnum; return Minutes; } int setSeconds(Snum){ Seconds = Snum; return Seconds; } int getTime(spec){ switch(spec){ case "Hours": return Hours; case "Minutes": return Minutes; case "Seconds": return Seconds; } } private: int Hours; int Minutes; int Seconds; };
bd5077c6a57d45e8a95fc2065a5729e457df88a1
f368e65e5a0e07f67cbcf65b7ca329315aa9051d
/extio.cc
5e31a7925393dd8ceeb0e9962567158d06c8c9db
[]
no_license
CodecupNL/Bubbles
935a5a7ac795b4f213b5a893a22cb778af4cfd83
488962bdf1e17dba34fd9e831a6d5798a6289324
refs/heads/master
2020-03-26T23:49:57.715911
2018-08-21T13:54:23
2018-08-21T13:54:23
145,570,676
0
0
null
null
null
null
UTF-8
C++
false
false
5,445
cc
extio.cc
#include <stdio.h> #include <string.h> #include <signal.h> #include <time.h> #include <sys/types.h> #include <sys/time.h> #include <sys/select.h> #include <unistd.h> //#include <sys/wait.h> #include <unistd.h> #include <curses.h> #include <stdlib.h> #include "woorden.h" #include "bord.h" #include "extio.h" int prog1pid, prog2pid; int prog1output[2], prog1input[2], prog2output[2], prog2input[2]; int prog1error[2], prog2error[2]; char prog1buf[256]; int prog1bufptr; char prog2buf[256]; int prog2bufptr; char letters[48]; int prog1_pos[48]; int prog2_pos[48]; char prog1_bord[49]; char prog2_bord[49]; char errormsg[256]; struct timeval left1, left2; void bordtoprog1(void) { int i=0; for (i=0; i<49; i++) prog1_bord[i]=bord[i]; } void bordtoprog2(void) { int i=0; for (i=0; i<49; i++) prog2_bord[i]=bord[i]; } void prog1tobord(void) { int i=0; for (i=0; i<49; i++) bord[i]=prog1_bord[i]; } void prog2tobord(void) { int i=0; for (i=0; i<49; i++) bord[i]=prog2_bord[i]; } int read_from_pipedes(int filedes[2], char *buf, int max, timeval *left) { int n; fd_set rfds; struct timeval tv, start, stop; int retval; FD_ZERO(&rfds); FD_SET(filedes[0], &rfds); tv=*left; // tv.tv_sec = 10; // tv.tv_usec = 0; gettimeofday(&start, NULL); retval=select(filedes[0]+1, &rfds, NULL, NULL, &tv); gettimeofday(&stop, NULL); left->tv_usec -= (stop.tv_usec-start.tv_usec); if (left->tv_usec<0) { left->tv_sec--; left->tv_usec+=1000000; } left->tv_sec -= (stop.tv_sec-start.tv_sec); if (left->tv_sec<0) return -2; if (retval) { n=read(filedes[0], buf, max-1); if (n<0) return -1; buf[n]='\0'; } else return -2; return n; } int read_from_pipedes_line(int *bufptr, char *buffer, int filedes[2], char *buf, int max, timeval *left) { int i, n; if (*bufptr==-1) // firstuse { n=read_from_pipedes(filedes, buffer, max, left); if (n<0) return n; *bufptr=0; } else if (buffer[*bufptr]=='\0') { n=read_from_pipedes(filedes, buffer, max, left); if (n<0) return n; *bufptr=0; } else (*bufptr)++; n=-1; if (buffer[*bufptr]=='\0' || buffer[*bufptr]=='\n') { n=read_from_pipedes(filedes, buffer, max, left); if (n<0) return n; *bufptr=0; } for (i=*bufptr; i<max; i++) { if (buffer[i]=='\n') { n=i; break; } else if (buffer[i]=='\0') { n=i; break; } } if (n==-1) n=max-1; for (i=*bufptr; i<n; i++) { buf[i-*bufptr]=buffer[i]; } buf[i-*bufptr]='\0'; n-=*bufptr; *bufptr+=n; return n; } int write_to_pipedes(int filedes[2], char *buf) { int i=0, j, n; n=strlen(buf); while (i<n) { j=write(filedes[1], buf+i, n-i); if (j<0) return j; i+=j; } return n; } void write_prog1(char *buf, int *error) { if (write_to_pipedes(prog1input, buf)<0) { strcpy(errormsg, "Error writing to pipe program 1...\n"); *error=1; } } void write_prog2(char *buf, int *error) { if (write_to_pipedes(prog2input, buf)<0) { strcpy(errormsg, "Error writing to pipe program 2...\n"); *error=2; } } void read_prog2(char *buf, int *error) { int n; if (*error) return; n=read_from_pipedes_line(&prog2bufptr, prog2buf, prog2output, buf, 256, &left2); if (n==-1) { strcpy(errormsg, "Error reading from pipe to program 2...\n"); *error=2; } else if (n==-2) { strcpy(errormsg, "Timeout program 2...\n"); *error=2; } } void read_prog1(char *buf, int *error) { int n; if (*error) return; n=read_from_pipedes_line(&prog1bufptr, prog1buf, prog1output, buf, 256, &left1); if (n==-1) { strcpy(errormsg, "Error reading from pipe to program 1...\n"); *error=1; } else if (n==-2) { strcpy(errormsg, "Timeout program 1...\n"); *error=1; } } void wread_prog2(WINDOW *scr, int x, char *buf, int *error) { int n; if (*error) return; n=read_from_pipedes_line(&prog2bufptr, prog2buf, prog2output, buf, 256, &left2); if (n==-1) { strcpy(errormsg, "Error reading from pipe to program 2...\n"); *error=2; } else if (n==-2) { strcpy(errormsg, "Timeout program 2...\n"); *error=2; } mvwprintw(scr, 0, x, "%d.%d\n", left2.tv_sec, left2.tv_usec); wrefresh(scr); } void wread_prog1(WINDOW *scr, int x, char *buf, int *error) { int n; if (*error) return; n=read_from_pipedes_line(&prog1bufptr, prog1buf, prog1output, buf, 256, &left1); if (n==-1) { strcpy(errormsg, "Error reading from pipe to program 1...\n"); *error=1; } else if (n==-2) { strcpy(errormsg, "Timeout program 1...\n"); *error=1; } mvwprintw(scr, 0, x, "%d.%d\n", left1.tv_sec, left1.tv_usec); wrefresh(scr); } void read_write_reset(void) { prog1bufptr=-1; prog2bufptr=-1; left1.tv_sec=30; left1.tv_usec=0; left2.tv_sec=30; left2.tv_usec=0; } void getprinterror(int i, int filedes[2], WINDOW *scr, bool log, char *logfile) { int n; int retval; fd_set rfds; struct timeval tv; char errorbuf[32768]; FD_ZERO(&rfds); FD_SET(filedes[0], &rfds); tv.tv_sec = 0; tv.tv_usec = 0; retval=select(filedes[0]+1, &rfds, NULL, NULL, &tv); if (retval) { n=read(filedes[0], errorbuf, 32767); if (n<0) return; errorbuf[n]='\0'; } else return; if (scr!=NULL) { wprintw(scr, "%s", errorbuf); wrefresh(scr); } if (log) { FILE *logstr=fopen(logfile, "a"); fprintf(logstr, "%s", errorbuf); fclose(logstr); } }
96751ccc3c473559d307276e0cd9ed3f62b70356
1120f23bf7808c565595edc1b0d65b660d738093
/xx/codeforces/Codeforces Round #436 (Div. 2)/d/d.cpp
339067341bbf3ce4a92974ab0a6c4100ddc23c05
[]
no_license
nn020701/OIER
f61cfdbcb406bc3a0e5111c5540378c798afd969
43f5a2987e2080c8f356edafb6875e4d0b707d99
refs/heads/master
2021-07-15T00:44:27.398058
2017-10-21T10:34:09
2017-10-21T10:34:09
104,617,028
0
0
null
null
null
null
UTF-8
C++
false
false
840
cpp
d.cpp
#include<vector> #include<cstdio> #include<cstring> #include<iostream> #include<algorithm> using namespace std; #define ll long long #define N 200005 inline int read(){ int x=0,f=1;char ch=getchar(); while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();} while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();} return x*f; } int n; int a[N]; int cnt,ans; int num[N]; bool vis[N]; int main(){ n = read(); for(int i = 1;i <= n;i++){ a[i] = read(); num[a[i]]++; if(num[a[i]] > 1) ans++; } cnt = 1; while(num[cnt] > 0) cnt++; for(int i = 1;i <= n;i++){ if(num[a[i]] > 1){ if(cnt < a[i] || vis[a[i]]){ num[a[i]]--; a[i] = cnt; num[cnt]++; while(num[cnt] > 0) cnt++; } else vis[a[i]] = true; } } printf("%d\n",ans); for(int i = 1;i < n;i++) printf("%d ",a[i]); printf("%d\n",a[n]); return 0; }
c538fda7dfbed372b93833c9bd3de47cbe9c74cc
c1c70168fe5ed0c9c81e08915a647961200d1766
/CodeForce/Problems/1485C.cpp
a49f07c2bf8392c01c2f7846216214fadf51b9e2
[]
no_license
cies96035/CPP_programs
046fa81e1d7d6e5594daee671772dbfdbdfb2870
9877fb44c0cd6927c7bfe591bd595886b1531501
refs/heads/master
2023-08-30T15:53:57.064865
2023-08-27T10:01:12
2023-08-27T10:01:12
250,568,619
0
0
null
null
null
null
UTF-8
C++
false
false
514
cpp
1485C.cpp
#include<bits/stdc++.h> using namespace std; using ll = long long; #define rep(i, a, b) for(int i = a; i <= b; i++) int t; int x, y; ll ans; int main() { cin.tie(0); ios_base::sync_with_stdio(0); cin >> t; while(t--){ cin >> x >> y; ans = 0; for(int i = 1, tmp, sx = sqrt(x); i <= sx && i < y; i++){ tmp = x / i - 1; if(i < tmp){ ans += min(tmp, y) - i; } } cout << ans << '\n'; } return 0; }
6326173436db504a70e0914add80ea0bf18d3b4a
2d17040d5f8e7eac41e9d1ef90b5cbab22e52bbf
/src/graphics/userinterface/drawable.cpp
c99e04aa8e2d3160ba574b37c69204c8d52bd93d
[]
no_license
ne0ndrag0n/Concordia
5818a09af5919288b3ebbca21f7f2fcef1a4f52a
98a0444509f9b0110a3e57cc9f4d535fd4585037
refs/heads/master
2021-06-17T17:20:22.976001
2019-07-27T20:41:47
2019-07-27T20:41:47
34,757,048
8
2
null
null
null
null
UTF-8
C++
false
false
3,683
cpp
drawable.cpp
#include "graphics/userinterface/drawable.hpp" #include "graphics/userinterface/element.hpp" #include "device/display/adapter/component/guicomponent.hpp" #include "configmanager.hpp" #include "tools/opengl.hpp" #include <glm/gtc/matrix_transform.hpp> namespace BlueBear { namespace Graphics { namespace UserInterface { std::vector< GLuint > Drawable::MESH_INDICES = { 0, 1, 2, 1, 2, 3 }; Drawable::Drawable( std::shared_ptr< Vector::Renderer::Texture > texture, unsigned int width, unsigned int height ) : dimensions( width, height ), texture( texture ) { glGenVertexArrays( 1, &VAO ); glGenBuffers( 1, &VBO ); glGenBuffers( 1, &EBO ); glBindVertexArray( VAO ); glBindBuffer( GL_ARRAY_BUFFER, VBO ); std::vector< Drawable::Corner > quad = generateMesh( width, height ); glBufferData( GL_ARRAY_BUFFER, quad.size() * sizeof( Drawable::Corner ), &quad[ 0 ], GL_STATIC_DRAW ); glEnableVertexAttribArray( 0 ); glVertexAttribPointer( 0, 3, GL_FLOAT, GL_FALSE, sizeof( Drawable::Corner ), ( GLvoid* ) 0 ); glEnableVertexAttribArray( 1 ); glVertexAttribPointer( 1, 2, GL_FLOAT, GL_FALSE, sizeof( Drawable::Corner ), ( GLvoid* ) offsetof( Drawable::Corner, texture ) ); glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, EBO ); glBufferData( GL_ELEMENT_ARRAY_BUFFER, MESH_INDICES.size() * sizeof( GLuint ), &MESH_INDICES[ 0 ], GL_STATIC_DRAW ); glBindBuffer( GL_ARRAY_BUFFER, 0 ); glBindVertexArray( 0 ); } Drawable::~Drawable() { glDeleteVertexArrays( 1, &VAO ); glDeleteBuffers( 1, &VBO ); glDeleteBuffers( 1, &EBO ); } std::vector< Drawable::Corner > Drawable::generateMesh( unsigned int width, unsigned int height ) { std::vector< Drawable::Corner > vertices = { { { 0.0f, 0.0f, 0.0f }, { 0.0f, 1.0f } }, { { width, 0.0f, 0.0f }, { 1.0f, 1.0f } }, { { 0.0f, height, 0.0f }, { 0.0f, 0.0f } }, { { width, height, 0.0f }, { 1.0f, 0.0f } } }; return vertices; } const glm::ivec2& Drawable::getDimensions() { return dimensions; } std::shared_ptr< Vector::Renderer::Texture > Drawable::getTexture() { return texture; } void Drawable::draw( const Shader& guiShader, const glm::ivec2& position ) { static float viewportX = ConfigManager::getInstance().getIntValue( "viewport_x" ); static float viewportY = ConfigManager::getInstance().getIntValue( "viewport_y" ); static glm::mat4 orthoProjection = glm::ortho( 0.0f, viewportX, viewportY, 0.0f, -1.0f, 1.0f ); if( !uniforms ) { uniforms = Uniforms { guiShader.getUniform( "orthoProjection" ), guiShader.getUniform( "translation" ), guiShader.getUniform( "surface" ) }; } guiShader.sendData( uniforms->orthoProjection, orthoProjection ); glm::mat4 translation = glm::translate( glm::mat4( 1.0f ), glm::vec3{ position.x, position.y, 0.0f } ); guiShader.sendData( uniforms->translation, translation ); glActiveTexture( GL_TEXTURE0 ); glBindTexture( GL_TEXTURE_2D, texture->getTextureId() ); guiShader.sendData( uniforms->surface, 0 ); glBindVertexArray( VAO ); glDrawElements( GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0 ); glBindVertexArray( 0 ); } } } }
3cbe909a93334322fa0d1503efddcb45ff4bf5ce
5616023cdb89fc3c1c3172da75387a588617d1e2
/packages/Microsoft.InformationProtection.Protection.1.10.97/build/native/include/mip/protection/rights.h
8a8ad19632b653e73e902c61e56e599498bbe6a7
[ "MIT" ]
permissive
jaydipdas007/AppInitialization
0ec995d07beee08258f4e396e5e12876b53b947b
32a79a66e8f309b56c555bb81796b5740c6fc278
refs/heads/master
2023-08-06T20:33:24.058736
2021-10-05T18:14:37
2021-10-05T18:14:37
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,528
h
rights.h
/* * * Copyright (c) Microsoft Corporation. * All rights reserved. * * This code is licensed under the MIT License. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files(the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and / or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions : * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * */ /** * @brief Defines functions describing rights * * @file rights.h */ #ifndef API_MIP_PROTECTION_RIGHTS_H_ #define API_MIP_PROTECTION_RIGHTS_H_ #include <string> #include <vector> #include "mip/mip_namespace.h" MIP_NAMESPACE_BEGIN namespace rights { /** * @brief Gets string identifier for 'owner' right * * @return String identifier for 'owner' right */ inline std::string Owner() { return "OWNER"; } /** * @brief Gets string identifier for 'view' right * * @return String identifier for 'view' right */ inline std::string View() { return "VIEW"; } /** * @brief Gets string identifier for 'audited extract' right * * @return String identifier for 'audited extract' right */ inline std::string AuditedExtract() { return "AUDITEDEXTRACT"; } /** * @brief Gets string identifier for 'edit' right * * @return String identifier for 'edit' right */ inline std::string Edit() { return "EDIT"; } /** * @brief Gets string identifier for 'export' right * * @return String identifier for 'export' right */ inline std::string Export() { return "EXPORT"; } /** * @brief Gets string identifier for 'extract' right * * @return String identifier for 'extract' right */ inline std::string Extract() { return "EXTRACT"; } /** * @brief Gets string identifier for 'print' right * * @return String identifier for 'print' right */ inline std::string Print() { return "PRINT"; } /** * @brief Gets string identifier for 'comment' right * * @return String identifier for 'comment' right */ inline std::string Comment() { return "COMMENT"; } /** * @brief Gets string identifier for 'reply' right * * @return String identifier for 'reply' right */ inline std::string Reply() { return "REPLY"; } /** * @brief Gets string identifier for 'reply all' right * * @return String identifier for 'reply all' right */ inline std::string ReplyAll() { return "REPLYALL"; } /** * @brief Gets string identifier for 'forward' right * * @return String identifier for 'forward' right */ inline std::string Forward() { return "FORWARD"; } /** * @brief Gets string identifier for 'view rights data' right * * @return String identifier for the right */ inline std::string ViewRightsData() { return "VIEWRIGHTSDATA"; } /** * @brief Gets string identifier for 'document edit' right * * @return String identifier for the right */ inline std::string DocumentEdit() { return "DOCEDIT"; } /** * @brief Gets string identifier for 'object model' right * * @return String identifier for the right */ inline std::string ObjectModel() { return "OBJMODEL"; } /** * @brief Gets string identifier for 'edit rights data' right * * @return String identifier for the right */ inline std::string EditRightsData() { return "EDITRIGHTSDATA"; } /** * @brief Gets a list of rights that apply to emails * * @return A list of rights that apply to emails */ inline std::vector<std::string> EmailRights() { return std::vector<std::string>{Extract(), Forward(), Owner(), Print(), Reply(), ReplyAll(), View()}; } /** * @brief Gets a list of rights that apply to documents * * @return A list of rights that apply to documents */ inline std::vector<std::string> EditableDocumentRights() { return std::vector<std::string>{Comment(), Edit(), Extract(), Owner(), Print(), View()}; } /** * @brief Gets a list of rights that apply in all scenarios * * @return A list of rights that apply in all scenarios */ inline std::vector<std::string> CommonRights() { return std::vector<std::string>{Owner(), View()}; } /** * @brief Gets a list of rights that apply to do not forward emails * * @return A list of rights */ inline std::vector<std::string> DoNotForwardRights() { return std::vector<std::string>{View(), Edit(), ObjectModel(), ViewRightsData(), Reply(), ReplyAll(), DocumentEdit()}; } /** * @brief Gets a list of rights that apply to do encrypt only emails * * @return A list of rights */ inline std::vector<std::string> EncryptOnlyRights() { return std::vector<std::string>{ View(), Edit(), Extract(), Print(), ObjectModel(), ViewRightsData(), Forward(), Reply(), ReplyAll(), DocumentEdit(), EditRightsData()}; } } // namespace rights MIP_NAMESPACE_END #endif // API_MIP_PROTECTION_RIGHTS_H_
37a8ce99fc5328f0b1c26c34fca60fff392d7432
e7bb8ce8dc2ac3d952b68bdd695cf6e75d7e5a06
/MindFlayer4.0/mfTexture.cpp
2eceafcabbc838aab7c532efa4f559aa4c5c94e6
[]
no_license
charre2017idv/MindFlayer_gBuffer
5bd33a1464b7d7862b9a861ca86751952d484bd2
5c00549f3458ce428c5e55d17e40e8bf55152414
refs/heads/master
2022-03-29T19:33:27.339885
2019-12-08T09:20:28
2019-12-08T09:20:28
222,577,954
0
0
null
null
null
null
UTF-8
C++
false
false
1,153
cpp
mfTexture.cpp
/** * @LC : 12/10/2019 * @file : mfTexture.cpp * @Author : Roberto Charreton (idv17c.rcharreton@uartesdigitales.edu.mx) * @date : 12/10/2019 * @brief : Class in charge of provide textures to different classes. * @bug : No known bugs. */ #include "mfTexture.h" mfTexture::mfTexture() { #ifdef mfDIRECTX m_texture.ResourceViewID = NULL; #endif // mfDIRECTX } mfTexture::~mfTexture() { } void mfTexture::Init(mfBaseTextureDesc _Desc) { if (_Desc.Filepath == NULL || _Desc.Filepath[0] == 0) { mfBaseTexture::Init(_Desc); } else { #ifdef mfDIRECTX D3DX11CreateShaderResourceViewFromFile ( mfGraphic_API::getSingleton().GetDevice().getInterface().ID, _Desc.Filepath, NULL, NULL, &m_texture.ResourceViewID, NULL ); #elif defined mfOPENGL #endif // mfDIRECTX } } void mfTexture::Render() { //mfRenderManager::getSingleton().PSSetShaderResources(0, 1, *this); } void mfTexture::Destroy() { mfBaseTexture::Destroy(); #ifdef mfDIRECTX SAFE_RELEASE(m_texture.ResourceViewID); #endif // mfDIRECTX } mfTextureID & mfTexture::getInterface() { return m_texture; }
2317d348a7cb4bcc67b7d361e4c24316d124de8a
4a159a80cf0f841070e8cc1d3475f7811c789f9e
/Task 8.cpp
4b2dc4baaf9eedbc41382cadef0334abe40cf825
[]
no_license
SolomonBradley/CodersPack
aea82c4e5d75b13fcadecda13463b32091a793bc
336b89354ea2867e8d8beceeb2d63d2dffb09092
refs/heads/master
2020-06-24T13:42:31.087653
2019-08-19T14:19:24
2019-08-19T14:19:24
198,977,784
0
0
null
null
null
null
UTF-8
C++
false
false
185
cpp
Task 8.cpp
#include<stdio.h> int main(){ int n; scanf("%d",&n); int a=1; printf("Multiplication table of %d",n); while(a<=10){ printf("%d*%d=%d\n",n,a,n*a); a=a+1; } return 0; }
d01610784516c345f27813755a6d085c887c3641
4536bfebac7acbe5a1c2e195418ee3616f3c50b7
/WirePlanet/Effect.h
1133c8626b3b7f8e564c67d1a54ce7629900f7dd
[ "MIT" ]
permissive
CdecPGL/Shooting-Game-WirePlanet
223750f0f65de3de25e1417d05015c2a6b8a6b9c
aba24d96a5279d1589cd21df93b2c873a5ec7be0
refs/heads/master
2021-09-04T11:48:08.746318
2018-01-18T12:11:53
2018-01-18T12:11:53
114,664,929
0
0
null
null
null
null
SHIFT_JIS
C++
false
false
419
h
Effect.h
#pragma once #include"object.h" class Effect : public Object { public: //コンストラクタ(ピクセルサイズ幅) Effect(); virtual ~Effect(); virtual int Init() = 0; virtual void Update()override = 0; virtual void Draw()override = 0; //初期化前に呼ぶ void SetWidth(int); protected: int size_w; //ピクセルサイズ幅(0で原寸大又は自動判別) void DeleteMe(); //自分を削除 };
75f80d734dbad96c30ecc639a49e6aaf93c654ce
22a794a73503d4dd1dd4a5833c74d851910d72b7
/W1/tools.h
1e82036d6a9e0b12497ae2f1be1e9b2a9f06c643
[]
no_license
skim33/OOP244
ee0a195a24291a2ce50f3f39d0dfd034a468c506
7dc36efce8b6c0798a1d3dcdbe6f947fad85c4bd
refs/heads/master
2020-03-30T03:38:17.953367
2018-09-28T07:06:42
2018-09-28T07:06:42
150,699,411
0
0
null
null
null
null
UTF-8
C++
false
false
342
h
tools.h
//It contains declarations of functions used in tools.cpp and graph.cpp //graph.h //1/22/2018 //Student Name: Woohyuk Kim //Student Number: 121968176 #ifndef SICT_TOOLS_H #define SICT_TOOLS_H namespace sict { // Displays the user interface menu int menu(); // Performs a fool-proof integer entry int getInt(int min, int max); } #endif
566669ece9e8410c5059376c7065d811c6bc9350
fbe77e9e2a53a4600a1d9b00b5f2c29ee3e8c59a
/externals/binaryen/test/emscripten/tests/poppler/qt4/demos/pageview.cpp
734dacb1ff08d2a7420a57751d89df55df8a32f3
[ "MIT", "NCSA", "GPL-1.0-or-later", "GPL-2.0-or-later", "LGPL-2.0-or-later", "GPL-2.0-only", "Apache-2.0", "BSD-3-Clause" ]
permissive
AcuteAngleCloud/Acute-Angle-Chain
8d4a1ad714f6de1493954326e109b6af112561b9
5ea50bee042212ccff797ece5018c64f3f50ceff
refs/heads/master
2021-04-26T21:52:25.560457
2020-03-21T07:29:06
2020-03-21T07:29:06
124,164,376
10
5
MIT
2020-07-16T07:14:45
2018-03-07T02:03:53
C++
UTF-8
C++
false
false
2,057
cpp
pageview.cpp
/* * Copyright (C) 2008-2009, Pino Toscano <pino@kde.org> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2, or (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. */ #include "pageview.h" #include <poppler-qt4.h> #include <QtGui/QApplication> #include <QtGui/QDesktopWidget> #include <QtGui/QImage> #include <QtGui/QLabel> #include <QtGui/QPixmap> PageView::PageView(QWidget *parent) : QScrollArea(parent) , m_zoom(1.0) , m_dpiX(QApplication::desktop()->physicalDpiX()) , m_dpiY(QApplication::desktop()->physicalDpiY()) { m_imageLabel = new QLabel(this); m_imageLabel->resize(0, 0); setWidget(m_imageLabel); } PageView::~PageView() { } void PageView::documentLoaded() { } void PageView::documentClosed() { m_imageLabel->clear(); m_imageLabel->resize(0, 0); } void PageView::pageChanged(int page) { Poppler::Page *popplerPage = document()->page(page); const double resX = m_dpiX * m_zoom; const double resY = m_dpiY * m_zoom; QImage image = popplerPage->renderToImage(resX, resY); if (!image.isNull()) { m_imageLabel->resize(image.size()); m_imageLabel->setPixmap(QPixmap::fromImage(image)); } else { m_imageLabel->resize(0, 0); m_imageLabel->setPixmap(QPixmap()); } delete popplerPage; } void PageView::slotZoomChanged(qreal value) { m_zoom = value; if (!document()) { return; } reloadPage(); } #include "pageview.moc"
41c7ba51dfc803ee89206cc357633ee1006efbf3
b8fdf8b5da98da91356b09955b70ca42045ff02c
/graphicsview.h
e0f6c67cba485675f02450677a3c51ec35f779ef
[]
no_license
andrewreeman/staffGames
b9280d8710444b2a0c310936eec4740be4c2952c
1351698c0cfefb102127ef3650126fee877469f1
refs/heads/master
2021-01-25T09:53:06.429101
2015-04-26T18:04:02
2015-04-26T18:04:02
21,549,555
1
0
null
null
null
null
UTF-8
C++
false
false
326
h
graphicsview.h
#ifndef GRAPHICSVIEW_H #define GRAPHICSVIEW_H #include <QGraphicsView> class GraphicsView : public QGraphicsView { Q_OBJECT public: explicit GraphicsView(QWidget *parent = 0); virtual bool viewportEvent(QEvent *event); signals: public slots: private: float totalScaleFactor; }; #endif // GRAPHICSVIEW_H
2a01f4c08a6f5ddebdeb6ea0cb4e68b2fb6f13a1
18db0fda5a6909e8dd4a255836dcf2410d41e1b2
/ConveyorElement.h
91b3e5a0d884c636cb962563160083ba8e39b25b
[]
no_license
MMiknich/mikrosha
f7bb42592a229947005084f01ae9df1e733f4251
3e1740a7144f06cf995202365b1cadddcd8ce5e5
refs/heads/master
2020-04-02T04:30:11.368938
2018-12-22T16:21:55
2018-12-22T16:21:55
154,019,930
0
0
null
null
null
null
UTF-8
C++
false
false
1,201
h
ConveyorElement.h
// // Created by mmiknich on 16.11.18. // #ifndef MIKROSHA_CONVEYORELEMENT_H #define MIKROSHA_CONVEYORELEMENT_H #define INPUT_MODE 1 // command < fname #define NEWOUTPUT_MODE 2 // command > fname #define EXISTINGOUTPUT_MODE 3 // command >> fname #include <string> void childSignal(int inp); class ConveyorElement { private: char **argv; // an array of arguments unsigned long numofArgv = 0; pid_t childPid; int timeMode = 0; public: ConveyorElement(std::string inputLine); ~ConveyorElement(); ConveyorElement(ConveyorElement const &); ConveyorElement &operator=(ConveyorElement const &); //TODO: pipe and others int ctm(); int run();// without inp/outp redirection int intoPipeIO(int I, int O); // pipe cut int intoPipe_O(int O); // input pipe plug int intoPipe_O(int O, std::string inpfName); int intoPipeI_(int I); // output pipe plug int intoPipeI_(int I,int mode , std::string outfName); int run(std::string fname, int mode);//with redirection of output int run(std::string inpFName,std::string outFName, int mode);//with redirection of output and input pid_t getPID(); }; #endif //MIKROSHA_CONVEYORELEMENT_H
12c38811bb589f27240ebe397c52fe21d1bddb51
877fff5bb313ccd23d1d01bf23b1e1f2b13bb85a
/app/src/main/cpp/dir7941/dir7942/dir8062/dir8063/dir12766/dir12767/dir13029/dir15097/dir18846/file18903.cpp
224091a5f6adad4df73e2916d7977c591ce9b3e1
[]
no_license
tgeng/HugeProject
829c3bdfb7cbaf57727c41263212d4a67e3eb93d
4488d3b765e8827636ce5e878baacdf388710ef2
refs/heads/master
2022-08-21T16:58:54.161627
2020-05-28T01:54:03
2020-05-28T01:54:03
267,468,475
0
0
null
null
null
null
UTF-8
C++
false
false
115
cpp
file18903.cpp
#ifndef file18903 #error "macro file18903 must be defined" #endif static const char* file18903String = "file18903";
45798b30269028f759253c56f1d84b2bdd46690d
768316ed72470715e641fda62a9166b610b27350
/02-CodeChef-Easy/368--Get a Bucket of Water.cpp
997e367ca3037820089ad251505515799bdea990
[]
no_license
dhnesh12/codechef-solutions
41113bb5922156888d9e57fdc35df89246e194f7
55bc7a69f76306bc0c3694180195c149cf951fb6
refs/heads/master
2023-03-31T15:42:04.649785
2021-04-06T05:38:38
2021-04-06T05:38:38
355,063,355
0
0
null
null
null
null
UTF-8
C++
false
false
462
cpp
368--Get a Bucket of Water.cpp
#include<bits/stdc++.h> using namespace std; int main() { while(1) { int a,b,c,k; cin>>a>>b>>c>>k; double x,t=1e9; if(a==0&&b==0&&c==0&&k==0) break; for(double i=0;i<=c;i=i+0.01) { double x1=sqrt(a*a + i*i); double x2= sqrt(b*b + (c-i)*(c-i)); if(t>(x1 + k*x2)) { t=x1+k*x2; x=x1+x2; } } printf("%f\n",x); } return 0; }
6efddbf901fa9a4e8c9a4d78198fb28a3cc8e5da
a0442fcd9edc8b6d0975ce8799ea5a67e808c568
/casa6/casa5/code/alma/Enumtcl/BaselineReferenceCode.cc
b79339f829eec9553bc183f38c246436e6f00d63
[]
no_license
kernsuite-debian/carta-casacore
f0046b996e2d0e59bfbf3dbc6b5d7eeaf97813f7
a88f662d4f6d7ba015dcaf13301d57117a2f3a17
refs/heads/master
2022-07-30T04:44:30.215120
2021-06-30T10:49:40
2021-06-30T10:49:40
381,669,021
0
0
null
null
null
null
UTF-8
C++
false
false
711
cc
BaselineReferenceCode.cc
#include <alma/Enumtcl/BaselineReferenceCode.h> std::string enum_map_traits<BaselineReferenceCodeMod::BaselineReferenceCode,void>::typeName_="BaselineReferenceCode"; std::string enum_map_traits<BaselineReferenceCodeMod::BaselineReferenceCode,void>::enumerationDesc_=""; std::string enum_map_traits<BaselineReferenceCodeMod::BaselineReferenceCode,void>::order_=""; std::string enum_map_traits<BaselineReferenceCodeMod::BaselineReferenceCode,void>::xsdBaseType_="void"; std::map<BaselineReferenceCodeMod::BaselineReferenceCode,EnumPar<void> > enum_map_traits<BaselineReferenceCodeMod::BaselineReferenceCode,void>::m_; bool enum_map_traits<BaselineReferenceCodeMod::BaselineReferenceCode,void>::init_=init();
67946b37e5cc2038e6a991541b42571501c2f80e
cc2bdea20b5f558ad098c9cee6adc73635929877
/time_series.cc
de5f967addd332237e3bccfe70f4ce691df1a8a0
[]
no_license
unrstuart/power_cycling
d0890de5b278d3d4728111266b9f2227df4f425a
ba181e3e99c9eff61bbad216dc7c4a8ff33b27f7
refs/heads/master
2021-01-22T03:18:12.942344
2017-02-19T10:01:21
2017-02-19T10:01:21
81,112,916
0
0
null
null
null
null
UTF-8
C++
false
false
1,768
cc
time_series.cc
#include "time_series.h" #include <cassert> #include <algorithm> #include <mutex> namespace cycling { namespace { using MutexLock = std::lock_guard<std::mutex>; } // namespace TimeSeries::TimeSeries() { mutex_.reset(new std::mutex); } void TimeSeries::Add(const TimeSample& sample) { TimeSample s(sample); Add(std::move(s)); } void TimeSeries::Add(TimeSample&& sample) { MutexLock lock{*mutex_}; if (!samples_.empty()) { assert(sample.time() > samples_.back().time()); } samples_.push_back(sample); } TimeSeries::TimePoint TimeSeries::BeginTime() const { MutexLock lock{*mutex_}; assert(!samples_.empty()); return samples_.front().time(); } TimeSeries::TimePoint TimeSeries::EndTime() const { MutexLock lock{*mutex_}; assert(!samples_.empty()); return samples_.back().time(); } void TimeSeries::PrepareVisit() const { mutex_->lock(); } void TimeSeries::FinishVisit() const { mutex_->unlock(); } void TimeSeries::Visit(const TimePoint& begin, const TimePoint& end, const Measurement::Type type, const MeasurementVisitor& visitor) const { auto b = std::lower_bound(samples_.begin(), samples_.end(), begin); if (b == samples_.end()) b = samples_.begin(); while (b != samples_.end() && b->time() <= end) { if (b->has_value(type)) { visitor(b->time(), b->value(type).coef()); } ++b; } } void TimeSeries::Visit(const TimePoint& begin, const TimePoint& end, const SampleVisitor& visitor) const { auto b = std::lower_bound(samples_.begin(), samples_.end(), begin); if (b == samples_.end()) b = samples_.begin(); while (b != samples_.end() && b->time() <= end) { visitor(*b); ++b; } } } // namespace cycling
2bed47f0c2913ae08b4e5bd44a60e339adcd3fa3
c9551f35bc1fc1573cd00b22678c8d25220f8783
/Data Structures and Algorithms I/Final Project/BSTree.h
69ca6aaa6da351c37baa9011413ee0193c808ecf
[]
no_license
coxcharlie1/UWB-CSS
ee80004cc3f974e82861544bed62e806a79e4bbb
957623e602d8e9c2933c93b5a2ce9cb02ae46e61
refs/heads/main
2023-05-06T22:47:05.959507
2021-05-24T23:52:07
2021-05-24T23:52:07
370,510,154
0
0
null
null
null
null
UTF-8
C++
false
false
1,142
h
BSTree.h
#pragma once #include "Account.h" #include<iostream> using namespace std; class BSTree { friend ostream& operator<<(ostream& theStream, const BSTree& tree); public: //Constructors BSTree(); BSTree(const BSTree& tree); ~BSTree(); //getters, setters int getCount() const; //Actions bool Insert(const int &key, Account *theAccount); // retrieve object, first parameter is the ID of the account // second parameter holds pointer to found object, NULL if not found bool Retrieve(const int &key, Account * &accountPtr) const; //Search(const int key) const; // displays the contents of a tree to cout bool Remove(const int key); //Inorder traversal void Display() const; void Empty(); bool isEmpty() const; //Overloads //BSTree& operator=(const BSTree & rhs); private: struct Node{ Account *pAcct; Node *right; Node* left; }; int count; Node *root; bool Insert(const int& key, Account *theAccount, Node* root); bool Search(const int &key, Account*& accountPtr, Node* root) const; void Display(Node* root) const; void Empty(Node* root); };
6b4e7fa6e191b3f4c5a207edc61e04800a802285
bae9699a14c3edc36382ddf8f58d0bcd011e0780
/hw_01_id_22.cpp
24608958eb8fed63b29af20edc9882381fb42e63
[]
no_license
sunandmoon2/hw01
3af6cb72d668187dcf8eb2bf58091735625b9a9f
ff3fab855f21d067dfd722e34a0641d0d79d09a9
refs/heads/master
2021-01-20T22:51:10.219863
2015-04-13T16:34:37
2015-04-13T16:34:37
30,363,025
0
0
null
2015-02-05T15:39:11
2015-02-05T15:39:11
null
UTF-8
C++
false
false
413
cpp
hw_01_id_22.cpp
// Author: Noe Romero andrade // Date: 13-april-2015 // Version: 01 /* Homework 01 this assignment Muestra desde la salida estandar el mensaje Hello wolrd y soy noe */ #include <iostream> int main () { std::cout<<"Hello world!!" <<std::endl;//se usa el comando cout para inprimir en la salida estandar std::cout<<"Soy Noe" <<std::endl;//se usa el endl para salto de linea return 0;//valor de retorno }
5bcffa4ec7143f8f16abfc5e11a9c2261c74c093
087dbdf976328941ea89f7c6830406dc8e539bb2
/01 White/Week 03/Lessons/01 White_Week 03_Lesson 06.cpp
06c407bb0dcf9aa9207d3f6ca9e8bc12072f398c
[]
no_license
aliaksei-ivanou-by/Coursera_Yandex_c-plus-plus-modern-development
45ff4e6e02dfa6b9f439174b3a4abf7d55801f6a
f7724dd60fff4c93e12124cfbd5392d8f74006b4
refs/heads/master
2023-03-20T10:31:25.555805
2021-03-03T18:18:25
2021-03-03T18:18:25
281,137,199
1
0
null
null
null
null
UTF-8
C++
false
false
1,294
cpp
01 White_Week 03_Lesson 06.cpp
// Основы разработки на C++: белый пояс. Третья неделя // Введение в структуры и классы. Зачем нужны структуры #include "iostream" #include "vector" using namespace std; struct Lecture { string title; int duration; string author; }; struct LectureTitle { string specialization; string course; string week; }; struct DetailedLecture { LectureTitle title; int duration; }; void PrintLecture(const Lecture& lecture) { cout << "Title: " << lecture.title << ", duration: " << lecture.duration << ", author: " << lecture.author << '\n'; } void PrintCourse(const vector<Lecture>& lectures) { for (const Lecture& lecture : lectures) { PrintLecture(lecture); } } Lecture GetCurrentLecture() { return {"OOP", 5400, "Anton"}; } int main() { Lecture lecture1; lecture1.title = "OOP"; lecture1.duration = 5400; lecture1.author = "Anton"; Lecture lecture2 = {"OOP", 5400, "Anton"}; PrintLecture({"OOP", 5400, "Anton"}); Lecture current_lecture = GetCurrentLecture(); LectureTitle title = {"C++", "While belt", "OOP"}; DetailedLecture lecture3 = {title, 5400}; DetailedLecture lecture4 = {{"C++", "White belt", "OOP"}, 5400}; cout << lecture4.title.specialization << '\n'; return 0; }
60cd9728698db96d32367c272bdd7812bf17d9b3
d11f08af2c4b039a204327d2a59a726c1a767e25
/version1/上交版本/yourcode/Rectangle.h
6bb6c003fd22d416af60a43fb4d9e7f656df01b1
[]
no_license
SimonNie98/Geo-Fencing
e964e4b61a2ac503af1a5323a8c2a0dd31989b5c
8f922e7ff21d4e805a6024f07909d9c919383d3f
refs/heads/master
2020-05-15T06:45:10.988183
2019-04-18T17:26:23
2019-04-18T17:26:23
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,264
h
Rectangle.h
// // Created by Simon Nie on 2018/12/12. // #ifndef INC_16307130133_RECTANGLE_H #define INC_16307130133_RECTANGLE_H #include <vector> #include <unordered_map> #include <climits> #include "RTree.h" const int MX = INT_MAX; const int MIN = INT_MIN; extern std::unordered_map<int, std::vector<std::pair<double, double> > > polygon_set; extern int polygon_nums; extern std::unordered_map<int, std::pair<double, double> > points_set; extern int point_nums; struct Rect { Rect() {} // constructor Rect(double& a_minX, double& a_minY, double& a_maxX, double& a_maxY) { min[0] = a_minX; min[1] = a_minY; max[0] = a_maxX; max[1] = a_maxY; } // copy constructor Rect(const Rect& a){ min[0] = a.min[0]; min[1] = a.min[1]; max[0] = a.max[0]; max[1] = a.max[1]; } ~Rect() = default; double min[2]; double max[2]; }; typedef RTree<int, double, 2, double> MyTree; extern MyTree polygonTree; extern MyTree pointTree; // each point is a rectangle extern std::vector<int> hit_polygon_ids; extern std::vector<int> hit_point_ids; extern std::unordered_map<int, Rect> polygon_rect; extern std::unordered_map<int, Rect> point_rect; #endif //INC_16307130133_RECTANGLE_H
4b8839c2a725cf40a3029fb187579bb3b11cb130
c5f52e0085bc56d3252bd079ea9070f5998ab818
/Coding_From_School/School_Practice/999EXPO.CPP
be12f50326e155bcf2b6796177e47e376ecf9d75
[]
no_license
vishalkumarsingh999/CPP_Practice
4e2ebd866c8587c02b49dd45211b45e584e711f0
5136b56dea9061d1a8c9910b409d01b20b8ead8e
refs/heads/main
2023-08-31T14:14:53.323406
2021-10-19T14:07:20
2021-10-19T14:07:20
null
0
0
null
null
null
null
UTF-8
C++
false
false
199
cpp
999EXPO.CPP
#include<iostream.h> #include<conio.h> void main() { double long a,b,c=1; cout<<"enter the value ofa & b to get a^b \n"; cin>>a>>b; while (b>0) { c=c*a ; b-- ; } cout<<c; getch(); }
9b9fd367c7073bb8e0d9e89990bc600584c17689
ffd2ca527b49d447def2702e45f8243897544702
/src/crayg/tests/fixtures/UsdGeomMeshFixtures.h
3f7ffd43e3ccabe35104cccdfbeeafdae956a9d7
[]
no_license
Latios96/crayg
17b730f745b9367cc15b55b8f1dbd095a29c86c9
57b206d755fb3cafd3dd7a04caa7382cd85f25f8
refs/heads/master
2023-08-17T10:26:10.310064
2023-08-07T16:23:21
2023-08-07T16:23:21
144,862,288
2
1
null
2023-01-26T11:43:21
2018-08-15T14:17:47
Mathematica
UTF-8
C++
false
false
2,147
h
UsdGeomMeshFixtures.h
#ifndef CRAYG_SRC_CRAYG_TESTS_FIXTURES_USDGEOMMESHFIXTURES_H_ #define CRAYG_SRC_CRAYG_TESTS_FIXTURES_USDGEOMMESHFIXTURES_H_ #include <pxr/usd/usd/stage.h> #include <pxr/usd/usdGeom/mesh.h> #include <pxr/usd/usdGeom/xformCommonAPI.h> namespace crayg { class UsdGeomMeshFixtures { public: static pxr::UsdGeomMesh createQuadPlane(const pxr::UsdStagePtr &stage, const pxr::TfToken &subdivisionScheme = pxr::UsdGeomTokens->none) { auto usdGeomMesh = pxr::UsdGeomMesh::Define(stage, pxr::SdfPath("/usdMesh")); usdGeomMesh.GetSubdivisionSchemeAttr().Set(subdivisionScheme); pxr::UsdGeomXformCommonAPI(usdGeomMesh).SetTranslate(pxr::GfVec3f(1, 2, 3)); pxr::VtVec3fArray points{{-0.5, 0, 0.5}, {0.5, 0, 0.5}, {-0.5, 0, -0.5}, {0.5, 0, -0.5}}; usdGeomMesh.GetPointsAttr().Set(points); pxr::VtIntArray faceVertexCounts({4}); usdGeomMesh.GetFaceVertexCountsAttr().Set(faceVertexCounts); pxr::VtIntArray faceVertexIndices({0, 1, 3, 2}); usdGeomMesh.GetFaceVertexIndicesAttr().Set(faceVertexIndices); usdGeomMesh.SetNormalsInterpolation(pxr::UsdGeomTokens->constant); return usdGeomMesh; } static pxr::UsdGeomMesh createTrianglePlane(const pxr::UsdStagePtr &stage) { auto usdGeomMesh = pxr::UsdGeomMesh::Define(stage, pxr::SdfPath("/usdMesh")); usdGeomMesh.GetSubdivisionSchemeAttr().Set(pxr::UsdGeomTokens->none); pxr::UsdGeomXformCommonAPI(usdGeomMesh).SetTranslate(pxr::GfVec3f(1, 2, 3)); pxr::VtVec3fArray points{{-0.5, 0, 0.5}, {0.5, 0, 0.5}, {-0.5, 0, -0.5}, {0.5, 0, -0.5}}; usdGeomMesh.GetPointsAttr().Set(points); pxr::VtIntArray faceVertexCounts({3, 3}); usdGeomMesh.GetFaceVertexCountsAttr().Set(faceVertexCounts); pxr::VtIntArray faceVertexIndices({0, 1, 2, 2, 1, 3}); usdGeomMesh.GetFaceVertexIndicesAttr().Set(faceVertexIndices); usdGeomMesh.SetNormalsInterpolation(pxr::UsdGeomTokens->constant); return usdGeomMesh; } }; } // crayg #endif // CRAYG_SRC_CRAYG_TESTS_FIXTURES_USDGEOMMESHFIXTURES_H_
a852692c077638db8dddf16340aa04e2e70b2c69
45d11ec1567845e25282f66a595a88d9722bae0e
/CombinationSum.cpp
2d06e30e4a72c14787f7700c3cc45f756d716b0e
[]
no_license
dongheekim23/Algorithm-Problems
472b8ddc11509e00fdf00ac388cb7fc07ab25239
2d06c010a50c18c8dc298749496a3096f0b261f2
refs/heads/master
2020-04-25T13:37:33.521085
2019-02-27T01:27:14
2019-02-27T01:27:14
172,815,195
0
0
null
null
null
null
UTF-8
C++
false
false
1,084
cpp
CombinationSum.cpp
// Given a set of candidate numbers (candidates) (without duplicates) and a target number (target), // find all unique combinations in candidates where the candidate numbers sums to target. void GetCombinationSums(vector<vector<int>>& combinationSums, const vector<int>& candidates, vector<int>& intVec, int index, int sum) { intVec.emplace_back(candidates[index]); sum -= candidates[index]; if (sum == 0) { combinationSums.emplace_back(intVec); return; } else if (sum < 0) { return; } for (int i = index; i < candidates.size(); ++i) { GetCombinationSums(combinationSums, candidates, intVec, i, sum); intVec.pop_back(); } } vector<vector<int>> combinationSum(vector<int>& candidates, int target) { vector<vector<int>> combinationSums; if (candidates.empty()) return combinationSums; sort(candidates.begin(), candidates.end()); vector<int> intVec; for (int i = 0; i < candidates.size(); ++i) { GetCombinationSums(combinationSums, candidates, intVec, i, target); intVec.clear(); } return combinationSums; }
1e6ec28c0c5446e2c429c0440748a602df25152f
3ee8f4623bda019a3e1fb5dfb8810d8f22d3a1ec
/source code/Location.h
a65c579e4a414c3b4a6f58f6b25cc689dd2c5edb
[]
no_license
suibun-code/GAME1011_Assignment2
c8d67359c8ee23fd05904507f36fa048a3b133ef
53058176b79b87bb5fd59157eb018a764cfce103
refs/heads/master
2020-05-05T13:48:15.540330
2019-04-08T07:50:42
2019-04-08T07:50:42
180,093,698
1
0
null
null
null
null
UTF-8
C++
false
false
653
h
Location.h
#pragma once #include <string> #include <vector> #include "Item.h" class Location { private: std::string name, description; int id; public: Location(); ~Location(); std::vector<Location*> nextLocations; std::vector<Item> items; void setName(std::string name) { this->name = name; } void setDesc(std::string description) { this->description = description; } void setID(int id) { this->id = id; } std::string getName() { return name; } std::string getDesc() { return description; } int getID() { return id; } void addLoc(Location &location); void addItem(Item item); void removeItem(int index); };
5755405a01029f1f94236e9b2a872d843a85ee50
20cf8883018e0c8f817807db37306ce98f73e8fc
/opencv_qml/src/threads/backend_thread.cpp
c84d3ab445409917ab66799f363e05a7926f4ae9
[ "MIT" ]
permissive
ahnan4arch/qt-video-player
cd6c822c06b045447f9d9cbabb514ccbc88d9ca4
28ff7c908736bb67c5ea761f69fec3261da0cea8
refs/heads/master
2023-04-03T19:51:50.846141
2021-04-14T06:51:41
2021-04-14T06:51:41
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,287
cpp
backend_thread.cpp
#include <iostream> #include "backend_thread.h" #include "opencv_thread.h" BackendThread::BackendThread(QObject *parent) : QObject(parent) { } void BackendThread::opencvStart() { qDebug() << ">>> [Backend] OpenCV Thread Start <<<"; QThread *thread = new QThread(0); OpenCVThread *worker = new OpenCVThread(); threads["OpenCV"] = thread; workers["OpenCV"] = QVariant::fromValue(worker); worker->moveToThread(thread); connect(worker, &OpenCVThread::frameReady, this, &BackendThread::frameReady); connect(worker, &OpenCVThread::finished, this, &BackendThread::finished); connect(thread, &QThread::finished, worker, &QObject::deleteLater); connect(thread, &QThread::started, worker, &OpenCVThread::start); thread->start(); } void BackendThread::opencvStop() { OpenCVThread *worker; if (workers.contains("OpenCV")) { worker = qvariant_cast<OpenCVThread*>(workers.value("OpenCV")); worker->stop(); } } void BackendThread::finished(QString thread_name) { QThread *thread; if (threads.contains(thread_name)) { thread = threads.value(thread_name); thread->quit(); thread->wait(); qDebug() << qPrintable(QString(">>> [Backend] %1 Thread Finish <<<").arg(thread_name)); } }
7fb4825c5b83d2e61a8309f69f399f5764009577
0f842042e2916273392f0272bd3d2b4921f4844c
/2DAE01_Exam_Timo_Nys/Source/Minigin/HealthComponent.cpp
05e755e2738004fecdf006c0b67f7352ec1b6160
[]
no_license
timonys1998/RiptideEngineRetake
891678f5c96a419556ec5ab7b28fe9747844cce9
20f3e91c4fb71a3cae2802b9abf324a08d498af9
refs/heads/master
2020-03-27T07:22:51.423305
2018-08-26T14:55:08
2018-08-26T14:55:08
146,186,361
0
0
null
null
null
null
UTF-8
C++
false
false
166
cpp
HealthComponent.cpp
#include "MiniginPCH.h" #include "HealthComponent.h" HealthComponent::HealthComponent(int health) :m_Lives(health) { } HealthComponent::~HealthComponent() { }
7498c3aa2724c87994e4b0d56bb414d4cc0521c7
d6b461bf38bdadc03b30d39b1511b7e658d4890a
/Game_Server/Card.cpp
57d590c3c563fbf9d05a82f0d20e8b785f512323
[]
no_license
koe22kr/2Dbasis
f27d74a038f6eb5f92ae91fae88ea2dbac2bd98c
1763942042c31f520a4039deba8d9ad9ad0fbc82
refs/heads/master
2022-04-05T08:26:19.643151
2020-03-04T01:42:09
2020-03-04T01:42:09
185,978,543
0
0
null
null
null
null
UTF-8
C++
false
false
367
cpp
Card.cpp
#include "Card.h" Card::Card(byte type, byte num, byte score): m_Card_type(type),m_Card_num(num),m_Card_Score(score) { } bool Card::Check() const { if (this->m_Card_num == 0 || this->m_Card_type == 0) { return false; } return true; } // //int Card::Get_Score() const //{ // return m_Card_Score; //} Card::Card() { } Card::~Card() { }
8c9b778efb4c4d7fb9800451ca1d088879dbbd34
5a74bcb0dedacb080de7e9851df11e2e556f99d9
/Computer vision course design/Head.h
f45631d6f5e9ee074c78240c30cff4415fa4bb16
[]
no_license
huantingbo/Computer-vision-course-design
fe7bcecf19fa0afe52bdd09c8817f76e22f95525
3a5683684ddc72358f68b1f1ee68ab47a277b3d2
refs/heads/master
2023-03-16T08:17:53.524476
2019-06-29T14:38:13
2019-06-29T14:38:13
null
0
0
null
null
null
null
TIS-620
C++
false
false
307
h
Head.h
#pragma once //นฒำรอท #ifndef _HEAD_H_ #define _HEAD_H_ #include <iostream> #include<algorithm> #include<vector> #include<math.h> #include<cassert> #include <opencv2/opencv.hpp> #include<opencv2/highgui/highgui.hpp> #include<opencv2/imgproc/imgproc.hpp> #define Pixellen 0.03125 #endif // HEAD
64953812a5e51cbdab4d93575af1bc7df1a94126
86e3e50451c58e149ee613527defce64418b7995
/aeron-client/src/test/cpp/concurrent/BroadcastReceiverTest.cpp
c96b4b637663ae36b5b2db3128ff899d221723ac
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
ronenhamias/aeron
c650ed7dcf6edc4e0439d048dc6806a14e6b9d85
4871864ba8f35c91c5b634c3adaecf5877f22d06
refs/heads/master
2020-03-26T08:07:32.637150
2018-08-13T11:02:23
2018-08-13T11:02:23
144,686,802
6
0
Apache-2.0
2018-08-14T07:48:53
2018-08-14T07:48:53
null
UTF-8
C++
false
false
12,840
cpp
BroadcastReceiverTest.cpp
/* * Copyright 2014-2018 Real Logic Ltd. * * 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. */ #include <array> #include <gtest/gtest.h> #include <thread> #include "MockAtomicBuffer.h" #include <concurrent/broadcast/BroadcastBufferDescriptor.h> #include <concurrent/broadcast/BroadcastReceiver.h> using namespace aeron::concurrent::broadcast; using namespace aeron::concurrent::mock; using namespace aeron::concurrent; using namespace aeron; #define CAPACITY (1024) #define TOTAL_BUFFER_LENGTH (CAPACITY + BroadcastBufferDescriptor::TRAILER_LENGTH) #define MSG_TYPE_ID (7) #define TAIL_INTENT_COUNTER_INDEX (CAPACITY + BroadcastBufferDescriptor::TAIL_INTENT_COUNTER_OFFSET) #define TAIL_COUNTER_INDEX (CAPACITY + BroadcastBufferDescriptor::TAIL_COUNTER_OFFSET) #define LATEST_COUNTER_INDEX (CAPACITY + BroadcastBufferDescriptor::LATEST_COUNTER_OFFSET) typedef std::array<std::uint8_t, TOTAL_BUFFER_LENGTH> buffer_t; class BroadcastReceiverTest : public testing::Test { public: BroadcastReceiverTest() : m_mockBuffer(&m_buffer[0], m_buffer.size()), m_broadcastReceiver(m_mockBuffer) { m_buffer.fill(0); } virtual void SetUp() { m_buffer.fill(0); } protected: AERON_DECL_ALIGNED(buffer_t m_buffer, 16); MockAtomicBuffer m_mockBuffer; BroadcastReceiver m_broadcastReceiver; }; TEST_F(BroadcastReceiverTest, shouldCalculateCapacityForBuffer) { EXPECT_EQ(m_broadcastReceiver.capacity(), CAPACITY); } TEST_F(BroadcastReceiverTest, shouldThrowExceptionForCapacityThatIsNotPowerOfTwo) { typedef std::array<std::uint8_t, (777 + BroadcastBufferDescriptor::TRAILER_LENGTH)> non_power_of_two_buffer_t; AERON_DECL_ALIGNED(non_power_of_two_buffer_t non_power_of_two_buffer, 16); AtomicBuffer buffer(&non_power_of_two_buffer[0], non_power_of_two_buffer.size()); ASSERT_THROW( { BroadcastReceiver receiver(buffer); }, util::IllegalStateException); } TEST_F(BroadcastReceiverTest, shouldNotBeLappedBeforeReception) { EXPECT_EQ(m_broadcastReceiver.lappedCount(), 0); } TEST_F(BroadcastReceiverTest, shouldNotReceiveFromEmptyBuffer) { EXPECT_CALL(m_mockBuffer, getInt64Volatile(TAIL_COUNTER_INDEX)) .Times(1) .WillOnce(testing::Return(0)); EXPECT_FALSE(m_broadcastReceiver.receiveNext()); } TEST_F(BroadcastReceiverTest, shouldReceiveFirstMessageFromBuffer) { const std::int32_t length = 8; const std::int32_t recordLength = length + RecordDescriptor::HEADER_LENGTH; const std::int32_t alignedRecordLength = util::BitUtil::align(recordLength, RecordDescriptor::RECORD_ALIGNMENT); const std::int64_t tail = alignedRecordLength; const std::int64_t latestRecord = tail - alignedRecordLength; const std::int32_t recordOffset = (std::int32_t)latestRecord; testing::Sequence sequence; EXPECT_CALL(m_mockBuffer, getInt64Volatile(TAIL_COUNTER_INDEX)) .Times(1) .InSequence(sequence) .WillOnce(testing::Return(tail)); EXPECT_CALL(m_mockBuffer, getInt64Volatile(TAIL_INTENT_COUNTER_INDEX)) .Times(2) .InSequence(sequence) .WillRepeatedly(testing::Return(tail)); EXPECT_CALL(m_mockBuffer, getInt64(LATEST_COUNTER_INDEX)) .Times(0); EXPECT_CALL(m_mockBuffer, getInt32(RecordDescriptor::lengthOffset(recordOffset))) .Times(2) .WillRepeatedly(testing::Return(recordLength)); EXPECT_CALL(m_mockBuffer, getInt32(RecordDescriptor::typeOffset(recordOffset))) .Times(2) .WillRepeatedly(testing::Return(MSG_TYPE_ID)); EXPECT_TRUE(m_broadcastReceiver.receiveNext()); EXPECT_EQ(m_broadcastReceiver.typeId(), MSG_TYPE_ID); EXPECT_EQ(&(m_broadcastReceiver.buffer()), &m_mockBuffer); EXPECT_EQ(m_broadcastReceiver.offset(), RecordDescriptor::msgOffset(recordOffset)); EXPECT_EQ(m_broadcastReceiver.length(), length); EXPECT_TRUE(m_broadcastReceiver.validate()); } TEST_F(BroadcastReceiverTest, shouldReceiveTwoMessagesFromBuffer) { const std::int32_t length = 8; const std::int32_t recordLength = length + RecordDescriptor::HEADER_LENGTH; const std::int32_t alignedRecordLength = util::BitUtil::align(recordLength, RecordDescriptor::RECORD_ALIGNMENT); const std::int64_t tail = alignedRecordLength * 2; const std::int64_t latestRecord = tail - alignedRecordLength; const std::int32_t recordOffsetOne = 0; const std::int32_t recordOffsetTwo = (std::int32_t)latestRecord; EXPECT_CALL(m_mockBuffer, getInt64Volatile(TAIL_COUNTER_INDEX)) .Times(2) .WillRepeatedly(testing::Return(tail)); EXPECT_CALL(m_mockBuffer, getInt64Volatile(TAIL_INTENT_COUNTER_INDEX)) .Times(4) .WillRepeatedly(testing::Return(tail)); EXPECT_CALL(m_mockBuffer, getInt64(LATEST_COUNTER_INDEX)) .Times(0); EXPECT_CALL(m_mockBuffer, getInt32(RecordDescriptor::lengthOffset(recordOffsetOne))) .Times(2) .WillRepeatedly(testing::Return(recordLength)); EXPECT_CALL(m_mockBuffer, getInt32(RecordDescriptor::typeOffset(recordOffsetOne))) .Times(2) .WillRepeatedly(testing::Return(MSG_TYPE_ID)); EXPECT_CALL(m_mockBuffer, getInt32(RecordDescriptor::lengthOffset(recordOffsetTwo))) .Times(2) .WillRepeatedly(testing::Return(recordLength)); EXPECT_CALL(m_mockBuffer, getInt32(RecordDescriptor::typeOffset(recordOffsetTwo))) .Times(2) .WillRepeatedly(testing::Return(MSG_TYPE_ID)); EXPECT_TRUE(m_broadcastReceiver.receiveNext()); EXPECT_EQ(m_broadcastReceiver.typeId(), MSG_TYPE_ID); EXPECT_EQ(&(m_broadcastReceiver.buffer()), &m_mockBuffer); EXPECT_EQ(m_broadcastReceiver.offset(), RecordDescriptor::msgOffset(recordOffsetOne)); EXPECT_EQ(m_broadcastReceiver.length(), length); EXPECT_TRUE(m_broadcastReceiver.validate()); EXPECT_TRUE(m_broadcastReceiver.receiveNext()); EXPECT_EQ(m_broadcastReceiver.typeId(), MSG_TYPE_ID); EXPECT_EQ(&(m_broadcastReceiver.buffer()), &m_mockBuffer); EXPECT_EQ(m_broadcastReceiver.offset(), RecordDescriptor::msgOffset(recordOffsetTwo)); EXPECT_EQ(m_broadcastReceiver.length(), length); EXPECT_TRUE(m_broadcastReceiver.validate()); } TEST_F(BroadcastReceiverTest, shouldLateJoinTransmission) { const std::int32_t length = 8; const std::int32_t recordLength = length + RecordDescriptor::HEADER_LENGTH; const std::int32_t alignedRecordLength = util::BitUtil::align(recordLength, RecordDescriptor::RECORD_ALIGNMENT); const std::int64_t tail = CAPACITY * 3 + RecordDescriptor::HEADER_LENGTH + alignedRecordLength; const std::int64_t latestRecord = tail - alignedRecordLength; const std::int32_t recordOffset = (std::int32_t)latestRecord & (CAPACITY - 1); EXPECT_CALL(m_mockBuffer, getInt64Volatile(TAIL_COUNTER_INDEX)) .Times(1) .WillOnce(testing::Return(tail)); EXPECT_CALL(m_mockBuffer, getInt64Volatile(TAIL_INTENT_COUNTER_INDEX)) .Times(2) .WillRepeatedly(testing::Return(tail)); EXPECT_CALL(m_mockBuffer, getInt64(LATEST_COUNTER_INDEX)) .Times(1) .WillOnce(testing::Return(latestRecord)); EXPECT_CALL(m_mockBuffer, getInt32(RecordDescriptor::lengthOffset(recordOffset))) .Times(2) .WillRepeatedly(testing::Return(recordLength)); EXPECT_CALL(m_mockBuffer, getInt32(RecordDescriptor::typeOffset(recordOffset))) .Times(2) .WillRepeatedly(testing::Return(MSG_TYPE_ID)); EXPECT_TRUE(m_broadcastReceiver.receiveNext()); EXPECT_EQ(m_broadcastReceiver.typeId(), MSG_TYPE_ID); EXPECT_EQ(&(m_broadcastReceiver.buffer()), &m_mockBuffer); EXPECT_EQ(m_broadcastReceiver.offset(), RecordDescriptor::msgOffset(recordOffset)); EXPECT_EQ(m_broadcastReceiver.length(), length); EXPECT_TRUE(m_broadcastReceiver.validate()); EXPECT_GT(m_broadcastReceiver.lappedCount(), 0); } TEST_F(BroadcastReceiverTest, shouldCopeWithPaddingRecordAndWrapOfBufferToNextRecord) { const std::int32_t length = 120; const std::int32_t recordLength = length + RecordDescriptor::HEADER_LENGTH; const std::int32_t alignedRecordLength = util::BitUtil::align(recordLength, RecordDescriptor::RECORD_ALIGNMENT); const std::int64_t catchupTail = (CAPACITY * 2) - RecordDescriptor::HEADER_LENGTH; const std::int64_t postPaddingTail = catchupTail + RecordDescriptor::HEADER_LENGTH + alignedRecordLength; const std::int64_t latestRecord = catchupTail - alignedRecordLength; const std::int32_t catchupOffset = (std::int32_t)latestRecord & (CAPACITY - 1); testing::Sequence sequence; EXPECT_CALL(m_mockBuffer, getInt64Volatile(TAIL_COUNTER_INDEX)) .Times(2) .WillOnce(testing::Return(catchupTail)) .WillOnce(testing::Return(postPaddingTail)); EXPECT_CALL(m_mockBuffer, getInt64Volatile(TAIL_INTENT_COUNTER_INDEX)) .Times(3) .WillOnce(testing::Return(catchupTail)) .WillRepeatedly(testing::Return(postPaddingTail)); EXPECT_CALL(m_mockBuffer, getInt64(LATEST_COUNTER_INDEX)) .Times(1) .WillOnce(testing::Return(latestRecord)); EXPECT_CALL(m_mockBuffer, getInt32(RecordDescriptor::lengthOffset(catchupOffset))) .Times(1) .WillOnce(testing::Return(recordLength)); EXPECT_CALL(m_mockBuffer, getInt32(RecordDescriptor::typeOffset(catchupOffset))) .Times(1) .WillOnce(testing::Return(MSG_TYPE_ID)); const std::int32_t paddingOffset = (std::int32_t)catchupTail & (CAPACITY - 1); const std::int32_t recordOffset = (std::int32_t)(postPaddingTail - alignedRecordLength) & (CAPACITY - 1); EXPECT_CALL(m_mockBuffer, getInt32(RecordDescriptor::lengthOffset(paddingOffset))) .Times(1) .WillOnce(testing::Return(0)); EXPECT_CALL(m_mockBuffer, getInt32(RecordDescriptor::typeOffset(paddingOffset))) .Times(1) .WillOnce(testing::Return(RecordDescriptor::PADDING_MSG_TYPE_ID)); EXPECT_CALL(m_mockBuffer, getInt32(RecordDescriptor::lengthOffset(recordOffset))) .Times(2) .WillRepeatedly(testing::Return(recordLength)); EXPECT_CALL(m_mockBuffer, getInt32(RecordDescriptor::typeOffset(recordOffset))) .Times(1) .WillOnce(testing::Return(MSG_TYPE_ID)); EXPECT_TRUE(m_broadcastReceiver.receiveNext()); EXPECT_TRUE(m_broadcastReceiver.receiveNext()); EXPECT_EQ(m_broadcastReceiver.typeId(), MSG_TYPE_ID); EXPECT_EQ(&(m_broadcastReceiver.buffer()), &m_mockBuffer); EXPECT_EQ(m_broadcastReceiver.offset(), RecordDescriptor::msgOffset(recordOffset)); EXPECT_EQ(m_broadcastReceiver.length(), length); EXPECT_TRUE(m_broadcastReceiver.validate()); } TEST_F(BroadcastReceiverTest, shouldDealWithRecordBecomingInvalidDueToOverwrite) { const std::int32_t length = 8; const std::int32_t recordLength = length + RecordDescriptor::HEADER_LENGTH; const std::int32_t alignedRecordLength = util::BitUtil::align(recordLength, RecordDescriptor::RECORD_ALIGNMENT); const std::int64_t tail = alignedRecordLength; const std::int64_t latestRecord = tail - alignedRecordLength; const std::int32_t recordOffset = (std::int32_t)latestRecord; testing::Sequence sequence; EXPECT_CALL(m_mockBuffer, getInt64Volatile(TAIL_INTENT_COUNTER_INDEX)) .Times(2) .WillOnce(testing::Return(tail)) .WillOnce(testing::Return(tail + (CAPACITY - alignedRecordLength))); EXPECT_CALL(m_mockBuffer, getInt64Volatile(TAIL_COUNTER_INDEX)) .Times(1) .InSequence(sequence) .WillOnce(testing::Return(tail)); EXPECT_CALL(m_mockBuffer, getInt64(LATEST_COUNTER_INDEX)) .Times(0); EXPECT_CALL(m_mockBuffer, getInt32(RecordDescriptor::lengthOffset(recordOffset))) .Times(2) .WillRepeatedly(testing::Return(recordLength)); EXPECT_CALL(m_mockBuffer, getInt32(RecordDescriptor::typeOffset(recordOffset))) .Times(2) .WillRepeatedly(testing::Return(MSG_TYPE_ID)); EXPECT_TRUE(m_broadcastReceiver.receiveNext()); EXPECT_EQ(m_broadcastReceiver.typeId(), MSG_TYPE_ID); EXPECT_EQ(&(m_broadcastReceiver.buffer()), &m_mockBuffer); EXPECT_EQ(m_broadcastReceiver.offset(), RecordDescriptor::msgOffset(recordOffset)); EXPECT_EQ(m_broadcastReceiver.length(), length); EXPECT_FALSE(m_broadcastReceiver.validate()); }
cd882191ec9d907058fefe5c99e93ee78bbee50b
cdbea19ba85553c130592fbef2c3aafa979d07ff
/Number Theory/Smallest Number Having Exactly K Divisors.cpp
1c27384a691a8269d1173a92dc26b5df54c001c2
[ "MIT" ]
permissive
alokkiitd1729/code-library
e5251cc6bd3770b9a8ce038ed01f85e83655af65
e6746f0627dc1f6c51d8c511e75c8fa6c2ff8397
refs/heads/master
2023-08-17T14:42:12.645470
2021-10-01T22:27:22
2021-10-01T22:27:22
406,870,622
0
0
MIT
2021-09-15T17:45:11
2021-09-15T17:45:10
null
UTF-8
C++
false
false
2,013
cpp
Smallest Number Having Exactly K Divisors.cpp
#include<bits/stdc++.h> using namespace std; const int N = 1e6 + 9, mod = 1e9 + 7; int power(long long n, long long k) { int ans = 1 % mod; n %= mod; if (n < 0) n += mod; while (k) { if (k & 1) ans = (long long) ans * n % mod; n = (long long) n * n % mod; k >>= 1; } return ans; } int spf[N]; vector<int> primes; void sieve() { for(int i = 2; i < N; i++) { if (spf[i] == 0) spf[i] = i, primes.push_back(i); int sz = primes.size(); for (int j = 0; j < sz && i * primes[j] < N && primes[j] <= spf[i]; j++) { spf[i * primes[j]] = primes[j]; } } } double lgp[N]; vector<long long> v; unordered_map<long long, pair<double, int>> dp[100]; pair<double, int> yo(int i, long long n) { // it solves for odd divisors if (n == 1) { return {0, 1}; } if (dp[i].find(n) != dp[i].end()) { return dp[i][n]; } pair<double, int> ans = {1e50, 0}; for (auto x: v) { if (x > n) break; if (n % x != 0) continue; auto z = lgp[i + 1] * (x - 1); // i for all divisors if (z > ans.first) { break; } auto cur = yo(i + 1, n / x); cur.first += z; cur.second = 1LL * cur.second * power(primes[i + 1], x - 1) % mod; // i for all divisors ans = min(ans, cur); } return dp[i][n] = ans; } int32_t main() { ios_base::sync_with_stdio(0); cin.tie(0); sieve(); for (int i = 0; i < 100; i++) { lgp[i] = log(primes[i]); } int t, cs = 0; cin >> t; while (t--) { long long n; cin >> n; ++n; if (n == 1) { cout << "Case " << ++cs << ": " << 1 << '\n'; continue; } v.clear(); for (int i = 1; 1LL * i * i <= n; i++) { if (n % i == 0) { if (i > 1) v.push_back(i); if (i != n / i) { v.push_back(n / i); } } } sort(v.begin(), v.end()); cout << "Case " << ++cs << ": " << yo(0, n).second << '\n'; } return 0; } // https://lightoj.com/problem/politeness
ddd4a19d90ed982dffe2fd97d60806d64a2116c5
0cb85cd0c88a9b9f0cca4472742c2bf9febef2d8
/AVP32/DOS shell/TV32.src/STRMSTAT.cpp
cfb48469ce6bc2c46ee52caa23d7f1a5e402db9f
[]
no_license
seth1002/antivirus-1
9dfbadc68e16e51f141ac8b3bb283c1d25792572
3752a3b20e1a8390f0889f6192ee6b851e99e8a4
refs/heads/master
2020-07-15T00:30:19.131934
2016-07-21T13:59:11
2016-07-21T13:59:11
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,078
cpp
STRMSTAT.cpp
/*------------------------------------------------------------*/ /* filename - strmstat.cpp */ /* */ /* defines the static members of class pstream */ /*------------------------------------------------------------*/ /*------------------------------------------------------------*/ /* */ /* Turbo Vision - Version 1.0 */ /* */ /* */ /* Copyright (c) 1991 by Borland International */ /* All Rights Reserved. */ /* */ /*------------------------------------------------------------*/ #ifndef NO_TV_STREAMS #define Uses_pstream #include "include\tv.h" TStreamableTypes * near pstream::types; #endif // ifndef NO_TV_STREAMS
7e3eba21dd7c94ca67ec13a5054daa9f9d7e63a0
1a2190b96ca17719d2b41a5fbcac6043cf9f08e4
/Treinos/2017-07-14 - MaratonIME Winter School/countpath.cpp
de9b6266e05d134db0dd4f5c5a6734125eda09d5
[]
no_license
eliasm2/problem-solving
13c1abbf397bb41683fccb3490b0113c36ce9010
15becf49315b5defb8c1267e0c43ce1579dcae1a
refs/heads/master
2020-09-07T07:12:17.112311
2018-07-20T17:27:43
2018-07-20T17:27:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
833
cpp
countpath.cpp
#include <bits/stdc++.h> using namespace std; template <typename T, size_t N, size_t M> using matrix = array<array<T, M>, N>; const int MAXN = 20; matrix<int64_t, (1<<MAXN), MAXN> dp; array<vector<int>, MAXN> gr; int main(int argc, char* argv[]) { ios::sync_with_stdio(false); cin.tie(NULL); int n, m; cin >> n >> m; while (m--) { int u, v; cin >> u >> v; gr[u].push_back(v); gr[v].push_back(u); } int all = (1<<n) - 1; int64_t total{0}; for (int can_use = 1; can_use <= all; ++can_use) { for (int u = 0; u < n; ++u) { if (can_use & (1 << u)) continue; for (int v : gr[u]) if (can_use & (1<<v)) { dp[can_use][u] += 1 + dp[can_use ^ (1<<v)][v]; } if ((can_use ^ (1<<u)) == all) total += dp[can_use][u]; } } cout << total << "\n"; return 0; }
174936f8e7d1ec19dbf76b4a8885ee2c4f34b512
47470fb93459d294bb425351abedebb6a2e284d6
/ptree/processorSet.hpp
0bd0b2121fd1d6b8b8512fdc080352c324bceb5c
[]
no_license
portegys/Parallel-tree
1a1cfafc8c5e4b668ff1289696470a5135ae1b99
6294e5677c66b010f92cfeb099a8dc42871013fa
refs/heads/master
2020-07-15T14:40:46.066921
2019-08-31T19:11:28
2019-08-31T19:11:28
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,662
hpp
processorSet.hpp
/* * This software is provided under the terms of the GNU General * Public License as published by the Free Software Foundation. * * Copyright (c) 2003 Tom Portegys, All Rights Reserved. * Permission to use, copy, modify, and distribute this software * and its documentation for NON-COMMERCIAL purposes and without * fee is hereby granted provided that this copyright notice * appears in all copies. * * THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. */ /* * Programmer : Tom Portegys <portegys@ilstu.edu> * File Name : processorSet.hpp * * Description : Flocking boids (alife creatures) tracked by octrees. * The octrees are distributed among processors. * * Date : 3/24/2003 */ #ifndef __PROCESSORSET_HPP__ #define __PROCESSORSET_HPP__ #ifdef UNIX #include <pvm3.h> #include <pthread.h> #endif #include "message.h" #include "Boid.h" #include "octree.hpp" #include "frustum.hpp" #define PRECISION 100.0 class ProcessorSet { public: // Maximum boundary movement rate for load-balancing. static const float MAX_BOUNDARY_VELOCITY; // Load-balancing partitions. typedef enum { XCUT, YCUT, ZCUT } CUT; // Centroid. typedef struct Centroid { Point3D position; int load; struct Centroid *next; } CENTROID; // Visible object. typedef struct Visible { int id; Point3D position; Point3D velocity; struct Visible *next; } VISIBLE; // Constructor. ProcessorSet(int dimension, float span, int numBoids, int *ptids, int tid, int randomSeed); // Destructor. ~ProcessorSet(); // Make boids. void makeBoids(int proc, int quantity); // Main loop. void run(); // Aim: update velocity and determine new position. void aim(); // Move to new position. void move(); // Report load. void report(); // Report statistics. void stats(); // Load-balance. void balance(); // Migrate boids. void migrate(); // Report ready. void ready(); // Insert boid into a processor. bool insert(int proc, Boid *boid); // Search a processor. // Returns list of matching boids. Boid *search(int proc, Point3D point, float radius); // Search for visible local objects. VISIBLE *searchVisible(Frustum *frustum); // Serve client processors. void serveClient(int operation); // Set load-balance. void setLoadBalance(bool mode) { loadBalance = mode; } // Load-balance. void balance(int *parray, int rows, int columns, int ranks, CUT cut, Octree::BOUNDS bounds, CENTROID *centroids); void sortCentroids(CENTROID * *, CUT); // Bounds intersection. bool intersects(Octree::BOUNDS, Octree::BOUNDS); // Partition processors among machines. static void partition(int *assign, int numMachines, int dimension); static void subPartition(int *assign, int *marray, int msize, int *parray, int rows, int columns, int ranks, CUT cut, Octree::BOUNDS bounds, Octree::BOUNDS *procBounds); // Data members. int dimension; float span; float margin; int numBoids; int numProcs; Octree **octrees; OctObject **migrations; int *ptids; int tid; Octree::BOUNDS *newBounds; bool loadBalance; int msgSent, msgRcv; }; #endif
d6328037143526647f3808c48fcbb59546c3f246
f5f60e487d18a98c67f93c0b45cad351b5f4f339
/1789.cpp
ff76f140b1af35a062c39d509dab7171127954af
[]
no_license
Dulun/Algorithm
d5f6d25c6765b3a2bb26495bf870434cf67d29f1
b3775852bff1f8dc2c55e048931832ca31385bde
refs/heads/master
2021-07-15T18:36:10.066423
2021-06-27T10:49:01
2021-06-27T10:49:01
54,180,167
3
0
null
null
null
null
UTF-8
C++
false
false
1,044
cpp
1789.cpp
/************************************************************************* > File Name: 1789.cpp > Author: dulun > Mail: dulun@xiyoulinux.org > Created Time: 2016年01月26日 星期二 11时15分18秒 ************************************************************************/ #include<iostream> #include<stdio.h> using namespace std; const int inf = 10; const int large = 2001; int n; char str[large][8]; int dist[large][large] = {0}; int weight(int i, int j) { int w = 0; for(int k=0; i<7; k++) { if(str[i][k] != str[j][k]) w++; } return w; } int prim() { bool visit[large]; int prim_w = 0; int min_w; int k, t = n; int low[large]; memset(visit, false, sizeof(u)); visit[s] = true; for(int i = 0; i < n; i++) { low[i] = inf; } while(t--) { for(int i = 0; i < n; i++) { min_w = inf; if(!visit[i] && low[i] > min_w ) k = i, min_w = low[i]; } visit[k] = true; } }
1a2eb61329aa35632e020bec1898d3a5040cd670
ed505166a9c743ef5b897e683a933341cdb6cea8
/UVa/UVa11804_Argentina/main.cpp
47b100fdacc9c23732d29f41446933abc699023f
[]
no_license
tada-s/ICPC_Training
fd0e8562d3c4723bf44da2c88c53bbfc8312e108
52e3b8ff094744deb454780aac7684a2f3ec7da3
refs/heads/master
2021-09-17T12:51:00.917086
2018-07-02T02:47:31
2018-07-02T02:47:31
64,604,455
0
0
null
null
null
null
UTF-8
C++
false
false
2,424
cpp
main.cpp
#include <bits/stdc++.h> using namespace std; #define mkp make_pair #define pb push_back vector< pair<string, pair<int, int> > > v; vector<string> attacker(5); list<int> li; int maxAS, maxDS; void take(int i, int m){ if(m == 0){ vector<int> v2(li.begin(), li.end()); //copy(li.begin(), li.end(), back_inserter(v2)); #define DEFENCE = 1 #define ATACKER = 2 int aS = 0; int dS = 0; for(int i = 0; i < 10; i++){ dS += v[i].second.second; } for(int i = 0; i < 5; i++){ aS += v[v2[i]].second.first; dS -= v[v2[i]].second.second; } if(aS > maxAS){ maxAS = aS; maxDS = dS; for(int i = 0; i < 5; i++){ attacker[i] = v[v2[i]].first; } }else if(aS == maxAS && dS > maxDS){ maxDS = dS; for(int i = 0; i < 5; i++){ attacker[i] = v[v2[i]].first; } } }else{ for(int j = i; j <= 10 - m; j++){ li.push_front(j); take(j + 1, m - 1); li.pop_front(); } } } int main(){ //freopen("input.txt", "r", stdin); int caseN = 1; int t; scanf("%d", &t); for(int tt = 0; tt < t; tt++){ maxAS = 0; maxDS = 0; for(int i = 0; i < 10; i++){ char str[20 + 1]; int a, d; scanf("%s%d%d", str, &a, &d); v.pb(mkp(str, mkp(a, d))); } sort(v.begin(), v.end()); take(0, 5); vector<string> defence; for(int i = 0; i < 10; i++){ bool exist = false; for(int j = 0; j < 5; j++){ if(v[i].first == attacker[j]){ exist = true; break; } } if(!exist){ defence.pb(v[i].first); } } sort(attacker.begin(), attacker.end()); sort(defence.begin(), defence.end()); printf("Case %d:\n", caseN++); printf("(%s", attacker[0].c_str()); for(int i = 1; i < 5; i++){ printf(", %s", attacker[i].c_str()); } printf(")\n(%s", defence[0].c_str()); for(int i = 1; i < 5; i++){ printf(", %s", defence[i].c_str()); } printf(")\n"); v.clear(); } return 0; }
9c3989c9aacd4847c6aa39122b820fe3e5d77aab
1a9ef412a09894302ca7df1fedd5d71e7da2f25f
/Stack Problems/Stack_impl.cpp
1be4d8ede3cb4f33c8b377a6d9e31a84bae53cb4
[]
no_license
barnwal-anand/Interview_Preparation
ca87f2fb0cac19f9e6eefe1f8c4ed1e9724e41db
4fd155ced74910e637b9d6453b2820b53cab7505
refs/heads/master
2023-07-19T07:33:34.927883
2023-07-07T22:22:47
2023-07-07T22:22:47
214,193,849
2
0
null
null
null
null
UTF-8
C++
false
false
764
cpp
Stack_impl.cpp
#include <iostream> using namespace std; class Stack { private: int *arr; int top; int size; public: Stack(int n) { size = n; top = -1; arr = new int[size]; } bool push(int); int pop(); }; bool Stack::push(int num) { if(top == size-1) { cout << "Stack overflow" << endl; return false; } arr[++top] = num; return true; } int Stack::pop() { if(top == -1) { cout << "Stack empty" << endl; return -1; } return arr[top--]; } int main() { Stack s1(2); s1.push(12); s1.push(15); s1.push(20); cout << s1.pop() << endl; cout << s1.pop() << endl; return 0; }
46a2078ca183e36f9faedb1c96c4039c71821421
e4c1125ebd80090a2a74e06a83cc9dba0c13bb4b
/jelly-share/src/emule/aich_hash.cpp
5efde7bad77682e09cf25599c28e6a054adba741
[]
no_license
tectronics/jellyfish
cdec7df07eab99d20b42b34940b46e4549eeffab
cc63e53aa39dc8689a9beb45135d0ac4549fa381
refs/heads/master
2018-01-11T15:00:09.952216
2012-03-30T14:17:37
2012-03-30T14:17:37
48,414,266
0
0
null
null
null
null
UTF-8
C++
false
false
1,187
cpp
aich_hash.cpp
#include "src/emule/aich_hash.h" #include <string.h> jellyfish::emule::aich_hash::aich_hash() { memset(buffer, 0, jellyfish::emule::aich_hash::hash_size); } jellyfish::emule::aich_hash::aich_hash( uint8* data ) { read(data); } jellyfish::emule::aich_hash::aich_hash( const aich_hash& k1 ) { if (this != &k1) { *this = k1; } } jellyfish::emule::aich_hash& jellyfish::emule::aich_hash::operator=( const aich_hash& k1 ) { memcpy(buffer, k1.buffer, jellyfish::emule::aich_hash::hash_size); return *this; } void jellyfish::emule::aich_hash::read( const uint8* data ) { memcpy(buffer, data, jellyfish::emule::aich_hash::hash_size); } uint8* jellyfish::emule::aich_hash::get_raw_hash() { return buffer; } jellyfish::emule::aich_hash::~aich_hash() { } // uint32 jellyfish::emule::aich_hash::DecodeBase32( const wxString &base32 ) // { // // } bool jellyfish::emule::operator==( const aich_hash& k1,const aich_hash& k2 ) { return memcmp(k1.buffer, k2.buffer, jellyfish::emule::aich_hash::hash_size) == 0; } bool jellyfish::emule::operator!=( const aich_hash& k1,const aich_hash& k2 ) { return !(k1 == k2); }